query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
TestNG returns a compound thread ID that includes the thread name and its numeric ID, separated by an 'at' sign. We only want to use the thread name as the ID is mostly unimportant and it takes up too much space in the generated report. @param threadId The compound thread ID. @return The thread name.
[ "public String stripThreadName(String threadId)\n {\n if (threadId == null)\n {\n return null;\n }\n else\n {\n int index = threadId.lastIndexOf('@');\n return index >= 0 ? threadId.substring(0, index) : threadId;\n }\n }" ]
[ "public static sslservice get(nitro_service service, String servicename) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\tobj.set_servicename(servicename);\n\t\tsslservice response = (sslservice) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void createFrameset(File outputDirectory) throws Exception\n {\n VelocityContext context = createContext();\n generateFile(new File(outputDirectory, INDEX_FILE),\n INDEX_FILE + TEMPLATE_EXTENSION,\n context);\n }", "@RequestMapping(value = \"/profiles\", method = RequestMethod.GET)\n public String list(Model model) {\n Profile profiles = new Profile();\n model.addAttribute(\"addNewProfile\", profiles);\n model.addAttribute(\"version\", Constants.VERSION);\n logger.info(\"Loading initial page\");\n\n return \"profiles\";\n }", "private String getParentWBS(String wbs)\n {\n String result;\n int index = wbs.lastIndexOf('.');\n if (index == -1)\n {\n result = null;\n }\n else\n {\n result = wbs.substring(0, index);\n }\n return result;\n }", "public static LBuffer loadFrom(File file) throws IOException {\n FileChannel fin = new FileInputStream(file).getChannel();\n long fileSize = fin.size();\n if (fileSize > Integer.MAX_VALUE)\n throw new IllegalArgumentException(\"Cannot load from file more than 2GB: \" + file);\n LBuffer b = new LBuffer((int) fileSize);\n long pos = 0L;\n WritableChannelWrap ch = new WritableChannelWrap(b);\n while (pos < fileSize) {\n pos += fin.transferTo(0, fileSize, ch);\n }\n return b;\n }", "public void remove(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\tconvertedObjects.remove(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}", "private void attributes(Options opt, FieldDoc fd[]) {\n\tfor (FieldDoc f : fd) {\n\t if (hidden(f))\n\t\tcontinue;\n\t stereotype(opt, f, Align.LEFT);\n\t String att = visibility(opt, f) + f.name();\n\t if (opt.showType)\n\t\tatt += typeAnnotation(opt, f.type());\n\t tableLine(Align.LEFT, att);\n\t tagvalue(opt, f);\n\t}\n }", "public void removeExtension(Resource rootResource, String moduleName, ManagementResourceRegistration rootRegistration) throws IllegalStateException {\n final ManagementResourceRegistration profileReg;\n if (rootRegistration.getPathAddress().size() == 0) {\n //domain or server extension\n // Can't use processType.isServer() to determine where to look for profile reg because a lot of test infrastructure\n // doesn't add the profile mrr even in HC-based tests\n ManagementResourceRegistration reg = rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(PROFILE)));\n if (reg == null) {\n reg = rootRegistration;\n }\n profileReg = reg;\n } else {\n //host model extension\n profileReg = rootRegistration;\n }\n ManagementResourceRegistration deploymentsReg = processType.isServer() ? rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT))) : null;\n\n ExtensionInfo extension = extensions.remove(moduleName);\n if (extension != null) {\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (extension) {\n Set<String> subsystemNames = extension.subsystems.keySet();\n\n final boolean dcExtension = processType.isHostController() ?\n rootRegistration.getPathAddress().size() == 0 : false;\n\n for (String subsystem : subsystemNames) {\n if (hasSubsystemsRegistered(rootResource, subsystem, dcExtension)) {\n // Restore the data\n extensions.put(moduleName, extension);\n throw ControllerLogger.ROOT_LOGGER.removingExtensionWithRegisteredSubsystem(moduleName, subsystem);\n }\n }\n for (Map.Entry<String, SubsystemInformation> entry : extension.subsystems.entrySet()) {\n String subsystem = entry.getKey();\n profileReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n if (deploymentsReg != null) {\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBDEPLOYMENT, subsystem));\n }\n\n if (extension.xmlMapper != null) {\n SubsystemInformationImpl subsystemInformation = SubsystemInformationImpl.class.cast(entry.getValue());\n for (String namespace : subsystemInformation.getXMLNamespaces()) {\n extension.xmlMapper.unregisterRootElement(new QName(namespace, SUBSYSTEM));\n }\n }\n }\n }\n }\n }", "public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n try {\n FileUtils.writeStringToFile(new File(outputDirName, \"plan.out\"), plan.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpPlanToFile: \" + e);\n }\n }\n }" ]
This method extracts project properties from a GanttProject file. @param ganttProject GanttProject file
[ "private void readProjectProperties(Project ganttProject)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(ganttProject.getName());\n mpxjProperties.setCompany(ganttProject.getCompany());\n mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS);\n\n String locale = ganttProject.getLocale();\n if (locale == null)\n {\n locale = \"en_US\";\n }\n m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale));\n }" ]
[ "@Override\n\tpublic void close() {\n\t\tlogger.info(\"Finished processing.\");\n\t\tthis.timer.stop();\n\t\tthis.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\tprintStatus();\n\t}", "public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}", "public static KieRuntimeLogger newFileLogger(KieRuntimeEventManager session,\n String fileName) {\n return getKnowledgeRuntimeLoggerProvider().newFileLogger( session,\n fileName );\n }", "private static boolean isAssignableFrom(Type from, ParameterizedType to,\n\t\t\tMap<String, Type> typeVarMap) {\n\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// First figure out the class and any type information.\n\t\tClass<?> clazz = getRawType(from);\n\t\tParameterizedType ptype = null;\n\t\tif (from instanceof ParameterizedType) {\n\t\t\tptype = (ParameterizedType) from;\n\t\t}\n\n\t\t// Load up parameterized variable info if it was parameterized.\n\t\tif (ptype != null) {\n\t\t\tType[] tArgs = ptype.getActualTypeArguments();\n\t\t\tTypeVariable<?>[] tParams = clazz.getTypeParameters();\n\t\t\tfor (int i = 0; i < tArgs.length; i++) {\n\t\t\t\tType arg = tArgs[i];\n\t\t\t\tTypeVariable<?> var = tParams[i];\n\t\t\t\twhile (arg instanceof TypeVariable) {\n\t\t\t\t\tTypeVariable<?> v = (TypeVariable<?>) arg;\n\t\t\t\t\targ = typeVarMap.get(v.getName());\n\t\t\t\t}\n\t\t\t\ttypeVarMap.put(var.getName(), arg);\n\t\t\t}\n\n\t\t\t// check if they are equivalent under our current mapping.\n\t\t\tif (typeEquals(ptype, to, typeVarMap)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tfor (Type itype : clazz.getGenericInterfaces()) {\n\t\t\tif (isAssignableFrom(itype, to, new HashMap<String, Type>(\n\t\t\t\t\ttypeVarMap))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// Interfaces didn't work, try the superclass.\n\t\tType sType = clazz.getGenericSuperclass();\n\t\tif (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "private void initDurationPanel() {\n\n m_durationPrefixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_PREFIX_0));\n m_durationAfterPostfixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_POSTFIX_0));\n m_seriesEndDate.setDateOnly(true);\n m_seriesEndDate.setAllowInvalidValue(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n m_seriesEndDate.getTextField().addFocusHandler(new FocusHandler() {\n\n public void onFocus(FocusEvent event) {\n\n if (handleChange()) {\n onSeriesEndDateFocus(event);\n }\n\n }\n });\n }", "void notifyMwRevisionProcessors(MwRevision mwRevision, boolean isCurrent) {\n\t\tif (mwRevision == null || mwRevision.getPageId() <= 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (MwRevisionProcessorBroker.RevisionSubscription rs : this.revisionSubscriptions) {\n\t\t\tif (rs.onlyCurrentRevisions == isCurrent\n\t\t\t\t\t&& (rs.model == null || mwRevision.getModel().equals(\n\t\t\t\t\t\t\trs.model))) {\n\t\t\t\trs.mwRevisionProcessor.processRevision(mwRevision);\n\t\t\t}\n\t\t}\n\t}", "String getDefaultReturnFields() {\n\n StringBuffer fields = new StringBuffer(\"\");\n fields.append(CmsSearchField.FIELD_PATH);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE).append('_').append(getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_END).append('_').append(getSearchLocale().toString()).append(\n \"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_INSTANCEDATE_CURRENT_TILL).append('_').append(\n getSearchLocale().toString()).append(\"_dt\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_SOLR_ID);\n fields.append(',');\n fields.append(CmsSearchField.FIELD_DISPTITLE).append('_').append(getSearchLocale().toString()).append(\"_sort\");\n fields.append(',');\n fields.append(CmsSearchField.FIELD_LINK);\n return fields.toString();\n }", "public static String escapeDoubleQuotesForJson(String text) {\n\t\tif ( text == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tStringBuilder builder = new StringBuilder( text.length() );\n\t\tfor ( int i = 0; i < text.length(); i++ ) {\n\t\t\tchar c = text.charAt( i );\n\t\t\tswitch ( c ) {\n\t\t\t\tcase '\"':\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tbuilder.append( \"\\\\\" );\n\t\t\t\tdefault:\n\t\t\t\t\tbuilder.append( c );\n\t\t\t}\n\t\t}\n\t\treturn builder.toString();\n\t}", "private List<TimephasedCost> getTimephasedActualCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n double actualCost = getActualCost().doubleValue();\n\n if (actualCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(getCalendar(), actualCost, getActualStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(getCalendar(), actualCost, getActualFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently; have to 'fill up' each\n //day with the standard amount before going to the next one\n double numWorkingDays = getCalendar().getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n result.addAll(splitCostProrated(getCalendar(), actualCost, standardAmountPerDay, getActualStart()));\n }\n }\n\n return result;\n }" ]
Returns the index of the segment containing the first byte outside the network prefix. When networkPrefixLength is null, or it matches or exceeds the bit length, returns the segment count. @param networkPrefixLength @param byteLength @return
[ "public static int getHostSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) {\n\t\tif(bytesPerSegment > 1) {\n\t\t\tif(bytesPerSegment == 2) {\n\t\t\t\treturn networkPrefixLength >> 4;\n\t\t\t}\n\t\t\treturn networkPrefixLength / bitsPerSegment;\n\t\t}\n\t\treturn networkPrefixLength >> 3;\n\t}" ]
[ "@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }", "public Where<T, ID> eq(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "@Override\n public String getText() {\n String retType = AstToTextHelper.getClassText(returnType);\n String exceptionTypes = AstToTextHelper.getThrowsClauseText(exceptions);\n String parms = AstToTextHelper.getParametersText(parameters);\n return AstToTextHelper.getModifiersText(modifiers) + \" \" + retType + \" \" + name + \"(\" + parms + \") \" + exceptionTypes + \" { ... }\";\n }", "public static java.sql.Date getDate(Object value) {\n try {\n return toDate(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "private <T> T populateBean(final T resultBean, final String[] nameMapping) {\n\t\t\n\t\t// map each column to its associated field on the bean\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\t\n\t\t\tfinal Object fieldValue = processedColumns.get(i);\n\t\t\t\n\t\t\t// don't call a set-method in the bean if there is no name mapping for the column or no result to store\n\t\t\tif( nameMapping[i] == null || fieldValue == null ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// invoke the setter on the bean\n\t\t\tMethod setMethod = cache.getSetMethod(resultBean, nameMapping[i], fieldValue.getClass());\n\t\t\tinvokeSetter(resultBean, setMethod, fieldValue);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn resultBean;\n\t}", "@Override\n public void removeNamespace(final MongoNamespace namespace) {\n this.instanceLock.writeLock().lock();\n try {\n if (!this.nsStreamers.containsKey(namespace)) {\n return;\n }\n final NamespaceChangeStreamListener streamer = this.nsStreamers.get(namespace);\n streamer.stop();\n this.nsStreamers.remove(namespace);\n } finally {\n this.instanceLock.writeLock().unlock();\n }\n }", "public void mutate(float amount) {\n\t\tfor (int i = 0; i < numKnots; i++) {\n\t\t\tint rgb = yKnots[i];\n\t\t\tint r = ((rgb >> 16) & 0xff);\n\t\t\tint g = ((rgb >> 8) & 0xff);\n\t\t\tint b = (rgb & 0xff);\n\t\t\tr = PixelUtils.clamp( (int)(r + amount * 255 * (Math.random()-0.5)) );\n\t\t\tg = PixelUtils.clamp( (int)(g + amount * 255 * (Math.random()-0.5)) );\n\t\t\tb = PixelUtils.clamp( (int)(b + amount * 255 * (Math.random()-0.5)) );\n\t\t\tyKnots[i] = 0xff000000 | (r << 16) | (g << 8) | b;\n\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\t}\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}", "public static boolean isRegularQueue(final Jedis jedis, final String key) {\n return LIST.equalsIgnoreCase(jedis.type(key));\n }", "public static void createDotStoryFile(String scenarioName,\n String srcTestRootFolder, String packagePath,\n String givenDescription, String whenDescription,\n String thenDescription) throws BeastException {\n String[] folders = packagePath.split(\".\");\n for (String folder : folders) {\n srcTestRootFolder += \"/\" + folder;\n }\n\n FileWriter writer = createFileWriter(createDotStoryName(scenarioName),\n packagePath, srcTestRootFolder);\n try {\n writer.write(\"Scenario: \" + scenarioName + \"\\n\");\n writer.write(\"Given \" + givenDescription + \"\\n\");\n writer.write(\"When \" + whenDescription + \"\\n\");\n writer.write(\"Then \" + thenDescription + \"\\n\");\n writer.close();\n } catch (Exception e) {\n String message = \"Unable to write the .story file for the scenario \"\n + scenarioName;\n logger.severe(message);\n logger.severe(e.getMessage());\n throw new BeastException(message, e);\n }\n }" ]
Commit an upload session after all parts have been uploaded, creating the new file or the version. @param digest the base64-encoded SHA-1 hash of the file being uploaded. @param parts the list of uploaded parts to be committed. @param attributes the key value pairs of attributes from the file instance. @param ifMatch ensures that your app only alters files/folders on Box if you have the current version. @param ifNoneMatch ensure that it retrieve unnecessary data if the most current version of file is on-hand. @return the created file instance.
[ "public BoxFile.Info commit(String digest, List<BoxFileUploadSessionPart> parts,\n Map<String, String> attributes, String ifMatch, String ifNoneMatch) {\n\n URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);\n\n if (ifMatch != null) {\n request.addHeader(HttpHeaders.IF_MATCH, ifMatch);\n }\n\n if (ifNoneMatch != null) {\n request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch);\n }\n\n //Creates the body of the request\n String body = this.getCommitBody(parts, attributes);\n request.setBody(body);\n\n BoxAPIResponse response = request.send();\n //Retry the commit operation after the given number of seconds if the HTTP response code is 202.\n if (response.getResponseCode() == 202) {\n String retryInterval = response.getHeaderField(\"retry-after\");\n if (retryInterval != null) {\n try {\n Thread.sleep(new Integer(retryInterval) * 1000);\n } catch (InterruptedException ie) {\n throw new BoxAPIException(\"Commit retry failed. \", ie);\n }\n\n return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch);\n }\n }\n\n if (response instanceof BoxJSONResponse) {\n //Create the file instance from the response\n return this.getFile((BoxJSONResponse) response);\n } else {\n throw new BoxAPIException(\"Commit response content type is not application/json. The response code : \"\n + response.getResponseCode());\n }\n }" ]
[ "public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n List<Versioned<V>> versionedValues;\n long startTime = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"PUT requested for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + startTime\n + \" . Nested GET and PUT VERSION requests to follow ---\");\n }\n\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent put might be faster such that all the\n // steps might finish within the allotted time\n requestWrapper.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(requestWrapper);\n Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues);\n\n long endTime = System.currentTimeMillis();\n if(versioned == null)\n versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock());\n else\n versioned.setObject(requestWrapper.getRawValue());\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime);\n if(timeLeft <= 0) {\n throw new StoreTimeoutException(\"PUT request timed out\");\n }\n CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(),\n versioned,\n timeLeft);\n putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs());\n Version result = putVersionedWithCustomTimeout(putVersionedRequestObject);\n long endTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT response received for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + endTimeInMs);\n }\n return result;\n }", "private void executeResult() throws Exception {\n\t\tresult = createResult();\n\n\t\tString timerKey = \"executeResult: \" + getResultCode();\n\t\ttry {\n\t\t\tUtilTimerStack.push(timerKey);\n\t\t\tif (result != null) {\n\t\t\t\tresult.execute(this);\n\t\t\t} else if (resultCode != null && !Action.NONE.equals(resultCode)) {\n\t\t\t\tthrow new ConfigurationException(\"No result defined for action \" + getAction().getClass().getName()\n\t\t\t\t\t\t+ \" and result \" + getResultCode(), proxy.getConfig());\n\t\t\t} else {\n\t\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\t\tLOG.debug(\"No result returned for action \" + getAction().getClass().getName() + \" at \"\n\t\t\t\t\t\t\t+ proxy.getConfig().getLocation());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tUtilTimerStack.pop(timerKey);\n\t\t}\n\t}", "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 }", "protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }", "public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {\n assertNumericArgument(corePoolSize, true);\n assertNumericArgument(maximumPoolSize, true);\n assertNumericArgument(corePoolSize + maximumPoolSize, false);\n assertNumericArgument(keepAliveTime, true);\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.keepAliveTime = unit.toMillis(keepAliveTime);\n return this;\n }", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "void updateFromResponseOnDeletePost(Response<ResponseBody> response) throws IOException {\n this.withResponse(response);\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n withStatus(AzureAsyncOperation.SUCCESS_STATUS, response.code());\n }", "public static boolean containsOnlyNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o!= null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }" ]
Recursively loads the metadata for this node
[ "public boolean load()\r\n {\r\n \t_load();\r\n \tjava.util.Iterator it = this.alChildren.iterator();\r\n \twhile (it.hasNext())\r\n \t{\r\n \t\tObject o = it.next();\r\n \t\tif (o instanceof OjbMetaTreeNode) ((OjbMetaTreeNode)o).load();\r\n \t}\r\n \treturn true;\r\n }" ]
[ "public static clusternodegroup[] get(nitro_service service) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tclusternodegroup[] response = (clusternodegroup[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void writeResource(Resource mpxjResource, net.sf.mpxj.planner.schema.Resource plannerResource)\n {\n ProjectCalendar resourceCalendar = mpxjResource.getResourceCalendar();\n if (resourceCalendar != null)\n {\n plannerResource.setCalendar(getIntegerString(resourceCalendar.getUniqueID()));\n }\n\n plannerResource.setEmail(mpxjResource.getEmailAddress());\n plannerResource.setId(getIntegerString(mpxjResource.getUniqueID()));\n plannerResource.setName(getString(mpxjResource.getName()));\n plannerResource.setNote(mpxjResource.getNotes());\n plannerResource.setShortName(mpxjResource.getInitials());\n plannerResource.setType(mpxjResource.getType() == ResourceType.MATERIAL ? \"2\" : \"1\");\n //plannerResource.setStdRate();\n //plannerResource.setOvtRate();\n plannerResource.setUnits(\"0\");\n //plannerResource.setProperties();\n m_eventManager.fireResourceWrittenEvent(mpxjResource);\n }", "public Collection<Integer> getNumericCodes() {\n Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver)\r\n {\r\n String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol);\r\n\r\n if (platform == null)\r\n {\r\n platform = (String)jdbcDriverToPlatform.get(jdbcDriver);\r\n }\r\n return platform;\r\n }", "private static OkHttpClient getUnsafeOkHttpClient() {\n try {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] {\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }\n };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new java.security.SecureRandom());\n // Create an ssl socket factory with our all-trusting manager\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n\n OkHttpClient okHttpClient = new OkHttpClient();\n okHttpClient.setSslSocketFactory(sslSocketFactory);\n okHttpClient.setHostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n return okHttpClient;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }", "public List<Long> getOffsets(OffsetRequest offsetRequest) {\n ILog log = getLog(offsetRequest.topic, offsetRequest.partition);\n if (log != null) {\n return log.getOffsetsBefore(offsetRequest);\n }\n return ILog.EMPTY_OFFSETS;\n }", "public float getPositionZ(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }" ]
Allocates a database connection. @throws SQLException
[ "private void allocateConnection() throws SQLException\n {\n if (m_connection == null)\n {\n m_connection = m_dataSource.getConnection();\n m_allocatedConnection = true;\n queryDatabaseMetaData();\n }\n }" ]
[ "public void setModificationState(ModificationState newModificationState)\r\n {\r\n if(newModificationState != modificationState)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"object state transition for object \" + this.oid + \" (\"\r\n + modificationState + \" --> \" + newModificationState + \")\");\r\n// try{throw new Exception();}catch(Exception e)\r\n// {\r\n// e.printStackTrace();\r\n// }\r\n }\r\n modificationState = newModificationState;\r\n }\r\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 }", "public void visitParameter(String name, int access) {\n if (mv != null) {\n mv.visitParameter(name, access);\n }\n }", "public static double blackScholesDigitalOptionDelta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate delta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);\n\n\t\t\treturn delta;\n\t\t}\n\t}", "@Override\n public boolean parseAndValidateRequest() {\n if(!super.parseAndValidateRequest()) {\n return false;\n }\n isGetVersionRequest = hasGetVersionRequestHeader();\n if(isGetVersionRequest && this.parsedKeys.size() > 1) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Get version request cannot have multiple keys\");\n return false;\n }\n return true;\n }", "@Deprecated\n public void parseAndSetParameter(String value, ModelNode operation, XMLStreamReader reader) throws XMLStreamException {\n //we use manual parsing here, and not #getParser().. to preserve backward compatibility.\n if (value != null) {\n for (String element : value.split(\",\")) {\n parseAndAddParameterElement(element.trim(), operation, reader);\n }\n }\n }", "public static Artifact withArtifactId(String artifactId)\n {\n Artifact artifact = new Artifact();\n artifact.artifactId = new RegexParameterizedPatternParser(artifactId);\n return artifact;\n }", "public static Operation createDeployOperation(final DeploymentDescription deployment) {\n Assert.checkNotNullParam(\"deployment\", deployment);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n addDeployOperationStep(builder, deployment);\n return builder.build();\n }", "public static base_response delete(nitro_service client, String fipskeyname) throws Exception {\n\t\tsslfipskey deleteresource = new sslfipskey();\n\t\tdeleteresource.fipskeyname = fipskeyname;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
Sets the specified long attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
[ "public void setLongAttribute(String name, Long value) {\n\t\tensureValue();\n\t\tAttribute attribute = new LongAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}" ]
[ "public String getLinkColor(JSONObject jsonObject){\n if(jsonObject == null) return null;\n try {\n return jsonObject.has(\"color\") ? jsonObject.getString(\"color\") : \"\";\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text Color with JSON - \"+e.getLocalizedMessage());\n return null;\n }\n }", "@Override\n\tpublic Set<String> getRoundingNames(String... providers) {\n Set<String> result = new HashSet<>();\n String[] providerNames = providers;\n if (providerNames.length == 0) {\n providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);\n }\n for (String providerName : providerNames) {\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {\n result.addAll(prov.getRoundingNames());\n }\n } catch (Exception e) {\n Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n }\n return result;\n }", "protected static File platformIndependentUriToFile(final URI fileURI) {\n File file;\n try {\n file = new File(fileURI);\n } catch (IllegalArgumentException e) {\n if (fileURI.toString().startsWith(\"file://\")) {\n file = new File(fileURI.toString().substring(\"file://\".length()));\n } else {\n throw e;\n }\n }\n return file;\n }", "private void deliverFoundAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceFound(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device found announcement to listener\", t);\n }\n }\n });\n }\n }", "private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }", "public void processPick(boolean touched, MotionEvent event)\n {\n mPickEventLock.lock();\n mTouched = touched;\n mMotionEvent = event;\n doPick();\n mPickEventLock.unlock();\n }", "public static base_response export(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey exportresource = new sslfipskey();\n\t\texportresource.fipskeyname = resource.fipskeyname;\n\t\texportresource.key = resource.key;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}", "private void writeResources()\n {\n Resources resources = m_factory.createResources();\n m_plannerProject.setResources(resources);\n List<net.sf.mpxj.planner.schema.Resource> resourceList = resources.getResource();\n for (Resource mpxjResource : m_projectFile.getResources())\n {\n net.sf.mpxj.planner.schema.Resource plannerResource = m_factory.createResource();\n resourceList.add(plannerResource);\n writeResource(mpxjResource, plannerResource);\n }\n }", "public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Gives an sequence of ByteBuffers of a specified range. Writing to these ByteBuffers modifies the contents of this LBuffer. @param offset @param size @return
[ "public ByteBuffer[] toDirectByteBuffers(long offset, long size) {\n long pos = offset;\n long blockSize = Integer.MAX_VALUE;\n long limit = offset + size;\n int numBuffers = (int) ((size + (blockSize - 1)) / blockSize);\n ByteBuffer[] result = new ByteBuffer[numBuffers];\n int index = 0;\n while (pos < limit) {\n long blockLength = Math.min(limit - pos, blockSize);\n result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this)\n .order(ByteOrder.nativeOrder());\n pos += blockLength;\n }\n return result;\n\n }" ]
[ "public static base_responses unset(nitro_service client, String trapname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm unsetresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tunsetresources[i] = new snmpalarm();\n\t\t\t\tunsetresources[i].trapname = trapname[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 java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }", "public List<AssignmentRow> getAssignmentRows(VariableType varType) {\n List<AssignmentRow> rows = new ArrayList<AssignmentRow>();\n List<Variable> handledVariables = new ArrayList<Variable>();\n // Create an AssignmentRow for each Assignment\n for (Assignment assignment : assignments) {\n if (assignment.getVariableType() == varType) {\n String dataType = getDisplayNameFromDataType(assignment.getDataType());\n AssignmentRow row = new AssignmentRow(assignment.getName(),\n assignment.getVariableType(),\n dataType,\n assignment.getCustomDataType(),\n assignment.getProcessVarName(),\n assignment.getConstant());\n rows.add(row);\n handledVariables.add(assignment.getVariable());\n }\n }\n List<Variable> vars = null;\n if (varType == VariableType.INPUT) {\n vars = inputVariables;\n } else {\n vars = outputVariables;\n }\n // Create an AssignmentRow for each Variable that doesn't have an Assignment\n for (Variable var : vars) {\n if (!handledVariables.contains(var)) {\n AssignmentRow row = new AssignmentRow(var.getName(),\n var.getVariableType(),\n var.getDataType(),\n var.getCustomDataType(),\n null,\n null);\n rows.add(row);\n }\n }\n\n return rows;\n }", "public 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 }", "public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@IntRange(from = 0, to = OPAQUE)\n private static int resolveLineAlpha(\n @IntRange(from = 0, to = OPAQUE) final int sceneAlpha,\n final float maxDistance,\n final float distance) {\n final float alphaPercent = 1f - distance / maxDistance;\n final int alpha = (int) ((float) OPAQUE * alphaPercent);\n return alpha * sceneAlpha / OPAQUE;\n }", "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 }", "public static String getDefaultConversionFor(String javaType)\r\n {\r\n return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null;\r\n }", "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }" ]
Executed read-resource-description and returns access-control info. Returns null in case there was any kind of problem. @param client @param address @return
[ "public static ModelNode getAccessControl(ModelControllerClient client, OperationRequestAddress address, boolean operations) {\n return getAccessControl(client, null, address, operations);\n }" ]
[ "private byte[] createErrorImage(int width, int height, Exception e) throws IOException {\n\t\tString error = e.getMessage();\n\t\tif (null == error) {\n\t\t\tWriter result = new StringWriter();\n\t\t\tPrintWriter printWriter = new PrintWriter(result);\n\t\t\te.printStackTrace(printWriter);\n\t\t\terror = result.toString();\n\t\t}\n\n\t\tBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);\n\t\tGraphics2D g = (Graphics2D) image.getGraphics();\n\n\t\tg.setColor(Color.RED);\n\t\tg.drawString(error, ERROR_MESSAGE_X, height / 2);\n\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tImageIO.write(image, \"PNG\", out);\n\t\tout.flush();\n\t\tbyte[] result = out.toByteArray();\n\t\tout.close();\n\n\t\treturn result;\n\t}", "public Weld extensions(Extension... extensions) {\n this.extensions.clear();\n for (Extension extension : extensions) {\n addExtension(extension);\n }\n return this;\n }", "public static double TopsoeDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double den = p[i] + q[i];\n r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);\n }\n }\n return r;\n }", "private void writeAssignmentTimephasedData(BigInteger assignmentID, List<TimephasedDataType> list, List<TimephasedWork> data, int type)\n {\n for (TimephasedWork mpx : data)\n {\n TimephasedDataType xml = m_factory.createTimephasedDataType();\n list.add(xml);\n\n xml.setStart(mpx.getStart());\n xml.setFinish(mpx.getFinish());\n xml.setType(BigInteger.valueOf(type));\n xml.setUID(assignmentID);\n xml.setUnit(DatatypeConverter.printDurationTimeUnits(mpx.getTotalAmount(), false));\n xml.setValue(DatatypeConverter.printDuration(this, mpx.getTotalAmount()));\n }\n }", "private List<Object> convertType(DataType type, byte[] data)\n {\n List<Object> result = new ArrayList<Object>();\n int index = 0;\n\n while (index < data.length)\n {\n switch (type)\n {\n case STRING:\n {\n String value = MPPUtility.getUnicodeString(data, index);\n result.add(value);\n index += ((value.length() + 1) * 2);\n break;\n }\n\n case CURRENCY:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index) / 100);\n result.add(value);\n index += 8;\n break;\n }\n\n case NUMERIC:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index));\n result.add(value);\n index += 8;\n break;\n }\n\n case DATE:\n {\n Date value = MPPUtility.getTimestamp(data, index);\n result.add(value);\n index += 4;\n break;\n\n }\n\n case DURATION:\n {\n TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, index + 4), m_properties.getDefaultDurationUnits());\n Duration value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(data, index), units);\n result.add(value);\n index += 6;\n break;\n }\n\n case BOOLEAN:\n {\n Boolean value = Boolean.valueOf(MPPUtility.getShort(data, index) == 1);\n result.add(value);\n index += 2;\n break;\n }\n\n default:\n {\n index = data.length;\n break;\n }\n }\n }\n\n return result;\n }", "public static DMatrixRBlock initializeQ(DMatrixRBlock Q,\n int numRows , int numCols , int blockLength ,\n boolean compact) {\n int minLength = Math.min(numRows,numCols);\n if( compact ) {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,minLength,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != minLength ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n } else {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,numRows,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != numRows ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n }\n return Q;\n }", "public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\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 userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }", "public boolean getBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n return (data[word] & (1 << offset)) != 0;\n }", "@AsParameterConverter\n\tpublic Trader retrieveTrader(String name) {\n\t\tfor (Trader trader : traders) {\n\t\t\tif (trader.getName().equals(name)) {\n\t\t\t\treturn trader;\n\t\t\t}\n\t\t}\n\t\treturn mockTradePersister().retrieveTrader(name);\n\t}" ]
Indicates that all of the packages within an archive are "known" by the package mapper. Generally this indicates that the archive does not contain customer code.
[ "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 }" ]
[ "private static Row row(List<StatementResult> results) {\n\t\tRow row = results.get( 0 ).getData().get( 0 );\n\t\treturn row;\n\t}", "@NonNull\n @SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher reset() {\n lastResponsePage = 0;\n lastRequestPage = 0;\n lastResponseId = 0;\n endReached = false;\n clearFacetRefinements();\n cancelPendingRequests();\n numericRefinements.clear();\n return this;\n }", "public void postPhoto(Photo photo, String blogId) throws FlickrException {\r\n postPhoto(photo, blogId, null);\r\n }", "@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }", "public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\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 void commit(String msg) throws GitAPIException {\n try (Git git = getGit()) {\n Status status = git.status().call();\n if (!status.isClean()) {\n git.commit().setMessage(msg).setAll(true).setNoVerify(true).call();\n }\n }\n }", "public void writeLine(String pattern, Object... parameters) {\n String line = (parameters == null || parameters.length == 0) ? pattern\n : String.format(pattern, parameters);\n lines.add(0, line); // we'll write bottom to top, then purge unwritten\n // lines from end\n updateHUD();\n }", "public static Cluster swapPartitions(final Cluster nextCandidateCluster,\n final int nodeIdA,\n final int partitionIdA,\n final int nodeIdB,\n final int partitionIdB) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n // Swap partitions between nodes!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdA,\n Lists.newArrayList(partitionIdB));\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdB,\n Lists.newArrayList(partitionIdA));\n\n return returnCluster;\n }" ]
Helper function to return the minimum size of the workspace to be passed to the reduction given the input and output tensors
[ "public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }" ]
[ "public static 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 setWeeklyDaysFromBitmap(Integer days, int[] masks)\n {\n if (days != null)\n {\n int value = days.intValue();\n for (Day day : Day.values())\n {\n setWeeklyDay(day, ((value & masks[day.getValue()]) != 0));\n }\n }\n }", "public static boolean isConstructorCall(Expression expression, List<String> classNames) {\r\n return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName());\r\n }", "public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\n }", "private void processCustomValueLists() throws IOException\n {\n CustomFieldValueReader9 reader = new CustomFieldValueReader9(m_projectDir, m_file.getProjectProperties(), m_projectProps, m_file.getCustomFields());\n reader.process();\n }", "public void setFieldConversionClassName(String fieldConversionClassName)\r\n {\r\n try\r\n {\r\n this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\r\n \"Could not instantiate FieldConversion class using default constructor\", e);\r\n }\r\n }", "private CmsTemplateMapperConfiguration getConfiguration(final CmsObject cms) {\n\n if (!m_enabled) {\n return CmsTemplateMapperConfiguration.EMPTY_CONFIG;\n }\n\n if (m_configPath == null) {\n m_configPath = OpenCms.getSystemInfo().getConfigFilePath(cms, \"template-mapping.xml\");\n }\n\n return (CmsTemplateMapperConfiguration)(CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().loadVfsObject(\n cms,\n m_configPath,\n new Transformer() {\n\n @Override\n public Object transform(Object input) {\n\n try {\n CmsFile file = cms.readFile(m_configPath, CmsResourceFilter.IGNORE_EXPIRATION);\n SAXReader saxBuilder = new SAXReader();\n try (ByteArrayInputStream stream = new ByteArrayInputStream(file.getContents())) {\n Document document = saxBuilder.read(stream);\n CmsTemplateMapperConfiguration config = new CmsTemplateMapperConfiguration(cms, document);\n return config;\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return new CmsTemplateMapperConfiguration(); // empty configuration, does not do anything\n }\n\n }\n }));\n }", "private Duration getDuration(TimeUnit units, Double duration)\n {\n Duration result = null;\n if (duration != null)\n {\n double durationValue = duration.doubleValue() * 100.0;\n\n switch (units)\n {\n case MINUTES:\n {\n durationValue *= MINUTES_PER_DAY;\n break;\n }\n\n case HOURS:\n {\n durationValue *= HOURS_PER_DAY;\n break;\n }\n\n case DAYS:\n {\n durationValue *= 3.0;\n break;\n }\n\n case WEEKS:\n {\n durationValue *= 0.6;\n break;\n }\n\n case MONTHS:\n {\n durationValue *= 0.15;\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported time units \" + units);\n }\n }\n\n durationValue = Math.round(durationValue) / 100.0;\n\n result = Duration.getInstance(durationValue, units);\n }\n\n return result;\n }", "private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,\r\n\t\t\tDayCountConvention daycountConvention) {\r\n\r\n\t\tboolean isFixed = leg.getElementsByTagName(\"interestType\").item(0).getTextContent().equalsIgnoreCase(\"FIX\");\r\n\r\n\t\tArrayList<Period> periods \t\t= new ArrayList<>();\r\n\t\tArrayList<Double> notionalsList\t= new ArrayList<>();\r\n\t\tArrayList<Double> rates\t\t\t= new ArrayList<>();\r\n\r\n\t\t//extracting data for each period\r\n\t\tNodeList periodsXML = leg.getElementsByTagName(\"incomePayment\");\r\n\t\tfor(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {\r\n\r\n\t\t\tElement periodXML = (Element) periodsXML.item(periodIndex);\r\n\r\n\t\t\tLocalDate startDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"startDate\").item(0).getTextContent());\r\n\t\t\tLocalDate endDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"endDate\").item(0).getTextContent());\r\n\r\n\t\t\tLocalDate fixingDate\t= startDate;\r\n\t\t\tLocalDate paymentDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"payDate\").item(0).getTextContent());\r\n\r\n\t\t\tif(! isFixed) {\r\n\t\t\t\tfixingDate = LocalDate.parse(periodXML.getElementsByTagName(\"fixingDate\").item(0).getTextContent());\r\n\t\t\t}\r\n\r\n\t\t\tperiods.add(new Period(fixingDate, paymentDate, startDate, endDate));\r\n\r\n\t\t\tdouble notional\t\t= Double.parseDouble(periodXML.getElementsByTagName(\"nominal\").item(0).getTextContent());\r\n\t\t\tnotionalsList.add(new Double(notional));\r\n\r\n\t\t\tif(isFixed) {\r\n\t\t\t\tdouble fixedRate\t= Double.parseDouble(periodXML.getElementsByTagName(\"fixedRate\").item(0).getTextContent());\r\n\t\t\t\trates.add(new Double(fixedRate));\r\n\t\t\t} else {\r\n\t\t\t\trates.add(new Double(0));\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);\r\n\t\tdouble[] notionals\t= notionalsList.stream().mapToDouble(Double::doubleValue).toArray();\r\n\t\tdouble[] spreads\t= rates.stream().mapToDouble(Double::doubleValue).toArray();\r\n\r\n\t\treturn new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);\r\n\t}" ]
Runs the example program. @param args @throws IOException if there was a problem in writing the output file
[ "public static void main(String[] args) throws IOException {\n\t\tExampleHelpers.configureLogging();\n\t\tJsonSerializationProcessor.printDocumentation();\n\n\t\tJsonSerializationProcessor jsonSerializationProcessor = new JsonSerializationProcessor();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(jsonSerializationProcessor);\n\t\tjsonSerializationProcessor.close();\n\t}" ]
[ "ValidationResult cleanObjectKey(String name) {\n ValidationResult vr = new ValidationResult();\n name = name.trim();\n for (String x : objectKeyCharsNotAllowed)\n name = name.replace(x, \"\");\n\n if (name.length() > Constants.MAX_KEY_LENGTH) {\n name = name.substring(0, Constants.MAX_KEY_LENGTH-1);\n vr.setErrorDesc(name.trim() + \"... exceeds the limit of \"+ Constants.MAX_KEY_LENGTH + \" characters. Trimmed\");\n vr.setErrorCode(520);\n }\n\n vr.setObject(name.trim());\n\n return vr;\n }", "public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}", "public boolean verify(String signatureVersion, String signatureAlgorithm, String primarySignature,\n String secondarySignature, String webHookPayload, String deliveryTimestamp) {\n\n // enforce versions supported by this implementation\n if (!SUPPORTED_VERSIONS.contains(signatureVersion)) {\n return false;\n }\n\n // enforce algorithms supported by this implementation\n BoxSignatureAlgorithm algorithm = BoxSignatureAlgorithm.byName(signatureAlgorithm);\n if (!SUPPORTED_ALGORITHMS.contains(algorithm)) {\n return false;\n }\n\n // check primary key signature if primary key exists\n if (this.primarySignatureKey != null && this.verify(this.primarySignatureKey, algorithm, primarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // check secondary key signature if secondary key exists\n if (this.secondarySignatureKey != null && this.verify(this.secondarySignatureKey, algorithm, secondarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // default strategy is false, to minimize security issues\n return false;\n }", "@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 void refreshCredentials() {\n if (this.credsProvider == null)\n return;\n\n try {\n AlibabaCloudCredentials creds = this.credsProvider.getCredentials();\n this.accessKeyID = creds.getAccessKeyId();\n this.accessKeySecret = creds.getAccessKeySecret();\n\n if (creds instanceof BasicSessionCredentials) {\n this.securityToken = ((BasicSessionCredentials) creds).getSessionToken();\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "private static Dimension adaptTileDimensions(\n final Dimension pixels, final int maxWidth, final int maxHeight) {\n return new Dimension(adaptTileDimension(pixels.width, maxWidth),\n adaptTileDimension(pixels.height, maxHeight));\n }", "protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }", "private Map<String, String> generateCommonConfigPart() {\n\n Map<String, String> result = new HashMap<>();\n if (m_category != null) {\n result.put(CONFIGURATION_CATEGORY, m_category);\n }\n // append 'only leafs' to configuration\n if (m_onlyLeafs) {\n result.put(CONFIGURATION_ONLYLEAFS, null);\n }\n // append 'property' to configuration\n if (m_property != null) {\n result.put(CONFIGURATION_PROPERTY, m_property);\n }\n // append 'selectionType' to configuration\n if (m_selectiontype != null) {\n result.put(CONFIGURATION_SELECTIONTYPE, m_selectiontype);\n }\n return result;\n }", "public static void checkFolderForFile(String fileName) throws IOException {\n\n\t\tif (fileName.lastIndexOf(File.separator) > 0) {\n\t\t\tString folder = fileName.substring(0, fileName.lastIndexOf(File.separator));\n\t\t\tdirectoryCheck(folder);\n\t\t}\n\t}" ]
Sets the character translator for all cells in the row. It will also remove any other translator set. Nothing will happen if the argument is null. @param charTranslator translator @return this to allow chaining
[ "public AT_Row setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public synchronized void releaseRebalancingPermit(int nodeId) {\n boolean removed = rebalancePermits.remove(nodeId);\n logger.info(\"Releasing rebalancing permit for node id \" + nodeId + \", returned: \" + removed);\n if(!removed)\n throw new VoldemortException(new IllegalStateException(\"Invalid state, must hold a \"\n + \"permit to release\"));\n }", "public static String resourceProviderFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).providerNamespace() : null;\n }", "public static DMatrixRMaj extractColumn(DMatrixRMaj a , int column , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(a.numRows,1);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numRows )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numRows);\n\n int index = column;\n for (int i = 0; i < a.numRows; i++, index += a.numCols ) {\n out.data[i] = a.data[index];\n }\n return out;\n }", "private static String guessDumpDate(String fileName) {\n\t\tPattern p = Pattern.compile(\"([0-9]{8})\");\n\t\tMatcher m = p.matcher(fileName);\n\n\t\tif (m.find()) {\n\t\t\treturn m.group(1);\n\t\t} else {\n\t\t\tlogger.info(\"Could not guess date of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to YYYYMMDD.\");\n\t\t\treturn \"YYYYMMDD\";\n\t\t}\n\t}", "public void prepareStatus() {\n globalLineCounter = new AtomicLong(0);\n time = new AtomicLong(System.currentTimeMillis());\n startTime = System.currentTimeMillis();\n lastCount = 0;\n\n // Status thread regularly reports on what is happening\n Thread statusThread = new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Status thread interrupted\");\n }\n\n long thisTime = System.currentTimeMillis();\n long currentCount = globalLineCounter.get();\n\n if (thisTime - time.get() > 1000) {\n long oldTime = time.get();\n time.set(thisTime);\n double avgRate = 1000.0 * currentCount / (thisTime - startTime);\n double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime);\n lastCount = currentCount;\n System.out.println(currentCount + \" AvgRage:\" + ((int) avgRate) + \" lines/sec instRate:\"\n + ((int) instRate) + \" lines/sec Unassigned Work: \"\n + remainingBlocks.get() + \" blocks\");\n }\n }\n }\n };\n statusThread.start();\n }", "public Date getStartDate()\n {\n Date startDate = 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. Note that the\n // behaviour is different for milestones. The milestone end date\n // is always correct, the milestone start date may be different\n // to reflect a missed deadline.\n //\n Date taskStartDate;\n if (task.getMilestone() == true)\n {\n taskStartDate = task.getActualFinish();\n if (taskStartDate == null)\n {\n taskStartDate = task.getFinish();\n }\n }\n else\n {\n taskStartDate = task.getActualStart();\n if (taskStartDate == null)\n {\n taskStartDate = task.getStart();\n }\n }\n\n if (taskStartDate != null)\n {\n if (startDate == null)\n {\n startDate = taskStartDate;\n }\n else\n {\n if (taskStartDate.getTime() < startDate.getTime())\n {\n startDate = taskStartDate;\n }\n }\n }\n }\n\n return (startDate);\n }", "public List<String> getArtifactVersions(final String gavc) {\n final DbArtifact artifact = getArtifact(gavc);\n return repositoryHandler.getArtifactVersions(artifact);\n }", "protected void processLabels(List<MonolingualTextValue> labels) {\n for(MonolingualTextValue label : labels) {\n \tString lang = label.getLanguageCode();\n \tNameWithUpdate currentValue = newLabels.get(lang);\n \tif (currentValue == null || !currentValue.value.equals(label)) {\n\t newLabels.put(lang,\n\t new NameWithUpdate(label, true));\n\t \n\t // Delete any alias that matches the new label\n\t AliasesWithUpdate currentAliases = newAliases.get(lang);\n\t if (currentAliases != null && currentAliases.aliases.contains(label)) {\n\t \tdeleteAlias(label);\n\t }\n \t}\n }\n \n }", "public static String cutEnd(String data, int maxLength) {\n if (data.length() > maxLength) {\n return data.substring(0, maxLength) + \"...\";\n } else {\n return data;\n }\n }" ]
Deserialize a javascript design document file to a DesignDocument object. @param file the design document javascript file (UTF-8 encoded) @return {@link DesignDocument} @throws FileNotFoundException if the file does not exist or cannot be read
[ "public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }" ]
[ "private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n for ( int i = 0; i < mEmitRate * 2; i +=2 )\n {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n return timeStamps;\n }", "private void recurseAndAddFiles(GraphRewrite event, EvaluationContext context,\n Path tempFolder,\n FileService fileService, ArchiveModel archiveModel,\n FileModel parentFileModel, boolean subArchivesOnly)\n {\n checkCancelled(event);\n\n int numberAdded = 0;\n\n FileFilter filter = TrueFileFilter.TRUE;\n if (archiveModel instanceof IdentifiedArchiveModel)\n {\n filter = new IdentifiedArchiveFileFilter(archiveModel);\n }\n\n File fileReference;\n if (parentFileModel instanceof ArchiveModel)\n fileReference = new File(((ArchiveModel) parentFileModel).getUnzippedDirectory());\n else\n fileReference = parentFileModel.asFile();\n\n WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n File[] subFiles = fileReference.listFiles();\n if (subFiles == null)\n return;\n\n for (File subFile : subFiles)\n {\n if (!filter.accept(subFile))\n continue;\n\n if (subArchivesOnly && !ZipUtil.endsWithZipExtension(subFile.getAbsolutePath()))\n continue;\n\n FileModel subFileModel = fileService.createByFilePath(parentFileModel, subFile.getAbsolutePath());\n\n // check if this file should be ignored\n if (windupJavaConfigurationService.checkIfIgnored(event, subFileModel))\n continue;\n\n numberAdded++;\n if (numberAdded % 250 == 0)\n event.getGraphContext().commit();\n\n if (subFile.isFile() && ZipUtil.endsWithZipExtension(subFileModel.getFilePath()))\n {\n File newZipFile = subFileModel.asFile();\n ArchiveModel newArchiveModel = GraphService.addTypeToModel(event.getGraphContext(), subFileModel, ArchiveModel.class);\n newArchiveModel.setParentArchive(archiveModel);\n newArchiveModel.setArchiveName(newZipFile.getName());\n\n /*\n * New archive must be reloaded in case the archive should be ignored\n */\n newArchiveModel = GraphService.refresh(event.getGraphContext(), newArchiveModel);\n\n ArchiveModel canonicalArchiveModel = null;\n for (FileModel otherMatches : fileService.findAllByProperty(FileModel.SHA1_HASH, newArchiveModel.getSHA1Hash()))\n {\n if (otherMatches instanceof ArchiveModel && !otherMatches.equals(newArchiveModel) && !(otherMatches instanceof DuplicateArchiveModel))\n {\n canonicalArchiveModel = (ArchiveModel)otherMatches;\n break;\n }\n }\n\n if (canonicalArchiveModel != null)\n {\n // handle as duplicate\n DuplicateArchiveModel duplicateArchive = GraphService.addTypeToModel(event.getGraphContext(), newArchiveModel, DuplicateArchiveModel.class);\n duplicateArchive.setCanonicalArchive(canonicalArchiveModel);\n\n // create dupes for child archives\n unzipToTempDirectory(event, context, tempFolder, newZipFile, duplicateArchive, true);\n } else\n {\n unzipToTempDirectory(event, context, tempFolder, newZipFile, newArchiveModel, false);\n }\n } else if (subFile.isDirectory())\n {\n recurseAndAddFiles(event, context, tempFolder, fileService, archiveModel, subFileModel, false);\n }\n }\n }", "public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) {\n if (imageHolder != null && imageView != null) {\n Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint);\n if (drawable != null) {\n imageView.setImageDrawable(drawable);\n imageView.setVisibility(View.VISIBLE);\n } else if (imageHolder.getBitmap() != null) {\n imageView.setImageBitmap(imageHolder.getBitmap());\n imageView.setVisibility(View.VISIBLE);\n } else {\n imageView.setVisibility(View.GONE);\n }\n } else if (imageView != null) {\n imageView.setVisibility(View.GONE);\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}", "protected void init(String configString, I_CmsSearchConfiguration baseConfig) throws JSONException {\n\n m_configObject = new JSONObject(configString);\n m_baseConfig = baseConfig;\n }", "public Set<String> getAttributeNames() {\n if (attributes == null) {\n return Collections.emptySet();\n } else {\n return Collections.unmodifiableSet(attributes.keySet());\n }\n }", "private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\n }", "private void adjustOptionsColumn(\n CmsMessageBundleEditorTypes.EditMode oldMode,\n CmsMessageBundleEditorTypes.EditMode newMode) {\n\n if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {\n m_table.removeGeneratedColumn(TableProperty.OPTIONS);\n if (m_model.isShowOptionsColumn(newMode)) {\n // Don't know why exactly setting the filter field invisible is necessary here,\n // it should be already set invisible - but apparently not setting it invisible again\n // will result in the field being visible.\n m_table.setFilterFieldVisible(TableProperty.OPTIONS, false);\n m_table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);\n }\n }\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 }" ]
Use this API to delete clusterinstance resources.
[ "public static base_responses delete(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance deleteresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new clusterinstance();\n\t\t\t\tdeleteresources[i].clid = resources[i].clid;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "@Override public View getView(int position, View convertView, ViewGroup parent) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withConvertView(convertView);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n return renderer.getRootView();\n }", "public IdRange[] parseIdRange(ImapRequestLineReader request)\n throws ProtocolException {\n CharacterValidator validator = new MessageSetCharValidator();\n String nextWord = consumeWord(request, validator);\n\n int commaPos = nextWord.indexOf(',');\n if (commaPos == -1) {\n return new IdRange[]{IdRange.parseRange(nextWord)};\n }\n\n List<IdRange> rangeList = new ArrayList<>();\n int pos = 0;\n while (commaPos != -1) {\n String range = nextWord.substring(pos, commaPos);\n IdRange set = IdRange.parseRange(range);\n rangeList.add(set);\n\n pos = commaPos + 1;\n commaPos = nextWord.indexOf(',', pos);\n }\n String range = nextWord.substring(pos);\n rangeList.add(IdRange.parseRange(range));\n return rangeList.toArray(new IdRange[rangeList.size()]);\n }", "final public void addOffset(Integer start, Integer end) {\n if (tokenOffset == null) {\n setOffset(start, end);\n } else if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\"Start offset after end offset\");\n } else {\n tokenOffset.add(start, end);\n }\n }", "public static dnssuffix get(nitro_service service, String Dnssuffix) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tobj.set_Dnssuffix(Dnssuffix);\n\t\tdnssuffix response = (dnssuffix) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "public static <T> Set<T> asSet(T[] o) {\r\n return new HashSet<T>(Arrays.asList(o));\r\n }", "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }", "public void applyPattern(String primaryPattern, String[] alternativePatterns, char decimalSeparator, char groupingSeparator)\n {\n m_symbols.setDecimalSeparator(decimalSeparator);\n m_symbols.setGroupingSeparator(groupingSeparator);\n\n setDecimalFormatSymbols(m_symbols);\n applyPattern(primaryPattern);\n\n if (alternativePatterns != null && alternativePatterns.length != 0)\n {\n int loop;\n if (m_alternativeFormats == null || m_alternativeFormats.length != alternativePatterns.length)\n {\n m_alternativeFormats = new DecimalFormat[alternativePatterns.length];\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop] = new DecimalFormat();\n }\n }\n\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop].setDecimalFormatSymbols(m_symbols);\n m_alternativeFormats[loop].applyPattern(alternativePatterns[loop]);\n }\n }\n }", "private void appendSubQuery(Query subQuery, StringBuffer buf)\r\n {\r\n buf.append(\" (\");\r\n buf.append(getSubQuerySQL(subQuery));\r\n buf.append(\") \");\r\n }" ]
Creates a new GridLines instance. @param data data block @param offset offset into data block @return new GridLines instance
[ "private GridLines getGridLines(byte[] data, int offset)\n {\n Color normalLineColor = ColorType.getInstance(data[offset]).getColor();\n LineStyle normalLineStyle = LineStyle.getInstance(data[offset + 3]);\n int intervalNumber = data[offset + 4];\n LineStyle intervalLineStyle = LineStyle.getInstance(data[offset + 5]);\n Color intervalLineColor = ColorType.getInstance(data[offset + 6]).getColor();\n return new GridLines(normalLineColor, normalLineStyle, intervalNumber, intervalLineStyle, intervalLineColor);\n }" ]
[ "public void createNewFile() throws SmbException {\n if( getUncPath0().length() == 1 ) {\n throw new SmbException( \"Invalid operation for workgroups, servers, or shares\" );\n }\n close( open0( O_RDWR | O_CREAT | O_EXCL, 0, ATTR_NORMAL, 0 ), 0L );\n }", "public static final String printExtendedAttributeDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }", "public static Dimension getDimension(File videoFile) throws IOException {\n try (FileInputStream fis = new FileInputStream(videoFile)) {\n return getDimension(fis, new AtomicReference<ByteBuffer>());\n }\n }", "private static boolean implementsMethod(ClassNode classNode, String methodName, Class[] argTypes) {\r\n List methods = classNode.getMethods();\r\n if (argTypes == null || argTypes.length ==0) {\r\n for (Iterator i = methods.iterator(); i.hasNext();) {\r\n MethodNode mn = (MethodNode) i.next();\r\n boolean methodMatch = mn.getName().equals(methodName);\r\n if(methodMatch)return true;\r\n // TODO Implement further parameter analysis\r\n }\r\n }\r\n return false;\r\n }", "private String toPath(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, \"\" + name.hashCode()) + size.getSuffix();\n }", "public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }", "private static boolean hasSelfPermissions(Context context, String... permissions) {\n for (String permission : permissions) {\n if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {\n return true;\n }\n }\n return false;\n }", "private void readTasks(Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n readLeafTasks(task, row.getInteger(\"FIRST_CHILD_TASK_ID\"));\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readTasks(childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }", "public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }" ]
Remove a tag from a photo. This method requires authentication with 'write' permission. @param tagId The tag ID @throws FlickrException
[ "public void removeTag(String tagId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REMOVE_TAG);\r\n\r\n parameters.put(\"tag_id\", tagId);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
[ "public static InetAddress getLocalHost() throws UnknownHostException {\n InetAddress addr;\n try {\n addr = InetAddress.getLocalHost();\n } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404\n addr = InetAddress.getByName(null);\n }\n return addr;\n }", "public static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) {\n // TODO ensure primary is visible\n\n IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class);\n RollbackCheckIterator.setLocktime(is, startTs);\n\n Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol);\n\n TxInfo txInfo = new TxInfo();\n\n if (entry == null) {\n txInfo.status = TxStatus.UNKNOWN;\n return txInfo;\n }\n\n ColumnType colType = ColumnType.from(entry.getKey());\n long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;\n\n switch (colType) {\n case LOCK: {\n if (ts == startTs) {\n txInfo.status = TxStatus.LOCKED;\n txInfo.lockValue = entry.getValue().get();\n } else {\n txInfo.status = TxStatus.UNKNOWN; // locked by another tx\n }\n break;\n }\n case DEL_LOCK: {\n DelLockValue dlv = new DelLockValue(entry.getValue().get());\n\n if (ts != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(prow + \" \" + pcol + \" (\" + ts + \" != \" + startTs + \") \");\n }\n\n if (dlv.isRollback()) {\n txInfo.status = TxStatus.ROLLED_BACK;\n } else {\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = dlv.getCommitTimestamp();\n }\n break;\n }\n case WRITE: {\n long timePtr = WriteValue.getTimestamp(entry.getValue().get());\n\n if (timePtr != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(\n prow + \" \" + pcol + \" (\" + timePtr + \" != \" + startTs + \") \");\n }\n\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = ts;\n break;\n }\n default:\n throw new IllegalStateException(\"unexpected col type returned \" + colType);\n }\n\n return txInfo;\n }", "public static int removeDuplicateNodeList(List<String> list) {\n\n int originCount = list.size();\n // add elements to all, including duplicates\n HashSet<String> hs = new LinkedHashSet<String>();\n hs.addAll(list);\n list.clear();\n list.addAll(hs);\n\n return originCount - list.size();\n }", "public static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void generateOutlineNumber(Task parent)\n {\n String outline;\n\n if (parent == null)\n {\n if (NumberHelper.getInt(getUniqueID()) == 0)\n {\n outline = \"0\";\n }\n else\n {\n outline = Integer.toString(getParentFile().getChildTasks().size() + 1);\n }\n }\n else\n {\n outline = parent.getOutlineNumber();\n\n int index = outline.lastIndexOf(\".0\");\n\n if (index != -1)\n {\n outline = outline.substring(0, index);\n }\n\n int childTaskCount = parent.getChildTasks().size() + 1;\n if (outline.equals(\"0\"))\n {\n outline = Integer.toString(childTaskCount);\n }\n else\n {\n outline += (\".\" + childTaskCount);\n }\n }\n\n setOutlineNumber(outline);\n }", "public void setOjbQuery(org.apache.ojb.broker.query.Query ojbQuery)\r\n {\r\n this.ojbQuery = ojbQuery;\r\n }", "public static URI setPath(final URI initialUri, final String path) {\n String finalPath = path;\n if (!finalPath.startsWith(\"/\")) {\n finalPath = '/' + path;\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,\n initialUri.getQuery(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n finalPath, initialUri.getQuery(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public static Cluster createUpdatedCluster(Cluster currentCluster,\n int stealerNodeId,\n List<Integer> donatedPartitions) {\n Cluster updatedCluster = Cluster.cloneCluster(currentCluster);\n // Go over every donated partition one by one\n for(int donatedPartition: donatedPartitions) {\n\n // Gets the donor Node that owns this donated partition\n Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition);\n Node stealerNode = updatedCluster.getNodeById(stealerNodeId);\n\n if(donorNode == stealerNode) {\n // Moving to the same location = No-op\n continue;\n }\n\n // Update the list of partitions for this node\n donorNode = removePartitionFromNode(donorNode, donatedPartition);\n stealerNode = addPartitionToNode(stealerNode, donatedPartition);\n\n // Sort the nodes\n updatedCluster = updateCluster(updatedCluster,\n Lists.newArrayList(donorNode, stealerNode));\n\n }\n\n return updatedCluster;\n }", "public 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 }" ]
Support the range subscript operator for String with IntRange @param text a String @param range an IntRange @return the resulting String @since 1.0
[ "public static String getAt(String text, IntRange range) {\n return getAt(text, (Range) range);\n }" ]
[ "private int getReplicaTypeForPartition(int partitionId) {\n List<Integer> routingPartitionList = routingStrategy.getReplicatingPartitionList(partitionId);\n\n // Determine if we should host this partition, and if so, whether we are a primary,\n // secondary or n-ary replica for it\n int correctReplicaType = -1;\n for (int replica = 0; replica < routingPartitionList.size(); replica++) {\n if(nodePartitionIds.contains(routingPartitionList.get(replica))) {\n // This means the partitionId currently being iterated on should be hosted\n // by this node. Let's remember its replica type in order to make sure the\n // files we have are properly named.\n correctReplicaType = replica;\n break;\n }\n }\n\n return correctReplicaType;\n }", "public static dos_stats get(nitro_service service, options option) throws Exception{\n\t\tdos_stats obj = new dos_stats();\n\t\tdos_stats[] response = (dos_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}", "public void prepare(Properties p, Connection cnx)\n {\n this.tablePrefix = p.getProperty(\"com.enioka.jqm.jdbc.tablePrefix\", \"\");\n queries.putAll(DbImplBase.queries);\n for (Map.Entry<String, String> entry : DbImplBase.queries.entrySet())\n {\n queries.put(entry.getKey(), this.adaptSql(entry.getValue()));\n }\n }", "private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\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 }", "@Override\n public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "private RawGcsCreationToken put(final GcsRestCreationToken token, ByteBuffer chunk,\n final boolean isFinalChunk, long timeoutMillis) throws IOException {\n final int length = chunk.remaining();\n HTTPRequest req = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);\n HTTPRequestInfo info = new HTTPRequestInfo(req);\n HTTPResponse response;\n try {\n response = urlfetch.fetch(req);\n } catch (IOException e) {\n throw createIOException(info, e);\n }\n return handlePutResponse(token, isFinalChunk, length, info, response);\n }", "public PayloadBuilder category(final String category) {\n if (category != null) {\n aps.put(\"category\", category);\n } else {\n aps.remove(\"category\");\n }\n return this;\n }", "@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 }" ]
Record the connection establishment time @param dest Destination of the socket to connect to. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param connEstTimeUs The number of us to wait before establishing a connection
[ "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 }" ]
[ "public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "private String formatAccrueType(AccrueType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.ACCRUE_TYPES)[type.getValue() - 1]);\n }", "ValidationResult cleanMultiValuePropertyKey(String name) {\n ValidationResult vr = cleanObjectKey(name);\n\n name = (String) vr.getObject();\n\n // make sure its not a known property key (reserved in the case of multi-value)\n\n try {\n RestrictedMultiValueFields rf = RestrictedMultiValueFields.valueOf(name);\n //noinspection ConstantConditions\n if (rf != null) {\n vr.setErrorDesc(name + \"... is a restricted key for multi-value properties. Operation aborted.\");\n vr.setErrorCode(523);\n vr.setObject(null);\n }\n } catch (Throwable t) {\n //no-op\n }\n\n return vr;\n }", "private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}", "public static base_response add(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 addresource = new nspbr6();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\taddresource.action = resource.action;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.nexthop = resource.nexthop;\n\t\taddresource.nexthopval = resource.nexthopval;\n\t\taddresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn addresource.add_resource(client);\n\t}", "public CustomHeadersInterceptor addHeader(String name, String value) {\n if (!this.headers.containsKey(name)) {\n this.headers.put(name, new ArrayList<String>());\n }\n this.headers.get(name).add(value);\n return this;\n }", "protected final void setDefaultValue() {\n\n m_start = null;\n m_end = null;\n m_patterntype = PatternType.NONE;\n m_dayOfMonth = 0;\n m_exceptions.clear();\n m_individualDates.clear();\n m_interval = 0;\n m_isEveryWorkingDay = false;\n m_isWholeDay = false;\n m_month = Month.JANUARY;\n m_seriesEndDate = null;\n m_seriesOccurrences = 0;\n m_weekDays.clear();\n m_weeksOfMonth.clear();\n m_endType = EndType.SINGLE;\n m_parentSeriesId = null;\n }", "public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\n }", "public static void recursiveAddZip(File parent, ZipOutputStream zout, File fileSource)\n throws IOException {\n\n File[] files = fileSource.listFiles();\n\n for (int i = 0; i < files.length; i++) {\n if (files[i].isDirectory()) {\n recursiveAddZip(parent, zout, files[i]);\n continue;\n }\n\n byte[] buffer = new byte[1024];\n\n FileInputStream fin = new FileInputStream(files[i]);\n\n ZipEntry zipEntry =\n new ZipEntry(files[i].getAbsolutePath()\n .replace(parent.getAbsolutePath(), \"\").substring(1)); //$NON-NLS-1$\n zout.putNextEntry(zipEntry);\n\n int length;\n while ((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n\n fin.close();\n\n }\n\n }" ]
Emit status line for an aggregated event.
[ "private void emitStatusLine(AggregatedResultEvent result, TestStatus status, long timeMillis) throws IOException {\n final StringBuilder line = new StringBuilder();\n\n line.append(shortTimestamp(result.getStartTimestamp()));\n line.append(Strings.padEnd(statusNames.get(status), 8, ' '));\n line.append(formatDurationInSeconds(timeMillis));\n if (forkedJvmCount > 1) {\n line.append(String.format(Locale.ROOT, jvmIdFormat, result.getSlave().id));\n }\n line.append(\" | \");\n\n line.append(formatDescription(result.getDescription()));\n if (!result.isSuccessful()) {\n line.append(FAILURE_MARKER);\n }\n line.append(\"\\n\");\n\n if (showThrowable) {\n // GH-82 (cause for ignored tests). \n if (status == TestStatus.IGNORED && result instanceof AggregatedTestResultEvent) {\n final StringWriter sw = new StringWriter();\n PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH);\n pos.write(\"Cause: \");\n pos.write(((AggregatedTestResultEvent) result).getCauseForIgnored());\n pos.completeLine();\n line.append(sw.toString());\n }\n\n final List<FailureMirror> failures = result.getFailures();\n if (!failures.isEmpty()) {\n final StringWriter sw = new StringWriter();\n PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH);\n int count = 0;\n for (FailureMirror fm : failures) {\n count++;\n if (fm.isAssumptionViolation()) {\n pos.write(String.format(Locale.ROOT, \n \"Assumption #%d: %s\",\n count, MoreObjects.firstNonNull(fm.getMessage(), \"(no message)\")));\n } else {\n pos.write(String.format(Locale.ROOT, \n \"Throwable #%d: %s\",\n count,\n showStackTraces ? filterStackTrace(fm.getTrace()) : fm.getThrowableString()));\n }\n }\n pos.completeLine();\n if (sw.getBuffer().length() > 0) {\n line.append(sw.toString());\n }\n }\n }\n\n logShort(line);\n }" ]
[ "public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\n }", "public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }", "public static Map<String, StoreDefinition> getSystemStoreDefMap() {\n Map<String, StoreDefinition> sysStoreDefMap = Maps.newHashMap();\n List<StoreDefinition> storesDefs = SystemStoreConstants.getAllSystemStoreDefs();\n for(StoreDefinition def: storesDefs) {\n sysStoreDefMap.put(def.getName(), def);\n }\n return sysStoreDefMap;\n }", "protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {\n try {\n // Add special methods for interceptors\n for (Method method : LifecycleMixin.class.getMethods()) {\n BeanLogger.LOG.addingMethodToProxy(method);\n MethodInformation methodInfo = new RuntimeMethodInformation(method);\n createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor);\n }\n Method getInstanceMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetInstance\");\n Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetClass\");\n generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod));\n generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod));\n\n Method setMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_setHandler\", MethodHandler.class);\n generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));\n\n Method getMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_getHandler\");\n generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }", "public static base_response update(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable updateresource = new bridgetable();\n\t\tupdateresource.bridgeage = resource.bridgeage;\n\t\treturn updateresource.update_resource(client);\n\t}", "private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) {\n\t\treturn IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString())\n\t\t\t\t.shouldDeleteMessages(this.properties.isDelete())\n\t\t\t\t.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead()));\n\t}", "private void clearDeckDetail(TrackMetadataUpdate update) {\n if (detailHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformDetailUpdate(update.player, null);\n }\n }", "public FieldType getField()\n {\n FieldType result = null;\n if (m_index < m_fields.length)\n {\n result = m_fields[m_index++];\n }\n\n return result;\n }", "private ModelNode createCPUNode() throws OperationFailedException {\n ModelNode cpu = new ModelNode().setEmptyObject();\n cpu.get(ARCH).set(getProperty(\"os.arch\"));\n cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());\n return cpu;\n }" ]
Retrieve a UUID in the form required by Primavera PMXML. @param guid UUID instance @return formatted UUID
[ "public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }" ]
[ "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }", "public void publish() {\n\n CmsDirectPublishDialogAction action = new CmsDirectPublishDialogAction();\n List<CmsResource> resources = getBundleResources();\n I_CmsDialogContext context = new A_CmsDialogContext(\"\", ContextType.appToolbar, resources) {\n\n public void focus(CmsUUID structureId) {\n\n //Nothing to do.\n }\n\n public List<CmsUUID> getAllStructureIdsInView() {\n\n return null;\n }\n\n public void updateUserInfo() {\n\n //Nothing to do.\n }\n };\n action.executeAction(context);\n updateLockInformation();\n\n }", "protected boolean showMoreEntries(Calendar nextDate, int previousOccurrences) {\n\n switch (getSerialEndType()) {\n case DATE:\n boolean moreByDate = nextDate.getTimeInMillis() < m_endMillis;\n boolean moreByOccurrences = previousOccurrences < CmsSerialDateUtil.getMaxEvents();\n if (moreByDate && !moreByOccurrences) {\n m_hasTooManyOccurrences = Boolean.TRUE;\n }\n return moreByDate && moreByOccurrences;\n case TIMES:\n case SINGLE:\n return previousOccurrences < getOccurrences();\n default:\n throw new IllegalArgumentException();\n }\n }", "public <T> T find(Class<T> classType, String id) {\n return db.find(classType, id);\n }", "@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "private static void listProjectProperties(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n ProjectProperties properties = file.getProjectProperties();\n Date startDate = properties.getStartDate();\n Date finishDate = properties.getFinishDate();\n String formattedStartDate = startDate == null ? \"(none)\" : df.format(startDate);\n String formattedFinishDate = finishDate == null ? \"(none)\" : df.format(finishDate);\n\n System.out.println(\"MPP file type: \" + properties.getMppFileType());\n System.out.println(\"Project Properties: StartDate=\" + formattedStartDate + \" FinishDate=\" + formattedFinishDate);\n System.out.println();\n }", "public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}", "private void updateDates(Task parentTask)\n {\n if (parentTask.hasChildTasks())\n {\n Date plannedStartDate = null;\n Date plannedFinishDate = null;\n\n for (Task task : parentTask.getChildTasks())\n {\n updateDates(task);\n plannedStartDate = DateHelper.min(plannedStartDate, task.getStart());\n plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish());\n }\n\n parentTask.setStart(plannedStartDate);\n parentTask.setFinish(plannedFinishDate);\n }\n }", "public synchronized Object next() throws NoSuchElementException\r\n {\r\n try\r\n {\r\n if (!isHasCalledCheck())\r\n {\r\n hasNext();\r\n }\r\n setHasCalledCheck(false);\r\n if (getHasNext())\r\n {\r\n Object obj = getObjectFromResultSet();\r\n m_current_row++;\r\n\r\n // Invoke events on PersistenceBrokerAware instances and listeners\r\n // set target object\r\n if (!disableLifeCycleEvents)\r\n {\r\n getAfterLookupEvent().setTarget(obj);\r\n getBroker().fireBrokerEvent(getAfterLookupEvent());\r\n getAfterLookupEvent().setTarget(null);\r\n } \r\n return obj;\r\n }\r\n else\r\n {\r\n throw new NoSuchElementException(\"inner hasNext was false\");\r\n }\r\n }\r\n catch (ResourceClosedException ex)\r\n {\r\n autoReleaseDbResources();\r\n throw ex;\r\n }\r\n catch (NoSuchElementException ex)\r\n {\r\n autoReleaseDbResources();\r\n logger.error(\"Error while iterate ResultSet for query \" + m_queryObject, ex);\r\n throw new NoSuchElementException(\"Could not obtain next object: \" + ex.getMessage());\r\n }\r\n }" ]
Parse a duration value. @param value duration value @return Duration instance
[ "public static final Duration parseDuration(String value)\n {\n return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);\n }" ]
[ "public static float[] toFloat(int[] array) {\n float[] n = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (float) array[i];\n }\n return n;\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 }", "public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }", "private void populateRelationList(Task task, TaskField field, String data)\n {\n DeferredRelationship dr = new DeferredRelationship();\n dr.setTask(task);\n dr.setField(field);\n dr.setData(data);\n m_deferredRelationships.add(dr);\n }", "public static final Date parseExtendedAttributeDate(String value)\n {\n Date result = null;\n\n if (value != null)\n {\n try\n {\n result = DATE_FORMAT.get().parse(value);\n }\n\n catch (ParseException ex)\n {\n // ignore exceptions\n }\n }\n\n return (result);\n }", "public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }", "public ConfigOptionBuilder setCommandLineOptionWithArgument( CommandLineOption commandLineOption, StringConverter converter ) {\n co.setCommandLineOption( commandLineOption );\n return setStringConverter( converter );\n }", "public void removeLicenseFromArtifact(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n //\n // The artifact may not have the exact string associated with it, but rather one\n // matching license regexp expression.\n //\n repositoryHandler.removeLicenseFromArtifact(dbArtifact, licenseId, licenseMatcher);\n }", "public static crvserver_binding get(nitro_service service, String name) throws Exception{\n\t\tcrvserver_binding obj = new crvserver_binding();\n\t\tobj.set_name(name);\n\t\tcrvserver_binding response = (crvserver_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Constructs a full capability name from a static base name and a dynamic element. @param baseName the base name. Cannot be {@code null} @param dynamicNameElement the dynamic portion of the name. Cannot be {@code null} @return the full capability name. Will not return {@code null}
[ "public static String buildDynamicCapabilityName(String baseName, String ... dynamicNameElement) {\n assert baseName != null;\n assert dynamicNameElement != null;\n assert dynamicNameElement.length > 0;\n StringBuilder sb = new StringBuilder(baseName);\n for (String part:dynamicNameElement){\n sb.append(\".\").append(part);\n }\n return sb.toString();\n }" ]
[ "public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "public byte[] toBytes(T object) {\n try {\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n ObjectOutputStream out = new ObjectOutputStream(stream);\n out.writeObject(object);\n return stream.toByteArray();\n } catch(IOException e) {\n throw new SerializationException(e);\n }\n }", "protected void doSplitTokenImpl(Token token, ITokenAcceptor result) {\n\t\tString text = token.getText();\n\t\tint indentation = computeIndentation(text);\n\t\tif (indentation == -1 || indentation == currentIndentation) {\n\t\t\t// no change of indentation level detected simply process the token\n\t\t\tresult.accept(token);\n\t\t} else if (indentation > currentIndentation) {\n\t\t\t// indentation level increased\n\t\t\tsplitIntoBeginToken(token, indentation, result);\n\t\t} else if (indentation < currentIndentation) {\n\t\t\t// indentation level decreased\n\t\t\tint charCount = computeIndentationRelevantCharCount(text);\n\t\t\tif (charCount > 0) {\n\t\t\t\t// emit whitespace including newline\n\t\t\t\tsplitWithText(token, text.substring(0, charCount), result);\t\n\t\t\t}\n\t\t\t// emit end tokens at the beginning of the line\n\t\t\tdecreaseIndentation(indentation, result);\n\t\t\tif (charCount != text.length()) {\n\t\t\t\thandleRemainingText(token, text.substring(charCount), indentation, result);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new IllegalStateException(String.valueOf(indentation));\n\t\t}\n\t}", "public IGoal[] getAgentGoals(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n\n goals = bia.getGoalbase().getGoals();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return goals;\n }", "public void add(final IndexableTaskItem taskItem) {\n this.dependsOnTaskGroup.addPostRunDependentTaskGroup(taskItem.taskGroup());\n this.collection.add(taskItem);\n }", "public static void mark(DeploymentUnit unit) {\n unit = DeploymentUtils.getTopDeploymentUnit(unit);\n unit.putAttachment(MARKER, Boolean.TRUE);\n }", "public void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\n }", "public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\n }", "static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }" ]
Get a project according to its full name. @param fullName The full name of the project. @return The project which answers the full name.
[ "private static AbstractProject<?, ?> getProject(String fullName) {\n Item item = Hudson.getInstance().getItemByFullName(fullName);\n if (item != null && item instanceof AbstractProject) {\n return (AbstractProject<?, ?>) item;\n }\n return null;\n }" ]
[ "public void setUserInfo(String username, String infoName, String value) throws CmsException {\n\n CmsUser user = m_cms.readUser(username);\n user.setAdditionalInfo(infoName, value);\n m_cms.writeUser(user);\n }", "public Duration getWork(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getWorkTimeUnit());\n }", "void applyFreshParticleOffScreen(\n @NonNull final Scene scene,\n final int position) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n float x = random.nextInt(w);\n float y = random.nextInt(h);\n\n // The offset to make when creating point of out bounds\n final short offset = (short) (scene.getParticleRadiusMin() + scene.getLineLength());\n\n // Point angle range\n final float startAngle;\n float endAngle;\n\n // Make random offset and calulate angles so that the direction of travel will always be\n // towards our View\n switch (random.nextInt(4)) {\n case 0:\n // offset to left\n x = (short) -offset;\n startAngle = angleDeg(pcc, pcc, x, y);\n endAngle = angleDeg(pcc, h - pcc, x, y);\n break;\n\n case 1:\n // offset to top\n y = (short) -offset;\n startAngle = angleDeg(w - pcc, pcc, x, y);\n endAngle = angleDeg(pcc, pcc, x, y);\n break;\n\n case 2:\n // offset to right\n x = (short) (w + offset);\n startAngle = angleDeg(w - pcc, h - pcc, x, y);\n endAngle = angleDeg(w - pcc, pcc, x, y);\n break;\n\n case 3:\n // offset to bottom\n y = (short) (h + offset);\n startAngle = angleDeg(pcc, h - pcc, x, y);\n endAngle = angleDeg(w - pcc, h - pcc, x, y);\n break;\n\n default:\n throw new IllegalArgumentException(\"Supplied value out of range\");\n }\n\n if (endAngle < startAngle) {\n endAngle += 360;\n }\n\n // Get random angle from angle range\n final float randomAngleInRange = startAngle + (random\n .nextInt((int) Math.abs(endAngle - startAngle)));\n final double direction = Math.toRadians(randomAngleInRange);\n\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }", "public static int writeVint(byte[] dest, int offset, int i) {\n if (i >= -112 && i <= 127) {\n dest[offset++] = (byte) i;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n dest[offset++] = (byte) len;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n for (int idx = len; idx != 0; idx--) {\n int shiftbits = (idx - 1) * 8;\n long mask = 0xFFL << shiftbits;\n dest[offset++] = (byte) ((i & mask) >> shiftbits);\n }\n }\n\n return offset;\n }", "public static Credential getServiceAccountCredential(String serviceAccountId,\n String privateKeyFile, Collection<String> serviceAccountScopes)\n throws GeneralSecurityException, IOException {\n return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)\n .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))\n .build();\n }", "public static base_response update(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy updateresource = new responderpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.undefaction = resource.undefaction;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.logaction = resource.logaction;\n\t\tupdateresource.appflowaction = resource.appflowaction;\n\t\treturn updateresource.update_resource(client);\n\t}", "@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (null == authenticationServices) {\n\t\t\tauthenticationServices = new ArrayList<AuthenticationService>();\n\t\t}\n\t\tif (!excludeDefault) {\n\t\t\tauthenticationServices.add(staticAuthenticationService);\n\t\t}\n\t}", "protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}", "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 }" ]
Hide multiple channels. All other channels will be shown. @param channels The channels to hide
[ "public static void hideOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.showAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }" ]
[ "protected void checkConsecutiveAlpha() {\n\n Pattern symbolsPatter = Pattern.compile(REGEX_ALPHA_UC + \"+\");\n Matcher matcher = symbolsPatter.matcher(this.password);\n int met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n\n // alpha lower case\n\n symbolsPatter = Pattern.compile(REGEX_ALPHA_LC + \"+\");\n matcher = symbolsPatter.matcher(this.password);\n met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n }", "@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }", "public final void setColorPreferred(boolean preferColor) {\n if (this.preferColor.compareAndSet(!preferColor, preferColor) && isRunning()) {\n stop();\n try {\n start();\n } catch (Exception e) {\n logger.error(\"Unexplained exception restarting; we had been running already!\", e);\n }\n }\n }", "@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 }", "private void writePredecessors(Task task)\n {\n List<Relation> relations = task.getPredecessors();\n for (Relation mpxj : relations)\n {\n RelationshipType xml = m_factory.createRelationshipType();\n m_project.getRelationship().add(xml);\n\n xml.setLag(getDuration(mpxj.getLag()));\n xml.setObjectId(Integer.valueOf(++m_relationshipObjectID));\n xml.setPredecessorActivityObjectId(mpxj.getTargetTask().getUniqueID());\n xml.setSuccessorActivityObjectId(mpxj.getSourceTask().getUniqueID());\n xml.setPredecessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSuccessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setType(RELATION_TYPE_MAP.get(mpxj.getType()));\n }\n }", "private static CustomInfoType convertCustomInfo(Map<String, String> customInfo) {\n if (customInfo == null) {\n return null;\n }\n\n CustomInfoType ciType = new CustomInfoType();\n for (Entry<String, String> entry : customInfo.entrySet()) {\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(entry.getKey());\n cItem.setValue(entry.getValue());\n ciType.getItem().add(cItem);\n }\n\n return ciType;\n }", "public static base_responses link(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey linkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tlinkresources[i] = new sslcertkey();\n\t\t\t\tlinkresources[i].certkey = resources[i].certkey;\n\t\t\t\tlinkresources[i].linkcertkeyname = resources[i].linkcertkeyname;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, linkresources,\"link\");\n\t\t}\n\t\treturn result;\n\t}", "public void cross(Vector3d v1, Vector3d v2) {\n double tmpx = v1.y * v2.z - v1.z * v2.y;\n double tmpy = v1.z * v2.x - v1.x * v2.z;\n double tmpz = v1.x * v2.y - v1.y * v2.x;\n\n x = tmpx;\n y = tmpy;\n z = tmpz;\n }", "public void setActiveView(View v, int position) {\n final View oldView = mActiveView;\n mActiveView = v;\n mActivePosition = position;\n\n if (mAllowIndicatorAnimation && oldView != null) {\n startAnimatingIndicator();\n }\n\n invalidate();\n }" ]
Render the scalebar. @param mapContext The context of the map for which the scalebar is created. @param scalebarParams The scalebar parameters. @param tempFolder The directory in which the graphic file is created. @param template The template that containts the scalebar processor
[ "public final URI render(\n final MapfishMapContext mapContext,\n final ScalebarAttributeValues scalebarParams,\n final File tempFolder,\n final Template template)\n throws IOException, ParserConfigurationException {\n final double dpi = mapContext.getDPI();\n\n // get the map bounds\n final Rectangle paintArea = new Rectangle(mapContext.getMapSize());\n MapBounds bounds = mapContext.getBounds();\n\n final DistanceUnit mapUnit = getUnit(bounds);\n final Scale scale = bounds.getScale(paintArea, PDF_DPI);\n final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,\n bounds.getProjection(), dpi, bounds.getCenter());\n\n DistanceUnit scaleUnit = scalebarParams.getUnit();\n if (scaleUnit == null) {\n scaleUnit = mapUnit;\n }\n\n // adjust scalebar width and height to the DPI value\n final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?\n scalebarParams.getSize().width : scalebarParams.getSize().height;\n\n final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)\n * scaleDenominator / scalebarParams.intervals;\n final double niceIntervalLengthInWorldUnits =\n getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);\n\n final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();\n settings.setParams(scalebarParams);\n settings.setMaxSize(scalebarParams.getSize());\n settings.setPadding(getPadding(settings));\n\n // start the rendering\n File path = null;\n if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {\n // render scalebar as SVG\n final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());\n\n try {\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".svg\", tempFolder);\n CreateMapProcessor.saveSvgFile(graphics2D, path);\n } finally {\n graphics2D.dispose();\n }\n } else {\n // render scalebar as raster graphic\n double dpiRatio = mapContext.getDPI() / PDF_DPI;\n final BufferedImage bufferedImage = new BufferedImage(\n (int) Math.round(scalebarParams.getSize().width * dpiRatio),\n (int) Math.round(scalebarParams.getSize().height * dpiRatio),\n TYPE_4BYTE_ABGR);\n final Graphics2D graphics2D = bufferedImage.createGraphics();\n\n try {\n AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());\n graphics2D.scale(dpiRatio, dpiRatio);\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n graphics2D.setTransform(saveAF);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".png\", tempFolder);\n ImageUtils.writeImage(bufferedImage, \"png\", path);\n } finally {\n graphics2D.dispose();\n }\n }\n\n return path.toURI();\n }" ]
[ "private SortedSet<Date> calculateDates() {\n\n if (null == m_allDates) {\n SortedSet<Date> result = new TreeSet<>();\n if (isAnyDatePossible()) {\n Calendar date = getFirstDate();\n int previousOccurrences = 0;\n while (showMoreEntries(date, previousOccurrences)) {\n result.add(date.getTime());\n toNextDate(date);\n previousOccurrences++;\n }\n }\n m_allDates = result;\n }\n return m_allDates;\n }", "private void addDependent(String pathName, String relativeTo) {\n if (relativeTo != null) {\n Set<String> dependents = dependenctRelativePaths.get(relativeTo);\n if (dependents == null) {\n dependents = new HashSet<String>();\n dependenctRelativePaths.put(relativeTo, dependents);\n }\n dependents.add(pathName);\n }\n }", "public void setBackgroundColor(int color) {\n colorUnpressed = color;\n\n if(!isSelected()) {\n if (rippleAnimationSupport()) {\n ripple.setRippleBackground(colorUnpressed);\n }\n else {\n view.setBackgroundColor(colorUnpressed);\n }\n }\n }", "private void createFieldMap(byte[] data)\n {\n int index = 0;\n int lastDataBlockOffset = 0;\n int dataBlockIndex = 0;\n\n while (index < data.length)\n {\n long mask = MPPUtility.getInt(data, index + 0);\n //mask = mask << 4;\n\n int dataBlockOffset = MPPUtility.getShort(data, index + 4);\n //int metaFlags = MPPUtility.getByte(data, index + 8);\n FieldType type = getFieldType(MPPUtility.getInt(data, index + 12));\n int category = MPPUtility.getShort(data, index + 20);\n //int sizeInBytes = MPPUtility.getShort(data, index + 22);\n //int metaIndex = MPPUtility.getInt(data, index + 24);\n\n //\n // Categories\n //\n // 02 - Short values [RATE_UNITS, WORKGROUP, ACCRUE, TIME_UNITS, PRIORITY, TASK_TYPE, CONSTRAINT, ACCRUE, PERCENTAGE, SHORT, WORK_UNITS] - BOOKING_TYPE, EARNED_VALUE_METHOD, DELIVERABLE_TYPE, RESOURCE_REQUEST_TYPE - we have as string in MPXJ????\n // 03 - Int values [DURATION, INTEGER] - Recalc outline codes as Boolean?\n // 05 - Rate, Number [RATE, NUMERIC]\n // 08 - String (and some durations!!!) [STRING, DURATION]\n // 0B - Boolean (meta block 0?) - [BOOLEAN]\n // 13 - Date - [DATE]\n // 48 - GUID - [GUID]\n // 64 - Boolean (meta block 1?)- [BOOLEAN]\n // 65 - Work, Currency [WORK, CURRENCY]\n // 66 - Units [UNITS]\n // 1D - Raw bytes [BINARY, ASCII_STRING] - Exception: outline code indexes, they are integers, but stored as part of a binary block\n\n int varDataKey;\n if (useTypeAsVarDataKey())\n {\n Integer substitute = substituteVarDataKey(type);\n if (substitute == null)\n {\n varDataKey = (MPPUtility.getInt(data, index + 12) & 0x0000FFFF);\n }\n else\n {\n varDataKey = substitute.intValue();\n }\n }\n else\n {\n varDataKey = MPPUtility.getByte(data, index + 6);\n }\n\n FieldLocation location;\n int metaBlock;\n\n switch (category)\n {\n case 0x0B:\n {\n location = FieldLocation.META_DATA;\n metaBlock = 0;\n break;\n }\n\n case 0x64:\n {\n location = FieldLocation.META_DATA;\n metaBlock = 1;\n break;\n }\n\n default:\n {\n metaBlock = 0;\n if (dataBlockOffset != 65535)\n {\n location = FieldLocation.FIXED_DATA;\n if (dataBlockOffset < lastDataBlockOffset)\n {\n ++dataBlockIndex;\n }\n lastDataBlockOffset = dataBlockOffset;\n int typeSize = getFixedDataFieldSize(type);\n\n if (dataBlockOffset + typeSize > m_maxFixedDataSize[dataBlockIndex])\n {\n m_maxFixedDataSize[dataBlockIndex] = dataBlockOffset + typeSize;\n }\n }\n else\n {\n if (varDataKey != 0)\n {\n location = FieldLocation.VAR_DATA;\n }\n else\n {\n location = FieldLocation.UNKNOWN;\n }\n }\n break;\n }\n }\n\n FieldItem item = new FieldItem(type, location, dataBlockIndex, dataBlockOffset, varDataKey, mask, metaBlock);\n if (m_debug)\n {\n System.out.println(ByteArrayHelper.hexdump(data, index, 28, false) + \" \" + item + \" mpxjDataType=\" + item.getType().getDataType() + \" index=\" + index);\n }\n m_map.put(type, item);\n\n index += 28;\n }\n }", "public static MBeanParameterInfo[] extractParameterInfo(Method m) {\n Class<?>[] types = m.getParameterTypes();\n Annotation[][] annotations = m.getParameterAnnotations();\n MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];\n for(int i = 0; i < params.length; i++) {\n boolean hasAnnotation = false;\n for(int j = 0; j < annotations[i].length; j++) {\n if(annotations[i][j] instanceof JmxParam) {\n JmxParam param = (JmxParam) annotations[i][j];\n params[i] = new MBeanParameterInfo(param.name(),\n types[i].getName(),\n param.description());\n hasAnnotation = true;\n break;\n }\n }\n if(!hasAnnotation) {\n params[i] = new MBeanParameterInfo(\"\", types[i].getName(), \"\");\n }\n }\n\n return params;\n }", "public static base_responses delete(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 deleteresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new appfwlearningdata();\n\t\t\t\tdeleteresources[i].profilename = resources[i].profilename;\n\t\t\t\tdeleteresources[i].starturl = resources[i].starturl;\n\t\t\t\tdeleteresources[i].cookieconsistency = resources[i].cookieconsistency;\n\t\t\t\tdeleteresources[i].fieldconsistency = resources[i].fieldconsistency;\n\t\t\t\tdeleteresources[i].formactionurl_ffc = resources[i].formactionurl_ffc;\n\t\t\t\tdeleteresources[i].crosssitescripting = resources[i].crosssitescripting;\n\t\t\t\tdeleteresources[i].formactionurl_xss = resources[i].formactionurl_xss;\n\t\t\t\tdeleteresources[i].sqlinjection = resources[i].sqlinjection;\n\t\t\t\tdeleteresources[i].formactionurl_sql = resources[i].formactionurl_sql;\n\t\t\t\tdeleteresources[i].fieldformat = resources[i].fieldformat;\n\t\t\t\tdeleteresources[i].formactionurl_ff = resources[i].formactionurl_ff;\n\t\t\t\tdeleteresources[i].csrftag = resources[i].csrftag;\n\t\t\t\tdeleteresources[i].csrfformoriginurl = resources[i].csrfformoriginurl;\n\t\t\t\tdeleteresources[i].xmldoscheck = resources[i].xmldoscheck;\n\t\t\t\tdeleteresources[i].xmlwsicheck = resources[i].xmlwsicheck;\n\t\t\t\tdeleteresources[i].xmlattachmentcheck = resources[i].xmlattachmentcheck;\n\t\t\t\tdeleteresources[i].totalxmlrequests = resources[i].totalxmlrequests;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public final void notifyFooterItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount + contentItemCount, itemCount);\n }", "private void handleContentLength(Event event) {\n if (event.getContent() == null) {\n return;\n }\n\n if (maxContentLength == -1 || event.getContent().length() <= maxContentLength) {\n return;\n }\n\n if (maxContentLength < CUT_START_TAG.length() + CUT_END_TAG.length()) {\n event.setContent(\"\");\n event.setContentCut(true);\n return;\n }\n\n int contentLength = maxContentLength - CUT_START_TAG.length() - CUT_END_TAG.length();\n event.setContent(CUT_START_TAG + event.getContent().substring(0, contentLength) + CUT_END_TAG);\n event.setContentCut(true);\n }", "private void insert(int position, int c) {\r\n for (int i = 143; i > position; i--) {\r\n set[i] = set[i - 1];\r\n character[i] = character[i - 1];\r\n }\r\n character[position] = c;\r\n }" ]
Use this API to fetch all the csparameter resources that are configured on netscaler.
[ "public static csparameter get(nitro_service service) throws Exception{\n\t\tcsparameter obj = new csparameter();\n\t\tcsparameter[] response = (csparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "public String getSearchJsonModel() throws IOException {\n DbSearch search = new DbSearch();\n search.setArtifacts(new ArrayList<>());\n search.setModules(new ArrayList<>());\n return JsonUtils.serialize(search);\n }", "public Task<Void> registerWithEmail(@NonNull final String email, @NonNull final String password) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n registerWithEmailInternal(email, password);\n return null;\n }\n });\n }", "public int getMinutesPerYear()\n {\n return m_minutesPerYear == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerYear()) : m_minutesPerYear.intValue();\n }", "public boolean getHidden() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_HIDDEN);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return personElement.getAttribute(\"hidden\").equals(\"1\") ? true : false;\r\n }", "public static void registerOgmExternalizers(SerializationConfigurationBuilder cfg) {\n\t\tfor ( AdvancedExternalizer<?> advancedExternalizer : ogmExternalizers.values() ) {\n\t\t\tcfg.addAdvancedExternalizer( advancedExternalizer );\n\t\t}\n\t}", "public static <T extends Comparable<? super T>> List<T> sort(Iterable<T> iterable) {\n\t\tList<T> asList = Lists.newArrayList(iterable);\n\t\tif (iterable instanceof SortedSet<?>) {\n\t\t\tif (((SortedSet<T>) iterable).comparator() == null) {\n\t\t\t\treturn asList;\n\t\t\t}\n\t\t}\n\t\treturn ListExtensions.sortInplace(asList);\n\t}", "public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public static <A extends Annotation> EnhancedAnnotation<A> create(SlimAnnotatedType<A> annotatedType, ClassTransformer classTransformer) {\n\n Class<A> annotationType = annotatedType.getJavaClass();\n\n Map<Class<? extends Annotation>, Annotation> annotationMap = new HashMap<Class<? extends Annotation>, Annotation>();\n annotationMap.putAll(buildAnnotationMap(annotatedType.getAnnotations()));\n annotationMap.putAll(buildAnnotationMap(classTransformer.getTypeStore().get(annotationType)));\n // Annotations and declared annotations are the same for annotation type\n return new EnhancedAnnotationImpl<A>(annotatedType, annotationMap, annotationMap, classTransformer);\n }", "private void processCalendars() throws SQLException\n {\n List<Row> rows = getTable(\"EXCEPTIONN\");\n Map<Integer, DayType> exceptionMap = m_reader.createExceptionTypeMap(rows);\n\n rows = getTable(\"WORK_PATTERN\");\n Map<Integer, Row> workPatternMap = m_reader.createWorkPatternMap(rows);\n\n rows = new LinkedList<Row>();// getTable(\"WORK_PATTERN_ASSIGNMENT\"); // Need to generate an example\n Map<Integer, List<Row>> workPatternAssignmentMap = m_reader.createWorkPatternAssignmentMap(rows);\n\n rows = getTable(\"EXCEPTION_ASSIGNMENT\");\n Map<Integer, List<Row>> exceptionAssignmentMap = m_reader.createExceptionAssignmentMap(rows);\n\n rows = getTable(\"TIME_ENTRY\");\n Map<Integer, List<Row>> timeEntryMap = m_reader.createTimeEntryMap(rows);\n\n rows = getTable(\"CALENDAR\");\n Collections.sort(rows, CALENDAR_COMPARATOR);\n for (Row row : rows)\n {\n m_reader.processCalendar(row, workPatternMap, workPatternAssignmentMap, exceptionAssignmentMap, timeEntryMap, exceptionMap);\n }\n\n //\n // Update unique counters at this point as we will be generating\n // resource calendars, and will need to auto generate IDs\n //\n m_reader.getProject().getProjectConfig().updateUniqueCounters();\n }" ]
Use this API to fetch all the appfwsignatures resources that are configured on netscaler.
[ "public static appfwsignatures get(nitro_service service) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tappfwsignatures[] response = (appfwsignatures[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "public final void notifyContentItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount, itemCount);\n }", "private static Point findMidnormalPoint(Point center, Point a, Point b, Rect area, int radius) {\n if (a.y == b.y) {\n //top\n if (a.y < center.y) {\n return new Point((a.x + b.x) / 2, center.y + radius);\n }\n //bottom\n return new Point((a.x + b.x) / 2, center.y - radius);\n }\n if (a.x == b.x) {\n //left\n if (a.x < center.x) {\n return new Point(center.x + radius, (a.y + b.y) / 2);\n }\n //right\n return new Point(center.x - radius, (a.y + b.y) / 2);\n }\n //slope of line ab\n double abSlope = (a.y - b.y) / (a.x - b.x * 1.0);\n //slope of midnormal\n double midnormalSlope = -1.0 / abSlope;\n\n double radian = Math.tan(midnormalSlope);\n int dy = (int) (radius * Math.sin(radian));\n int dx = (int) (radius * Math.cos(radian));\n Point point = new Point(center.x + dx, center.y + dy);\n if (!inArea(point, area, 0)) {\n point = new Point(center.x - dx, center.y - dy);\n }\n return point;\n }", "private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\n }", "public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}", "private void cullDisabledPaths() throws Exception {\n\n ArrayList<EndpointOverride> removePaths = new ArrayList<EndpointOverride>();\n RequestInformation requestInfo = requestInformation.get();\n for (EndpointOverride selectedPath : requestInfo.selectedResponsePaths) {\n\n // check repeat count on selectedPath\n // -1 is unlimited\n if (selectedPath != null && selectedPath.getRepeatNumber() == 0) {\n // skip\n removePaths.add(selectedPath);\n } else if (selectedPath != null && selectedPath.getRepeatNumber() != -1) {\n // need to decrement the #\n selectedPath.updateRepeatNumber(selectedPath.getRepeatNumber() - 1);\n }\n }\n\n // remove paths if we need to\n for (EndpointOverride removePath : removePaths) {\n requestInfo.selectedResponsePaths.remove(removePath);\n }\n }", "private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {\n String separator = launcher.isUnix() ? \"/\" : \"\\\\\";\n String java_home = extendedEnv.get(\"JAVA_HOME\");\n if (StringUtils.isNotEmpty(java_home)) {\n if (!StringUtils.endsWith(java_home, separator)) {\n java_home += separator;\n }\n extendedEnv.put(\"PATH+JDK\", java_home + \"bin\");\n }\n }", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }", "private void parse(String header)\n {\n ArrayList<String> list = new ArrayList<String>(4);\n StringBuilder sb = new StringBuilder();\n int index = 1;\n while (index < header.length())\n {\n char c = header.charAt(index++);\n if (Character.isDigit(c))\n {\n sb.append(c);\n }\n else\n {\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n sb.setLength(0);\n }\n }\n }\n\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n }\n\n m_id = list.get(0);\n m_sequence = Integer.parseInt(list.get(1));\n m_type = Integer.valueOf(list.get(2));\n if (list.size() > 3)\n {\n m_subtype = Integer.parseInt(list.get(3));\n }\n }", "public List<ProjectFile> readAll() throws MPXJException\n {\n Map<Integer, String> projects = listProjects();\n List<ProjectFile> result = new ArrayList<ProjectFile>(projects.keySet().size());\n for (Integer id : projects.keySet())\n {\n setProjectID(id.intValue());\n result.add(read());\n }\n return result;\n }" ]
Wrapper delayed emission, based on delayProvider. @param event the event to emit @param milliseconds the delay in milliseconds @param <T> the type of event @return delayed observable
[ "public static <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return delayProvider.delayedEmitAsync(event, milliseconds);\n }" ]
[ "public static String join(Iterable<?> iterable, String separator) {\n if (iterable != null) {\n StringBuilder buf = new StringBuilder();\n Iterator<?> it = iterable.iterator();\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n while (it.hasNext()) {\n buf.append(it.next());\n if (it.hasNext()) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }", "public void runOnInvariantViolationPlugins(Invariant invariant,\n\t\t\tCrawlerContext context) {\n\t\tLOGGER.debug(\"Running OnInvariantViolationPlugins...\");\n\t\tcounters.get(OnInvariantViolationPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {\n\t\t\tif (plugin instanceof OnInvariantViolationPlugin) {\n\t\t\t\ttry {\n\t\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\t\t((OnInvariantViolationPlugin) plugin).onInvariantViolation(\n\t\t\t\t\t\t\tinvariant, context);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "private void buildJoinTree(Criteria crit)\r\n {\r\n Enumeration e = crit.getElements();\r\n\r\n while (e.hasMoreElements())\r\n {\r\n Object o = e.nextElement();\r\n if (o instanceof Criteria)\r\n {\r\n buildJoinTree((Criteria) o);\r\n }\r\n else\r\n {\r\n SelectionCriteria c = (SelectionCriteria) o;\r\n \r\n // BRJ skip SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n continue;\r\n }\r\n \r\n // BRJ: Outer join for OR\r\n boolean useOuterJoin = (crit.getType() == Criteria.OR);\r\n\r\n // BRJ: do not build join tree for subQuery attribute \r\n if (c.getAttribute() != null && c.getAttribute() instanceof String)\r\n {\r\n\t\t\t\t\t//buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getAlias(), c.getPathClasses());\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n if (c instanceof FieldCriteria)\r\n {\r\n FieldCriteria cc = (FieldCriteria) c;\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) cc.getValue(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n }\r\n }\r\n }", "public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }", "private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_HEIGHT, \"\" + this.getHeight());\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_WIDTH, \"\" + this.getWidth());\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_POSX, \"\" + this.getBounds().x);\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_POSY, \"\" + this.getBounds().y);\r\n Main.getProperties().storeProperties(\"\");\r\n System.exit(0);\r\n }", "public static java.sql.Time toTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Time) {\n return (java.sql.Time) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime());\n }", "private void writeMapFile(String mapFileName, File jarFile, boolean mapClassMethods) throws IOException, XMLStreamException, ClassNotFoundException, IntrospectionException\n {\n FileWriter fw = new FileWriter(mapFileName);\n XMLOutputFactory xof = XMLOutputFactory.newInstance();\n XMLStreamWriter writer = xof.createXMLStreamWriter(fw);\n //XMLStreamWriter writer = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(fw));\n\n writer.writeStartDocument();\n writer.writeStartElement(\"root\");\n writer.writeStartElement(\"assembly\");\n\n addClasses(writer, jarFile, mapClassMethods);\n\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndDocument();\n writer.flush();\n writer.close();\n\n fw.flush();\n fw.close();\n }", "public static int getNavigationBarHeight(Context context) {\n Resources resources = context.getResources();\n int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? \"navigation_bar_height\" : \"navigation_bar_height_landscape\", \"dimen\", \"android\");\n if (id > 0) {\n return resources.getDimensionPixelSize(id);\n }\n return 0;\n }" ]
Write a Date attribute. @param name attribute name @param value attribute value
[ "public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }" ]
[ "public Set<ConstraintViolation> validate(DataSetInfo info) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\ttry {\r\n\t\t\tif (info.isMandatory() && get(info.getDataSetNumber()) == null) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));\r\n\t\t\t}\r\n\t\t\tif (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));\r\n\t\t\t}\r\n\t\t} catch (SerializationException e) {\r\n\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}", "protected static int calculateShift(int minimumValue, int maximumValue) {\n\t\tint shift = 0;\n\t\tint value = 1;\n\t\twhile (value < minimumValue && value < maximumValue) {\n\t\t\tvalue <<= 1;\n\t\t\tshift++;\n\t\t}\n\t\treturn shift;\n\t}", "public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) {\n if (imageHolder != null && imageView != null) {\n Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint);\n if (drawable != null) {\n imageView.setImageDrawable(drawable);\n imageView.setVisibility(View.VISIBLE);\n } else if (imageHolder.getBitmap() != null) {\n imageView.setImageBitmap(imageHolder.getBitmap());\n imageView.setVisibility(View.VISIBLE);\n } else {\n imageView.setVisibility(View.GONE);\n }\n } else if (imageView != null) {\n imageView.setVisibility(View.GONE);\n }\n }", "private <T> Observable<PollingState<T>> updateStateFromGetResourceOperationAsync(final PollingState<T> pollingState, String url) {\n return pollAsync(url, pollingState.loggingContext())\n .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(Response<ResponseBody> response) {\n try {\n pollingState.updateFromResponseOnPutPatch(response);\n return Observable.just(pollingState);\n } catch (CloudException | IOException e) {\n return Observable.error(e);\n }\n }\n });\n }", "protected void applyBanners() {\n DynamicReportOptions options = getReport().getOptions();\n if (options.getFirstPageImageBanners().isEmpty() && options.getImageBanners().isEmpty()){\n return;\n }\n\n\t\t/*\n\t\t First create image banners for the first page only\n\t\t */\n\t\tJRDesignBand title = (JRDesignBand) getDesign().getTitle();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (title == null && !options.getFirstPageImageBanners().isEmpty()){\n\t\t\ttitle = new JRDesignBand();\n\t\t\tgetDesign().setTitle(title);\n\t\t}\n\t\tapplyImageBannersToBand(title, options.getFirstPageImageBanners().values(), null, true);\n\n\t\t/*\n\t\t Now create image banner for the rest of the pages\n\t\t */\n\t\tJRDesignBand pageHeader = (JRDesignBand) getDesign().getPageHeader();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (pageHeader == null && !options.getImageBanners().isEmpty()){\n\t\t\tpageHeader = new JRDesignBand();\n\t\t\tgetDesign().setPageHeader(pageHeader);\n\t\t}\n\t\tJRDesignExpression printWhenExpression = null;\n\t\tif (!options.getFirstPageImageBanners().isEmpty()){\n\t\t\tprintWhenExpression = new JRDesignExpression();\n\t\t\tprintWhenExpression.setValueClass(Boolean.class);\n\t\t\tprintWhenExpression.setText(EXPRESSION_TRUE_WHEN_NOT_FIRST_PAGE);\n\t\t}\n\t\tapplyImageBannersToBand(pageHeader, options.getImageBanners().values(),printWhenExpression, true);\n\n\n\n\t}", "private Object readMetadataFromXML(InputSource source, Class target)\r\n throws MalformedURLException, ParserConfigurationException, SAXException, IOException\r\n {\r\n // TODO: make this configurable\r\n boolean validate = false;\r\n \r\n // get a xml reader instance:\r\n SAXParserFactory factory = SAXParserFactory.newInstance();\r\n log.info(\"RepositoryPersistor using SAXParserFactory : \" + factory.getClass().getName());\r\n if (validate)\r\n {\r\n factory.setValidating(true);\r\n }\r\n SAXParser p = factory.newSAXParser();\r\n XMLReader reader = p.getXMLReader();\r\n if (validate)\r\n {\r\n reader.setErrorHandler(new OJBErrorHandler());\r\n }\r\n\r\n Object result;\r\n if (DescriptorRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n DescriptorRepository repository = new DescriptorRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new RepositoryXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n result = repository;\r\n }\r\n else if (ConnectionRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n ConnectionRepository repository = new ConnectionRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n //LoggerFactory.getBootLogger().info(\"loading XML took \" + (stop - start) + \" msecs\");\r\n result = repository;\r\n }\r\n else\r\n throw new MetadataException(\"Could not build a repository instance for '\" + target +\r\n \"', using source \" + source);\r\n return result;\r\n }", "public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "public static void doMetaUpdateVersionsOnStores(AdminClient adminClient,\n List<StoreDefinition> oldStoreDefs,\n List<StoreDefinition> newStoreDefs) {\n Set<String> storeNamesUnion = new HashSet<String>();\n Map<String, StoreDefinition> oldStoreDefinitionMap = new HashMap<String, StoreDefinition>();\n Map<String, StoreDefinition> newStoreDefinitionMap = new HashMap<String, StoreDefinition>();\n List<String> storesChanged = new ArrayList<String>();\n for(StoreDefinition storeDef: oldStoreDefs) {\n String storeName = storeDef.getName();\n storeNamesUnion.add(storeName);\n oldStoreDefinitionMap.put(storeName, storeDef);\n }\n for(StoreDefinition storeDef: newStoreDefs) {\n String storeName = storeDef.getName();\n storeNamesUnion.add(storeName);\n newStoreDefinitionMap.put(storeName, storeDef);\n }\n for(String storeName: storeNamesUnion) {\n StoreDefinition oldStoreDef = oldStoreDefinitionMap.get(storeName);\n StoreDefinition newStoreDef = newStoreDefinitionMap.get(storeName);\n if(oldStoreDef == null && newStoreDef != null || oldStoreDef != null\n && newStoreDef == null || oldStoreDef != null && newStoreDef != null\n && !oldStoreDef.equals(newStoreDef)) {\n storesChanged.add(storeName);\n }\n }\n System.out.println(\"Updating metadata version for the following stores: \"\n + storesChanged);\n try {\n adminClient.metadataMgmtOps.updateMetadataversion(adminClient.getAdminClientCluster()\n .getNodeIds(),\n storesChanged);\n } catch(Exception e) {\n System.err.println(\"Error while updating metadata version for the specified store.\");\n }\n }", "@Override\n public void attachScriptFile(IScriptable target, IScriptFile scriptFile) {\n mScriptMap.put(target, scriptFile);\n scriptFile.invokeFunction(\"onAttach\", new Object[] { target });\n }" ]
called when we are completed finished with using the TcpChannelHub
[ "@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }" ]
[ "public static void applyHyperLinkToElement(DynamicJasperDesign design, DJHyperLink djlink, JRDesignChart chart, String name) {\n\t\tJRDesignExpression hlpe = ExpressionUtils.createAndRegisterExpression(design, name, djlink.getExpression());\n\t\tchart.setHyperlinkReferenceExpression(hlpe);\n\t\tchart.setHyperlinkType( HyperlinkTypeEnum.REFERENCE ); //FIXME Should this be a parameter in the future?\n\t\t\t\t\n\t\tif (djlink.getTooltip() != null){\t\t\t\n\t\t\tJRDesignExpression tooltipExp = ExpressionUtils.createAndRegisterExpression(design, \"tooltip_\" + name, djlink.getTooltip());\n\t\t\tchart.setHyperlinkTooltipExpression(tooltipExp);\n\t\t}\n\t}", "public Iterable<V> sorted(Iterator<V> input) {\n ExecutorService executor = new ThreadPoolExecutor(this.numThreads,\n this.numThreads,\n 1000L,\n TimeUnit.MILLISECONDS,\n new SynchronousQueue<Runnable>(),\n new CallerRunsPolicy());\n final AtomicInteger count = new AtomicInteger(0);\n final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());\n while(input.hasNext()) {\n final int segmentId = count.getAndIncrement();\n final long segmentStartMs = System.currentTimeMillis();\n logger.info(\"Segment \" + segmentId + \": filling sort buffer for segment...\");\n @SuppressWarnings(\"unchecked\")\n final V[] buffer = (V[]) new Object[internalSortSize];\n int segmentSizeIter = 0;\n for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)\n buffer[segmentSizeIter] = input.next();\n final int segmentSize = segmentSizeIter;\n logger.info(\"Segment \" + segmentId + \": sort buffer filled...adding to sort queue.\");\n\n // sort and write out asynchronously\n executor.execute(new Runnable() {\n\n public void run() {\n logger.info(\"Segment \" + segmentId + \": sorting buffer.\");\n long start = System.currentTimeMillis();\n Arrays.sort(buffer, 0, segmentSize, comparator);\n long elapsed = System.currentTimeMillis() - start;\n logger.info(\"Segment \" + segmentId + \": sort completed in \" + elapsed\n + \" ms, writing to temp file.\");\n\n // write out values to a temp file\n try {\n File tempFile = File.createTempFile(\"segment-\", \".dat\", tempDir);\n tempFile.deleteOnExit();\n tempFiles.add(tempFile);\n OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),\n bufferSize);\n if(gzip)\n os = new GZIPOutputStream(os);\n DataOutputStream output = new DataOutputStream(os);\n for(int i = 0; i < segmentSize; i++)\n writeValue(output, buffer[i]);\n output.close();\n } catch(IOException e) {\n throw new VoldemortException(e);\n }\n long segmentElapsed = System.currentTimeMillis() - segmentStartMs;\n logger.info(\"Segment \" + segmentId + \": completed processing of segment in \"\n + segmentElapsed + \" ms.\");\n }\n });\n }\n\n // wait for all sorting to complete\n executor.shutdown();\n try {\n executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n // create iterator over sorted values\n return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize\n / tempFiles.size()));\n } catch(InterruptedException e) {\n throw new RuntimeException(e);\n }\n }", "public <T> DiffNode compare(final T working, final T base)\n\t{\n\t\tdispatcher.resetInstanceMemory();\n\t\ttry\n\t\t{\n\t\t\treturn dispatcher.dispatch(DiffNode.ROOT, Instances.of(working, base), RootAccessor.getInstance());\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tdispatcher.clearInstanceMemory();\n\t\t}\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 }", "private void readRecord(byte[] buffer, Table table)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, true, 16, \"\"));\n int deletedFlag = getShort(buffer, 0);\n if (deletedFlag != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(0, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n table.addRow(m_definition.getPrimaryKeyColumnName(), row);\n }\n }", "public 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 }", "public int getMinutesPerMonth()\n {\n return m_minutesPerMonth == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerMonth()) : m_minutesPerMonth.intValue();\n }", "public void addStoreDefinition(StoreDefinition storeDef) {\n // acquire write lock\n writeLock.lock();\n\n try {\n // Check if store already exists\n if(this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Store already exists !\");\n }\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemaAsNeeded(storeDef);\n\n // Otherwise add to the STORES directory\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr);\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, null);\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr));\n\n // Re-initialize the store definitions. This is primarily required\n // to re-create the value for key: 'stores.xml'. This is necessary\n // for backwards compatibility.\n initStoreDefinitions(null);\n\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }", "public WebSocketContext sendToTagged(String message, String tag) {\n return sendToTagged(message, tag, false);\n }" ]
Add a Renderer instance as prototype. @param renderer to use as prototype. @return the current RendererBuilder instance.
[ "public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) {\n if (renderer == null) {\n throw new NeedsPrototypesException(\n \"RendererBuilder can't use a null Renderer<T> instance as prototype\");\n }\n this.prototypes.add(renderer);\n return this;\n }" ]
[ "public static HttpResponse getResponse(String urls, HttpRequest request,\n HttpMethod method, int connectTimeoutMillis, int readTimeoutMillis) throws IOException {\n OutputStream out = null;\n InputStream content = null;\n HttpResponse response = null;\n HttpURLConnection httpConn = request\n .getHttpConnection(urls, method.name());\n httpConn.setConnectTimeout(connectTimeoutMillis);\n httpConn.setReadTimeout(readTimeoutMillis);\n\n try {\n httpConn.connect();\n if (null != request.getPayload() && request.getPayload().length > 0) {\n out = httpConn.getOutputStream();\n out.write(request.getPayload());\n }\n content = httpConn.getInputStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } catch (SocketTimeoutException e) {\n throw e;\n } catch (IOException e) {\n content = httpConn.getErrorStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } finally {\n if (content != null) {\n content.close();\n }\n httpConn.disconnect();\n }\n }", "protected static PropertyDescriptor findPropertyDescriptor(Class aClass, String aPropertyName)\r\n {\r\n BeanInfo info;\r\n PropertyDescriptor[] pd;\r\n PropertyDescriptor descriptor = null;\r\n\r\n try\r\n {\r\n info = Introspector.getBeanInfo(aClass);\r\n pd = info.getPropertyDescriptors();\r\n for (int i = 0; i < pd.length; i++)\r\n {\r\n if (pd[i].getName().equals(aPropertyName))\r\n {\r\n descriptor = pd[i];\r\n break;\r\n }\r\n }\r\n if (descriptor == null)\r\n {\r\n /*\r\n\t\t\t\t * Daren Drummond: \tThrow here so we are consistent\r\n\t\t\t\t * \t\t\t\t\twith PersistentFieldDefaultImpl.\r\n\t\t\t\t */\r\n throw new MetadataException(\"Can't find property \" + aPropertyName + \" in \" + aClass.getName());\r\n }\r\n return descriptor;\r\n }\r\n catch (IntrospectionException ex)\r\n {\r\n /*\r\n\t\t\t * Daren Drummond: \tThrow here so we are consistent\r\n\t\t\t * \t\t\t\t\twith PersistentFieldDefaultImpl.\r\n\t\t\t */\r\n throw new MetadataException(\"Can't find property \" + aPropertyName + \" in \" + aClass.getName(), ex);\r\n }\r\n }", "private void updateMaxMin(IntervalRBTreeNode<T> n, IntervalRBTreeNode<T> c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n if (n.min > c.min) {\n n.min = c.min;\n }\n }\n }", "public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }", "public static base_response delete(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager deleteresource = new snmpmanager();\n\t\tdeleteresource.ipaddress = resource.ipaddress;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public Object assignIdValue(ConnectionSource connectionSource, Object data, Number val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\tObject idVal = dataPersister.convertIdNumber(val);\n\t\tif (idVal == null) {\n\t\t\tthrow new SQLException(\"Invalid class \" + dataPersister + \" for sequence-id \" + this);\n\t\t} else {\n\t\t\tassignField(connectionSource, data, idVal, false, objectCache);\n\t\t\treturn idVal;\n\t\t}\n\t}", "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 }", "private <T> T readIntoBean(final T bean, final String[] nameMapping, final CellProcessor[] processors)\n\t\tthrows IOException {\n\t\t\n\t\tif( readRow() ) {\n\t\t\tif( nameMapping.length != length() ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\t\"the nameMapping array and the number of columns read \"\n\t\t\t\t\t\t+ \"should be the same size (nameMapping length = %d, columns = %d)\", nameMapping.length,\n\t\t\t\t\tlength()));\n\t\t\t}\n\t\t\t\n\t\t\tif( processors == null ) {\n\t\t\t\tprocessedColumns.clear();\n\t\t\t\tprocessedColumns.addAll(getColumns());\n\t\t\t} else {\n\t\t\t\texecuteProcessors(processedColumns, processors);\n\t\t\t}\n\t\t\t\n\t\t\treturn populateBean(bean, nameMapping);\n\t\t}\n\t\t\n\t\treturn null; // EOF\n\t}", "public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {\n return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);\n }" ]
Returns a source excerpt of a JavaDoc link to a method on this type.
[ "public JavadocLink javadocMethodLink(String memberName, Type... types) {\n return new JavadocLink(\"%s#%s(%s)\",\n getQualifiedName(),\n memberName,\n (Excerpt) code -> {\n String separator = \"\";\n for (Type type : types) {\n code.add(\"%s%s\", separator, type.getQualifiedName());\n separator = \", \";\n }\n });\n }" ]
[ "private String getIndirectionTableColName(TableAlias mnAlias, String path)\r\n {\r\n int dotIdx = path.lastIndexOf(\".\");\r\n String column = path.substring(dotIdx);\r\n return mnAlias.alias + column;\r\n }", "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 static Object objectify(ObjectMapper mapper, Object source) {\n return objectify(mapper, source, Object.class);\n }", "public static int rank(SingularValueDecomposition_F64 svd , double threshold ) {\n int numRank=0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] > threshold)\n numRank++;\n }\n\n return numRank;\n }", "private List<Versioned<byte[]>> filterExpiredEntries(ByteArray key, List<Versioned<byte[]>> vals) {\n Iterator<Versioned<byte[]>> valsIterator = vals.iterator();\n while(valsIterator.hasNext()) {\n Versioned<byte[]> val = valsIterator.next();\n VectorClock clock = (VectorClock) val.getVersion();\n // omit if expired\n if(clock.getTimestamp() < (time.getMilliseconds() - this.retentionTimeMs)) {\n valsIterator.remove();\n // delete stale value if configured\n if(deleteExpiredEntries) {\n getInnerStore().delete(key, clock);\n }\n }\n }\n return vals;\n }", "public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }", "@Override\n public boolean decompose( ZMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be square.\");\n if( A.numRows <= 0 )\n return false;\n\n QH = A;\n\n N = A.numCols;\n\n if( b.length < N*2 ) {\n b = new double[ N*2 ];\n gammas = new double[ N ];\n u = new double[ N*2 ];\n }\n return _decompose();\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 }", "protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }" ]
Retrieves a long value from the extended data. @param type Type identifier @return long value
[ "public long getLong(Integer type)\n {\n long result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getLong6(item, 0);\n }\n\n return (result);\n }" ]
[ "protected boolean isZero( int index ) {\n double bottom = Math.abs(diag[index])+Math.abs(diag[index+1]);\n\n return( Math.abs(off[index]) <= bottom*UtilEjml.EPS);\n }", "public SignedJWT verifyToken(String jwtString) throws ParseException {\n try {\n SignedJWT jwt = SignedJWT.parse(jwtString);\n if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) {\n return jwt;\n }\n return null;\n } catch (JOSEException e) {\n throw new RuntimeException(\"Error verifying JSON Web Token\", e);\n }\n }", "private long recover() throws IOException {\n checkMutable();\n long len = channel.size();\n ByteBuffer buffer = ByteBuffer.allocate(4);\n long validUpTo = 0;\n long next = 0L;\n do {\n next = validateMessage(channel, validUpTo, len, buffer);\n if (next >= 0) validUpTo = next;\n } while (next >= 0);\n channel.truncate(validUpTo);\n setSize.set(validUpTo);\n setHighWaterMark.set(validUpTo);\n logger.info(\"recover high water mark:\" + highWaterMark());\n /* This should not be necessary, but fixes bug 6191269 on some OSs. */\n channel.position(validUpTo);\n needRecover.set(false);\n return len - validUpTo;\n }", "protected ServiceName serviceName(final String name) {\n return baseServiceName != null ? baseServiceName.append(name) : null;\n }", "@NonNull\n @Override\n public Loader<SortedList<FtpFile>> getLoader() {\n return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {\n @Override\n public SortedList<FtpFile> loadInBackground() {\n SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {\n @Override\n public int compare(FtpFile lhs, FtpFile rhs) {\n if (lhs.isDirectory() && !rhs.isDirectory()) {\n return -1;\n } else if (rhs.isDirectory() && !lhs.isDirectory()) {\n return 1;\n } else {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n }\n\n @Override\n public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {\n return oldItem.getName().equals(newItem.getName());\n }\n\n @Override\n public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {\n return item1.getName().equals(item2.getName());\n }\n });\n\n\n if (!ftp.isConnected()) {\n // Connect\n try {\n ftp.connect(server, port);\n\n ftp.setFileType(FTP.ASCII_FILE_TYPE);\n ftp.enterLocalPassiveMode();\n ftp.setUseEPSVwithIPv4(false);\n\n if (!(loggedIn = ftp.login(username, password))) {\n ftp.logout();\n Log.e(TAG, \"Login failed\");\n }\n } catch (IOException e) {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException ignored) {\n }\n }\n Log.e(TAG, \"Could not connect to server.\");\n }\n }\n\n if (loggedIn) {\n try {\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n sortedList.beginBatchedUpdates();\n for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {\n FtpFile file;\n if (f.isDirectory()) {\n file = new FtpDir(mCurrentPath, f.getName());\n } else {\n file = new FtpFile(mCurrentPath, f.getName());\n }\n if (isItemVisible(file)) {\n sortedList.add(file);\n }\n }\n sortedList.endBatchedUpdates();\n } catch (IOException e) {\n Log.e(TAG, \"IOException: \" + e.getMessage());\n }\n }\n\n return sortedList;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n forceLoad();\n }\n };\n }", "public static <E> Set<E> intersection(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n s.addAll(s1);\r\n s.retainAll(s2);\r\n return s;\r\n }", "boolean undoChanges() {\n final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY);\n if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) {\n // Was actually completed already\n return false;\n }\n PatchingTaskContext.Mode currentMode = this.mode;\n mode = PatchingTaskContext.Mode.UNDO;\n final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null);\n // Undo changes for the identity\n undoChanges(identityEntry, loader);\n // TODO maybe check if we need to do something for the layers too !?\n if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) {\n // For apply the state needs to be invalidate\n // For rollback the files are invalidated as part of the tasks\n final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY;\n for (final File file : moduleInvalidations) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, mode);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n if(!modulesToReenable.isEmpty()) {\n for (final File file : modulesToReenable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n if(!modulesToDisable.isEmpty()) {\n for (final File file : modulesToDisable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n }\n return true;\n }", "protected VelocityContext createContext()\n {\n VelocityContext context = new VelocityContext();\n context.put(META_KEY, META);\n context.put(UTILS_KEY, UTILS);\n context.put(MESSAGES_KEY, MESSAGES);\n return context;\n }", "protected Connection newConnectionFromDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JNDI lookup\r\n DataSource ds = jcd.getDataSource();\r\n\r\n if (ds == null)\r\n {\r\n // [tomdz] Would it suffice to store the datasources only at the JCDs ?\r\n // Only possible problem would be serialization of the JCD because\r\n // the data source object in the JCD does not 'survive' this\r\n ds = (DataSource) dataSourceCache.get(jcd.getDatasourceName());\r\n }\r\n try\r\n {\r\n if (ds == null)\r\n {\r\n /**\r\n * this synchronization block won't be a big deal as we only look up\r\n * new datasources not found in the map.\r\n */\r\n synchronized (dataSourceCache)\r\n {\r\n InitialContext ic = new InitialContext();\r\n ds = (DataSource) ic.lookup(jcd.getDatasourceName());\r\n /**\r\n * cache the datasource lookup.\r\n */\r\n dataSourceCache.put(jcd.getDatasourceName(), ds);\r\n }\r\n }\r\n if (jcd.getUserName() == null)\r\n {\r\n retval = ds.getConnection();\r\n }\r\n else\r\n {\r\n retval = ds.getConnection(jcd.getUserName(), jcd.getPassWord());\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n throw new LookupException(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n }\r\n catch (NamingException namingEx)\r\n {\r\n log.error(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() + \")\", namingEx);\r\n throw new LookupException(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() +\r\n \")\", namingEx);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DataSource: \"+retval);\r\n return retval;\r\n }" ]
Gets an app client by its client app id if it has been initialized; throws if none can be found. @param clientAppId the client app id of the app client to get. @return the app client associated with the client app id.
[ "public static StitchAppClient getAppClient(\n @Nonnull final String clientAppId\n ) {\n ensureInitialized();\n\n synchronized (Stitch.class) {\n if (!appClients.containsKey(clientAppId)) {\n throw new IllegalStateException(\n String.format(\"client for app '%s' has not yet been initialized\", clientAppId));\n }\n return appClients.get(clientAppId);\n }\n }" ]
[ "public double compute( DMatrix1Row mat ) {\n if( width != mat.numCols || width != mat.numRows ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n\n // make sure everything is in the proper state before it starts\n initStructures();\n\n// System.arraycopy(mat.data,0,minorMatrix[0],0,mat.data.length);\n\n int level = 0;\n while( true ) {\n int levelWidth = width-level;\n int levelIndex = levelIndexes[level];\n\n if( levelIndex == levelWidth ) {\n if( level == 0 ) {\n return levelResults[0];\n }\n int prevLevelIndex = levelIndexes[level-1]++;\n\n double val = mat.get((level-1)*width+levelRemoved[level-1]);\n if( prevLevelIndex % 2 == 0 ) {\n levelResults[level-1] += val * levelResults[level];\n } else {\n levelResults[level-1] -= val * levelResults[level];\n }\n\n putIntoOpen(level-1);\n\n levelResults[level] = 0;\n levelIndexes[level] = 0;\n level--;\n } else {\n int excluded = openRemove( levelIndex );\n\n levelRemoved[level] = excluded;\n\n if( levelWidth == minWidth ) {\n createMinor(mat);\n double subresult = mat.get(level*width+levelRemoved[level]);\n\n subresult *= UnrolledDeterminantFromMinor_DDRM.det(tempMat);\n\n if( levelIndex % 2 == 0 ) {\n levelResults[level] += subresult;\n } else {\n levelResults[level] -= subresult;\n }\n\n // put it back into the list\n putIntoOpen(level);\n levelIndexes[level]++;\n } else {\n level++;\n }\n }\n }\n }", "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 }", "public AsciiTable setPaddingTop(int paddingTop) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private <T extends TimephasedItem<?>> int getStartIndex(DateRange range, List<T> assignments, int startIndex)\n {\n int result = -1;\n if (assignments != null)\n {\n long rangeStart = range.getStart().getTime();\n long rangeEnd = range.getEnd().getTime();\n\n for (int loop = startIndex; loop < assignments.size(); loop++)\n {\n T assignment = assignments.get(loop);\n int compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeStart);\n\n //\n // The start of the target range falls after the assignment end -\n // move on to test the next assignment.\n //\n if (compareResult > 0)\n {\n continue;\n }\n\n //\n // The start of the target range falls within the assignment -\n // return the index of this assignment to the caller.\n //\n if (compareResult == 0)\n {\n result = loop;\n break;\n }\n\n //\n // At this point, we know that the start of the target range is before\n // the assignment start. We need to determine if the end of the\n // target range overlaps the assignment.\n //\n compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeEnd);\n if (compareResult >= 0)\n {\n result = loop;\n break;\n }\n }\n }\n return result;\n }", "public boolean getCritical()\n {\n Boolean critical = (Boolean) getCachedValue(TaskField.CRITICAL);\n if (critical == null)\n {\n Duration totalSlack = getTotalSlack();\n ProjectProperties props = getParentFile().getProjectProperties();\n int criticalSlackLimit = NumberHelper.getInt(props.getCriticalSlackLimit());\n if (criticalSlackLimit != 0 && totalSlack.getDuration() != 0 && totalSlack.getUnits() != TimeUnit.DAYS)\n {\n totalSlack = totalSlack.convertUnits(TimeUnit.DAYS, props);\n }\n critical = Boolean.valueOf(totalSlack.getDuration() <= criticalSlackLimit && NumberHelper.getInt(getPercentageComplete()) != 100 && ((getTaskMode() == TaskMode.AUTO_SCHEDULED) || (getDurationText() == null && getStartText() == null && getFinishText() == null)));\n set(TaskField.CRITICAL, critical);\n }\n return (BooleanHelper.getBoolean(critical));\n }", "public static final String printTaskUID(Integer value)\n {\n ProjectFile file = PARENT_FILE.get();\n if (file != null)\n {\n file.getEventManager().fireTaskWrittenEvent(file.getTaskByUniqueID(value));\n }\n return (value.toString());\n }", "private void cleanUpAction() {\n\n try {\n m_model.deleteDescriptorIfNecessary();\n } catch (CmsException e) {\n LOG.error(m_messages.key(Messages.ERR_DELETING_DESCRIPTOR_0), e);\n }\n // unlock resource\n m_model.unlock();\n }", "void attachMetadataCacheInternal(SlotReference slot, MetadataCache cache) {\n MetadataCache oldCache = metadataCacheFiles.put(slot, cache);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing previous metadata cache\", e);\n }\n }\n\n deliverCacheUpdate(slot, cache);\n }", "private static void firstDotConstellation(int[] dollarPositions, int[] dotPositions, int nestingLevel) {\n int i = 0;\n int unassigned = dotPositions.length - nestingLevel;\n\n for (; i < unassigned; ++i) {\n dotPositions[i] = -1;\n }\n\n for (; i < dotPositions.length; ++i) {\n dotPositions[i] = dollarPositions[i];\n }\n }" ]
Create a host target. @param hostName the host name @param client the connected controller client to the master host. @return the remote target
[ "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 }" ]
[ "private Number calculatePercentComplete(Row row)\n {\n Number result;\n switch (PercentCompleteType.getInstance(row.getString(\"complete_pct_type\")))\n {\n case UNITS:\n {\n result = calculateUnitsPercentComplete(row);\n break;\n }\n\n case DURATION:\n {\n result = calculateDurationPercentComplete(row);\n break;\n }\n\n default:\n {\n result = calculatePhysicalPercentComplete(row);\n break;\n }\n }\n\n return result;\n }", "public boolean process(DMatrixRMaj A , int numSingularValues, DMatrixRMaj nullspace ) {\n decomposition.decompose(A);\n\n if( A.numRows > A.numCols ) {\n Q.reshape(A.numCols,Math.min(A.numRows,A.numCols));\n decomposition.getQ(Q, true);\n } else {\n Q.reshape(A.numCols, A.numCols);\n decomposition.getQ(Q, false);\n }\n\n nullspace.reshape(Q.numRows,numSingularValues);\n CommonOps_DDRM.extract(Q,0,Q.numRows,Q.numCols-numSingularValues,Q.numCols,nullspace,0,0);\n\n return true;\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 }", "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 }", "public Conditionals addIfMatch(Tag tag) {\n Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));\n Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));\n List<Tag> match = new ArrayList<>(this.match);\n\n if (tag == null) {\n tag = Tag.ALL;\n }\n if (Tag.ALL.equals(tag)) {\n match.clear();\n }\n if (!match.contains(Tag.ALL)) {\n if (!match.contains(tag)) {\n match.add(tag);\n }\n }\n else {\n throw new IllegalArgumentException(\"Tag ALL already in the list\");\n }\n return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);\n }", "private void addCalendarDay(MpxjTreeNode parentNode, ProjectCalendar calendar, final Day day)\n {\n MpxjTreeNode dayNode = new MpxjTreeNode(day)\n {\n @Override public String toString()\n {\n return day.name();\n }\n };\n parentNode.add(dayNode);\n addHours(dayNode, calendar.getHours(day));\n }", "public FindByIndexOptions useIndex(String designDocument, String indexName) {\r\n assertNotNull(designDocument, \"designDocument\");\r\n assertNotNull(indexName, \"indexName\");\r\n JsonArray index = new JsonArray();\r\n index.add(new JsonPrimitive(designDocument));\r\n index.add(new JsonPrimitive(indexName));\r\n this.useIndex = index;\r\n return this;\r\n }", "public static void setQuota(final GreenMailUser user, final Quota quota) {\r\n Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP);\r\n try {\r\n Store store = session.getStore(\"imap\");\r\n store.connect(user.getEmail(), user.getPassword());\r\n try {\r\n ((QuotaAwareStore) store).setQuota(quota);\r\n } finally {\r\n store.close();\r\n }\r\n } catch (Exception ex) {\r\n throw new IllegalStateException(\"Can not set quota \" + quota\r\n + \" for user \" + user, ex);\r\n }\r\n }", "private List<StyleFilter> initStyleFilters(List<FeatureStyleInfo> styleDefinitions) throws GeomajasException {\n\t\tList<StyleFilter> styleFilters = new ArrayList<StyleFilter>();\n\t\tif (styleDefinitions == null || styleDefinitions.size() == 0) {\n\t\t\tstyleFilters.add(new StyleFilterImpl()); // use default.\n\t\t} else {\n\t\t\tfor (FeatureStyleInfo styleDef : styleDefinitions) {\n\t\t\t\tStyleFilterImpl styleFilterImpl = null;\n\t\t\t\tString formula = styleDef.getFormula();\n\t\t\t\tif (null != formula && formula.length() > 0) {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(filterService.parseFilter(formula), styleDef);\n\t\t\t\t} else {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(Filter.INCLUDE, styleDef);\n\t\t\t\t}\n\t\t\t\tstyleFilters.add(styleFilterImpl);\n\t\t\t}\n\t\t}\n\t\treturn styleFilters;\n\t}" ]
Allocate a timestamp
[ "public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }" ]
[ "@SuppressWarnings(\"unused\")\n private void setTextureNumber(int type, int number) {\n m_numTextures.put(AiTextureType.fromRawValue(type), number);\n }", "private List<Entity> runQuery(Query query) throws DatastoreException {\n RunQueryRequest.Builder request = RunQueryRequest.newBuilder();\n request.setQuery(query);\n RunQueryResponse response = datastore.runQuery(request.build());\n\n if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {\n System.err.println(\"WARNING: partial results\\n\");\n }\n List<EntityResult> results = response.getBatch().getEntityResultsList();\n List<Entity> entities = new ArrayList<Entity>(results.size());\n for (EntityResult result : results) {\n entities.add(result.getEntity());\n }\n return entities;\n }", "public void sub(Vector3d v1) {\n x -= v1.x;\n y -= v1.y;\n z -= v1.z;\n }", "private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {\n this.stats.startTime = System.currentTimeMillis();\n try {\n // build and record parsed units\n reportProgress(Messages.compilation_beginningToCompile);\n\n if (this.options.complianceLevel >= ClassFileConstants.JDK9) {\n // in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:\n sortModuleDeclarationsFirst(sourceUnits);\n }\n if (this.annotationProcessorManager == null) {\n beginToCompile(sourceUnits);\n } else {\n ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs\n try {\n beginToCompile(sourceUnits);\n if (!lastRound) {\n processAnnotations();\n }\n if (!this.options.generateClassFiles) {\n // -proc:only was set on the command line\n return;\n }\n } catch (SourceTypeCollisionException e) {\n backupAptProblems();\n reset();\n // a generated type was referenced before it was created\n // the compiler either created a MissingType or found a BinaryType for it\n // so add the processor's generated files & start over,\n // but remember to only pass the generated files to the annotation processor\n int originalLength = originalUnits.length;\n int newProcessedLength = e.newAnnotationProcessorUnits.length;\n ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];\n System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);\n System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);\n this.annotationProcessorStartIndex = originalLength;\n compile(combinedUnits, e.isLastRound);\n return;\n }\n }\n // Restore the problems before the results are processed and cleaned up.\n restoreAptProblems();\n processCompiledUnits(0, lastRound);\n } catch (AbortCompilation e) {\n this.handleInternalException(e, null);\n }\n if (this.options.verbose) {\n if (this.totalUnits > 1) {\n this.out.println(\n Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));\n } else {\n this.out.println(\n Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));\n }\n }\n }", "protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\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 }", "protected List<Reference> mergeReferences(\n\t\t\tList<? extends Reference> references1,\n\t\t\tList<? extends Reference> references2) {\n\t\tList<Reference> result = new ArrayList<>();\n\t\tfor (Reference reference : references1) {\n\t\t\taddBestReferenceToList(reference, result);\n\t\t}\n\t\tfor (Reference reference : references2) {\n\t\t\taddBestReferenceToList(reference, result);\n\t\t}\n\t\treturn result;\n\t}", "private DecompilerSettings getDefaultSettings(File outputDir)\n {\n DecompilerSettings settings = new DecompilerSettings();\n procyonConf.setDecompilerSettings(settings);\n settings.setOutputDirectory(outputDir.getPath());\n settings.setShowSyntheticMembers(false);\n settings.setForceExplicitImports(true);\n\n if (settings.getTypeLoader() == null)\n settings.setTypeLoader(new ClasspathTypeLoader());\n return settings;\n }", "public Where<T, ID> isNull(String columnName) throws SQLException {\n\t\taddClause(new IsNull(columnName, findColumnFieldType(columnName)));\n\t\treturn this;\n\t}" ]
Returns the designer version from the manifest. @param context @return version
[ "public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }" ]
[ "public static Method getSAMMethod(Class<?> c) {\n // SAM = single public abstract method\n // if the class is not abstract there is no abstract method\n if (!Modifier.isAbstract(c.getModifiers())) return null;\n if (c.isInterface()) {\n Method[] methods = c.getMethods();\n // res stores the first found abstract method\n Method res = null;\n for (Method mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (mi.getAnnotation(Traits.Implemented.class)!=null) continue;\n try {\n Object.class.getMethod(mi.getName(), mi.getParameterTypes());\n continue;\n } catch (NoSuchMethodException e) {/*ignore*/}\n\n // we have two methods, so no SAM\n if (res!=null) return null;\n res = mi;\n }\n return res;\n\n } else {\n\n LinkedList<Method> methods = new LinkedList();\n getAbstractMethods(c, methods);\n if (methods.isEmpty()) return null;\n ListIterator<Method> it = methods.listIterator();\n while (it.hasNext()) {\n Method m = it.next();\n if (hasUsableImplementation(c, m)) it.remove();\n }\n return getSingleNonDuplicateMethod(methods);\n }\n }", "public FormInput inputField(InputType type, Identification identification) {\r\n\t\tFormInput input = new FormInput(type, identification);\r\n\t\tthis.formInputs.add(input);\r\n\t\treturn input;\r\n\t}", "public static void validate(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n try {\n validateEmpty(bic);\n validateLength(bic);\n validateCase(bic);\n validateBankCode(bic);\n validateCountryCode(bic);\n validateLocationCode(bic);\n\n if(hasBranchCode(bic)) {\n validateBranchCode(bic);\n }\n } catch (UnsupportedCountryException e) {\n throw e;\n } catch (RuntimeException e) {\n throw new BicFormatException(UNKNOWN, e.getMessage());\n }\n }", "private String format(Object o)\n {\n String result;\n\n if (o == null)\n {\n result = \"\";\n }\n else\n {\n if (o instanceof Boolean == true)\n {\n result = LocaleData.getString(m_locale, (((Boolean) o).booleanValue() == true ? LocaleData.YES : LocaleData.NO));\n }\n else\n {\n if (o instanceof Float == true || o instanceof Double == true)\n {\n result = (m_formats.getDecimalFormat().format(((Number) o).doubleValue()));\n }\n else\n {\n if (o instanceof Day)\n {\n result = Integer.toString(((Day) o).getValue());\n }\n else\n {\n result = o.toString();\n }\n }\n }\n\n //\n // At this point there should be no line break characters in\n // the file. If we find any, replace them with spaces\n //\n result = stripLineBreaks(result, MPXConstants.EOL_PLACEHOLDER_STRING);\n\n //\n // Finally we check to ensure that there are no embedded\n // quotes or separator characters in the value. If there are, then\n // we quote the value and escape any existing quote characters.\n //\n if (result.indexOf('\"') != -1)\n {\n result = escapeQuotes(result);\n }\n else\n {\n if (result.indexOf(m_delimiter) != -1)\n {\n result = '\"' + result + '\"';\n }\n }\n }\n\n return (result);\n }", "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}", "@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 validationErrors() {\n\n List<String> errors = new ArrayList<>();\n for (File config : getConfigFiles()) {\n String filename = config.getName();\n try (FileInputStream stream = new FileInputStream(config)) {\n CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true);\n } catch (CmsXmlException e) {\n errors.add(filename + \":\" + e.getCause().getMessage());\n } catch (Exception e) {\n errors.add(filename + \":\" + e.getMessage());\n }\n }\n if (errors.size() == 0) {\n return null;\n }\n String errString = CmsStringUtil.listAsString(errors, \"\\n\");\n JSONObject obj = new JSONObject();\n try {\n obj.put(\"err\", errString);\n } catch (JSONException e) {\n\n }\n return obj.toString();\n }", "private void useSearchService() throws Exception {\n\n System.out.println(\"Searching...\");\n\n WebClient wc = WebClient.create(\"http://localhost:\" + port + \"/services/personservice/search\");\n WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);\n wc.accept(MediaType.APPLICATION_XML);\n \n // Moves to \"/services/personservice/search\"\n wc.path(\"person\");\n \n SearchConditionBuilder builder = SearchConditionBuilder.instance(); \n \n System.out.println(\"Find people with the name Fred or Lorraine:\");\n \n String query = builder.is(\"name\").equalTo(\"Fred\").or()\n .is(\"name\").equalTo(\"Lorraine\")\n .query();\n findPersons(wc, query);\n \n System.out.println(\"Find all people who are no more than 30 years old\");\n query = builder.is(\"age\").lessOrEqualTo(30)\n \t\t.query();\n \n findPersons(wc, query);\n \n System.out.println(\"Find all people who are older than 28 and whose father name is John\");\n query = builder.is(\"age\").greaterThan(28)\n \t\t.and(\"fatherName\").equalTo(\"John\")\n \t\t.query();\n \n findPersons(wc, query);\n\n System.out.println(\"Find all people who have children with name Fred\");\n query = builder.is(\"childName\").equalTo(\"Fred\")\n \t\t.query();\n \n findPersons(wc, query);\n \n //Moves to \"/services/personservice/personinfo\"\n wc.reset().accept(MediaType.APPLICATION_XML);\n wc.path(\"personinfo\");\n \n System.out.println(\"Find all people younger than 40 using JPA2 Tuples\");\n query = builder.is(\"age\").lessThan(40).query();\n \n // Use URI path component to capture the query expression\n wc.path(query);\n \n \n Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);\n for (PersonInfo pi : personInfos) {\n \tSystem.out.println(\"ID : \" + pi.getId());\n }\n\n wc.close();\n }", "public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
Write an integer field to the JSON file. @param fieldName field name @param value field value
[ "private void writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }" ]
[ "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 }", "private void writeCustomField(CustomField field) throws IOException\n {\n if (field.getAlias() != null)\n {\n m_writer.writeStartObject(null);\n m_writer.writeNameValuePair(\"field_type_class\", field.getFieldType().getFieldTypeClass().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_type\", field.getFieldType().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_alias\", field.getAlias());\n m_writer.writeEndObject();\n }\n }", "private void addJoin(TableAlias left, Object[] leftKeys, TableAlias right, Object[] rightKeys, boolean outer,\r\n String name)\r\n {\r\n TableAlias extAlias, rightCopy;\r\n\r\n left.addJoin(new Join(left, leftKeys, right, rightKeys, outer, name));\r\n\r\n // build join between left and extents of right\r\n if (right.hasExtents())\r\n {\r\n for (int i = 0; i < right.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) right.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) rightKeys);\r\n\r\n left.addJoin(new Join(left, leftKeys, extAlias, extKeys, true, name));\r\n }\r\n }\r\n\r\n // we need to copy the alias on the right for each extent on the left\r\n if (left.hasExtents())\r\n {\r\n for (int i = 0; i < left.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) left.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) leftKeys);\r\n rightCopy = right.copy(\"C\" + i);\r\n\r\n // copies are treated like normal extents\r\n right.extents.add(rightCopy);\r\n right.extents.addAll(rightCopy.extents);\r\n\r\n addJoin(extAlias, extKeys, rightCopy, rightKeys, true, name);\r\n }\r\n }\r\n }", "public static List<String> getArgumentNames(MethodCallExpression methodCall) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n Expression arguments = methodCall.getArguments();\r\n List<Expression> argExpressions = null;\r\n if (arguments instanceof ArrayExpression) {\r\n argExpressions = ((ArrayExpression) arguments).getExpressions();\r\n } else if (arguments instanceof ListExpression) {\r\n argExpressions = ((ListExpression) arguments).getExpressions();\r\n } else if (arguments instanceof TupleExpression) {\r\n argExpressions = ((TupleExpression) arguments).getExpressions();\r\n } else {\r\n LOG.warn(\"getArgumentNames arguments is not an expected type\");\r\n }\r\n\r\n if (argExpressions != null) {\r\n for (Expression exp : argExpressions) {\r\n if (exp instanceof VariableExpression) {\r\n result.add(((VariableExpression) exp).getName());\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public static void createMetadataCache(SlotReference slot, int playlistId, File cache) throws Exception {\n createMetadataCache(slot, playlistId, cache, null);\n }", "public Collection<Exif> getExif(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_EXIF);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n List<Exif> exifs = new ArrayList<Exif>();\r\n Element photoElement = response.getPayload();\r\n NodeList exifElements = photoElement.getElementsByTagName(\"exif\");\r\n for (int i = 0; i < exifElements.getLength(); i++) {\r\n Element exifElement = (Element) exifElements.item(i);\r\n Exif exif = new Exif();\r\n exif.setTagspace(exifElement.getAttribute(\"tagspace\"));\r\n exif.setTagspaceId(exifElement.getAttribute(\"tagspaceid\"));\r\n exif.setTag(exifElement.getAttribute(\"tag\"));\r\n exif.setLabel(exifElement.getAttribute(\"label\"));\r\n exif.setRaw(XMLUtilities.getChildValue(exifElement, \"raw\"));\r\n exif.setClean(XMLUtilities.getChildValue(exifElement, \"clean\"));\r\n exifs.add(exif);\r\n }\r\n return exifs;\r\n }", "public Where<T, ID> le(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }", "public <T extends Widget & Checkable> List<T> getCheckedWidgets() {\n List<T> checked = new ArrayList<>();\n\n for (Widget c : getChildren()) {\n if (c instanceof Checkable && ((Checkable) c).isChecked()) {\n checked.add((T) c);\n }\n }\n\n return checked;\n }" ]
Obtains a local date in Symmetry454 calendar system from the era, year-of-era and day-of-year fields. @param era the Symmetry454 era, not null @param yearOfEra the year-of-era @param dayOfYear the day-of-year @return the Symmetry454 local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code IsoEra}
[ "@Override\n public Symmetry454Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
[ "protected void addEnumList(String key, List<? extends Enum> list) {\n optionsMap.put(key, list.stream().map(i -> i.toString()).collect(Collectors.toList()));\n }", "public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) {\r\n\t\treturn ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(),\r\n\t\t\t\tgetShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}", "public ActivityCodeValue addValue(Integer uniqueID, String name, String description)\n {\n ActivityCodeValue value = new ActivityCodeValue(this, uniqueID, name, description);\n m_values.add(value);\n return value;\n }", "public static final long getLong(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "private void set(FieldType field, boolean value)\n {\n set(field, (value ? Boolean.TRUE : Boolean.FALSE));\n }", "protected float[] transformPosition(float x, float y)\n {\n Point2D.Float point = super.transformedPoint(x, y);\n AffineTransform pageTransform = createCurrentPageTransformation();\n Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null);\n\n return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()};\n }", "public boolean getEnterpriseFlag(int index)\n {\n return (BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(TaskFieldLists.ENTERPRISE_FLAG, index))));\n }", "protected static File platformIndependentUriToFile(final URI fileURI) {\n File file;\n try {\n file = new File(fileURI);\n } catch (IllegalArgumentException e) {\n if (fileURI.toString().startsWith(\"file://\")) {\n file = new File(fileURI.toString().substring(\"file://\".length()));\n } else {\n throw e;\n }\n }\n return file;\n }", "public static int cudnnOpTensor(\n cudnnHandle handle, \n cudnnOpTensorDescriptor opTensorDesc, \n Pointer alpha1, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer alpha2, \n cudnnTensorDescriptor bDesc, \n Pointer B, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnOpTensorNative(handle, opTensorDesc, alpha1, aDesc, A, alpha2, bDesc, B, beta, cDesc, C));\n }" ]
Write an int to the byte array starting at the given offset @param bytes The byte array @param value The int to write @param offset The offset to begin writing at
[ "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 static double blackScholesDigitalOptionVega(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate vega\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;\n\n\t\t\treturn vega;\n\t\t}\n\t}", "public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }", "public static <T> Set<T> getSet(Collection<T> collection) {\n Set<T> set = new LinkedHashSet<T>();\n set.addAll(collection);\n\n return set;\n }", "void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }", "public static void hideChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }", "public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new ClusterMapper().writeCluster(cluster));\n } catch(IOException e) {\n logger.error(\"IOException during dumpClusterToFile: \" + e);\n }\n }\n }", "public static transformpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\ttransformpolicylabel response = (transformpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "private boolean isDebug(CmsObject cms, CmsSolrQuery query) {\r\n\r\n String[] debugSecretValues = query.remove(REQUEST_PARAM_DEBUG_SECRET);\r\n String debugSecret = (debugSecretValues == null) || (debugSecretValues.length < 1)\r\n ? null\r\n : debugSecretValues[0];\r\n if ((null != debugSecret) && !debugSecret.trim().isEmpty() && (null != m_handlerDebugSecretFile)) {\r\n try {\r\n CmsFile secretFile = cms.readFile(m_handlerDebugSecretFile);\r\n String secret = new String(secretFile.getContents(), CmsFileUtil.getEncoding(cms, secretFile));\r\n return secret.trim().equals(debugSecret.trim());\r\n } catch (Exception e) {\r\n LOG.info(\r\n \"Failed to read secret file for index \\\"\"\r\n + getName()\r\n + \"\\\" at path \\\"\"\r\n + m_handlerDebugSecretFile\r\n + \"\\\".\");\r\n }\r\n }\r\n return false;\r\n }", "@Override\n public void init(NamedList args) {\n\n Object regex = args.remove(PARAM_REGEX);\n if (null == regex) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REGEX);\n }\n try {\n m_regex = Pattern.compile(regex.toString());\n } catch (PatternSyntaxException e) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Invalid regex: \" + regex, e);\n }\n\n Object replacement = args.remove(PARAM_REPLACEMENT);\n if (null == replacement) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REPLACEMENT);\n }\n m_replacement = replacement.toString();\n\n Object source = args.remove(PARAM_SOURCE);\n if (null == source) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_SOURCE);\n }\n m_source = source.toString();\n\n Object target = args.remove(PARAM_TARGET);\n if (null == target) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_TARGET);\n }\n m_target = target.toString();\n\n }" ]
If the variable is a local temporary variable it will be resized so that the operation can complete. If not temporary then it will not be reshaped @param mat Variable containing the matrix @param numRows Desired number of rows @param numCols Desired number of columns
[ "protected void resize( VariableMatrix mat , int numRows , int numCols ) {\n if( mat.isTemp() ) {\n mat.matrix.reshape(numRows,numCols);\n }\n }" ]
[ "@Override public Task addTask()\n {\n ProjectFile parent = getParentFile();\n\n Task task = new Task(parent, this);\n\n m_children.add(task);\n\n parent.getTasks().add(task);\n\n setSummary(true);\n\n return (task);\n }", "public static Region create(String name, String label) {\n Region region = VALUES_BY_NAME.get(name.toLowerCase());\n if (region != null) {\n return region;\n } else {\n return new Region(name, label);\n }\n }", "public static String getAggregatedResultHuman(Map<String, LinkedHashSet<String>> aggregateResultMap){\n\n StringBuilder res = new StringBuilder();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n LinkedHashSet<String> valueSet = entry.getValue(); \n res.append(\"[\" + entry.getKey() + \" COUNT: \" +valueSet.size() + \" ]:\\n\");\n for(String str: valueSet){\n res.append(\"\\t\" + str + \"\\n\");\n }\n res.append(\"###################################\\n\\n\");\n }\n \n return res.toString();\n \n }", "static Parameter createParameter(final String name, final String value) {\n if (value != null && isQuoted(value)) {\n return new QuotedParameter(name, value);\n }\n return new Parameter(name, value);\n }", "private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}", "public static String marshal(Object object) {\n if (object == null) {\n return null;\n }\n\n try {\n JAXBContext jaxbCtx = JAXBContext.newInstance(object.getClass());\n\n Marshaller marshaller = jaxbCtx.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n\n StringWriter sw = new StringWriter();\n marshaller.marshal(object, sw);\n\n return sw.toString();\n } catch (Exception e) {\n }\n\n return null;\n }", "public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {\r\n String[] coVariables = action.getCoVariables().split(\",\");\r\n int n = Integer.valueOf(action.getN());\n\r\n List<Map<String, String>> newPossibleStateList = new ArrayList<>();\n\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n Map<String, String[]> variableDomains = new HashMap<>();\r\n Map<String, String> defaultVariableValues = new HashMap<>();\r\n for (String variable : coVariables) {\r\n String variableMetaInfo = possibleState.get(variable);\r\n String[] variableDomain = variableMetaInfo.split(\",\");\r\n variableDomains.put(variable, variableDomain);\r\n defaultVariableValues.put(variable, variableDomain[0]);\r\n }\n\r\n List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);\r\n for (Map<String, String> nWiseCombination : nWiseCombinations) {\r\n Map<String, String> newPossibleState = new HashMap<>(possibleState);\r\n newPossibleState.putAll(defaultVariableValues);\r\n newPossibleState.putAll(nWiseCombination);\r\n newPossibleStateList.add(newPossibleState);\r\n }\r\n }\n\r\n return newPossibleStateList;\r\n }", "private String getDurationString(Duration value)\n {\n String result = null;\n\n if (value != null)\n {\n double seconds = 0;\n\n switch (value.getUnits())\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n seconds = value.getDuration() * 60;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n seconds = value.getDuration() * (60 * 60);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n seconds = value.getDuration() * (minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n seconds = value.getDuration() * (24 * 60 * 60);\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = m_projectFile.getProjectProperties().getMinutesPerWeek().doubleValue();\n seconds = value.getDuration() * (minutesPerWeek * 60);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n seconds = value.getDuration() * (7 * 24 * 60 * 60);\n break;\n }\n\n case MONTHS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n seconds = value.getDuration() * (30 * 24 * 60 * 60);\n break;\n }\n\n case YEARS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (12 * daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n seconds = value.getDuration() * (365 * 24 * 60 * 60);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n result = Long.toString((long) seconds);\n }\n\n return (result);\n }", "private int getMaxHeight() {\n int result = 0;\n for (int i = 0; i < segmentCount; i++) {\n result = Math.max(result, segmentHeight(i, false));\n }\n return result;\n }" ]
Find the index of the first matching element in the list @param element the element value to find @return the index of the first matching element, or <code>-1</code> if none found
[ "public long indexOf(final String element) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return doIndexOf(jedis, element);\n }\n });\n }" ]
[ "public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }", "@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }", "public static double huntKennedyCMSOptionValue(\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 a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble valueUnadjusted\t= blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t\tdouble valueAdjusted\t= blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);\n\n\t\treturn a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;\n\t}", "private static void readAndAddDocumentsFromStream(\n final SolrClient client,\n final String lang,\n final InputStream is,\n final List<SolrInputDocument> documents,\n final boolean closeStream) {\n\n final BufferedReader br = new BufferedReader(new InputStreamReader(is));\n\n try {\n String line = br.readLine();\n while (null != line) {\n\n final SolrInputDocument document = new SolrInputDocument();\n // Each field is named after the schema \"entry_xx\" where xx denotes\n // the two digit language code. See the file spellcheck/conf/schema.xml.\n document.addField(\"entry_\" + lang, line);\n documents.add(document);\n\n // Prevent OutOfMemoryExceptions ...\n if (documents.size() >= MAX_LIST_SIZE) {\n addDocuments(client, documents, false);\n documents.clear();\n }\n\n line = br.readLine();\n }\n } catch (IOException e) {\n LOG.error(\"Could not read spellcheck dictionary from input stream.\");\n } catch (SolrServerException e) {\n LOG.error(\"Error while adding documents to Solr server. \");\n } finally {\n try {\n if (closeStream) {\n br.close();\n }\n } catch (Exception e) {\n // Nothing to do here anymore ....\n }\n }\n }", "public int compare(Vector3 o1, Vector3 o2) {\n\t\tint ans = 0;\n\n\t\tif (o1 != null && o2 != null) {\n\t\t\tVector3 d1 = o1;\n\t\t\tVector3 d2 = o2;\n\n\t\t\tif (d1.x > d2.x)\n\t\t\t\treturn 1;\n\t\t\tif (d1.x < d2.x)\n\t\t\t\treturn -1;\n\t\t\t// x1 == x2\n\t\t\tif (d1.y > d2.y)\n\t\t\t\treturn 1;\n\t\t\tif (d1.y < d2.y)\n\t\t\t\treturn -1;\n\t\t} else {\n\t\t\tif (o1 == null && o2 == null)\n\t\t\t\treturn 0;\n\t\t\tif (o1 == null && o2 != null)\n\t\t\t\treturn 1;\n\t\t\tif (o1 != null && o2 == null)\n\t\t\t\treturn -1;\n\t\t}\n\t\t\n\t\treturn ans;\n\t}", "public static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {\n StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);\n for (String kp : keyPrefix) {\n prefix.append('.').append(kp);\n }\n return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, LoggingExtension.class.getClassLoader(), true, false) {\n @Override\n public String getOperationParameterDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDescription(operationName, paramName, locale, bundle);\n }\n\n @Override\n public String getOperationParameterValueTypeDescription(final String operationName, final String paramName, final Locale locale,\n final ResourceBundle bundle, final String... suffixes) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterValueTypeDescription(operationName, paramName, locale, bundle, suffixes);\n }\n\n @Override\n public String getOperationParameterDeprecatedDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDeprecatedDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDeprecatedDescription(operationName, paramName, locale, bundle);\n }\n };\n }", "public static AccumuloClient getClient(FluoConfiguration config) {\n return Accumulo.newClient().to(config.getAccumuloInstance(), config.getAccumuloZookeepers())\n .as(config.getAccumuloUser(), config.getAccumuloPassword()).build();\n }", "public void fire(StepStartedEvent event) {\n Step step = new Step();\n event.process(step);\n stepStorage.put(step);\n\n notifier.fire(event);\n }", "public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\n }" ]
Set the start time. @param date the start time to set.
[ "public void setStartTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getStart(), date)) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setStart(date);\r\n setPatternDefaultValues(date);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }" ]
[ "private static boolean equalAsInts(Vec2d a, Vec2d b) {\n return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y);\n }", "public static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader) throws SQLException {\n\t\tList<DatabaseTableConfig<?>> list = new ArrayList<DatabaseTableConfig<?>>();\n\t\twhile (true) {\n\t\t\tDatabaseTableConfig<?> config = DatabaseTableConfigLoader.fromReader(reader);\n\t\t\tif (config == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlist.add(config);\n\t\t}\n\t\treturn list;\n\t}", "public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {\n // We can't detect if their codecRegistry has any duplicate providers. There's also a chance\n // that putting ours first may prevent decoding of some of their classes if for example they\n // have their own way of decoding an Integer.\n final CodecRegistry newReg =\n CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);\n return new StitchObjectMapper(this, newReg);\n }", "@Override\n\tpublic boolean addAll(Collection<? extends T> collection) {\n\t\tboolean changed = false;\n\t\tfor (T data : collection) {\n\t\t\ttry {\n\t\t\t\tif (addElement(data)) {\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not create data elements in dao\", e);\n\t\t\t}\n\t\t}\n\t\treturn changed;\n\t}", "@OnClick(R.id.navigateToSampleActivity)\n public void onSampleActivityCTAClick() {\n StringParcel parcel1 = new StringParcel(\"Andy\");\n StringParcel parcel2 = new StringParcel(\"Tony\");\n\n List<StringParcel> parcelList = new ArrayList<>();\n parcelList.add(parcel1);\n parcelList.add(parcel2);\n\n SparseArray<StringParcel> parcelSparseArray = new SparseArray<>();\n parcelSparseArray.put(0, parcel1);\n parcelSparseArray.put(2, parcel2);\n\n Intent intent = HensonNavigator.gotoSampleActivity(this)\n .defaultKeyExtra(\"defaultKeyExtra\")\n .extraInt(4)\n .extraListParcelable(parcelList)\n .extraParcel(parcel1)\n .extraParcelable(ComplexParcelable.random())\n .extraSparseArrayParcelable(parcelSparseArray)\n .extraString(\"a string\")\n .build();\n\n startActivity(intent);\n }", "private static ClosableIterator<Tuple> doDistinct(final MongoDBQueryDescriptor queryDescriptor, final MongoCollection<Document> collection) {\n\t\tDistinctIterable<?> distinctFieldValues = collection.distinct( queryDescriptor.getDistinctFieldName(), queryDescriptor.getCriteria(), String.class );\n\t\tCollation collation = getCollation( queryDescriptor.getOptions() );\n\n\t\tdistinctFieldValues = collation != null ? distinctFieldValues.collation( collation ) : distinctFieldValues;\n\n\t\tMongoCursor<?> cursor = distinctFieldValues.iterator();\n\t\tList<Object> documents = new ArrayList<>();\n\t\twhile ( cursor.hasNext() ) {\n\t\t\tdocuments.add( cursor.next() );\n\t\t}\n\t\tMapTupleSnapshot snapshot = new MapTupleSnapshot( Collections.<String, Object>singletonMap( \"n\", documents ) );\n\t\treturn CollectionHelper.newClosableIterator( Collections.singletonList( new Tuple( snapshot, SnapshotType.UNKNOWN ) ) );\n\t}", "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 }", "private void listGreetings(String guestbookName) throws DatastoreException {\n Query.Builder query = Query.newBuilder();\n query.addKindBuilder().setName(GREETING_KIND);\n query.setFilter(makeFilter(KEY_PROPERTY, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(makeKey(GUESTBOOK_KIND, guestbookName))));\n query.addOrder(makeOrder(DATE_PROPERTY, PropertyOrder.Direction.DESCENDING));\n\n List<Entity> greetings = runQuery(query.build());\n if (greetings.size() == 0) {\n System.out.println(\"no greetings in \" + guestbookName);\n }\n for (Entity greeting : greetings) {\n Map<String, Value> propertyMap = greeting.getProperties();\n System.out.println(\n DatastoreHelper.toDate(propertyMap.get(DATE_PROPERTY)) + \": \" +\n DatastoreHelper.getString(propertyMap.get(USER_PROPERTY)) + \" says \" +\n DatastoreHelper.getString(propertyMap.get(MESSAGE_PROPERTY)));\n }\n }", "public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }" ]
Handle the given response, return the deserialized object when the response is successful. @param <T> Type @param response Response @param returnType Return type @throws ApiException If the response has a unsuccessful status code or fail to deserialize the response body @return Type
[ "public <T> T handleResponse(Response response, Type returnType) throws ApiException {\n if (response.isSuccessful()) {\n if (returnType == null || response.code() == 204) {\n // returning null if the returnType is not defined,\n // or the status code is 204 (No Content)\n return null;\n } else {\n return deserialize(response, returnType);\n }\n } else {\n String respBody = null;\n if (response.body() != null) {\n try {\n respBody = response.body().string();\n } catch (IOException e) {\n throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());\n }\n }\n throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);\n }\n }" ]
[ "private I_CmsSearchIndex getIndex() {\n\n I_CmsSearchIndex index = null;\n // get the configured index or the selected index\n if (isInitialCall()) {\n // the search form is in the initial state\n // get the configured index\n index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName());\n } else {\n // the search form is not in the inital state, the submit button was used already or the\n // search index was changed already\n // get the selected index in the search dialog\n index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter(\"indexName.0\"));\n }\n return index;\n }", "@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }", "private void initComponents(List<CmsSetupComponent> components) {\n\n for (CmsSetupComponent component : components) {\n CheckBox checkbox = new CheckBox();\n checkbox.setValue(component.isChecked());\n checkbox.setCaption(component.getName() + \" - \" + component.getDescription());\n checkbox.setDescription(component.getDescription());\n checkbox.setData(component);\n checkbox.setWidth(\"100%\");\n m_components.addComponent(checkbox);\n m_componentCheckboxes.add(checkbox);\n m_componentMap.put(component.getId(), component);\n\n }\n }", "private PlayState3 findPlayState3() {\n PlayState3 result = PLAY_STATE_3_MAP.get(packetBytes[157]);\n if (result == null) {\n return PlayState3.UNKNOWN;\n }\n return result;\n }", "private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day)\n {\n ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate());\n if (day.isIsDayWorking())\n {\n for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n mpxjException.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }", "protected boolean isSlopDead(Cluster cluster, Set<String> storeNames, Slop slop) {\n // destination node , no longer exists\n if(!cluster.getNodeIds().contains(slop.getNodeId())) {\n return true;\n }\n\n // destination store, no longer exists\n if(!storeNames.contains(slop.getStoreName())) {\n return true;\n }\n\n // else. slop is alive\n return false;\n }", "public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }", "public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "public Search groupField(String fieldName, boolean isNumber) {\r\n assertNotEmpty(fieldName, \"fieldName\");\r\n if (isNumber) {\r\n databaseHelper.query(\"group_field\", fieldName + \"<number>\");\r\n } else {\r\n databaseHelper.query(\"group_field\", fieldName);\r\n }\r\n return this;\r\n }" ]
Extract Primavera project data and export in another format. @param driverClass JDBC driver class name @param connectionString JDBC connection string @param projectID project ID @param outputFile output file @throws Exception
[ "public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }" ]
[ "public String convertToReadableDate(Holiday holiday) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n\n if (holiday.isInDateForm()) {\n String month = Integer.toString(holiday.getMonth()).length() < 2\n ? \"0\" + holiday.getMonth() : Integer.toString(holiday.getMonth());\n String day = Integer.toString(holiday.getDayOfMonth()).length() < 2\n ? \"0\" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth());\n return holiday.getYear() + \"-\" + month + \"-\" + day;\n } else {\n /*\n * 5 denotes the final occurrence of the day in the month. Need to find actual\n * number of occurrences\n */\n if (holiday.getOccurrence() == 5) {\n holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(),\n holiday.getDayOfWeek()));\n }\n\n DateTime date = parser.parseDateTime(holiday.getYear() + \"-\"\n + holiday.getMonth() + \"-\" + \"01\");\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date.toDate());\n int count = 0;\n\n while (count < holiday.getOccurrence()) {\n if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) {\n count++;\n if (count == holiday.getOccurrence()) {\n break;\n }\n }\n date = date.plusDays(1);\n calendar.setTime(date.toDate());\n }\n return date.toString().substring(0, 10);\n }\n }", "protected Path normalizePath(final Path parent, final String path) {\n return parent.resolve(path).toAbsolutePath().normalize();\n }", "private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) {\n String fileName = file.getAbsolutePath().replace(\"\\\\\", \"/\");\n return fileName.substring(classPathRootOnDisk.length());\n }", "public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\n }", "public static boolean streamHasText(InputStream in, String text) {\n final byte[] readBuffer = new byte[8192];\n\n StringBuffer sb = new StringBuffer();\n try {\n if (in.available() > 0) {\n int bytesRead = 0;\n while ((bytesRead = in.read(readBuffer)) != -1) {\n sb.append(new String(readBuffer, 0, bytesRead));\n\n if (sb.toString().contains(text)) {\n sb = null;\n return true;\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return false;\n }", "public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }", "public void afterCompletion(int status)\r\n {\r\n if(afterCompletionCall) return;\r\n\r\n log.info(\"Method afterCompletion was called\");\r\n try\r\n {\r\n switch(status)\r\n {\r\n case Status.STATUS_COMMITTED:\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Method afterCompletion: Do commit internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n }\r\n commit();\r\n break;\r\n default:\r\n log.error(\"Method afterCompletion: Do abort call on internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n abort();\r\n }\r\n }\r\n finally\r\n {\r\n afterCompletionCall = true;\r\n log.info(\"Method afterCompletion finished\");\r\n }\r\n }", "private String trim(String line) {\n char[] chars = line.toCharArray();\n int len = chars.length;\n\n while (len > 0) {\n if (!Character.isWhitespace(chars[len - 1])) {\n break;\n }\n len--;\n }\n\n return line.substring(0, len);\n }", "@Override\n public <X> X getScreenshotAs(OutputType<X> target) {\n // Get the screenshot as base64 and convert it to the requested type (i.e. OutputType<T>)\n String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();\n return target.convertFromBase64Png(base64);\n }" ]
Writes an untagged OK response, with the supplied response code, and an optional message. @param responseCode The response code, included in []. @param message The message to follow the []
[ "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 <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }", "public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }", "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 }", "private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}", "public void setFileFormat(String fileFormat) {\n\n if (fileFormat.toUpperCase().equals(FileFormat.JSON.toString())) {\n m_fileFormat = FileFormat.JSON;\n }\n }", "private static synchronized boolean isLog4JConfigured()\r\n {\r\n if(!log4jConfigured)\r\n {\r\n Enumeration en = org.apache.log4j.Logger.getRootLogger().getAllAppenders();\r\n\r\n if (!(en instanceof org.apache.log4j.helpers.NullEnumeration))\r\n {\r\n log4jConfigured = true;\r\n }\r\n else\r\n {\r\n Enumeration cats = LogManager.getCurrentLoggers();\r\n while (cats.hasMoreElements())\r\n {\r\n org.apache.log4j.Logger c = (org.apache.log4j.Logger) cats.nextElement();\r\n if (!(c.getAllAppenders() instanceof org.apache.log4j.helpers.NullEnumeration))\r\n {\r\n log4jConfigured = true;\r\n }\r\n }\r\n }\r\n if(log4jConfigured)\r\n {\r\n String msg = \"Log4J is already configured, will not search for log4j properties file\";\r\n LoggerFactory.getBootLogger().info(msg);\r\n }\r\n else\r\n {\r\n LoggerFactory.getBootLogger().info(\"Log4J is not configured\");\r\n }\r\n }\r\n return log4jConfigured;\r\n }", "private void processPredecessors(Gantt gantt)\n {\n for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())\n {\n String predecessors = ganttTask.getP();\n if (predecessors != null && !predecessors.isEmpty())\n {\n String wbs = ganttTask.getID();\n Task task = m_taskMap.get(wbs);\n for (String predecessor : predecessors.split(\";\"))\n {\n Task predecessorTask = m_projectFile.getTaskByID(Integer.valueOf(predecessor));\n task.addPredecessor(predecessorTask, RelationType.FINISH_START, ganttTask.getL());\n }\n }\n }\n }", "@Override\n public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type)\n {\n pipelineCriteria.add(new QueryGremlinCriterion()\n {\n @Override\n public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline)\n {\n pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get()));\n }\n });\n return this;\n }", "private long getTotalUploadSize() throws IOException {\n long size = 0;\n for (Map.Entry<String, File> entry : files.entrySet()) {\n size += entry.getValue().length();\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n size += entry.getValue().available();\n }\n return size;\n }" ]
Create a text message that will be stored in the database. Must be called inside a transaction.
[ "static void createMessage(String textMessage, JobInstance jobInstance, DbConn cnx)\n {\n cnx.runUpdate(\"message_insert\", jobInstance.getId(), textMessage);\n }" ]
[ "public Entry<T>[] entries() {\n @SuppressWarnings(\"unchecked\")\n Entry<T>[] entries = new Entry[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n entries[idx++] = entry;\n entry = entry.next;\n }\n }\n return entries;\n }", "public static int countTrue(BMatrixRMaj A) {\n int total = 0;\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n if( A.data[i] )\n total++;\n }\n\n return total;\n }", "public Collection<License> getInfo() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n List<License> licenses = new ArrayList<License>();\r\n Element licensesElement = response.getPayload();\r\n NodeList licenseElements = licensesElement.getElementsByTagName(\"license\");\r\n for (int i = 0; i < licenseElements.getLength(); i++) {\r\n Element licenseElement = (Element) licenseElements.item(i);\r\n License license = new License();\r\n license.setId(licenseElement.getAttribute(\"id\"));\r\n license.setName(licenseElement.getAttribute(\"name\"));\r\n license.setUrl(licenseElement.getAttribute(\"url\"));\r\n licenses.add(license);\r\n }\r\n return licenses;\r\n }", "public void writeNameValuePair(String name, double value) throws IOException\n {\n internalWriteNameValuePair(name, Double.toString(value));\n }", "private Object toReference(int type, Object referent, int hash)\r\n {\r\n switch (type)\r\n {\r\n case HARD:\r\n return referent;\r\n case SOFT:\r\n return new SoftRef(hash, referent, queue);\r\n case WEAK:\r\n return new WeakRef(hash, referent, queue);\r\n default:\r\n throw new Error();\r\n }\r\n }", "private void deliverMountUpdate(SlotReference slot, boolean mounted) {\n if (mounted) {\n logger.info(\"Reporting media mounted in \" + slot);\n\n } else {\n logger.info(\"Reporting media removed from \" + slot);\n }\n for (final MountListener listener : getMountListeners()) {\n try {\n if (mounted) {\n listener.mediaMounted(slot);\n } else {\n listener.mediaUnmounted(slot);\n }\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering mount update to listener\", t);\n }\n }\n if (mounted) {\n MetadataCache.tryAutoAttaching(slot);\n }\n }", "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 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 final Bytes of(CharSequence cs) {\n if (cs instanceof String) {\n return of((String) cs);\n }\n\n Objects.requireNonNull(cs);\n if (cs.length() == 0) {\n return EMPTY;\n }\n\n ByteBuffer bb = StandardCharsets.UTF_8.encode(CharBuffer.wrap(cs));\n\n if (bb.hasArray()) {\n // this byte buffer has never escaped so can use its byte array directly\n return new Bytes(bb.array(), bb.position() + bb.arrayOffset(), bb.limit());\n } else {\n byte[] data = new byte[bb.remaining()];\n bb.get(data);\n return new Bytes(data);\n }\n }" ]
Copies from buffer to our internal strBufferIndex, expanding the internal buffer if necessary @param offset offset in the buffer to start copying from @param length length to copy
[ "private void copyToStrBuffer(byte[] buffer, int offset, int length) {\n Preconditions.checkArgument(length >= 0);\n if (strBuffer.length - strBufferIndex < length) {\n // cannot fit, expanding buffer\n expandStrBuffer(length);\n }\n System.arraycopy(\n buffer, offset, strBuffer, strBufferIndex, Math.min(length, MAX_ALLOWABLE_BUFFER_SIZE - strBufferIndex));\n strBufferIndex += length;\n }" ]
[ "public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }", "private void emit(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n float[] allParticlePositions = new float[particlePositions.length + particleBoundingVolume.length];\n System.arraycopy(particlePositions, 0, allParticlePositions, 0, particlePositions.length);\n System.arraycopy(particleBoundingVolume, 0, allParticlePositions,\n particlePositions.length, particleBoundingVolume.length);\n\n float[] allSpawnTimes = new float[particleTimeStamps.length + BVSpawnTimes.length];\n System.arraycopy(particleTimeStamps, 0, allSpawnTimes, 0, particleTimeStamps.length);\n System.arraycopy(BVSpawnTimes, 0, allSpawnTimes, particleTimeStamps.length, BVSpawnTimes.length);\n\n float[] allParticleVelocities = new float[particleVelocities.length + BVVelocities.length];\n System.arraycopy(particleVelocities, 0, allParticleVelocities, 0, particleVelocities.length);\n System.arraycopy(BVVelocities, 0, allParticleVelocities, particleVelocities.length, BVVelocities.length);\n\n\n Particles particleMesh = new Particles(mGVRContext, mMaxAge,\n mParticleSize, mEnvironmentAcceleration, mParticleSizeRate, mFadeWithAge,\n mParticleTexture, mColor, mNoiseFactor);\n\n\n GVRSceneObject particleObject = particleMesh.makeParticleMesh(allParticlePositions,\n allParticleVelocities, allSpawnTimes);\n\n this.addChildObject(particleObject);\n meshInfo.add(Pair.create(particleObject, currTime));\n }", "String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }", "String generateSynopsis() {\n synopsisOptions = buildSynopsisOptions(opts, arg, domain);\n StringBuilder synopsisBuilder = new StringBuilder();\n if (parentName != null) {\n synopsisBuilder.append(parentName).append(\" \");\n }\n synopsisBuilder.append(commandName);\n if (isOperation && !opts.isEmpty()) {\n synopsisBuilder.append(\"(\");\n } else {\n synopsisBuilder.append(\" \");\n }\n boolean hasOptions = arg != null || !opts.isEmpty();\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" [\");\n }\n if (hasActions) {\n synopsisBuilder.append(\" <action>\");\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ] || [\");\n }\n SynopsisOption opt;\n while ((opt = retrieveNextOption(synopsisOptions, false)) != null) {\n String content = addSynopsisOption(opt);\n if (content != null) {\n synopsisBuilder.append(content.trim());\n if (isOperation) {\n if (!synopsisOptions.isEmpty()) {\n synopsisBuilder.append(\",\");\n } else {\n synopsisBuilder.append(\")\");\n }\n }\n synopsisBuilder.append(\" \");\n }\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ]\");\n }\n return synopsisBuilder.toString();\n }", "public static void unsetCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)\r\n throws PBFactoryException\r\n {\r\n HashMap map = (HashMap) currentBrokerMap.get();\r\n WeakHashMap set = null;\r\n if(map != null)\r\n {\r\n set = (WeakHashMap) map.get(key);\r\n if(set != null)\r\n {\r\n set.remove(broker);\r\n if(set.isEmpty())\r\n {\r\n map.remove(key);\r\n }\r\n }\r\n if(map.isEmpty())\r\n {\r\n currentBrokerMap.set(null);\r\n synchronized(lock) {\r\n loadedHMs.remove(map);\r\n }\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 Duration getDuration(Double duration)\n {\n Duration result = null;\n\n if (duration != null)\n {\n result = Duration.getInstance(NumberHelper.getDouble(duration), TimeUnit.HOURS);\n }\n\n return result;\n }", "public void writeLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock writeLock = lock.writeLock();\n\t\tacquireLock( key, timeout, writeLock );\n\t}", "private JSONObject getJsonFormattedSpellcheckResult(CmsSpellcheckingRequest request) {\n\n final JSONObject response = new JSONObject();\n\n try {\n if (null != request.m_id) {\n response.put(JSON_ID, request.m_id);\n }\n\n response.put(JSON_RESULT, request.m_wordSuggestions);\n\n } catch (Exception e) {\n try {\n response.put(JSON_ERROR, true);\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", e);\n } catch (JSONException ex) {\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", ex);\n }\n }\n\n return response;\n }" ]
Fills in the element with the InputValues for input @param element the node element @param input the input data
[ "protected void setInputElementValue(Node element, FormInput input) {\n\n\t\tLOGGER.debug(\"INPUTFIELD: {} ({})\", input.getIdentification(), input.getType());\n\t\tif (element == null || input.getInputValues().isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\n\t\t\tswitch (input.getType()) {\n\t\t\t\tcase TEXT:\n\t\t\t\tcase TEXTAREA:\n\t\t\t\tcase PASSWORD:\n\t\t\t\t\thandleText(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase HIDDEN:\n\t\t\t\t\thandleHidden(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHECKBOX:\n\t\t\t\t\thandleCheckBoxes(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase RADIO:\n\t\t\t\t\thandleRadioSwitches(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SELECT:\n\t\t\t\t\thandleSelectBoxes(input);\n\t\t\t}\n\n\t\t} catch (ElementNotVisibleException e) {\n\t\t\tLOGGER.warn(\"Element not visible, input not completed.\");\n\t\t} catch (BrowserConnectionException e) {\n\t\t\tthrow e;\n\t\t} catch (RuntimeException e) {\n\t\t\tLOGGER.error(\"Could not input element values\", e);\n\t\t}\n\t}" ]
[ "static boolean uninstall() {\n boolean uninstalled = false;\n synchronized (lock) {\n if (locationCollectionClient != null) {\n locationCollectionClient.locationEngineController.onDestroy();\n locationCollectionClient.settingsChangeHandlerThread.quit();\n locationCollectionClient.sharedPreferences.unregisterOnSharedPreferenceChangeListener(locationCollectionClient);\n locationCollectionClient = null;\n uninstalled = true;\n }\n }\n return uninstalled;\n }", "@RequestMapping(value=\"/{subscription}\", method=GET, params=\"hub.mode=subscribe\")\n\tpublic @ResponseBody String verifySubscription(\n\t\t\t@PathVariable(\"subscription\") String subscription,\n\t\t\t@RequestParam(\"hub.challenge\") String challenge,\n\t\t\t@RequestParam(\"hub.verify_token\") String verifyToken) {\n\t\tlogger.debug(\"Received subscription verification request for '\" + subscription + \"'.\");\n\t\treturn tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : \"\";\n\t}", "protected float getLayoutOffset() {\n //final int offsetSign = getOffsetSign();\n final float axisSize = getViewPortSize(getOrientationAxis());\n float layoutOffset = - axisSize / 2;\n Log.d(LAYOUT, TAG, \"getLayoutOffset(): dimension: %5.2f, layoutOffset: %5.2f\",\n axisSize, layoutOffset);\n\n return layoutOffset;\n }", "public static File createTempDirectory(String prefix) {\n\tFile temp = null;\n\t\n\ttry {\n\t temp = File.createTempFile(prefix != null ? prefix : \"temp\", Long.toString(System.nanoTime()));\n\t\n\t if (!(temp.delete())) {\n\t throw new IOException(\"Could not delete temp file: \"\n\t\t + temp.getAbsolutePath());\n\t }\n\t\n\t if (!(temp.mkdir())) {\n\t throw new IOException(\"Could not create temp directory: \"\n\t + temp.getAbsolutePath());\n\t }\n\t} catch (IOException e) {\n\t throw new DukeException(\"Unable to create temporary directory with prefix \" + prefix, e);\n\t}\n\t\n\treturn temp;\n }", "public Where<T, ID> between(String columnName, Object low, Object high) throws SQLException {\n\t\taddClause(new Between(columnName, findColumnFieldType(columnName), low, high));\n\t\treturn this;\n\t}", "public void check(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureColumn(fieldDef, checkLevel);\r\n ensureJdbcType(fieldDef, checkLevel);\r\n ensureConversion(fieldDef, checkLevel);\r\n ensureLength(fieldDef, checkLevel);\r\n ensurePrecisionAndScale(fieldDef, checkLevel);\r\n checkLocking(fieldDef, checkLevel);\r\n checkSequenceName(fieldDef, checkLevel);\r\n checkId(fieldDef, checkLevel);\r\n if (fieldDef.isAnonymous())\r\n {\r\n checkAnonymous(fieldDef, checkLevel);\r\n }\r\n else\r\n {\r\n checkReadonlyAccessForNativePKs(fieldDef, checkLevel);\r\n }\r\n }", "public static base_response add(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy addresource = new spilloverpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.comment = resource.comment;\n\t\treturn addresource.add_resource(client);\n\t}", "public AreaOfInterest copy() {\n AreaOfInterest aoi = new AreaOfInterest();\n aoi.display = this.display;\n aoi.area = this.area;\n aoi.polygon = this.polygon;\n aoi.style = this.style;\n aoi.renderAsSvg = this.renderAsSvg;\n return aoi;\n }", "private void precheckStateAllNull() throws IllegalStateException {\n if ((doubleValue != null) || (doubleArray != null)\n || (longValue != null) || (longArray != null)\n || (stringValue != null) || (stringArray != null)\n || (map != null)) {\n throw new IllegalStateException(\"Expected all properties to be empty: \" + this);\n }\n }" ]
Sends this request while monitoring its progress and returns a BoxAPIResponse containing the server's response. <p>A ProgressListener is generally only useful when the size of the request is known beforehand. If the size is unknown, then the ProgressListener will be updated for each byte sent, but the total number of bytes will be reported as 0.</p> <p> See {@link #send} for more information on sending requests.</p> @param listener a listener for monitoring the progress of the request. @throws BoxAPIException if the server returns an error code or if a network error occurs. @return a {@link BoxAPIResponse} containing the server's response.
[ "public BoxAPIResponse send(ProgressListener listener) {\n if (this.api == null) {\n this.backoffCounter.reset(BoxGlobalSettings.getMaxRequestAttempts());\n } else {\n this.backoffCounter.reset(this.api.getMaxRequestAttempts());\n }\n\n while (this.backoffCounter.getAttemptsRemaining() > 0) {\n try {\n return this.trySend(listener);\n } catch (BoxAPIException apiException) {\n if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {\n throw apiException;\n }\n\n try {\n this.resetBody();\n } catch (IOException ioException) {\n throw apiException;\n }\n\n try {\n this.backoffCounter.waitBackoff();\n } catch (InterruptedException interruptedException) {\n Thread.currentThread().interrupt();\n throw apiException;\n }\n }\n }\n\n throw new RuntimeException();\n }" ]
[ "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 void deleteLicense(final String licName) {\n final DbLicense dbLicense = getLicense(licName);\n\n repoHandler.deleteLicense(dbLicense.getName());\n\n final FiltersHolder filters = new FiltersHolder();\n final LicenseIdFilter licenseIdFilter = new LicenseIdFilter(licName);\n filters.addFilter(licenseIdFilter);\n\n for (final DbArtifact artifact : repoHandler.getArtifacts(filters)) {\n repoHandler.removeLicenseFromArtifact(artifact, licName, this);\n }\n }", "public void init(ServletContext context) {\n if (profiles != null) {\n for (IDiagramProfile profile : profiles) {\n profile.init(context);\n _registry.put(profile.getName(),\n profile);\n }\n }\n }", "@Override\r\n public String remove(Object key) {\r\n\r\n String result = m_configurationStrings.remove(key);\r\n m_configurationObjects.remove(key);\r\n return result;\r\n }", "public synchronized void stop(long quietPeriod, long timeout, TimeUnit unit) throws Exception {\n if (state == State.STOPPED) {\n LOG.debug(\"Ignore stop() call on HTTP service {} since it has already been stopped.\", serviceName);\n return;\n }\n\n LOG.info(\"Stopping HTTP Service {}\", serviceName);\n\n try {\n try {\n channelGroup.close().awaitUninterruptibly();\n } finally {\n try {\n shutdownExecutorGroups(quietPeriod, timeout, unit,\n bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup);\n } finally {\n resourceHandler.destroy(handlerContext);\n }\n }\n } catch (Throwable t) {\n state = State.FAILED;\n throw t;\n }\n state = State.STOPPED;\n LOG.debug(\"Stopped HTTP Service {} on address {}\", serviceName, bindAddress);\n }", "public static base_response enable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm enableresource = new snmpalarm();\n\t\tenableresource.trapname = trapname;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // check constraints now after all classes have been processed\r\n for (Iterator it = getClasses(); it.hasNext();)\r\n {\r\n ((ClassDescriptorDef)it.next()).checkConstraints(checkLevel);\r\n }\r\n // additional model constraints that either deal with bigger parts of the model or\r\n // can only be checked after the individual classes have been checked (e.g. specific\r\n // attributes have been ensured)\r\n new ModelConstraints().check(this, checkLevel);\r\n }", "public static final String getString(byte[] data, int offset)\n {\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int loop = 0; offset + loop < data.length; loop++)\n {\n c = (char) data[offset + loop];\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }", "public final File getBuildFileFor(\n final Configuration configuration, final File jasperFileXml,\n final String extension, final Logger logger) {\n final String configurationAbsolutePath = configuration.getDirectory().getPath();\n final int prefixToConfiguration = configurationAbsolutePath.length() + 1;\n final String parentDir = jasperFileXml.getAbsoluteFile().getParent();\n final String relativePathToFile;\n if (configurationAbsolutePath.equals(parentDir)) {\n relativePathToFile = FilenameUtils.getBaseName(jasperFileXml.getName());\n } else {\n final String relativePathToContainingDirectory = parentDir.substring(prefixToConfiguration);\n relativePathToFile = relativePathToContainingDirectory + File.separator +\n FilenameUtils.getBaseName(jasperFileXml.getName());\n }\n\n final File buildFile = new File(getJasperCompilation(configuration), relativePathToFile + extension);\n\n if (!buildFile.getParentFile().exists() && !buildFile.getParentFile().mkdirs()) {\n logger.error(\"Unable to create directory for containing compiled jasper report templates: {}\",\n buildFile.getParentFile());\n }\n return buildFile;\n }" ]
Calculate start dates for a monthly absolute recurrence. @param calendar current date @param frequency frequency @param dates array of start dates
[ "private void getMonthlyAbsoluteDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDayNumber = calendar.get(Calendar.DAY_OF_MONTH);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int requiredDayNumber = NumberHelper.getInt(m_dayNumber);\n if (requiredDayNumber < currentDayNumber)\n {\n calendar.add(Calendar.MONTH, 1);\n }\n\n while (moreDates(calendar, dates))\n {\n int useDayNumber = requiredDayNumber;\n int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n if (useDayNumber > maxDayNumber)\n {\n useDayNumber = maxDayNumber;\n }\n calendar.set(Calendar.DAY_OF_MONTH, useDayNumber);\n dates.add(calendar.getTime());\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }" ]
[ "public static Multimap<String, String> getParameters(final String rawQuery) {\n Multimap<String, String> result = HashMultimap.create();\n if (rawQuery == null) {\n return result;\n }\n\n StringTokenizer tokens = new StringTokenizer(rawQuery, \"&\");\n while (tokens.hasMoreTokens()) {\n String pair = tokens.nextToken();\n int pos = pair.indexOf('=');\n String key;\n String value;\n if (pos == -1) {\n key = pair;\n value = \"\";\n } else {\n\n try {\n key = URLDecoder.decode(pair.substring(0, pos), \"UTF-8\");\n value = URLDecoder.decode(pair.substring(pos + 1), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n\n result.put(key, value);\n }\n return result;\n }", "public static void mergeHints(InputStream is, Map<String,List<Long>> hints) throws IOException {\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(is, Charsets.UTF_8));\n \n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\"))\n continue;\n\n final int equals = line.indexOf('=');\n if (equals <= 0) {\n throw new IOException(\"No '=' character on a non-comment line?: \" + line);\n } else {\n String key = line.substring(0, equals);\n List<Long> values = hints.get(key);\n if (values == null) {\n hints.put(key, values = new ArrayList<>());\n }\n for (String v : line.substring(equals + 1).split(\"[\\\\,]\")) {\n if (!v.isEmpty()) values.add(Long.parseLong(v));\n }\n }\n }\n }", "public static String getTabularData(String[] labels, String[][] data, int padding) {\n int[] size = new int[labels.length];\n \n for (int i = 0; i < labels.length; i++) {\n size[i] = labels[i].length() + padding;\n }\n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n if (row[i].length() >= size[i]) {\n size[i] = row[i].length() + padding;\n }\n }\n }\n \n StringBuffer tabularData = new StringBuffer();\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(labels[i]);\n tabularData.append(fill(' ', size[i] - labels[i].length()));\n }\n \n tabularData.append(\"\\n\");\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(fill('=', size[i] - 1)).append(\" \");\n }\n \n tabularData.append(\"\\n\");\n \n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n tabularData.append(row[i]);\n tabularData.append(fill(' ', size[i] - row[i].length()));\n }\n \n tabularData.append(\"\\n\");\n }\n \n return tabularData.toString();\n }", "private void writeAssignments(Project project)\n {\n Project.Assignments assignments = m_factory.createProjectAssignments();\n project.setAssignments(assignments);\n List<Project.Assignments.Assignment> list = assignments.getAssignment();\n\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n list.add(writeAssignment(assignment));\n }\n\n //\n // Check to see if we have any tasks that have a percent complete value\n // but do not have resource assignments. If any exist, then we must\n // write a dummy resource assignment record to ensure that the MSPDI\n // file shows the correct percent complete amount for the task.\n //\n ProjectConfig config = m_projectFile.getProjectConfig();\n boolean autoUniqueID = config.getAutoAssignmentUniqueID();\n if (!autoUniqueID)\n {\n config.setAutoAssignmentUniqueID(true);\n }\n\n for (Task task : m_projectFile.getTasks())\n {\n double percentComplete = NumberHelper.getDouble(task.getPercentageComplete());\n if (percentComplete != 0 && task.getResourceAssignments().isEmpty() == true)\n {\n ResourceAssignment dummy = new ResourceAssignment(m_projectFile, task);\n Duration duration = task.getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.HOURS);\n }\n double durationValue = duration.getDuration();\n TimeUnit durationUnits = duration.getUnits();\n double actualWork = (durationValue * percentComplete) / 100;\n double remainingWork = durationValue - actualWork;\n\n dummy.setResourceUniqueID(NULL_RESOURCE_ID);\n dummy.setWork(duration);\n dummy.setActualWork(Duration.getInstance(actualWork, durationUnits));\n dummy.setRemainingWork(Duration.getInstance(remainingWork, durationUnits));\n \n // Without this, MS Project will mark a 100% complete milestone as 99% complete\n if (percentComplete == 100 && duration.getDuration() == 0)\n { \n dummy.setActualFinish(task.getActualStart());\n }\n \n list.add(writeAssignment(dummy));\n }\n }\n\n config.setAutoAssignmentUniqueID(autoUniqueID);\n }", "public static Collection<String> getFormatProviderNames() {\n Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(\n () -> new MonetaryException(\n \"No MonetaryFormatsSingletonSpi loaded, query functionality is not available.\"))\n .getProviderNames();\n if (Objects.isNull(providers)) {\n Logger.getLogger(MonetaryFormats.class.getName()).warning(\n \"No supported rate/conversion providers returned by SPI: \" +\n getMonetaryFormatsSpi().getClass().getName());\n return Collections.emptySet();\n }\n return providers;\n }", "public static Filter.Builder makeAncestorFilter(Key ancestor) {\n return makeFilter(\n DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(ancestor));\n }", "protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\n }", "private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }", "private Set<Annotation> getFieldAnnotations(final Class<?> clazz)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn new LinkedHashSet<Annotation>(asList(clazz.getDeclaredField(propertyName).getAnnotations()));\n\t\t}\n\t\tcatch (final NoSuchFieldException e)\n\t\t{\n\t\t\tif (clazz.getSuperclass() != null)\n\t\t\t{\n\t\t\t\treturn getFieldAnnotations(clazz.getSuperclass());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogger.debug(\"Cannot find propertyName: {}, declaring class: {}\", propertyName, clazz);\n\t\t\t\treturn new LinkedHashSet<Annotation>(0);\n\t\t\t}\n\t\t}\n\t}" ]
Places a new value at the end of the existing value array, increasing the field length accordingly. @param newValue - the 2 floats making the new SFVec2f appended to the MFVec2f array list
[ "public void append(float[] newValue) {\n if ( (newValue.length % 2) == 0) {\n for (int i = 0; i < (newValue.length/2); i++) {\n value.add( new SFVec2f(newValue[i*2], newValue[i*2+1]) );\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec3f append set with array length not divisible by 2\");\n }\n }" ]
[ "public static base_response clear(nitro_service client, route6 resource) throws Exception {\n\t\troute6 clearresource = new route6();\n\t\tclearresource.routetype = resource.routetype;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public static boolean start(RootDoc root) {\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", running the standard doclet\");\n\tStandard.start(root);\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", altering javadocs\");\n\ttry {\n\t String outputFolder = findOutputPath(root.options());\n\n Options opt = UmlGraph.buildOptions(root);\n\t opt.setOptions(root.options());\n\t // in javadoc enumerations are always printed\n\t opt.showEnumerations = true;\n\t opt.relativeLinksForSourcePackages = true;\n\t // enable strict matching for hide expressions\n\t opt.strictMatching = true;\n//\t root.printNotice(opt.toString());\n\n\t generatePackageDiagrams(root, opt, outputFolder);\n\t generateContextDiagrams(root, opt, outputFolder);\n\t} catch(Throwable t) {\n\t root.printWarning(\"Error: \" + t.toString());\n\t t.printStackTrace();\n\t return false;\n\t}\n\treturn true;\n }", "public void updateInfo(BoxTermsOfServiceUserStatus.Info info) {\n URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n info.update(responseJSON);\n }", "public static dnspolicy_dnsglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnsglobal_binding obj = new dnspolicy_dnsglobal_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnsglobal_binding response[] = (dnspolicy_dnsglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@AfterThrowing(pointcut = \"execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))\", throwing = \"throwable\")\n public void logErrorFromThrownException(final JoinPoint joinPoint, final Throwable throwable) {\n final String className = joinPoint.getTarget().getClass().getName();\n final String methodName = joinPoint.getSignature().getName();\n\n logger.error(\"Could not write to cassandra! Method: \" + className + \".\"+ methodName + \"()\", throwable);\n }", "public List<TimephasedWork> getTimephasedOvertimeWork()\n {\n if (m_timephasedOvertimeWork == null && m_timephasedWork != null && getOvertimeWork() != null)\n {\n double perDayFactor = getRemainingOvertimeWork().getDuration() / (getRemainingWork().getDuration() - getRemainingOvertimeWork().getDuration());\n double totalFactor = getRemainingOvertimeWork().getDuration() / getRemainingWork().getDuration();\n\n perDayFactor = Double.isNaN(perDayFactor) ? 0 : perDayFactor;\n totalFactor = Double.isNaN(totalFactor) ? 0 : totalFactor;\n\n m_timephasedOvertimeWork = new DefaultTimephasedWorkContainer(m_timephasedWork, perDayFactor, totalFactor);\n }\n return m_timephasedOvertimeWork == null ? null : m_timephasedOvertimeWork.getData();\n }", "public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }", "public static base_responses add(nitro_service client, appfwjsoncontenttype resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwjsoncontenttype addresources[] = new appfwjsoncontenttype[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new appfwjsoncontenttype();\n\t\t\t\taddresources[i].jsoncontenttypevalue = resources[i].jsoncontenttypevalue;\n\t\t\t\taddresources[i].isregex = resources[i].isregex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "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 }" ]
Gets the node meta data. @param key - the meta data key @return the node meta data value for this key
[ "public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }" ]
[ "String fetchToken(String tokenType) throws IOException, MediaWikiApiErrorException {\n\t\tMap<String, String> params = new HashMap<>();\n\t\tparams.put(ApiConnection.PARAM_ACTION, \"query\");\n\t\tparams.put(\"meta\", \"tokens\");\n\t\tparams.put(\"type\", tokenType);\n\n\t\ttry {\n\t\t\tJsonNode root = this.sendJsonRequest(\"POST\", params);\n\t\t\treturn root.path(\"query\").path(\"tokens\").path(tokenType + \"token\").textValue();\n\t\t} catch (IOException | MediaWikiApiErrorException e) {\n\t\t\tlogger.error(\"Error when trying to fetch token: \" + e.toString());\n\t\t}\n\t\treturn null;\n\t}", "public static String getDumpFileName(DumpContentType dumpContentType,\n\t\t\tString projectName, String dateStamp) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\treturn dateStamp + WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t} else {\n\t\t\treturn projectName + \"-\" + dateStamp\n\t\t\t\t\t+ WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t}\n\t}", "private void parseJSON(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n JsonValue value = member.getValue();\n if (value.isNull()) {\n continue;\n }\n\n try {\n String memberName = member.getName();\n if (memberName.equals(\"id\")) {\n this.versionID = value.asString();\n } else if (memberName.equals(\"sha1\")) {\n this.sha1 = value.asString();\n } else if (memberName.equals(\"name\")) {\n this.name = value.asString();\n } else if (memberName.equals(\"size\")) {\n this.size = Double.valueOf(value.toString()).longValue();\n } else if (memberName.equals(\"created_at\")) {\n this.createdAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_at\")) {\n this.modifiedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"trashed_at\")) {\n this.trashedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_by\")) {\n JsonObject userJSON = value.asObject();\n String userID = userJSON.get(\"id\").asString();\n BoxUser user = new BoxUser(getAPI(), userID);\n this.modifiedBy = user.new Info(userJSON);\n }\n } catch (ParseException e) {\n assert false : \"A ParseException indicates a bug in the SDK.\";\n }\n }\n }", "public void update(short number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_SHORT];\n ByteUtils.writeShort(numberInBytes, number, 0);\n update(numberInBytes);\n }", "public void promoteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.promoteModulePath(name, version));\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"promote module\", name, version);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "public 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 }", "private <T> void add(EjbDescriptor<T> ejbDescriptor) {\n InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor);\n ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor);\n ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName());\n }", "static PathAddress toPathAddress(String domain, ImmutableManagementResourceRegistration registry, ObjectName name) {\n if (!name.getDomain().equals(domain)) {\n return PathAddress.EMPTY_ADDRESS;\n }\n if (name.equals(ModelControllerMBeanHelper.createRootObjectName(domain))) {\n return PathAddress.EMPTY_ADDRESS;\n }\n final Hashtable<String, String> properties = name.getKeyPropertyList();\n return searchPathAddress(PathAddress.EMPTY_ADDRESS, registry, properties);\n }", "private boolean replaceValues(Locale locale) {\n\n try {\n SortedProperties localization = getLocalization(locale);\n if (hasDescriptor()) {\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n } else {\n m_container.removeAllItems();\n Set<Object> keyset = m_keyset.getKeySet();\n for (Object key : keyset) {\n Object itemId = m_container.addItem();\n Item item = m_container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n if (m_container.getItemIds().isEmpty()) {\n m_container.addItem();\n }\n }\n return true;\n } catch (IOException | CmsException e) {\n // The problem should typically be a problem with locking or reading the file containing the translation.\n // This should be reported in the editor, if false is returned here.\n return false;\n }\n }" ]
Add a property with the given name and the given list of values to this Properties object. Name and values are trimmed before the property is added. @param name the name of the property, must not be <code>null</code>. @param values the values of the property, must no be <code>null</code>, none of the values must be <code>null</code>
[ "public void addProperty(String name, String... values) {\n List<String> valueList = new ArrayList<String>();\n for (String value : values) {\n valueList.add(value.trim());\n }\n properties.put(name.trim(), valueList);\n }" ]
[ "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\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 Weld property(String key, Object value) {\n properties.put(key, value);\n return this;\n }", "public static AliasOperationTransformer replaceLastElement(final PathElement element) {\n return create(new AddressTransformer() {\n @Override\n public PathAddress transformAddress(final PathAddress original) {\n final PathAddress address = original.subAddress(0, original.size() -1);\n return address.append(element);\n }\n });\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}", "@Nonnull\n public static Builder builder(Revapi revapi) {\n List<String> knownExtensionIds = new ArrayList<>();\n\n addExtensionIds(revapi.getPipelineConfiguration().getApiAnalyzerTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getTransformTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getFilterTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getReporterTypes(), knownExtensionIds);\n\n return new Builder(knownExtensionIds);\n }", "@Override\n public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) {\n return DiscordianDate.of(prolepticYear, month, dayOfMonth);\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 }" ]
Return the next word of the string, in other words it stops when a space is encountered.
[ "public static String nextWord(String string) {\n int index = 0;\n while (index < string.length() && !Character.isWhitespace(string.charAt(index))) {\n index++;\n }\n return string.substring(0, index);\n }" ]
[ "protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n if (jobTypes == null) {\n throw new IllegalArgumentException(\"jobTypes must not be null\");\n }\n for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) {\n try {\n checkJobType(entry.getKey(), entry.getValue());\n } catch (IllegalArgumentException iae) {\n throw new IllegalArgumentException(\"jobTypes contained invalid value\", iae);\n }\n }\n }", "public void reset() {\n state = BreakerState.CLOSED;\n isHardTrip = false;\n byPass = false;\n isAttemptLive = false;\n\n notifyBreakerStateChange(getStatus());\n }", "public void openReport(String newState, A_CmsReportThread thread, String label) {\n\n setReport(newState, thread);\n m_labels.put(thread, label);\n openSubView(newState, true);\n }", "protected void fireEvent(HotKey hotKey) {\n HotKeyEvent event = new HotKeyEvent(hotKey);\n if (useSwingEventQueue) {\n SwingUtilities.invokeLater(event);\n } else {\n if (eventQueue == null) {\n eventQueue = Executors.newSingleThreadExecutor();\n }\n eventQueue.execute(event);\n }\n }", "private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) {\n\n Map<String, String> result = new LinkedHashMap<>();\n for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) {\n String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY));\n String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE));\n result.put(key, value);\n }\n return Collections.unmodifiableMap(result);\n }", "public void setFieldConversionClassName(String fieldConversionClassName)\r\n {\r\n try\r\n {\r\n this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\r\n \"Could not instantiate FieldConversion class using default constructor\", e);\r\n }\r\n }", "private static String toColumnName(String fieldName) {\n int lastDot = fieldName.indexOf('.');\n if (lastDot > -1) {\n return fieldName.substring(lastDot + 1);\n } else {\n return fieldName;\n }\n }", "public @Nullable String build() {\n StringBuilder queryString = new StringBuilder();\n\n for (NameValuePair param : params) {\n if (queryString.length() > 0) {\n queryString.append(PARAM_SEPARATOR);\n }\n queryString.append(Escape.urlEncode(param.getName()));\n queryString.append(VALUE_SEPARATOR);\n queryString.append(Escape.urlEncode(param.getValue()));\n }\n\n if (queryString.length() > 0) {\n return queryString.toString();\n }\n else {\n return null;\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 }" ]
Run a query on the datastore. @return The entities returned by the query. @throws DatastoreException on error
[ "private List<Entity> runQuery(Query query) throws DatastoreException {\n RunQueryRequest.Builder request = RunQueryRequest.newBuilder();\n request.setQuery(query);\n RunQueryResponse response = datastore.runQuery(request.build());\n\n if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {\n System.err.println(\"WARNING: partial results\\n\");\n }\n List<EntityResult> results = response.getBatch().getEntityResultsList();\n List<Entity> entities = new ArrayList<Entity>(results.size());\n for (EntityResult result : results) {\n entities.add(result.getEntity());\n }\n return entities;\n }" ]
[ "private void addTraceForFrame(WebSocketFrame frame, String type) {\n\t\tMap<String, Object> trace = new LinkedHashMap<>();\n\t\ttrace.put(\"type\", type);\n\t\ttrace.put(\"direction\", \"in\");\n\t\tif (frame instanceof TextWebSocketFrame) {\n\t\t\ttrace.put(\"payload\", ((TextWebSocketFrame) frame).text());\n\t\t}\n\n\t\tif (traceEnabled) {\n\t\t\twebsocketTraceRepository.add(trace);\n\t\t}\n\t}", "public Sequence compile( String equation , boolean assignment, boolean debug ) {\n\n functions.setManagerTemp(managerTemp);\n\n Sequence sequence = new Sequence();\n TokenList tokens = extractTokens(equation,managerTemp);\n\n if( tokens.size() < 3 )\n throw new RuntimeException(\"Too few tokens\");\n\n TokenList.Token t0 = tokens.getFirst();\n\n if( t0.word != null && t0.word.compareToIgnoreCase(\"macro\") == 0 ) {\n parseMacro(tokens,sequence);\n } else {\n insertFunctionsAndVariables(tokens);\n insertMacros(tokens);\n if (debug) {\n System.out.println(\"Parsed tokens:\\n------------\");\n tokens.print();\n System.out.println();\n }\n\n // Get the results variable\n if (t0.getType() != Type.VARIABLE && t0.getType() != Type.WORD) {\n compileTokens(sequence,tokens);\n // If there's no output then this is acceptable, otherwise it's assumed to be a bug\n // If there's no output then a configuration was changed\n Variable variable = tokens.getFirst().getVariable();\n if( variable != null ) {\n if( assignment )\n throw new IllegalArgumentException(\"No assignment to an output variable could be found. Found \" + t0);\n else {\n sequence.output = variable; // set this to be the output for print()\n }\n }\n\n } else {\n compileAssignment(sequence, tokens, t0);\n }\n\n if (debug) {\n System.out.println(\"Operations:\\n------------\");\n for (int i = 0; i < sequence.operations.size(); i++) {\n System.out.println(sequence.operations.get(i).name());\n }\n }\n }\n\n return sequence;\n }", "public void setSegmentReject(String reject) {\n\t\tif (!StringUtils.hasText(reject)) {\n\t\t\treturn;\n\t\t}\n\t\tInteger parsedLimit = null;\n\t\ttry {\n\t\t\tparsedLimit = Integer.parseInt(reject);\n\t\t\tsegmentRejectType = SegmentRejectType.ROWS;\n\t\t} catch (NumberFormatException e) {\n\t\t}\n\t\tif (parsedLimit == null && reject.contains(\"%\")) {\n\t\t\ttry {\n\t\t\t\tparsedLimit = Integer.parseInt(reject.replace(\"%\", \"\").trim());\n\t\t\t\tsegmentRejectType = SegmentRejectType.PERCENT;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t}\n\t\t}\n\t\tsegmentRejectLimit = parsedLimit;\n\t}", "private void toNextDate(Calendar date, int interval) {\n\n long previousDate = date.getTimeInMillis();\n if (!m_weekOfMonthIterator.hasNext()) {\n date.add(Calendar.MONTH, interval);\n m_weekOfMonthIterator = m_weeksOfMonth.iterator();\n }\n toCorrectDateWithDay(date, m_weekOfMonthIterator.next());\n if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.\n toNextDate(date);\n }\n\n }", "private void checkObjectCache(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n ObjectCacheDef objCacheDef = classDef.getObjectCache();\r\n\r\n if (objCacheDef == null)\r\n {\r\n return;\r\n }\r\n\r\n String objectCacheName = objCacheDef.getName();\r\n\r\n if ((objectCacheName == null) || (objectCacheName.length() == 0))\r\n {\r\n throw new ConstraintException(\"No class specified for the object-cache of class \"+classDef.getName());\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(objectCacheName, OBJECT_CACHE_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+objectCacheName+\" specified as object-cache of class \"+classDef.getName()+\" does not implement the interface \"+OBJECT_CACHE_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the object-cache class \"+objectCacheName+\" of class \"+classDef.getName());\r\n }\r\n }", "@JsonProperty(\"paging\")\n void paging(String paging) {\n builder.paging(IndexPagingState.fromByteBuffer(ByteBufferUtils.byteBuffer(paging)));\n }", "public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }", "public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }", "public Set<? extends AbstractBean<?, ?>> resolveSpecializedBeans(Bean<?> specializingBean) {\n if (specializingBean instanceof AbstractClassBean<?>) {\n AbstractClassBean<?> abstractClassBean = (AbstractClassBean<?>) specializingBean;\n if (abstractClassBean.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n if (specializingBean instanceof ProducerMethod<?, ?>) {\n ProducerMethod<?, ?> producerMethod = (ProducerMethod<?, ?>) specializingBean;\n if (producerMethod.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n return Collections.emptySet();\n }" ]
Setting the type of Checkbox.
[ "public void setType(CheckBoxType type) {\n this.type = type;\n switch (type) {\n case FILLED:\n Element input = DOM.getChild(getElement(), 0);\n input.setAttribute(\"class\", CssName.FILLED_IN);\n break;\n case INTERMEDIATE:\n addStyleName(type.getCssName() + \"-checkbox\");\n break;\n default:\n addStyleName(type.getCssName());\n break;\n }\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public <T extends ReportModel> T getReportByName(String name, Class<T> clazz)\n {\n WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name);\n try\n {\n return (T) model;\n }\n catch (ClassCastException ex)\n {\n throw new WindupException(\"The vertex is not of expected frame type \" + clazz.getName() + \": \" + model.toPrettyString());\n }\n }", "protected long buildNextSequence(PersistenceBroker broker, ClassDescriptor cld, String sequenceName)\r\n throws LookupException, SQLException, PlatformException\r\n {\r\n CallableStatement cs = null;\r\n try\r\n {\r\n Connection con = broker.serviceConnectionManager().getConnection();\r\n cs = getPlatform().prepareNextValProcedureStatement(con, PROCEDURE_NAME, sequenceName);\r\n cs.executeUpdate();\r\n return cs.getLong(1);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (cs != null)\r\n cs.close();\r\n }\r\n catch (SQLException ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n }", "@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}", "public static String confSetName() {\n String profile = SysProps.get(AppConfigKey.PROFILE.key());\n if (S.blank(profile)) {\n profile = Act.mode().name().toLowerCase();\n }\n return profile;\n }", "public Double getProgress() {\n\n if (state.equals(ParallelTaskState.IN_PROGRESS)) {\n if (requestNum != 0) {\n return 100.0 * ((double) responsedNum / (double) requestNumActual);\n } else {\n return 0.0;\n }\n }\n\n if (state.equals(ParallelTaskState.WAITING)) {\n return 0.0;\n }\n\n // fix task if fail validation, still try to poll progress 0901\n if (state.equals(ParallelTaskState.COMPLETED_WITH_ERROR)\n || state.equals(ParallelTaskState.COMPLETED_WITHOUT_ERROR)) {\n return 100.0;\n }\n\n return 0.0;\n\n }", "public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable unsetresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new bridgetable();\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "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 }", "private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) {\n final Response response = doLoginRequest(credential, asLinkRequest);\n\n final StitchUserT previousUser = activeUser;\n final StitchUserT user = processLoginResponse(credential, response, asLinkRequest);\n\n if (asLinkRequest) {\n onUserLinked(user);\n } else {\n onUserLoggedIn(user);\n onActiveUserChanged(activeUser, previousUser);\n }\n\n return user;\n }", "private void fillQueue(QueueItem item, Integer minStartPosition,\n Integer maxStartPosition, Integer minEndPosition) throws IOException {\n int newStartPosition;\n int newEndPosition;\n Integer firstRetrievedPosition = null;\n // remove everything below minStartPosition\n if ((minStartPosition != null) && (item.lowestPosition != null)\n && (item.lowestPosition < minStartPosition)) {\n item.del((minStartPosition - 1));\n }\n // fill queue\n while (!item.noMorePositions) {\n boolean doNotCollectAnotherPosition;\n doNotCollectAnotherPosition = item.filledPosition\n && (minStartPosition == null) && (maxStartPosition == null);\n doNotCollectAnotherPosition |= item.filledPosition\n && (maxStartPosition != null) && (item.lastRetrievedPosition != null)\n && (maxStartPosition < item.lastRetrievedPosition);\n if (doNotCollectAnotherPosition) {\n return;\n } else {\n // collect another full position\n firstRetrievedPosition = null;\n while (!item.noMorePositions) {\n newStartPosition = item.sequenceSpans.spans.nextStartPosition();\n if (newStartPosition == NO_MORE_POSITIONS) {\n if (!item.queue.isEmpty()) {\n item.filledPosition = true;\n item.lastFilledPosition = item.lastRetrievedPosition;\n }\n item.noMorePositions = true;\n return;\n } else if ((minStartPosition != null)\n && (newStartPosition < minStartPosition)) {\n // do nothing\n } else {\n newEndPosition = item.sequenceSpans.spans.endPosition();\n if ((minEndPosition == null) || (newEndPosition >= minEndPosition\n - ignoreItem.getMinStartPosition(docId, newEndPosition))) {\n item.add(newStartPosition, newEndPosition);\n if (firstRetrievedPosition == null) {\n firstRetrievedPosition = newStartPosition;\n } else if (!firstRetrievedPosition.equals(newStartPosition)) {\n break;\n }\n }\n }\n }\n }\n }\n }" ]
Shutdown task scheduler.
[ "public synchronized void shutdownTaskScheduler(){\n if (scheduler != null && !scheduler.isShutdown()) {\n scheduler.shutdown();\n logger.info(\"shutdowned the task scheduler. No longer accepting new tasks\");\n scheduler = null;\n }\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 }", "private static Converter<List<String>, Object> createStringConstructorConverter(Class<?> resultClass) {\n try {\n final Constructor<?> constructor = resultClass.getConstructor(String.class);\n return new BasicConverter(defaultValue(resultClass)) {\n @Override\n protected Object convert(String value) throws Exception {\n return constructor.newInstance(value);\n }\n };\n } catch (Exception e) {\n return null;\n }\n }", "private ModelNode createJVMNode() throws OperationFailedException {\n ModelNode jvm = new ModelNode().setEmptyObject();\n jvm.get(NAME).set(getProperty(\"java.vm.name\"));\n jvm.get(JAVA_VERSION).set(getProperty(\"java.vm.specification.version\"));\n jvm.get(JVM_VERSION).set(getProperty(\"java.version\"));\n jvm.get(JVM_VENDOR).set(getProperty(\"java.vm.vendor\"));\n jvm.get(JVM_HOME).set(getProperty(\"java.home\"));\n return jvm;\n }", "public static void createMetadataCache(SlotReference slot, int playlistId, File cache) throws Exception {\n createMetadataCache(slot, playlistId, cache, null);\n }", "public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }", "public static base_responses add(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 addresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nspbr6();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].action = resources[i].action;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].nexthop = resources[i].nexthop;\n\t\t\t\taddresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\taddresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static boolean isOperationDefined(final ModelNode operation) {\n for (final AttributeDefinition def : ROOT_ATTRIBUTES) {\n if (operation.hasDefined(def.getName())) {\n return true;\n }\n }\n return false;\n }", "private void readResource(Document.Resources.Resource resource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setName(resource.getName());\n mpxjResource.setResourceCalendar(m_calendarMap.get(resource.getCalendarID()));\n mpxjResource.setStandardRate(new Rate(resource.getCost(), resource.getCostTimeUnit()));\n mpxjResource.setEmailAddress(resource.getEMail());\n mpxjResource.setGroup(resource.getGroup());\n //resource.getHyperlinks()\n mpxjResource.setUniqueID(resource.getID());\n //resource.getMarkerID()\n mpxjResource.setNotes(resource.getNote());\n mpxjResource.setID(Integer.valueOf(resource.getOutlineNumber()));\n //resource.getStyleProject()\n mpxjResource.setType(resource.getSubType() == null ? resource.getType() : resource.getSubType());\n }", "public ServerSetup createCopy(String bindAddress) {\r\n ServerSetup setup = new ServerSetup(getPort(), bindAddress, getProtocol());\r\n setup.setServerStartupTimeout(getServerStartupTimeout());\r\n setup.setConnectionTimeout(getConnectionTimeout());\r\n setup.setReadTimeout(getReadTimeout());\r\n setup.setWriteTimeout(getWriteTimeout());\r\n setup.setVerbose(isVerbose());\r\n\r\n return setup;\r\n }" ]
Flat the map of list of string to map of strings, with theoriginal values, seperated by comma
[ "protected static Map<String, String> getHeadersAsMap(ResponseEntity response) {\n\n Map<String, List<String>> headers = new HashMap<>(response.getHeaders());\n Map<String, String> map = new HashMap<>();\n\n for ( Map.Entry<String, List<String>> header :headers.entrySet() ) {\n String headerValue = Joiner.on(\",\").join(header.getValue());\n map.put(header.getKey(), headerValue);\n }\n\n return map;\n }" ]
[ "public HomekitRoot createBridge(\n HomekitAuthInfo authInfo,\n String label,\n String manufacturer,\n String model,\n String serialNumber)\n throws IOException {\n HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);\n root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));\n return root;\n }", "public PlaybackState getFurthestPlaybackState() {\n PlaybackState result = null;\n for (PlaybackState state : playbackStateMap.values()) {\n if (result == null || (!result.playing && state.playing) ||\n (result.position < state.position) && (state.playing || !result.playing)) {\n result = state;\n }\n }\n return result;\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 }", "public static void Shuffle(double[] array, long seed) {\n Random random = new Random();\n if (seed != 0) random.setSeed(seed);\n\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n double temp = array[index];\n array[index] = array[i];\n array[i] = temp;\n }\n }", "public int consume(Map<String, String> initialVars) {\r\n int result = 0;\n\r\n for (int i = 0; i < repeatNumber; i++) {\r\n result += super.consume(initialVars);\r\n }\n\r\n return result;\r\n }", "void reportError(Throwable throwable) {\n if (logger != null)\n logger.error(\"Timer reported error\", throwable);\n status = \"Thread blocked on error: \" + throwable;\n error_skips = error_factor;\n }", "public static <K,V> Map<K,V> asImmutable(Map<? extends K, ? extends V> self) {\n return Collections.unmodifiableMap(self);\n }", "public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "public T withAlias(String text, String languageCode) {\n\t\twithAlias(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}" ]
Processes the template for the comma-separated value pairs in an attribute of the current object on the specified level. @param template The template @param attributes The attributes of the tag @exception XDocletException if an error occurs @doc.tag type="block" @doc.param name="level" optional="false" description="The level for the current object" values="class,field,reference,collection" @doc.param name="name" optional="true" description="The name of the attribute containg attributes (defaults to 'attributes')" @doc.param name="default-right" optional="true" description="The default right value if none is given (defaults to empty value)"
[ "public void forAllValuePairs(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME, \"attributes\");\r\n String defaultValue = attributes.getProperty(ATTRIBUTE_DEFAULT_RIGHT, \"\");\r\n String attributePairs = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), name);\r\n\r\n if ((attributePairs == null) || (attributePairs.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n String token;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(attributePairs); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos >= 0)\r\n {\r\n _curPairLeft = token.substring(0, pos);\r\n _curPairRight = (pos < token.length() - 1 ? token.substring(pos + 1) : defaultValue);\r\n }\r\n else\r\n {\r\n _curPairLeft = token;\r\n _curPairRight = defaultValue;\r\n }\r\n if (_curPairLeft.length() > 0)\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }" ]
[ "public void setSessionFactory(SessionFactory sessionFactory) throws HibernateLayerException {\n\t\ttry {\n\t\t\tthis.sessionFactory = sessionFactory;\n\t\t\tif (null != layerInfo) {\n\t\t\t\tentityMetadata = sessionFactory.getClassMetadata(layerInfo.getFeatureInfo().getDataSourceName());\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_NO_SESSION_FACTORY);\n\t\t}\n\t}", "@SuppressWarnings(\"deprecation\")\n public boolean cancelOnTargetHosts(List<String> targetHosts) {\n\n boolean success = false;\n\n try {\n\n switch (state) {\n\n case IN_PROGRESS:\n if (executionManager != null\n && !executionManager.isTerminated()) {\n executionManager.tell(new CancelTaskOnHostRequest(\n targetHosts), executionManager);\n logger.info(\n \"asked task to stop from running on target hosts with count {}...\",\n targetHosts.size());\n } else {\n logger.info(\"manager already killed or not exist.. NO OP\");\n }\n success = true;\n break;\n case COMPLETED_WITHOUT_ERROR:\n case COMPLETED_WITH_ERROR:\n case WAITING:\n logger.info(\"will NO OP for cancelOnTargetHost as it is not in IN_PROGRESS state\");\n success = true;\n break;\n default:\n break;\n\n }\n\n } catch (Exception e) {\n logger.error(\n \"cancel task {} on hosts with count {} error with exception details \",\n this.getTaskId(), targetHosts.size(), e);\n }\n\n return success;\n }", "@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }", "public int getMinutesPerYear()\n {\n return m_minutesPerYear == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerYear()) : m_minutesPerYear.intValue();\n }", "private static void parseRessource(ArrayList<Shape> shapes,\n HashMap<String, JSONObject> flatJSON,\n String resourceId,\n Boolean keepGlossaryLink)\n throws JSONException {\n JSONObject modelJSON = flatJSON.get(resourceId);\n Shape current = getShapeWithId(modelJSON.getString(\"resourceId\"),\n shapes);\n\n parseStencil(modelJSON,\n current);\n\n parseProperties(modelJSON,\n current,\n keepGlossaryLink);\n parseOutgoings(shapes,\n modelJSON,\n current);\n parseChildShapes(shapes,\n modelJSON,\n current);\n parseDockers(modelJSON,\n current);\n parseBounds(modelJSON,\n current);\n parseTarget(shapes,\n modelJSON,\n current);\n }", "public static vpnsessionaction[] get(nitro_service service) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tvpnsessionaction[] response = (vpnsessionaction[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void updatePathTable(String columnName, Object newData, int path_id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + columnName + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setObject(1, newData);\n statement.setInt(2, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "static PatchingTask createTask(final PatchingTasks.ContentTaskDefinition definition, final PatchContentProvider provider, final IdentityPatchContext.PatchEntry context) {\n final PatchContentLoader contentLoader = provider.getLoader(definition.getTarget().getPatchId());\n final PatchingTaskDescription description = PatchingTaskDescription.create(definition, contentLoader);\n return PatchingTask.Factory.create(description, context);\n }", "public GroovyFieldDoc[] fields() {\n Collections.sort(fields);\n return fields.toArray(new GroovyFieldDoc[fields.size()]);\n }" ]
Describes the scenario. Must be called before any step invocation. @param description the description @return this for a fluent interface
[ "@Override\n public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {\n super.startScenario( description );\n return this;\n\n }" ]
[ "public List<SquigglyNode> parse(String filter) {\n filter = StringUtils.trim(filter);\n\n if (StringUtils.isEmpty(filter)) {\n return Collections.emptyList();\n }\n\n // get it from the cache if we can\n List<SquigglyNode> cachedNodes = CACHE.getIfPresent(filter);\n\n if (cachedNodes != null) {\n return cachedNodes;\n }\n\n\n SquigglyExpressionLexer lexer = ThrowingErrorListener.overwrite(new SquigglyExpressionLexer(new ANTLRInputStream(filter)));\n SquigglyExpressionParser parser = ThrowingErrorListener.overwrite(new SquigglyExpressionParser(new CommonTokenStream(lexer)));\n\n Visitor visitor = new Visitor();\n List<SquigglyNode> nodes = Collections.unmodifiableList(visitor.visit(parser.parse()));\n\n CACHE.put(filter, nodes);\n return nodes;\n }", "public long getStartTime(List<IInvokedMethod> methods)\n {\n long startTime = System.currentTimeMillis();\n for (IInvokedMethod method : methods)\n {\n startTime = Math.min(startTime, method.getDate());\n }\n return startTime;\n }", "public boolean detectTierRichCss() {\r\n\r\n boolean result = false;\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n if (detectMobileQuick()) {\r\n\r\n //Exclude iPhone Tier and e-Ink Kindle devices.\r\n if (!detectTierIphone() && !detectKindle()) {\r\n\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n //Older Windows 'Mobile' isn't good enough for iPhone Tier.\r\n if (detectWebkit()\r\n || detectS60OssBrowser()\r\n || detectBlackBerryHigh()\r\n || detectWindowsMobile()\r\n || (userAgent.indexOf(engineTelecaQ) != -1)) {\r\n result = true;\r\n } // if detectWebkit()\r\n } //if !detectTierIphone()\r\n } //if detectMobileQuick()\r\n return result;\r\n }", "private static void setupFlowId(SoapMessage message) {\n String flowId = FlowIdHelper.getFlowId(message);\n\n if (flowId == null) {\n flowId = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n flowId = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n Exchange ex = message.getExchange();\n if (null!=ex){\n Message reqMsg = ex.getOutMessage();\n if ( null != reqMsg) {\n flowId = FlowIdHelper.getFlowId(reqMsg);\n }\n }\n }\n\n if (flowId != null && !flowId.isEmpty()) {\n FlowIdHelper.setFlowId(message, flowId);\n }\n }", "public static String getSerializedVectorClock(VectorClock vc) {\n VectorClockWrapper vcWrapper = new VectorClockWrapper(vc);\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vcWrapper);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "public static <T_Result, T_Source> List<T_Result> map(Collection<T_Source> source,\n Mapper<T_Result, T_Source> mapper) {\n List<T_Result> result = new LinkedList<T_Result>();\n for (T_Source element : source) {\n result.add(mapper.map(element));\n }\n return result;\n }", "@Override\n public List<Integer> getReplicatingPartitionList(int index) {\n List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas());\n List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas());\n\n // Copy Zone based Replication Factor\n HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>();\n requiredRepFactor.putAll(zoneReplicationFactor);\n\n // Cross-check if individual zone replication factor equals global\n int sum = 0;\n for(Integer zoneRepFactor: requiredRepFactor.values()) {\n sum += zoneRepFactor;\n }\n\n if(sum != getNumReplicas())\n throw new IllegalArgumentException(\"Number of zone replicas is not equal to the total replication factor\");\n\n if(getPartitionToNode().length == 0) {\n return new ArrayList<Integer>(0);\n }\n\n for(int i = 0; i < getPartitionToNode().length; i++) {\n // add this one if we haven't already, and it can satisfy some zone\n // replicationFactor\n Node currentNode = getNodeByPartition(index);\n if(!preferenceNodesList.contains(currentNode)) {\n preferenceNodesList.add(currentNode);\n if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId()))\n replicationPartitionsList.add(index);\n }\n\n // if we have enough, go home\n if(replicationPartitionsList.size() >= getNumReplicas())\n return replicationPartitionsList;\n // move to next clockwise slot on the ring\n index = (index + 1) % getPartitionToNode().length;\n }\n\n // we don't have enough, but that may be okay\n return replicationPartitionsList;\n }", "public Integer getInteger(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "private long size(final Jedis jedis, final String queueName) {\n final String key = key(QUEUE, queueName);\n final long size;\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZCARD\n size = jedis.zcard(key);\n } else { // Else, use LLEN\n size = jedis.llen(key);\n }\n return size;\n }" ]
Uses current variable assignments and info in an NWiseActionTag to expand on an n wise combinatorial set @param action an NWiseAction Action @param possibleStateList a current list of possible states produced so far from expanding a model state @return every input possible state expanded on an n wise combinatorial set defined by that input possible state
[ "public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {\r\n String[] coVariables = action.getCoVariables().split(\",\");\r\n int n = Integer.valueOf(action.getN());\n\r\n List<Map<String, String>> newPossibleStateList = new ArrayList<>();\n\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n Map<String, String[]> variableDomains = new HashMap<>();\r\n Map<String, String> defaultVariableValues = new HashMap<>();\r\n for (String variable : coVariables) {\r\n String variableMetaInfo = possibleState.get(variable);\r\n String[] variableDomain = variableMetaInfo.split(\",\");\r\n variableDomains.put(variable, variableDomain);\r\n defaultVariableValues.put(variable, variableDomain[0]);\r\n }\n\r\n List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);\r\n for (Map<String, String> nWiseCombination : nWiseCombinations) {\r\n Map<String, String> newPossibleState = new HashMap<>(possibleState);\r\n newPossibleState.putAll(defaultVariableValues);\r\n newPossibleState.putAll(nWiseCombination);\r\n newPossibleStateList.add(newPossibleState);\r\n }\r\n }\n\r\n return newPossibleStateList;\r\n }" ]
[ "protected void debugLog(String operationType, Long receivedTimeInMs) {\n long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs);\n int numVectorClockEntries = (this.parsedVectorClock == null ? 0\n : this.parsedVectorClock.getVersionMap()\n .size());\n logger.debug(\"Received a new request. Operation type: \" + operationType + \" , Key(s): \"\n + keysHexString(this.parsedKeys) + \" , Store: \" + this.storeName\n + \" , Origin time (in ms): \" + (this.parsedRequestOriginTimeInMs)\n + \" , Request received at time(in ms): \" + receivedTimeInMs\n + \" , Num vector clock entries: \" + numVectorClockEntries\n + \" , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): \"\n + durationInMs);\n\n }", "public WindupConfiguration setOptionValue(String name, Object value)\n {\n configurationOptions.put(name, value);\n return this;\n }", "public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }", "private void addGreeting(String guestbookName, String user, String message)\n throws DatastoreException {\n Entity.Builder greeting = Entity.newBuilder();\n greeting.setKey(makeKey(GUESTBOOK_KIND, guestbookName, GREETING_KIND));\n greeting.getMutableProperties().put(USER_PROPERTY, makeValue(user).build());\n greeting.getMutableProperties().put(MESSAGE_PROPERTY, makeValue(message).build());\n greeting.getMutableProperties().put(DATE_PROPERTY, makeValue(new Date()).build());\n Key greetingKey = insert(greeting.build());\n System.out.println(\"greeting key is: \" + greetingKey);\n }", "public Pair<int[][][][], int[][]> documentsToDataAndLabels(Collection<List<IN>> documents) {\r\n\r\n // first index is the number of the document\r\n // second index is position in the document also the index of the\r\n // clique/factor table\r\n // third index is the number of elements in the clique/window these features\r\n // are for (starting with last element)\r\n // fourth index is position of the feature in the array that holds them\r\n // element in data[i][j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique of the ith document\r\n // int[][][][] data = new int[documentsSize][][][];\r\n List<int[][][]> data = new ArrayList<int[][][]>();\r\n\r\n // first index is the number of the document\r\n // second index is the position in the document\r\n // element in labels[i][j] is the index of the correct label (if it exists)\r\n // at position j in document i\r\n // int[][] labels = new int[documentsSize][];\r\n List<int[]> labels = new ArrayList<int[]>();\r\n\r\n int numDatums = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n data.add(docPair.first());\r\n labels.add(docPair.second());\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + data.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n printFeatures();\r\n\r\n int[][][][] dataA = new int[0][][][];\r\n int[][] labelsA = new int[0][];\r\n\r\n return new Pair<int[][][][], int[][]>(data.toArray(dataA), labels.toArray(labelsA));\r\n }", "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }", "public static autoscaleaction[] get(nitro_service service) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tautoscaleaction[] response = (autoscaleaction[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static XClass getMemberType() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getType();\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().getType();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getType();\r\n }\r\n }\r\n return null;\r\n }", "public ItemRequest<User> findById(String user) {\n \n String path = String.format(\"/users/%s\", user);\n return new ItemRequest<User>(this, User.class, path, \"GET\");\n }" ]
Derives the OJB platform to use for a database that is connected via a url using the specified subprotocol, and where the specified jdbc driver is used. @param jdbcSubProtocol The JDBC subprotocol used to connect to the database @param jdbcDriver The JDBC driver used to connect to the database @return The platform identifier or <code>null</code> if no platform could be found
[ "public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver)\r\n {\r\n String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol);\r\n\r\n if (platform == null)\r\n {\r\n platform = (String)jdbcDriverToPlatform.get(jdbcDriver);\r\n }\r\n return platform;\r\n }" ]
[ "public static Object parsePrimitive(\n final String fieldName, final PrimitiveAttribute<?> pAtt, final PObject requestData) {\n Class<?> valueClass = pAtt.getValueClass();\n Object value;\n try {\n value = parseValue(false, new String[0], valueClass, fieldName, requestData);\n } catch (UnsupportedTypeException e) {\n String type = e.type.getName();\n if (e.type.isArray()) {\n type = e.type.getComponentType().getName() + \"[]\";\n }\n throw new RuntimeException(\n \"The type '\" + type + \"' is not a supported type when parsing json. \" +\n \"See documentation for supported types.\\n\\nUnsupported type found in attribute \" +\n fieldName\n + \"\\n\\nTo support more types add the type to \" +\n \"parseValue and parseArrayValue in this class and add a test to the test class\",\n e);\n }\n pAtt.validateValue(value);\n\n return value;\n }", "public static <T> AddQuery<T> start(T query, long correlationId) {\n return start(query, correlationId, \"default\", null);\n }", "public void printProbs(String filename,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n ObjectBank<List<IN>> docs =\r\n makeObjectBankFromFile(filename, readerAndWriter);\r\n printProbsDocuments(docs);\r\n }", "public void setOccurrences(String occurrences) {\r\n\r\n int o = CmsSerialDateUtil.toIntWithDefault(occurrences, -1);\r\n if (m_model.getOccurrences() != o) {\r\n m_model.setOccurrences(o);\r\n valueChanged();\r\n }\r\n }", "private List<Versioned<byte[]>> filterExpiredEntries(ByteArray key, List<Versioned<byte[]>> vals) {\n Iterator<Versioned<byte[]>> valsIterator = vals.iterator();\n while(valsIterator.hasNext()) {\n Versioned<byte[]> val = valsIterator.next();\n VectorClock clock = (VectorClock) val.getVersion();\n // omit if expired\n if(clock.getTimestamp() < (time.getMilliseconds() - this.retentionTimeMs)) {\n valsIterator.remove();\n // delete stale value if configured\n if(deleteExpiredEntries) {\n getInnerStore().delete(key, clock);\n }\n }\n }\n return vals;\n }", "public float getTexCoordU(int vertex, int coords) {\n if (!hasTexCoords(coords)) {\n throw new IllegalStateException(\n \"mesh has no texture coordinate set \" + coords);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for coords are done by java for us */\n \n return m_texcoords[coords].getFloat(\n vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);\n }", "private void prefetchRelationships(Query query)\r\n {\r\n List prefetchedRel;\r\n Collection owners;\r\n String relName;\r\n RelationshipPrefetcher[] prefetchers;\r\n\r\n if (query == null || query.getPrefetchedRelationships() == null || query.getPrefetchedRelationships().isEmpty())\r\n {\r\n return;\r\n }\r\n\r\n if (!supportsAdvancedJDBCCursorControl())\r\n {\r\n logger.info(\"prefetching relationships requires JDBC level 2.0\");\r\n return;\r\n }\r\n\r\n // prevent releasing of DBResources\r\n setInBatchedMode(true);\r\n\r\n prefetchedRel = query.getPrefetchedRelationships();\r\n prefetchers = new RelationshipPrefetcher[prefetchedRel.size()];\r\n\r\n // disable auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n relName = (String) prefetchedRel.get(i);\r\n prefetchers[i] = getBroker().getRelationshipPrefetcherFactory()\r\n .createRelationshipPrefetcher(getQueryObject().getClassDescriptor(), relName);\r\n prefetchers[i].prepareRelationshipSettings();\r\n }\r\n\r\n // materialize ALL owners of this Iterator\r\n owners = getOwnerObjects();\r\n\r\n // prefetch relationships and associate with owners\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].prefetchRelationship(owners);\r\n }\r\n\r\n // reset auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].restoreRelationshipSettings();\r\n }\r\n\r\n try\r\n {\r\n getRsAndStmt().m_rs.beforeFirst(); // reposition resultset jdbc 2.0\r\n }\r\n catch (SQLException e)\r\n {\r\n logger.error(\"beforeFirst failed !\", e);\r\n }\r\n\r\n setInBatchedMode(false);\r\n setHasCalledCheck(false);\r\n }", "public Map<String, T> parseMap(JsonParser jsonParser) throws IOException {\n HashMap<String, T> map = new HashMap<String, T>();\n while (jsonParser.nextToken() != JsonToken.END_OBJECT) {\n String key = jsonParser.getText();\n jsonParser.nextToken();\n if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) {\n map.put(key, null);\n } else{\n map.put(key, parse(jsonParser));\n }\n }\n return map;\n }", "private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) {\n Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap();\n for(Node node: cluster.getNodes()) {\n nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size());\n }\n\n return nodeIdToPrimaryCount;\n }" ]
Concats two arrays. @param first the first array @param second the second array @param <T> the type of the element in the array @return a new array created adding the element in the second array after the first one
[ "public static <T> T[] concat(T[] first, T... second) {\n\t\tint firstLength = first.length;\n\t\tint secondLength = second.length;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( first.getClass().getComponentType(), firstLength + secondLength );\n\t\tSystem.arraycopy( first, 0, result, 0, firstLength );\n\t\tSystem.arraycopy( second, 0, result, firstLength, secondLength );\n\n\t\treturn result;\n\t}" ]
[ "private String visibility(Options opt, ProgramElementDoc e) {\n\treturn opt.showVisibility ? Visibility.get(e).symbol : \" \";\n }", "public void revisitThrowEvents(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<Signal> toAddSignals = new ArrayList<Signal>();\n Set<Error> toAddErrors = new HashSet<Error>();\n Set<Escalation> toAddEscalations = new HashSet<Escalation>();\n Set<Message> toAddMessages = new HashSet<Message>();\n Set<ItemDefinition> toAddItemDefinitions = new HashSet<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setThrowEventsInfo((Process) root,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n }\n for (Lane lane : _lanes) {\n setThrowEventsInfoForLanes(lane,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n for (Signal s : toAddSignals) {\n def.getRootElements().add(s);\n }\n for (Error er : toAddErrors) {\n def.getRootElements().add(er);\n }\n for (Escalation es : toAddEscalations) {\n def.getRootElements().add(es);\n }\n for (ItemDefinition idef : toAddItemDefinitions) {\n def.getRootElements().add(idef);\n }\n for (Message msg : toAddMessages) {\n def.getRootElements().add(msg);\n }\n }", "@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }", "private Query.Builder createScatterQuery(Query query, int numSplits) {\n // TODO(pcostello): We can potentially support better splits with equality filters in our query\n // if there exists a composite index on property, __scatter__, __key__. Until an API for\n // metadata exists, this isn't possible. Note that ancestor and inequality queries fall into\n // the same category.\n Query.Builder scatterPointQuery = Query.newBuilder();\n scatterPointQuery.addAllKind(query.getKindList());\n scatterPointQuery.addOrder(DatastoreHelper.makeOrder(\n DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING));\n // There is a split containing entities before and after each scatter entity:\n // ||---*------*------*------*------*------*------*---|| = scatter entity\n // If we represent each split as a region before a scatter entity, there is an extra region\n // following the last scatter point. Thus, we do not need the scatter entities for the last\n // region.\n scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT);\n scatterPointQuery.addProjection(Projection.newBuilder().setProperty(\n PropertyReference.newBuilder().setName(\"__key__\")));\n return scatterPointQuery;\n }", "public void process(DirectoryEntry projectDir, ProjectFile file, DocumentInputStreamFactory inputStreamFactory) throws IOException\n {\n DirectoryEntry consDir;\n try\n {\n consDir = (DirectoryEntry) projectDir.getEntry(\"TBkndCons\");\n }\n\n catch (FileNotFoundException ex)\n {\n consDir = null;\n }\n\n if (consDir != null)\n {\n FixedMeta consFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"FixedMeta\"))), 10);\n FixedData consFixedData = new FixedData(consFixedMeta, 20, inputStreamFactory.getInstance(consDir, \"FixedData\"));\n // FixedMeta consFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"Fixed2Meta\"))), 9);\n // FixedData consFixed2Data = new FixedData(consFixed2Meta, 48, getEncryptableInputStream(consDir, \"Fixed2Data\"));\n\n int count = consFixedMeta.getAdjustedItemCount();\n int lastConstraintID = -1;\n\n ProjectProperties properties = file.getProjectProperties();\n EventManager eventManager = file.getEventManager();\n\n boolean project15 = NumberHelper.getInt(properties.getMppFileType()) == 14 && NumberHelper.getInt(properties.getApplicationVersion()) > ApplicationVersion.PROJECT_2010;\n int durationUnitsOffset = project15 ? 18 : 14;\n int durationOffset = project15 ? 14 : 16;\n\n for (int loop = 0; loop < count; loop++)\n {\n byte[] metaData = consFixedMeta.getByteArrayValue(loop);\n\n //\n // SourceForge bug 2209477: we were reading an int here, but\n // it looks like the deleted flag is just a short.\n //\n if (MPPUtility.getShort(metaData, 0) != 0)\n {\n continue;\n }\n\n int index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4));\n if (index == -1)\n {\n continue;\n }\n\n //\n // Do we have enough data?\n //\n byte[] data = consFixedData.getByteArrayValue(index);\n if (data.length < 14)\n {\n continue;\n }\n\n int constraintID = MPPUtility.getInt(data, 0);\n if (constraintID <= lastConstraintID)\n {\n continue;\n }\n\n lastConstraintID = constraintID;\n int taskID1 = MPPUtility.getInt(data, 4);\n int taskID2 = MPPUtility.getInt(data, 8);\n\n if (taskID1 == taskID2)\n {\n continue;\n }\n\n // byte[] metaData2 = consFixed2Meta.getByteArrayValue(loop);\n // int index2 = consFixed2Data.getIndexFromOffset(MPPUtility.getInt(metaData2, 4));\n // byte[] data2 = consFixed2Data.getByteArrayValue(index2);\n\n Task task1 = file.getTaskByUniqueID(Integer.valueOf(taskID1));\n Task task2 = file.getTaskByUniqueID(Integer.valueOf(taskID2));\n if (task1 != null && task2 != null)\n {\n RelationType type = RelationType.getInstance(MPPUtility.getShort(data, 12));\n TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, durationUnitsOffset));\n Duration lag = MPPUtility.getAdjustedDuration(properties, MPPUtility.getInt(data, durationOffset), durationUnits);\n Relation relation = task2.addPredecessor(task1, type, lag);\n relation.setUniqueID(Integer.valueOf(constraintID));\n eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }", "public CmsResource buildResource() {\n\n return new CmsResource(\n m_structureId,\n m_resourceId,\n m_rootPath,\n m_type,\n m_flags,\n m_projectLastModified,\n m_state,\n m_dateCreated,\n m_userCreated,\n m_dateLastModified,\n m_userLastModified,\n m_dateReleased,\n m_dateExpired,\n m_length,\n m_flags,\n m_dateContent,\n m_version);\n }", "protected void removeInvalidChildren() {\n\n if (getLoadState() == LoadState.LOADED) {\n List<CmsSitemapTreeItem> toDelete = new ArrayList<CmsSitemapTreeItem>();\n for (int i = 0; i < getChildCount(); i++) {\n CmsSitemapTreeItem item = (CmsSitemapTreeItem)getChild(i);\n CmsUUID id = item.getEntryId();\n if ((id != null) && (CmsSitemapView.getInstance().getController().getEntryById(id) == null)) {\n toDelete.add(item);\n }\n }\n for (CmsSitemapTreeItem deleteItem : toDelete) {\n m_children.removeItem(deleteItem);\n }\n }\n }", "static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }", "private String registerEventHandler(GFXEventHandler h) {\n //checkInitialized();\n if (!registeredOnJS) {\n JSObject doc = (JSObject) runtime.execute(\"document\");\n doc.setMember(\"jsHandlers\", jsHandlers);\n registeredOnJS = true;\n }\n return jsHandlers.registerHandler(h);\n }" ]
Converts the provided object to a date, if possible. @param date the date. @return the date as {@link java.util.Date}
[ "public Date toDate(Object date) {\n\n Date d = null;\n if (null != date) {\n if (date instanceof Date) {\n d = (Date)date;\n } else if (date instanceof Long) {\n d = new Date(((Long)date).longValue());\n } else {\n try {\n long l = Long.parseLong(date.toString());\n d = new Date(l);\n } catch (Exception e) {\n // do nothing, just let d remain null\n }\n }\n }\n return d;\n }" ]
[ "public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\n }", "public BoxCollaborationWhitelistExemptTarget.Info getInfo() {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(),\n this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n return new Info(JsonObject.readFrom(response.getJSON()));\n }", "private void processRedirect(String stringStatusCode,\n HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse) throws Exception {\n // Check if the proxy response is a redirect\n // The following code is adapted from\n // org.tigris.noodle.filters.CheckForRedirect\n // Hooray for open source software\n\n String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();\n if (stringLocation == null) {\n throw new ServletException(\"Received status code: \"\n + stringStatusCode + \" but no \"\n + STRING_LOCATION_HEADER\n + \" header was found in the response\");\n }\n // Modify the redirect to go to this proxy servlet rather than the proxied host\n String stringMyHostName = httpServletRequest.getServerName();\n if (httpServletRequest.getServerPort() != 80) {\n stringMyHostName += \":\" + httpServletRequest.getServerPort();\n }\n stringMyHostName += httpServletRequest.getContextPath();\n httpServletResponse.sendRedirect(stringLocation.replace(\n getProxyHostAndPort() + this.getProxyPath(),\n stringMyHostName));\n }", "String checkVersion(String pluginName, String dependency, String requestedVersion, String availableVersion) {\n\t\tif (null == availableVersion) {\n\t\t\treturn \"Dependency \" + dependency + \" not found for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed.\\n\";\n\t\t}\n\t\tif (requestedVersion.startsWith(EXPR_START) || availableVersion.startsWith(EXPR_START)) {\n\t\t\treturn \"\";\n\t\t}\n\t\tVersion requested = new Version(requestedVersion);\n\t\tVersion available = new Version(availableVersion);\n\t\tif (requested.getMajor() != available.getMajor()) {\n\t\t\treturn \"Dependency \" + dependency + \" is provided in a incompatible API version for plug-in \" +\n\t\t\t\t\tpluginName + \", which requests version \" + requestedVersion +\n\t\t\t\t\t\", but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\tif (requested.after(available)) {\n\t\t\treturn \"Dependency \" + dependency + \" too old for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed, but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\treturn \"\";\n\t}", "public static base_responses update(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction updateresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new tmtrafficaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\tupdateresources[i].sso = resources[i].sso;\n\t\t\t\tupdateresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\tupdateresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\tupdateresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private JsonObject getPendingJSONObject() {\n for (Map.Entry<String, BoxJSONObject> entry : this.children.entrySet()) {\n BoxJSONObject child = entry.getValue();\n JsonObject jsonObject = child.getPendingJSONObject();\n if (jsonObject != null) {\n if (this.pendingChanges == null) {\n this.pendingChanges = new JsonObject();\n }\n\n this.pendingChanges.set(entry.getKey(), jsonObject);\n }\n }\n return this.pendingChanges;\n }", "private void exportModules() {\n\n // avoid to export modules if unnecessary\n if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue())\n || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) {\n m_logStream.println();\n m_logStream.println(\"NOT EXPORTING MODULES - you disabled copy and unzip.\");\n m_logStream.println();\n return;\n }\n CmsModuleManager moduleManager = OpenCms.getModuleManager();\n\n Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty())\n ? m_currentConfiguration.getConfiguredModules()\n : m_modulesToExport;\n\n for (String moduleName : modulesToExport) {\n CmsModule module = moduleManager.getModule(moduleName);\n if (module != null) {\n CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler(\n getCmsObject(),\n module,\n \"Git export handler\");\n try {\n handler.exportData(\n getCmsObject(),\n new CmsPrintStreamReport(\n m_logStream,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()),\n false));\n } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) {\n e.printStackTrace(m_logStream);\n }\n }\n }\n }", "private void parseUsersAuthentication(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list)\n throws XMLStreamException {\n final ModelNode usersAddress = realmAddress.clone().add(AUTHENTICATION, USERS);\n list.add(Util.getEmptyOperation(ADD, usersAddress));\n\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n switch (element) {\n case USER: {\n parseUser(reader, usersAddress, list);\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }", "public static final int getInt(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Integer.parseInt(value));\n }" ]
Set the list of supported resolutions. Each resolution is specified in map units per pixel. @param resolutions resolutions @deprecated use {@link #setZoomLevels()}
[ "@Deprecated\n\tpublic void setResolutions(List<Double> resolutions) {\n\t\tgetZoomLevels().clear();\n\t\tfor (Double resolution : resolutions) {\n\t\t\tgetZoomLevels().add(new ScaleInfo(1. / resolution));\n\t\t}\n\t}" ]
[ "private void createStringMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int position) throws IOException {\n // System.out.println(\"createStringMappings string \");\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n if (stringValues.length > 0 && !stringValues[0].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"t\", filterString(stringValues[0].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n if (stringValues.length > 1 && !stringValues[1].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"lemma\", filterString(stringValues[1].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n }", "private void deliverMountUpdate(SlotReference slot, boolean mounted) {\n if (mounted) {\n logger.info(\"Reporting media mounted in \" + slot);\n\n } else {\n logger.info(\"Reporting media removed from \" + slot);\n }\n for (final MountListener listener : getMountListeners()) {\n try {\n if (mounted) {\n listener.mediaMounted(slot);\n } else {\n listener.mediaUnmounted(slot);\n }\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering mount update to listener\", t);\n }\n }\n if (mounted) {\n MetadataCache.tryAutoAttaching(slot);\n }\n }", "private Set<T> findMatching(R resolvable) {\n Set<T> result = new HashSet<T>();\n for (T bean : getAllBeans(resolvable)) {\n if (matches(resolvable, bean)) {\n result.add(bean);\n }\n }\n return result;\n }", "public static int cudnnGetReductionIndicesSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }", "public static String getSolrRangeString(String from, String to) {\n\n // If a parameter is not initialized, use the asterisk '*' operator\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(from)) {\n from = \"*\";\n }\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(to)) {\n to = \"*\";\n }\n\n return String.format(\"[%s TO %s]\", from, to);\n }", "public String getAlias(String path)\r\n {\r\n if (m_allPathsAliased && m_attributePath.lastIndexOf(path) != -1)\r\n {\r\n return m_name;\r\n }\r\n Object retObj = m_mapping.get(path);\r\n if (retObj != null)\r\n {\r\n return (String) retObj;\r\n }\r\n return null;\r\n }", "@Override\n public boolean parseAndValidateRequest() {\n boolean result = false;\n if(!super.parseAndValidateRequest() || !hasVectorClock(this.isVectorClockOptional)\n || !hasContentLength() || !hasContentType()) {\n result = false;\n } else {\n result = true;\n }\n\n return result;\n }", "public static base_responses add(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction addresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].profilename = resources[i].profilename;\n\t\t\t\taddresources[i].parameters = resources[i].parameters;\n\t\t\t\taddresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\taddresources[i].quiettime = resources[i].quiettime;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public UpdateBuilder<T, ID> updateColumnValue(String columnName, Object value) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetValue(columnName, fieldType, value));\n\t\treturn this;\n\t}" ]
Blocking function which completes the migration of one store @param storeName The name of the store @param adminClient Admin client used to initiate the copying of data @param stealInfo The steal information @param isReadOnlyStore Boolean indicating that this is a read-only store
[ "private void rebalanceStore(String storeName,\n final AdminClient adminClient,\n RebalanceTaskInfo stealInfo,\n boolean isReadOnlyStore) {\n // Move partitions\n if (stealInfo.getPartitionIds(storeName) != null && stealInfo.getPartitionIds(storeName).size() > 0) {\n\n logger.info(getHeader(stealInfo) + \"Starting partitions migration for store \"\n + storeName + \" from donor node \" + stealInfo.getDonorId());\n\n int asyncId = adminClient.storeMntOps.migratePartitions(stealInfo.getDonorId(),\n metadataStore.getNodeId(),\n storeName,\n stealInfo.getPartitionIds(storeName),\n null,\n stealInfo.getInitialCluster());\n rebalanceStatusList.add(asyncId);\n\n if(logger.isDebugEnabled()) {\n logger.debug(getHeader(stealInfo) + \"Waiting for completion for \" + storeName\n + \" with async id \" + asyncId);\n }\n adminClient.rpcOps.waitForCompletion(metadataStore.getNodeId(),\n asyncId,\n voldemortConfig.getRebalancingTimeoutSec(),\n TimeUnit.SECONDS,\n getStatus());\n\n rebalanceStatusList.remove((Object) asyncId);\n\n logger.info(getHeader(stealInfo) + \"Completed partition migration for store \"\n + storeName + \" from donor node \" + stealInfo.getDonorId());\n }\n\n logger.info(getHeader(stealInfo) + \"Finished all migration for store \" + storeName);\n }" ]
[ "public static void init(Context cx, Scriptable scope, boolean sealed)\n throws RhinoException {\n JSAdapter obj = new JSAdapter(cx.newObject(scope));\n obj.setParentScope(scope);\n obj.setPrototype(getFunctionPrototype(scope));\n obj.isPrototype = true;\n ScriptableObject.defineProperty(scope, \"JSAdapter\", obj,\n ScriptableObject.DONTENUM);\n }", "public static base_responses unset(nitro_service client, String name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (name != null && name.length > 0) {\n\t\t\tclusternodegroup unsetresources[] = new clusternodegroup[name.length];\n\t\t\tfor (int i=0;i<name.length;i++){\n\t\t\t\tunsetresources[i] = new clusternodegroup();\n\t\t\t\tunsetresources[i].name = name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator)\n {\n GenericCriteria result = new GenericCriteria(m_properties);\n result.setOperator(operator);\n list.add(result);\n processBlock(result.getCriteriaList(), getChildBlock(block));\n processBlock(list, getListNextBlock(block));\n }", "public static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) {\n List<String> storeNames = Lists.newArrayList();\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeNames.add(storeDefinition.getName());\n }\n return storeNames;\n }", "public CollectionRequest<Task> getTasksWithTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "public static String detokenize(List<String> tokens) {\n return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens));\n }", "public static InstalledIdentity load(final InstalledImage installedImage, final ProductConfig productConfig, List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n return LayersFactory.load(installedImage, productConfig, moduleRoots, bundleRoots);\n }", "public static String pennPOSToWordnetPOS(String s) {\r\n if (s.matches(\"NN|NNP|NNS|NNPS\")) {\r\n return \"noun\";\r\n }\r\n if (s.matches(\"VB|VBD|VBG|VBN|VBZ|VBP|MD\")) {\r\n return \"verb\";\r\n }\r\n if (s.matches(\"JJ|JJR|JJS|CD\")) {\r\n return \"adjective\";\r\n }\r\n if (s.matches(\"RB|RBR|RBS|RP|WRB\")) {\r\n return \"adverb\";\r\n }\r\n return null;\r\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 }" ]
Use this API to fetch all the nsrollbackcmd resources that are configured on netscaler. This uses nsrollbackcmd_args which is a way to provide additional arguments while fetching the resources.
[ "public static nsrollbackcmd[] get(nitro_service service, nsrollbackcmd_args args) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service, option);\n\t\treturn response;\n\t}" ]
[ "public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{\n\t\trnatparam unsetresource = new rnatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }", "public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {\n\n int width = originalImage.getWidth();\n\n int height = originalImage.getHeight();\n\n int heightPercent = (heightOut * 100) / height;\n\n int newWidth = (width * heightPercent) / 100;\n\n BufferedImage resizedImage =\n new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);\n g.dispose();\n\n return resizedImage;\n }", "private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date)\n {\n String year = date.getYear();\n if (year == null || year.isEmpty())\n {\n // In order to process recurring exceptions using MPXJ, we need a start and end date\n // to constrain the number of dates we generate.\n // May need to pre-process the tasks in order to calculate a start and finish date.\n // TODO: handle recurring exceptions\n }\n else\n {\n Calendar calendar = DateHelper.popCalendar();\n calendar.set(Calendar.YEAR, Integer.parseInt(year));\n calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth()));\n calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate()));\n Date exceptionDate = calendar.getTime();\n DateHelper.pushCalendar(calendar);\n ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate);\n\n // TODO: not sure how NEUTRAL should be handled\n if (\"WORKING_DAY\".equals(date.getType()))\n {\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "public List<Long> getOffsets(OffsetRequest offsetRequest) {\n ILog log = getLog(offsetRequest.topic, offsetRequest.partition);\n if (log != null) {\n return log.getOffsetsBefore(offsetRequest);\n }\n return ILog.EMPTY_OFFSETS;\n }", "public Duration getStartVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.START_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineStart(), getStart(), format);\n set(AssignmentField.START_VARIANCE, variance);\n }\n return (variance);\n }", "protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tif (!this.cachedPoolStrategy){\r\n\t\t\tconnectionHandle.clearStatementCaches(false);\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.getReplayLog() != null){\r\n\t\t\tconnectionHandle.getReplayLog().clear();\r\n\t\t\tconnectionHandle.recoveryResult.getReplaceTarget().clear();\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.isExpired() || \r\n\t\t\t\t(!this.poolShuttingDown \r\n\t\t\t\t\t\t&& connectionHandle.isPossiblyBroken()\r\n\t\t\t\t&& !isConnectionHandleAlive(connectionHandle))){\r\n\r\n if (connectionHandle.isExpired()) {\r\n connectionHandle.internalClose();\r\n }\r\n\r\n\t\t\tConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition();\r\n\t\t\tpostDestroyConnection(connectionHandle);\r\n\r\n\t\t\tmaybeSignalForMoreConnections(connectionPartition);\r\n\t\t\tconnectionHandle.clearStatementCaches(true);\r\n\t\t\treturn; // don't place back in queue - connection is broken or expired.\r\n\t\t}\r\n\r\n\r\n\t\tconnectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis());\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tputConnectionBackInPartition(connectionHandle);\r\n\t\t} else {\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}", "private MBeanServer getServerForName(String name) {\n try {\n MBeanServer mbeanServer = null;\n final ObjectName objectNameQuery = new ObjectName(name + \":type=Service,*\");\n\n for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {\n if (server.queryNames(objectNameQuery, null).size() > 0) {\n mbeanServer = server;\n // we found it, bail out\n break;\n }\n }\n\n return mbeanServer;\n } catch (Exception e) {\n }\n\n return null;\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 }" ]
Prints a debug log message that details the time taken for the Http request to be parsed by the coordinator @param operationType @param receivedTimeInMs
[ "protected void debugLog(String operationType, Long receivedTimeInMs) {\n long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs);\n int numVectorClockEntries = (this.parsedVectorClock == null ? 0\n : this.parsedVectorClock.getVersionMap()\n .size());\n logger.debug(\"Received a new request. Operation type: \" + operationType + \" , Key(s): \"\n + keysHexString(this.parsedKeys) + \" , Store: \" + this.storeName\n + \" , Origin time (in ms): \" + (this.parsedRequestOriginTimeInMs)\n + \" , Request received at time(in ms): \" + receivedTimeInMs\n + \" , Num vector clock entries: \" + numVectorClockEntries\n + \" , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): \"\n + durationInMs);\n\n }" ]
[ "private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }", "public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "private void writeFields(String objectName, FieldContainer container, FieldType[] fields) throws IOException\n {\n m_writer.writeStartObject(objectName);\n for (FieldType field : fields)\n {\n Object value = container.getCurrentValue(field);\n if (value != null)\n {\n writeField(field, value);\n }\n }\n m_writer.writeEndObject();\n }", "private static void listResourceNotes(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n String notes = resource.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + resource.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }", "private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }", "protected Declaration createDeclaration(String property, Term<?> term)\n {\n Declaration d = CSSFactory.getRuleFactory().createDeclaration();\n d.unlock();\n d.setProperty(property);\n d.add(term);\n return d;\n }", "public SourceBuilder addLine(String fmt, Object... args) {\n add(fmt, args);\n source.append(LINE_SEPARATOR);\n return this;\n }", "public void setDateAttribute(String name, Date value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DateAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\t}", "public void addModuleToExport(final String moduleName) {\n\n if (m_modulesToExport == null) {\n m_modulesToExport = new HashSet<String>();\n }\n m_modulesToExport.add(moduleName);\n }" ]
Seeks to the given day within the current month @param dayOfMonth the day of the month to seek to, represented as an integer from 1 to 31. Must be guaranteed to parse as an Integer. If this day is beyond the last day of the current month, the actual last day of the month will be used.
[ "public void seekToDayOfMonth(String dayOfMonth) {\n int dayOfMonthInt = Integer.parseInt(dayOfMonth);\n assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31);\n \n markDateInvocation();\n \n dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt);\n }" ]
[ "@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new SingleInstanceWorkloadStrategy(job, name, arguments, endpointRegistry, execService));\n }\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 }", "public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public GroovyFieldDoc[] fields() {\n Collections.sort(fields);\n return fields.toArray(new GroovyFieldDoc[fields.size()]);\n }", "public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n String url = null;\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 AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Synchronize metadata versions across all nodes\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n System.out.println(\" node = all nodes\");\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient);\n\n Versioned<Properties> versionedProps = mergeAllVersions(adminClient);\n\n printVersions(versionedProps);\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm,\n \"do you want to synchronize metadata versions to all node\"))\n return;\n\n adminClient.metadataMgmtOps.setMetadataVersion(versionedProps);\n }", "private void setCorrectDay(Calendar date) {\n\n if (monthHasNotDay(date)) {\n date.set(Calendar.DAY_OF_MONTH, date.getActualMaximum(Calendar.DAY_OF_MONTH));\n } else {\n date.set(Calendar.DAY_OF_MONTH, m_dayOfMonth);\n }\n }", "public void ifMemberTagValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n if (isTagValueEqual(attributes, FOR_FIELD)) {\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (isTagValueEqual(attributes, FOR_METHOD)) {\r\n generate(template);\r\n }\r\n }\r\n }", "public static ManagerFunctions.InputN createMultTransA() {\n return (inputs, manager) -> {\n if( inputs.size() != 2 )\n throw new RuntimeException(\"Two inputs required\");\n\n final Variable varA = inputs.get(0);\n final Variable varB = inputs.get(1);\n\n Operation.Info ret = new Operation.Info();\n\n if( varA instanceof VariableMatrix && varB instanceof VariableMatrix ) {\n\n // The output matrix or scalar variable must be created with the provided manager\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"multTransA-mm\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)varA).matrix;\n DMatrixRMaj mB = ((VariableMatrix)varB).matrix;\n\n CommonOps_DDRM.multTransA(mA,mB,output.matrix);\n }\n };\n } else {\n throw new IllegalArgumentException(\"Expected both inputs to be a matrix\");\n }\n\n return ret;\n };\n }", "public int findAnimation(GVRAnimation findme)\n {\n int index = 0;\n for (GVRAnimation anim : mAnimations)\n {\n if (anim == findme)\n {\n return index;\n }\n ++index;\n }\n return -1;\n }" ]
Indicates if a bean is proxyable @param bean The bean to test @return True if proxyable, false otherwise
[ "public static boolean isBeanProxyable(Bean<?> bean, BeanManagerImpl manager) {\n if (bean instanceof RIBean<?>) {\n return ((RIBean<?>) bean).isProxyable();\n } else {\n return Proxies.isTypesProxyable(bean.getTypes(), manager.getServices());\n }\n }" ]
[ "public int getBoneIndex(GVRSceneObject bone)\n {\n for (int i = 0; i < getNumBones(); ++i)\n if (mBones[i] == bone)\n return i;\n return -1;\n }", "private void writeTasks() throws IOException\n {\n writeAttributeTypes(\"task_types\", TaskField.values());\n\n m_writer.writeStartList(\"tasks\");\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task);\n }\n m_writer.writeEndList();\n }", "public InputStream getAvatar() {\n URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n return response.getBody();\n }", "void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }", "private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }", "public Weld addPackages(boolean scanRecursively, Class<?>... packageClasses) {\n for (Class<?> packageClass : packageClasses) {\n addPackage(scanRecursively, packageClass);\n }\n return this;\n }", "public static int writeVint(byte[] dest, int offset, int i) {\n if (i >= -112 && i <= 127) {\n dest[offset++] = (byte) i;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n dest[offset++] = (byte) len;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n for (int idx = len; idx != 0; idx--) {\n int shiftbits = (idx - 1) * 8;\n long mask = 0xFFL << shiftbits;\n dest[offset++] = (byte) ((i & mask) >> shiftbits);\n }\n }\n\n return offset;\n }", "public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {\n return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();\n }", "public static double TopsoeDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double den = p[i] + q[i];\n r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);\n }\n }\n return r;\n }" ]
Checks to see if a WORD matches the name of a macro. if it does it applies the macro at that location
[ "void insertMacros(TokenList tokens ) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD ) {\n Macro v = lookupMacro(t.word);\n if (v != null) {\n TokenList.Token before = t.previous;\n List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();\n t = parseMacroInput(inputs,t.next);\n\n TokenList sniplet = v.execute(inputs);\n tokens.extractSubList(before.next,t);\n tokens.insertAfter(before,sniplet);\n t = sniplet.last;\n }\n }\n t = t.next;\n }\n }" ]
[ "private void add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }", "private int[] getCompressIndexAndCount(CompressOptions options, boolean createMixed) {\n\t\tif(options != null) {\n\t\t\tCompressionChoiceOptions rangeSelection = options.rangeSelection;\n\t\t\tRangeList compressibleSegs = rangeSelection.compressHost() ? getZeroRangeSegments() : getZeroSegments();\n\t\t\tint maxIndex = -1, maxCount = 0;\n\t\t\tint segmentCount = getSegmentCount();\n\t\t\t\n\t\t\tboolean compressMixed = createMixed && options.compressMixedOptions.compressMixed(this);\n\t\t\tboolean preferHost = (rangeSelection == CompressOptions.CompressionChoiceOptions.HOST_PREFERRED);\n\t\t\tboolean preferMixed = createMixed && (rangeSelection == CompressOptions.CompressionChoiceOptions.MIXED_PREFERRED);\n\t\t\tfor(int i = compressibleSegs.size() - 1; i >= 0 ; i--) {\n\t\t\t\tRange range = compressibleSegs.getRange(i);\n\t\t\t\tint index = range.index;\n\t\t\t\tint count = range.length;\n\t\t\t\tif(createMixed) {\n\t\t\t\t\t//so here we shorten the range to exclude the mixed part if necessary\n\t\t\t\t\tint mixedIndex = IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - addressSegmentIndex;\n\t\t\t\t\tif(!compressMixed ||\n\t\t\t\t\t\t\tindex > mixedIndex || index + count < segmentCount) { //range does not include entire mixed part. We never compress only part of a mixed part.\n\t\t\t\t\t\t//the compressible range must stop at the mixed part\n\t\t\t\t\t\tcount = Math.min(count, mixedIndex - index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//select this range if is the longest\n\t\t\t\tif(count > 0 && count >= maxCount && (options.compressSingle || count > 1)) {\n\t\t\t\t\tmaxIndex = index;\n\t\t\t\t\tmaxCount = count;\n\t\t\t\t}\n\t\t\t\tif(preferHost && isPrefixed() &&\n\t\t\t\t\t\t((index + count) * IPv6Address.BITS_PER_SEGMENT) > getNetworkPrefixLength()) { //this range contains the host\n\t\t\t\t\t//Since we are going backwards, this means we select as the maximum any zero segment that includes the host\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(preferMixed && index + count >= segmentCount) { //this range contains the mixed section\n\t\t\t\t\t//Since we are going backwards, this means we select to compress the mixed segment\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(maxIndex >= 0) {\n\t\t\t\treturn new int[] {maxIndex, maxCount};\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "private static boolean waitTillNoNotifications(Environment env, TableRange range)\n throws TableNotFoundException {\n boolean sawNotifications = false;\n long retryTime = MIN_SLEEP_MS;\n\n log.debug(\"Scanning tablet {} for notifications\", range);\n\n long start = System.currentTimeMillis();\n while (hasNotifications(env, range)) {\n sawNotifications = true;\n long sleepTime = Math.max(System.currentTimeMillis() - start, retryTime);\n log.debug(\"Tablet {} had notfications, will rescan in {}ms\", range, sleepTime);\n UtilWaitThread.sleep(sleepTime);\n retryTime = Math.min(MAX_SLEEP_MS, (long) (retryTime * 1.5));\n start = System.currentTimeMillis();\n }\n\n return sawNotifications;\n }", "public static void main(String[] args) throws Exception {\n if(args.length < 1)\n Utils.croak(\"USAGE: java \" + HdfsFetcher.class.getName()\n + \" url [keytab-location kerberos-username hadoop-config-path [destDir]]\");\n String url = args[0];\n\n VoldemortConfig config = new VoldemortConfig(-1, \"\");\n\n HdfsFetcher fetcher = new HdfsFetcher(config);\n\n String destDir = null;\n Long diskQuotaSizeInKB;\n if(args.length >= 4) {\n fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]);\n fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]);\n fetcher.voldemortConfig.setHadoopConfigPath(args[3]);\n }\n if(args.length >= 5)\n destDir = args[4];\n\n if(args.length >= 6)\n diskQuotaSizeInKB = Long.parseLong(args[5]);\n else\n diskQuotaSizeInKB = null;\n\n // for testing we want to be able to download a single file\n allowFetchingOfSingleFile = true;\n\n FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url);\n Path p = new Path(url);\n\n FileStatus status = fs.listStatus(p)[0];\n long size = status.getLen();\n long start = System.currentTimeMillis();\n if(destDir == null)\n destDir = System.getProperty(\"java.io.tmpdir\") + File.separator + start;\n\n File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB);\n\n double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMaximumFractionDigits(2);\n System.out.println(\"Fetch to \" + location + \" completed: \"\n + nf.format(rate / (1024.0 * 1024.0)) + \" MB/sec.\");\n fs.close();\n }", "PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\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 void setTime(Calendar cal, Date time)\n {\n if (time != null)\n {\n Calendar startCalendar = popCalendar(time);\n cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));\n cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));\n cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND));\n pushCalendar(startCalendar);\n }\n }", "public void store(String gavc,\n String action,\n String commentText,\n DbCredential credential,\n String entityType) {\n DbComment comment = new DbComment();\n comment.setEntityId(gavc);\n comment.setEntityType(entityType);\n comment.setDbCommentedBy(credential.getUser());\n comment.setAction(action);\n\n if(!commentText.isEmpty()) {\n comment.setDbCommentText(commentText);\n }\n\n comment.setDbCreatedDateTime(new Date());\n\n repositoryHandler.store(comment);\n }", "public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}" ]
Used to determine if multiple cost rates apply to this assignment. @return true if multiple cost rates apply to this assignment
[ "private boolean hasMultipleCostRates()\n {\n boolean result = false;\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n //\n // We assume here that if there is just one entry in the cost rate\n // table, this is an open ended rate which covers any work, it won't\n // have specific dates attached to it.\n //\n if (table.size() > 1)\n {\n //\n // If we have multiple rates in the table, see if the same rate\n // is in force at the start and the end of the aaaignment.\n //\n CostRateTableEntry startEntry = table.getEntryByDate(getStart());\n CostRateTableEntry finishEntry = table.getEntryByDate(getFinish());\n result = (startEntry != finishEntry);\n }\n }\n return result;\n }" ]
[ "private void toCorrectDateWithDay(Calendar date, WeekOfMonth week) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int daysToFirstWeekDayMatch = ((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS)\n - (date.get(Calendar.DAY_OF_WEEK))) % I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n date.add(Calendar.DAY_OF_MONTH, daysToFirstWeekDayMatch);\n int wouldBeDayOfMonth = date.get(Calendar.DAY_OF_MONTH)\n + ((week.ordinal()) * I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n if (wouldBeDayOfMonth > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth - I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n } else {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth);\n }\n\n }", "@UiHandler(\"m_atDay\")\r\n void onWeekDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekDay(event.getValue());\r\n }\r\n }", "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 }", "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 static Properties loadGradleProperties(FilePath gradlePropertiesFilePath)\n throws IOException, InterruptedException {\n return gradlePropertiesFilePath.act(new MasterToSlaveFileCallable<Properties>() {\n public Properties invoke(File gradlePropertiesFile, VirtualChannel channel) throws IOException, InterruptedException {\n Properties gradleProps = new Properties();\n if (gradlePropertiesFile.exists()) {\n debuggingLogger.fine(\"Gradle properties file exists at: \" + gradlePropertiesFile.getAbsolutePath());\n FileInputStream stream = null;\n try {\n stream = new FileInputStream(gradlePropertiesFile);\n gradleProps.load(stream);\n } catch (IOException e) {\n debuggingLogger.fine(\"IO exception occurred while trying to read properties file from: \" +\n gradlePropertiesFile.getAbsolutePath());\n throw new RuntimeException(e);\n } finally {\n IOUtils.closeQuietly(stream);\n }\n }\n return gradleProps;\n }\n });\n\n }", "private double CosineInterpolate(double x1, double x2, double a) {\n double f = (1 - Math.cos(a * Math.PI)) * 0.5;\n\n return x1 * (1 - f) + x2 * f;\n }", "public void process(CustomFieldContainer indicators, ProjectProperties properties, Props props)\n {\n m_container = indicators;\n m_properties = properties;\n m_data = props.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n\n if (m_data != null)\n {\n int columnsCount = MPPUtility.getInt(m_data, 4);\n m_headerOffset = 8;\n for (int loop = 0; loop < columnsCount; loop++)\n {\n processColumns();\n }\n }\n }", "public Collection<Integer> getNumericCodes() {\n Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public Long getLong(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}" ]
Locate the no arg constructor for the class.
[ "private Constructor<T> findNoArgConstructor(Class<T> dataClass) {\n\t\tConstructor<T>[] constructors;\n\t\ttry {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tConstructor<T>[] consts = (Constructor<T>[]) dataClass.getDeclaredConstructors();\n\t\t\t// i do this [grossness] to be able to move the Suppress inside the method\n\t\t\tconstructors = consts;\n\t\t} catch (Exception e) {\n\t\t\tthrow new IllegalArgumentException(\"Can't lookup declared constructors for \" + dataClass, e);\n\t\t}\n\t\tfor (Constructor<T> con : constructors) {\n\t\t\tif (con.getParameterTypes().length == 0) {\n\t\t\t\tif (!con.isAccessible()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcon.setAccessible(true);\n\t\t\t\t\t} catch (SecurityException e) {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Could not open access to constructor for \" + dataClass);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn con;\n\t\t\t}\n\t\t}\n\t\tif (dataClass.getEnclosingClass() == null) {\n\t\t\tthrow new IllegalArgumentException(\"Can't find a no-arg constructor for \" + dataClass);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Can't find a no-arg constructor for \" + dataClass + \". Missing static on inner class?\");\n\t\t}\n\t}" ]
[ "private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }", "public static base_responses add(nitro_service client, cachepolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachepolicylabel addresources[] = new cachepolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cachepolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].evaluates = resources[i].evaluates;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static base_response Import(nitro_service client, responderhtmlpage resource) throws Exception {\n\t\tresponderhtmlpage Importresource = new responderhtmlpage();\n\t\tImportresource.src = resource.src;\n\t\tImportresource.name = resource.name;\n\t\tImportresource.comment = resource.comment;\n\t\tImportresource.overwrite = resource.overwrite;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}", "public static BoxCollaborationWhitelistExemptTarget.Info create(final BoxAPIConnection api, String userID) {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"user\", new JsonObject()\n .add(\"type\", \"user\")\n .add(\"id\", userID));\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelistExemptTarget userWhitelist = new BoxCollaborationWhitelistExemptTarget(api,\n responseJSON.get(\"id\").asString());\n\n return userWhitelist.new Info(responseJSON);\n }", "private List<Versioned<byte[]>> disassembleValues(byte[] values) throws IOException {\n\n if(values == null)\n return new ArrayList<Versioned<byte[]>>(0);\n\n List<Versioned<byte[]>> returnList = new ArrayList<Versioned<byte[]>>();\n ByteArrayInputStream stream = new ByteArrayInputStream(values);\n DataInputStream dataStream = new DataInputStream(stream);\n\n while(dataStream.available() > 0) {\n byte[] object = new byte[dataStream.readInt()];\n dataStream.read(object);\n\n byte[] clockBytes = new byte[dataStream.readInt()];\n dataStream.read(clockBytes);\n VectorClock clock = new VectorClock(clockBytes);\n\n returnList.add(new Versioned<byte[]>(object, clock));\n }\n\n return returnList;\n }", "public Search groupField(String fieldName, boolean isNumber) {\r\n assertNotEmpty(fieldName, \"fieldName\");\r\n if (isNumber) {\r\n databaseHelper.query(\"group_field\", fieldName + \"<number>\");\r\n } else {\r\n databaseHelper.query(\"group_field\", fieldName);\r\n }\r\n return this;\r\n }", "protected void runQuery() {\n\n String pool = m_pool.getValue();\n String stmt = m_script.getValue();\n if (stmt.trim().isEmpty()) {\n return;\n }\n CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);\n List<Throwable> errors = new ArrayList<>();\n CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);\n if (errors.size() > 0) {\n CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));\n } else {\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));\n window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));\n A_CmsUI.get().addWindow(window);\n window.center();\n }\n\n }", "public static DMatrixRBlock initializeQ(DMatrixRBlock Q,\n int numRows , int numCols , int blockLength ,\n boolean compact) {\n int minLength = Math.min(numRows,numCols);\n if( compact ) {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,minLength,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != minLength ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n } else {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,numRows,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != numRows ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n }\n return Q;\n }", "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}" ]
Create the label for a grid line. @param value the value of the line @param unit the unit that the value is in
[ "public static String createLabel(final double value, final String unit, final GridLabelFormat format) {\n final double zero = 0.000000001;\n if (format != null) {\n return format.format(value, unit);\n } else {\n if (Math.abs(value - Math.round(value)) < zero) {\n return String.format(\"%d %s\", Math.round(value), unit);\n } else if (\"m\".equals(unit)) {\n // meter: no decimals\n return String.format(\"%1.0f %s\", value, unit);\n } else if (NonSI.DEGREE_ANGLE.toString().equals(unit)) {\n // degree: by default 6 decimals\n return String.format(\"%1.6f %s\", value, unit);\n } else {\n return String.format(\"%f %s\", value, unit);\n }\n }\n }" ]
[ "protected synchronized void quit() {\n log.debug(\"Stopping {}\", getName());\n closeServerSocket();\n\n // Close all handlers. Handler threads terminate if run loop exits\n synchronized (handlers) {\n for (ProtocolHandler handler : handlers) {\n handler.close();\n }\n handlers.clear();\n }\n log.debug(\"Stopped {}\", getName());\n }", "public static vpath[] get(nitro_service service) throws Exception{\n\t\tvpath obj = new vpath();\n\t\tvpath[] response = (vpath[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);\n } catch (IncompatibleTestMatrixException e) {\n LOGGER.info(String.format(\"Unable to load test matrix for %s\", testName), e);\n resultBuilder.recordError(testName, e);\n }\n }\n return resultBuilder.build();\n }", "public PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }", "public Duration getWorkVariance()\n {\n Duration variance = (Duration) getCachedValue(ResourceField.WORK_VARIANCE);\n if (variance == null)\n {\n Duration work = getWork();\n Duration baselineWork = getBaselineWork();\n if (work != null && baselineWork != null)\n {\n variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectProperties()).getDuration(), work.getUnits());\n set(ResourceField.WORK_VARIANCE, variance);\n }\n }\n return (variance);\n }", "private Expression getExpression(String expressionString) throws ParseException {\n\t\tif (!expressionCache.containsKey(expressionString)) {\n\t\t\tExpression expression;\n\t\t\texpression = parser.parseExpression(expressionString);\n\t\t\texpressionCache.put(expressionString, expression);\n\t\t}\n\t\treturn expressionCache.get(expressionString);\n\n\t}", "public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\n }", "public static boolean containsOnlyNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o!= null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public static final List<String> listProjectNames(File directory)\n {\n List<String> result = new ArrayList<String>();\n\n File[] files = directory.listFiles(new FilenameFilter()\n {\n @Override public boolean accept(File dir, String name)\n {\n return name.toUpperCase().endsWith(\"STR.P3\");\n }\n });\n\n if (files != null)\n {\n for (File file : files)\n {\n String fileName = file.getName();\n String prefix = fileName.substring(0, fileName.length() - 6);\n result.add(prefix);\n }\n }\n\n Collections.sort(result);\n\n return result;\n }" ]
Check if the given class represents an array of primitive wrappers, i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double. @param clazz the class to check @return whether the given class is a primitive wrapper array class
[ "public static boolean isPrimitiveWrapperArray(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));\n\t}" ]
[ "public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}", "@Override\n public void onKeyDown(KeyDownEvent event) {\n\tchar c = MiscUtils.getCharCode(event.getNativeEvent());\n\tonKeyCodeEvent(event, box.getValue()+c);\n }", "private void processPredecessors(Gantt gantt)\n {\n for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())\n {\n String predecessors = ganttTask.getP();\n if (predecessors != null && !predecessors.isEmpty())\n {\n String wbs = ganttTask.getID();\n Task task = m_taskMap.get(wbs);\n for (String predecessor : predecessors.split(\";\"))\n {\n Task predecessorTask = m_projectFile.getTaskByID(Integer.valueOf(predecessor));\n task.addPredecessor(predecessorTask, RelationType.FINISH_START, ganttTask.getL());\n }\n }\n }\n }", "private void readDefinitions()\n {\n for (MapRow row : m_tables.get(\"TTL\"))\n {\n Integer id = row.getInteger(\"DEFINITION_ID\");\n List<MapRow> list = m_definitions.get(id);\n if (list == null)\n {\n list = new ArrayList<MapRow>();\n m_definitions.put(id, list);\n }\n list.add(row);\n }\n\n List<MapRow> rows = m_definitions.get(WBS_FORMAT_ID);\n if (rows != null)\n {\n m_wbsFormat = new SureTrakWbsFormat(rows.get(0));\n }\n }", "public static String getCountryCodeAndCheckDigit(final String iban) {\n return iban.substring(COUNTRY_CODE_INDEX,\n COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH);\n }", "public static servicegroup_stats get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_stats response = (servicegroup_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public List<CmsJspNavElement> getSubNavigation() {\n\n if (m_subNavigation == null) {\n if (m_resource.isFile()) {\n m_subNavigation = Collections.emptyList();\n } else if (m_navContext == null) {\n try {\n throw new Exception(\"Can not get subnavigation because navigation context is not set.\");\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n m_subNavigation = Collections.emptyList();\n }\n } else {\n CmsJspNavBuilder navBuilder = m_navContext.getNavBuilder();\n m_subNavigation = navBuilder.getNavigationForFolder(\n navBuilder.getCmsObject().getSitePath(m_resource),\n m_navContext.getVisibility(),\n m_navContext.getFilter());\n }\n\n }\n return m_subNavigation;\n\n }", "public void check(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureNoTableInfoIfNoRepositoryInfo(classDef, checkLevel);\r\n checkModifications(classDef, checkLevel);\r\n checkExtents(classDef, checkLevel);\r\n ensureTableIfNecessary(classDef, checkLevel);\r\n checkFactoryClassAndMethod(classDef, checkLevel);\r\n checkInitializationMethod(classDef, checkLevel);\r\n checkPrimaryKey(classDef, checkLevel);\r\n checkProxyPrefetchingLimit(classDef, checkLevel);\r\n checkRowReader(classDef, checkLevel);\r\n checkObjectCache(classDef, checkLevel);\r\n checkProcedures(classDef, checkLevel);\r\n }", "public ResponseFromManager generateUpdateExecuteTask(ParallelTask task) {\n\n // add to map now; as can only pass final\n ParallelTaskManager.getInstance().addTaskToInProgressMap(\n task.getTaskId(), task);\n logger.info(\"Added task {} to the running inprogress map...\",\n task.getTaskId());\n\n boolean useReplacementVarMap = false;\n boolean useReplacementVarMapNodeSpecific = false;\n Map<String, StrStrMap> replacementVarMapNodeSpecific = null;\n Map<String, String> replacementVarMap = null;\n\n ResponseFromManager batchResponseFromManager = null;\n\n switch (task.getRequestReplacementType()) {\n case UNIFORM_VAR_REPLACEMENT:\n useReplacementVarMap = true;\n useReplacementVarMapNodeSpecific = false;\n replacementVarMap = task.getReplacementVarMap();\n break;\n case TARGET_HOST_SPECIFIC_VAR_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = true;\n replacementVarMapNodeSpecific = task\n .getReplacementVarMapNodeSpecific();\n break;\n case NO_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = false;\n break;\n default:\n logger.error(\"error request replacement type. default as no replacement\");\n }// end switch\n\n // generate content in nodedata\n InternalDataProvider dp = InternalDataProvider.getInstance();\n dp.genNodeDataMap(task);\n\n VarReplacementProvider.getInstance()\n .updateRequestWithReplacement(task, useReplacementVarMap,\n replacementVarMap, useReplacementVarMapNodeSpecific,\n replacementVarMapNodeSpecific);\n\n batchResponseFromManager = \n sendTaskToExecutionManager(task);\n\n removeTaskFromInProgressMap(task.getTaskId());\n logger.info(\n \"Removed task {} from the running inprogress map... \"\n + \". This task should be garbage collected if there are no other pointers.\",\n task.getTaskId());\n return batchResponseFromManager;\n\n }" ]
Reads the header data from a block. @param buffer block data @param offset current offset into block data @param postHeaderSkipBytes bytes to skip after reading the header @return current BlockHeader instance
[ "public BlockHeader read(byte[] buffer, int offset, int postHeaderSkipBytes)\n {\n m_offset = offset;\n\n System.arraycopy(buffer, m_offset, m_header, 0, 8);\n m_offset += 8;\n\n int nameLength = FastTrackUtility.getInt(buffer, m_offset);\n m_offset += 4;\n\n if (nameLength < 1 || nameLength > 255)\n {\n throw new UnexpectedStructureException();\n }\n\n m_name = new String(buffer, m_offset, nameLength, CharsetHelper.UTF16LE);\n m_offset += nameLength;\n\n m_columnType = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_flags = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_skip = new byte[postHeaderSkipBytes];\n System.arraycopy(buffer, m_offset, m_skip, 0, postHeaderSkipBytes);\n m_offset += postHeaderSkipBytes;\n\n return this;\n }" ]
[ "public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }", "@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }", "public static ProjectReader getProjectReader(String name) throws MPXJException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectReader> fileClass = READER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot read files of type: \" + extension);\n }\n\n try\n {\n ProjectReader file = fileClass.newInstance();\n return (file);\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to load project reader\", ex);\n }\n }", "public void setKnots(int[] x, int[] rgb, byte[] types) {\n\t\tnumKnots = rgb.length+2;\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tif (x != null)\n\t\t\tSystem.arraycopy(x, 0, xKnots, 1, numKnots-2);\n\t\telse\n\t\t\tfor (int i = 1; i > numKnots-1; i++)\n\t\t\t\txKnots[i] = 255*i/(numKnots-2);\n\t\tSystem.arraycopy(rgb, 0, yKnots, 1, numKnots-2);\n\t\tif (types != null)\n\t\t\tSystem.arraycopy(types, 0, knotTypes, 1, numKnots-2);\n\t\telse\n\t\t\tfor (int i = 0; i > numKnots; i++)\n\t\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}", "public static int daysDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS));\n }", "private void processHyperlinkData(Task task, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n task.setHyperlink(hyperlink);\n task.setHyperlinkAddress(address);\n task.setHyperlinkSubAddress(subaddress);\n }\n }", "synchronized JSONObject fetchEvents(Table table, final int limit) {\n final String tName = table.getName();\n Cursor cursor = null;\n String lastId = null;\n\n final JSONArray events = new JSONArray();\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getReadableDatabase();\n cursor = db.rawQuery(\"SELECT * FROM \" + tName +\n \" ORDER BY \" + KEY_CREATED_AT + \" ASC LIMIT \" + limit, null);\n\n\n while (cursor.moveToNext()) {\n if (cursor.isLast()) {\n lastId = cursor.getString(cursor.getColumnIndex(\"_id\"));\n }\n try {\n final JSONObject j = new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA)));\n events.put(j);\n } catch (final JSONException e) {\n // Ignore\n }\n }\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Could not fetch records out of database \" + tName + \".\", e);\n lastId = null;\n } finally {\n dbHelper.close();\n if (cursor != null) {\n cursor.close();\n }\n }\n\n if (lastId != null) {\n try {\n final JSONObject ret = new JSONObject();\n ret.put(lastId, events);\n return ret;\n } catch (JSONException e) {\n // ignore\n }\n }\n\n return null;\n }", "public void validateUniqueIDsForMicrosoftProject()\n {\n if (!isEmpty())\n {\n for (T entity : this)\n {\n if (NumberHelper.getInt(entity.getUniqueID()) > MS_PROJECT_MAX_UNIQUE_ID)\n {\n renumberUniqueIDs();\n break;\n }\n }\n }\n }", "public boolean load()\r\n {\r\n \t_load();\r\n \tjava.util.Iterator it = this.alChildren.iterator();\r\n \twhile (it.hasNext())\r\n \t{\r\n \t\tObject o = it.next();\r\n \t\tif (o instanceof OjbMetaTreeNode) ((OjbMetaTreeNode)o).load();\r\n \t}\r\n \treturn true;\r\n }" ]
Record the resource request wait time in us @param dest Destination of the socket for which the resource was requested. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param resourceRequestTimeUs The number of us to wait before getting a socket
[ "public void recordResourceRequestTimeUs(SocketDestination dest, long resourceRequestTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n } else {\n this.resourceRequestTimeRequestCounter.addRequest(resourceRequestTimeUs\n * Time.NS_PER_US);\n }\n }" ]
[ "public static boolean isSinglePositionPrefix(FieldInfo fieldInfo,\n String prefix) throws IOException {\n if (fieldInfo == null) {\n throw new IOException(\"no fieldInfo\");\n } else {\n String info = fieldInfo.getAttribute(\n MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n if (info == null) {\n throw new IOException(\"no \"\n + MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n } else {\n return Arrays.asList(info.split(Pattern.quote(MtasToken.DELIMITER)))\n .contains(prefix);\n }\n }\n }", "public static String formatConnectionEstablishmentMessage(final String connectionName, final String host, final String connectionReason) {\n\t\treturn CON_ESTABLISHMENT_FORMAT.format(new Object[] { connectionName, host, connectionReason });\n\t}", "public List<TerminalString> getOptionLongNamesWithDash() {\n List<ProcessedOption> opts = getOptions();\n List<TerminalString> names = new ArrayList<>(opts.size());\n for (ProcessedOption o : opts) {\n if(o.getValues().size() == 0 &&\n o.activator().isActivated(new ParsedCommand(this)))\n names.add(o.getRenderedNameWithDashes());\n }\n\n return names;\n }", "private void attachLocaleGroups(CmsResource copiedPage) throws CmsException {\n\n CmsLocaleGroupService localeGroupService = getRootCms().getLocaleGroupService();\n if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) {\n try {\n localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n }", "@Override\n public void invert(DMatrixRMaj A_inv) {\n blockB.reshape(A_inv.numRows,A_inv.numCols,false);\n\n alg.invert(blockB);\n\n MatrixOps_DDRB.convert(blockB,A_inv);\n }", "private void countCoordinates(int xCoord, int yCoord,\n\t\t\tItemDocument itemDocument) {\n\n\t\tfor (String siteKey : itemDocument.getSiteLinks().keySet()) {\n\t\t\tInteger count = this.siteCounts.get(siteKey);\n\t\t\tif (count == null) {\n\t\t\t\tthis.siteCounts.put(siteKey, 1);\n\t\t\t} else {\n\t\t\t\tthis.siteCounts.put(siteKey, count + 1);\n\t\t\t}\n\t\t}\n\n\t\tfor (ValueMap vm : this.valueMaps) {\n\t\t\tvm.countCoordinates(xCoord, yCoord, itemDocument);\n\t\t}\n\t}", "public int numOccurrences(int year, int month, int day) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(year + \"-\" + month + \"-\" + \"01\");\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n GregorianChronology calendar = GregorianChronology.getInstance();\n DateTimeField field = calendar.dayOfMonth();\n\n int days = 0;\n int count = 0;\n int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));\n while (days < num) {\n if (cal.get(Calendar.DAY_OF_WEEK) == day) {\n count++;\n }\n date = date.plusDays(1);\n cal.setTime(date.toDate());\n\n days++;\n }\n return count;\n }", "public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}", "protected void checkActiveState(Widget child) {\n // Check if this widget has a valid href\n String href = child.getElement().getAttribute(\"href\");\n String url = Window.Location.getHref();\n int pos = url.indexOf(\"#\");\n String location = pos >= 0 ? url.substring(pos, url.length()) : \"\";\n\n if (!href.isEmpty() && location.startsWith(href)) {\n ListItem li = findListItemParent(child);\n if (li != null) {\n makeActive(li);\n }\n } else if (child instanceof HasWidgets) {\n // Recursive check\n for (Widget w : (HasWidgets) child) {\n checkActiveState(w);\n }\n }\n }" ]
Logs an error by sending an error event to all listeners. Error events can be generated by any part of GearVRF, from any thread. They are always sent to the event receiver of the GVRContext. @param message error message @param sender object which had the error @see IErrorEvents
[ "public void logError(String message, Object sender) {\n getEventManager().sendEvent(this, IErrorEvents.class, \"onError\", new Object[] { message, sender });\n }" ]
[ "@Override\n protected void reset() {\n super.reset();\n mapClassesToNamedBoundProviders.clear();\n mapClassesToUnNamedBoundProviders.clear();\n hasTestModules = false;\n installBindingForScope();\n }", "public static VectorTile.Tile.GeomType toGeomType(Geometry geometry) {\n VectorTile.Tile.GeomType result = VectorTile.Tile.GeomType.UNKNOWN;\n\n if(geometry instanceof Point\n || geometry instanceof MultiPoint) {\n result = VectorTile.Tile.GeomType.POINT;\n\n } else if(geometry instanceof LineString\n || geometry instanceof MultiLineString) {\n result = VectorTile.Tile.GeomType.LINESTRING;\n\n } else if(geometry instanceof Polygon\n || geometry instanceof MultiPolygon) {\n result = VectorTile.Tile.GeomType.POLYGON;\n }\n\n return result;\n }", "public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,\n final int greedyAttempts,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<Integer> greedySwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(greedySwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(greedySwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n for(int i = 0; i < greedyAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,\n nodeIds,\n greedySwapMaxPartitionsPerNode,\n greedySwapMaxPartitionsPerZone,\n storeDefs);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (swap attempt \" + i + \" in zone \"\n + zoneIds.get(zoneIdOffset) + \")\");\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n return returnCluster;\n }", "public static void main(String[] args) {\r\n try {\r\n TreeFactory tf = new LabeledScoredTreeFactory();\r\n Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), \"UTF-8\"));\r\n TreeReader tr = new PennTreeReader(r, tf);\r\n Tree t = tr.readTree();\r\n while (t != null) {\r\n System.out.println(t);\r\n System.out.println();\r\n t = tr.readTree();\r\n }\r\n r.close();\r\n } catch (IOException ioe) {\r\n ioe.printStackTrace();\r\n }\r\n }", "public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public LuaScriptBlock endBlockReturn(LuaValue value) {\n add(new LuaAstReturnStatement(argument(value)));\n return new LuaScriptBlock(script);\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}", "public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }", "@Override\n\tpublic <T> T get(Object key, Resource resource, Provider<T> provider) {\n\t\tif(resource == null) {\n\t\t\treturn provider.get();\n\t\t}\n\t\tCacheAdapter adapter = getOrCreate(resource);\n\t\tT element = adapter.<T>internalGet(key);\n\t\tif (element==null) {\n\t\t\telement = provider.get();\n\t\t\tcacheMiss(adapter);\n\t\t\tadapter.set(key, element);\n\t\t} else {\n\t\t\tcacheHit(adapter);\n\t\t}\n\t\tif (element == CacheAdapter.NULL) {\n\t\t\treturn null;\n\t\t}\n\t\treturn element;\n\t}" ]
Checks the component type of the given array against the expected component type. @param array the array to be checked. May not be <code>null</code>. @param expectedComponentType the expected component type of the array. May not be <code>null</code>. @return the unchanged array. @throws ArrayStoreException if the expected runtime {@code componentType} does not match the actual runtime component type.
[ "private static Object checkComponentType(Object array, Class<?> expectedComponentType) {\n\t\tClass<?> actualComponentType = array.getClass().getComponentType();\n\t\tif (!expectedComponentType.isAssignableFrom(actualComponentType)) {\n\t\t\tthrow new ArrayStoreException(\n\t\t\t\t\tString.format(\"The expected component type %s is not assignable from the actual type %s\",\n\t\t\t\t\t\t\texpectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));\n\t\t}\n\t\treturn array;\n\t}" ]
[ "public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags)\n {\n Map<Set<String>, Vertex> cache = getCache(event);\n Vertex vertex = cache.get(tags);\n if (vertex == null)\n {\n TagSetModel model = create();\n model.setTags(tags);\n cache.put(tags, model.getElement());\n return model;\n }\n else\n {\n return frame(vertex);\n }\n }", "public DJCrosstab build(){\r\n\t\tif (crosstab.getMeasures().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one measure\");\r\n\t\t}\r\n\t\tif (crosstab.getColumns().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one column\");\r\n\t\t}\r\n\t\tif (crosstab.getRows().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one row\");\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t//Ensure default dimension values\r\n\t\tfor (DJCrosstabColumn col : crosstab.getColumns()) {\r\n\t\t\tif (col.getWidth() == -1 && cellWidth != -1)\r\n\t\t\t\tcol.setWidth(cellWidth);\r\n\r\n\t\t\tif (col.getWidth() == -1 )\r\n\t\t\t\tcol.setWidth(DEFAULT_CELL_WIDTH);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1 && columnHeaderHeight != -1)\r\n\t\t\t\tcol.setHeaderHeight(columnHeaderHeight);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1)\r\n\t\t\t\tcol.setHeaderHeight(DEFAULT_COLUMN_HEADER_HEIGHT);\r\n\t\t}\r\n\r\n\t\tfor (DJCrosstabRow row : crosstab.getRows()) {\r\n\t\t\tif (row.getHeight() == -1 && cellHeight != -1)\r\n\t\t\t\trow.setHeight(cellHeight);\r\n\r\n\t\t\tif (row.getHeight() == -1 )\r\n\t\t\t\trow.setHeight(DEFAULT_CELL_HEIGHT);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1 && rowHeaderWidth != -1)\r\n\t\t\t\trow.setHeaderWidth(rowHeaderWidth);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1)\r\n\t\t\t\trow.setHeaderWidth(DEFAULT_ROW_HEADER_WIDTH);\r\n\r\n\t\t}\r\n\t\treturn crosstab;\r\n\t}", "protected void addAlias(MonolingualTextValue alias) {\n String lang = alias.getLanguageCode();\n AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang);\n \n NameWithUpdate currentLabel = newLabels.get(lang);\n // If there isn't any label for that language, put the alias there\n if (currentLabel == null) {\n newLabels.put(lang, new NameWithUpdate(alias, true));\n // If the new alias is equal to the current label, skip it\n } else if (!currentLabel.value.equals(alias)) {\n \tif (currentAliasesUpdate == null) {\n \t\tcurrentAliasesUpdate = new AliasesWithUpdate(new ArrayList<MonolingualTextValue>(), true);\n \t}\n \tList<MonolingualTextValue> currentAliases = currentAliasesUpdate.aliases;\n \tif(!currentAliases.contains(alias)) {\n \t\tcurrentAliases.add(alias);\n \t\tcurrentAliasesUpdate.added.add(alias);\n \t\tcurrentAliasesUpdate.write = true;\n \t}\n \tnewAliases.put(lang, currentAliasesUpdate);\n }\n }", "public double get( int index ) {\n MatrixType type = mat.getType();\n\n if( type.isReal()) {\n if (type.getBits() == 64) {\n return ((DMatrixRMaj) mat).data[index];\n } else {\n return ((FMatrixRMaj) mat).data[index];\n }\n } else {\n throw new IllegalArgumentException(\"Complex matrix. Call get(int,Complex64F) instead\");\n }\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 }", "static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException {\n // See if the prerequisites are met\n for (final String required : condition.getRequires()) {\n if (!target.isApplied(required)) {\n throw PatchLogger.ROOT_LOGGER.requiresPatch(required);\n }\n }\n // Check for incompatibilities\n for (final String incompatible : condition.getIncompatibleWith()) {\n if (target.isApplied(incompatible)) {\n throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible);\n }\n }\n }", "private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature,\n String webHookPayload, String deliveryTimestamp) {\n if (actualSignature == null) {\n return false;\n }\n\n byte[] actual = Base64.decode(actualSignature);\n byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp);\n\n return Arrays.equals(expected, actual);\n }", "public static void mark(DeploymentUnit unit) {\n unit = DeploymentUtils.getTopDeploymentUnit(unit);\n unit.putAttachment(MARKER, Boolean.TRUE);\n }", "public int scrollToPage(int pageNumber) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToPage pageNumber = %d mPageCount = %d\",\n pageNumber, mPageCount);\n\n if (mSupportScrollByPage &&\n (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) {\n scrollToItem(getFirstItemIndexOnPage(pageNumber));\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n return mCurrentItemIndex;\n\t}" ]
XER files can contain multiple projects when there are cross-project dependencies. As the UniversalProjectReader is designed just to read a single project, we need to select one project from those available in the XER file. The original project selected for export by the user will have its "export flag" set to true. We'll return the first project we find where the export flag is set to true, otherwise we'll just return the first project we find in the file. @param stream schedule data @return ProjectFile instance
[ "private ProjectFile handleXerFile(InputStream stream) throws Exception\n {\n PrimaveraXERFileReader reader = new PrimaveraXERFileReader();\n reader.setCharset(m_charset);\n List<ProjectFile> projects = reader.readAll(stream);\n ProjectFile project = null;\n for (ProjectFile file : projects)\n {\n if (file.getProjectProperties().getExportFlag())\n {\n project = file;\n break;\n }\n }\n if (project == null && !projects.isEmpty())\n {\n project = projects.get(0);\n }\n return project;\n }" ]
[ "public void setValue(Vector3f scale) {\n mX = scale.x;\n mY = scale.y;\n mZ = scale.z;\n }", "private void readProjectProperties(Project ganttProject)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(ganttProject.getName());\n mpxjProperties.setCompany(ganttProject.getCompany());\n mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS);\n\n String locale = ganttProject.getLocale();\n if (locale == null)\n {\n locale = \"en_US\";\n }\n m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale));\n }", "public static String changeFileNameSuffixTo(String filename, String suffix) {\n\n int dotPos = filename.lastIndexOf('.');\n if (dotPos != -1) {\n return filename.substring(0, dotPos + 1) + suffix;\n } else {\n // the string has no suffix\n return filename;\n }\n }", "public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }", "public static base_responses add(nitro_service client, vlan resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tvlan addresources[] = new vlan[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new vlan();\n\t\t\t\taddresources[i].id = resources[i].id;\n\t\t\t\taddresources[i].aliasname = resources[i].aliasname;\n\t\t\t\taddresources[i].ipv6dynamicrouting = resources[i].ipv6dynamicrouting;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private int findIndexForName(String[] fieldNames, String searchName)\r\n {\r\n for(int i = 0; i < fieldNames.length; i++)\r\n {\r\n if(searchName.equals(fieldNames[i]))\r\n {\r\n return i;\r\n }\r\n }\r\n throw new PersistenceBrokerException(\"Can't find field name '\" + searchName +\r\n \"' in given array of field names\");\r\n }", "public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}", "public int tally() {\n long currentTimeMillis = clock.currentTimeMillis();\n\n // calculates time for which we remove any errors before\n final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;\n\n synchronized (queue) {\n // drain out any expired timestamps but don't drain past empty\n while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {\n queue.removeFirst();\n }\n return queue.size();\n }\n }", "static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }" ]
Create an image of the proper size to hold a new waveform preview image and draw it.
[ "private void updateWaveform(WaveformPreview preview) {\n this.preview.set(preview);\n if (preview == null) {\n waveformImage.set(null);\n } else {\n BufferedImage image = new BufferedImage(preview.segmentCount, preview.maxHeight, BufferedImage.TYPE_INT_RGB);\n Graphics g = image.getGraphics();\n g.setColor(Color.BLACK);\n g.fillRect(0, 0, preview.segmentCount, preview.maxHeight);\n for (int segment = 0; segment < preview.segmentCount; segment++) {\n g.setColor(preview.segmentColor(segment, false));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, false));\n if (preview.isColor) { // We have a front color segment to draw on top.\n g.setColor(preview.segmentColor(segment, true));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, true));\n }\n }\n waveformImage.set(image);\n }\n }" ]
[ "public ArrayList getFields(String fieldNames) throws NoSuchFieldException\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new NoSuchFieldException(name);\r\n }\r\n result.add(fieldDef);\r\n }\r\n return result;\r\n }", "@Override\n public HandlerRegistration addChangeHandler(final ChangeHandler handler) {\n return getRangeInputElement().addDomHandler(handler, ChangeEvent.getType());\n }", "public ModelNode buildRequest() throws OperationFormatException {\n\n ModelNode address = request.get(Util.ADDRESS);\n if(prefix.isEmpty()) {\n address.setEmptyList();\n } else {\n Iterator<Node> iterator = prefix.iterator();\n while (iterator.hasNext()) {\n OperationRequestAddress.Node node = iterator.next();\n if (node.getName() != null) {\n address.add(node.getType(), node.getName());\n } else if (iterator.hasNext()) {\n throw new OperationFormatException(\n \"The node name is not specified for type '\"\n + node.getType() + \"'\");\n }\n }\n }\n\n if(!request.hasDefined(Util.OPERATION)) {\n throw new OperationFormatException(\"The operation name is missing or the format of the operation request is wrong.\");\n }\n\n return request;\n }", "public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "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 }", "private static long switchValue8(long currentHexValue, int digitCount) {\n\t\tlong result = 0x7 & currentHexValue;\n\t\tint shift = 0;\n\t\twhile(--digitCount > 0) {\n\t\t\tshift += 3;\n\t\t\tcurrentHexValue >>>= 4;\n\t\t\tresult |= (0x7 & currentHexValue) << shift;\n\t\t}\n\t\treturn result;\n\t}", "@Override\n public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n if (this.options.verbose) {\n this.out.println(\n Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));\n//\t\t\tnew Exception(\"TRACE BINARY\").printStackTrace(System.out);\n//\t\t System.out.println();\n }\n LookupEnvironment env = packageBinding.environment;\n env.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);\n }", "public Request header(String key, String value) {\n this.headers.put(key, value);\n return this;\n }", "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 }" ]
Adds an edge between the current and new state. @return true if the new state is not found in the state machine.
[ "public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,\n\t\t\t\t\t\t\t\t\t\t\t\tCrawlerContext context) {\n\t\tStateVertex cloneState = this.addStateToCurrentState(newState, event);\n\n\t\trunOnInvariantViolationPlugins(context);\n\n\t\tif (cloneState == null) {\n\t\t\tchangeState(newState);\n\t\t\tplugins.runOnNewStatePlugins(context, newState);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tchangeState(cloneState);\n\t\t\treturn false;\n\t\t}\n\t}" ]
[ "private void processDestructionQueue(HttpServletRequest request) {\n Object contextsAttribute = request.getAttribute(DESTRUCTION_QUEUE_ATTRIBUTE_NAME);\n if (contextsAttribute instanceof Map) {\n Map<String, List<ContextualInstance<?>>> contexts = cast(contextsAttribute);\n synchronized (contexts) {\n FastEvent<String> beforeDestroyedEvent = FastEvent.of(String.class, beanManager, BeforeDestroyed.Literal.CONVERSATION);\n FastEvent<String> destroyedEvent = FastEvent.of(String.class, beanManager, Destroyed.Literal.CONVERSATION);\n for (Iterator<Entry<String, List<ContextualInstance<?>>>> iterator = contexts.entrySet().iterator(); iterator.hasNext();) {\n Entry<String, List<ContextualInstance<?>>> entry = iterator.next();\n beforeDestroyedEvent.fire(entry.getKey());\n for (ContextualInstance<?> contextualInstance : entry.getValue()) {\n destroyContextualInstance(contextualInstance);\n }\n // Note that for the attached/current conversation we fire the destroyed event twice because we can't reliably identify such a conversation\n destroyedEvent.fire(entry.getKey());\n iterator.remove();\n }\n }\n }\n }", "public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}", "protected BlockBox createBlock(BlockBox parent, Element n, boolean replaced)\n {\n BlockBox root;\n if (replaced)\n {\n BlockReplacedBox rbox = new BlockReplacedBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n rbox.setViewport(viewport);\n rbox.setContentObj(new ReplacedImage(rbox, rbox.getVisualContext(), baseurl, n.getAttribute(\"src\")));\n root = rbox;\n }\n else\n {\n root = new BlockBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n root.setViewport(viewport);\n }\n root.setBase(baseurl);\n root.setParent(parent);\n root.setContainingBlockBox(parent);\n root.setClipBlock(viewport);\n root.setOrder(next_order++);\n return root;\n }", "public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }", "public String pop() {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.spop(getKey());\n }\n });\n }", "public static dbdbprofile[] get(nitro_service service) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tdbdbprofile[] response = (dbdbprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}", "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}", "private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}", "private <T> void requestAsync(ClientRequest<T> delegate,\n NonblockingStoreCallback callback,\n long timeoutMs,\n String operationName) {\n pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName);\n }" ]
Turn map into string @param propMap Map to be converted @return
[ "private String getJSONFromMap(Map<String, Object> propMap) {\n try {\n return new JSONObject(propMap).toString();\n } catch (Exception e) {\n return \"{}\";\n }\n }" ]
[ "public int getTotalCreatedConnections(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}", "public String[] getNormalizedLabels() {\n\t\tif(isValid()) {\n\t\t\treturn parsedHost.getNormalizedLabels();\n\t\t}\n\t\tif(host.length() == 0) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn new String[] {host};\n\t}", "public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public EventBus emit(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getMessageUniqueID()));\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getConfirmed() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getResponsePending() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getScheduleID()));\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\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 static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }", "public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}", "GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,\n final boolean isFinalChunk,\n final int length,\n final HTTPRequestInfo reqInfo,\n HTTPResponse resp) throws Error, IOException {\n switch (resp.getResponseCode()) {\n case 200:\n if (!isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 200 on non-final chunk. Request: \\n\"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return null;\n }\n case 308:\n if (isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 308 on final chunk: \"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);\n }\n default:\n throw HttpErrorHandler.error(resp.getResponseCode(),\n URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n }\n }" ]
Access all of the elements of the collection that evaluate to true for the provided query predicate. @param predicate An OQL boolean query predicate. @return An iterator used to iterate over the elements that evaluated true for the predicate. @exception org.odmg.QueryInvalidException The query predicate is invalid.
[ "public Iterator select(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return this.query(predicate).iterator();\r\n }" ]
[ "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attribute));\n }", "@SafeVarargs\n private final <T> Set<T> join(Set<T>... sets)\n {\n Set<T> result = new HashSet<>();\n if (sets == null)\n return result;\n\n for (Set<T> set : sets)\n {\n if (set != null)\n result.addAll(set);\n }\n return result;\n }", "private Integer getKeyPartitionId(byte[] key) {\n Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key);\n\n Utils.notNull(keyPartitionId);\n return keyPartitionId;\n }", "public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}", "public static boolean toBoolean(String value, boolean defaultValue)\r\n {\r\n return \"true\".equals(value) ? true : (\"false\".equals(value) ? false : defaultValue);\r\n }", "public void addAssertions(Assertions asserts) {\n if (getCommandline().getAssertions() != null) {\n throw new BuildException(\"Only one assertion declaration is allowed\");\n }\n getCommandline().setAssertions(asserts);\n }", "public static Object lookup(String jndiName)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"lookup(\"+jndiName+\") was called\");\r\n try\r\n {\r\n return getContext().lookup(jndiName);\r\n }\r\n catch (NamingException e)\r\n {\r\n throw new OJBRuntimeException(\"Lookup failed for: \" + jndiName, e);\r\n }\r\n catch(OJBRuntimeException e)\r\n {\r\n throw e;\r\n }\r\n }", "public Integer getGroupIdFromName(String groupName) {\n return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName,\n Constants.DB_TABLE_GROUPS);\n }", "public void writeLine(String pattern, Object... parameters) {\n String line = (parameters == null || parameters.length == 0) ? pattern\n : String.format(pattern, parameters);\n lines.add(0, line); // we'll write bottom to top, then purge unwritten\n // lines from end\n updateHUD();\n }" ]
Signals that the processor to finish and waits until it finishes.
[ "@Override\n public void finish() {\n if (started.get() && !finished.getAndSet(true)) {\n waitUntilFinished();\n super.finish();\n // recreate thread (don't start) for processor reuse\n createProcessorThread();\n clearQueues();\n started.set(false);\n }\n }" ]
[ "private void executeRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n PluginResponse httpServletResponse,\n History history) throws Exception {\n int intProxyResponseCode = 999;\n // Create a default HttpClient\n HttpClient httpClient = new HttpClient();\n HttpState state = new HttpState();\n\n try {\n httpMethodProxyRequest.setFollowRedirects(false);\n ArrayList<String> headersToRemove = getRemoveHeaders();\n\n httpClient.getParams().setSoTimeout(60000);\n\n httpServletRequest.setAttribute(\"com.groupon.odo.removeHeaders\", headersToRemove);\n\n // exception handling for httpclient\n HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {\n public boolean retryMethod(\n final HttpMethod method,\n final IOException exception,\n int executionCount) {\n return false;\n }\n };\n\n httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);\n\n intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);\n } catch (Exception e) {\n // Return a gateway timeout\n httpServletResponse.setStatus(504);\n httpServletResponse.setHeader(Constants.HEADER_STATUS, \"504\");\n httpServletResponse.flushBuffer();\n return;\n }\n logger.info(\"Response code: {}, {}\", intProxyResponseCode,\n HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n\n // Pass the response code back to the client\n httpServletResponse.setStatus(intProxyResponseCode);\n\n // Pass response headers back to the client\n Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();\n for (Header header : headerArrayResponse) {\n // remove transfer-encoding header. The http libraries will handle this encoding\n if (header.getName().toLowerCase().equals(\"transfer-encoding\")) {\n continue;\n }\n\n httpServletResponse.setHeader(header.getName(), header.getValue());\n }\n\n // there is no data for a HTTP 304 or 204\n if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&\n intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {\n // Send the content to the client\n httpServletResponse.resetBuffer();\n httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());\n }\n\n // copy cookies to servlet response\n for (Cookie cookie : state.getCookies()) {\n javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());\n\n if (cookie.getPath() != null) {\n servletCookie.setPath(cookie.getPath());\n }\n\n if (cookie.getDomain() != null) {\n servletCookie.setDomain(cookie.getDomain());\n }\n\n // convert expiry date to max age\n if (cookie.getExpiryDate() != null) {\n servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));\n }\n\n servletCookie.setSecure(cookie.getSecure());\n\n servletCookie.setVersion(cookie.getVersion());\n\n if (cookie.getComment() != null) {\n servletCookie.setComment(cookie.getComment());\n }\n\n httpServletResponse.addCookie(servletCookie);\n }\n }", "@Override\n public EnvironmentConfig setSetting(@NotNull final String key, @NotNull final Object value) {\n return (EnvironmentConfig) super.setSetting(key, value);\n }", "public void update(int number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];\n ByteUtils.writeInt(numberInBytes, number, 0);\n update(numberInBytes);\n }", "public String astring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n return atom(request);\n }\n }", "public int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }", "public static List<Integer> getAllNodeIds(AdminClient adminClient) {\n List<Integer> nodeIds = Lists.newArrayList();\n for(Integer nodeId: adminClient.getAdminClientCluster().getNodeIds()) {\n nodeIds.add(nodeId);\n }\n return nodeIds;\n }", "public void retrieveReference(Object pInstance, String pAttributeName) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n \tlogger.debug(\"Retrieving reference named [\"+pAttributeName+\"] on object of type [\"+\n \t pInstance.getClass().getName()+\"]\");\n }\n ClassDescriptor cld = getClassDescriptor(pInstance.getClass());\n CollectionDescriptor cod = cld.getCollectionDescriptorByName(pAttributeName);\n getInternalCache().enableMaterializationCache();\n // to avoid problems with circular references, locally cache the current object instance\n Identity oid = serviceIdentity().buildIdentity(pInstance);\n boolean needLocalRemove = false;\n if(getInternalCache().doLocalLookup(oid) == null)\n {\n getInternalCache().doInternalCache(oid, pInstance, MaterializationCache.TYPE_TEMP);\n needLocalRemove = true;\n }\n try\n {\n if (cod != null)\n {\n referencesBroker.retrieveCollection(pInstance, cld, cod, true);\n }\n else\n {\n ObjectReferenceDescriptor ord = cld.getObjectReferenceDescriptorByName(pAttributeName);\n if (ord != null)\n {\n referencesBroker.retrieveReference(pInstance, cld, ord, true);\n }\n else\n {\n throw new PersistenceBrokerException(\"did not find attribute \" + pAttributeName +\n \" for class \" + pInstance.getClass().getName());\n }\n }\n // do locally remove the object to avoid problems with object state detection (insert/update),\n // because objects found in the cache detected as 'old' means 'update'\n if(needLocalRemove) getInternalCache().doLocalRemove(oid);\n getInternalCache().disableMaterializationCache();\n }\n catch(RuntimeException e)\n {\n getInternalCache().doLocalClear();\n throw e;\n }\n }", "public static String encode(String value) throws UnsupportedEncodingException {\n if (isNullOrEmpty(value)) return value;\n return URLEncoder.encode(value, URL_ENCODING);\n }", "public static final Bytes of(byte[] array) {\n Objects.requireNonNull(array);\n if (array.length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[array.length];\n System.arraycopy(array, 0, copy, 0, array.length);\n return new Bytes(copy);\n }" ]
A method for determining from and to information when using this IntRange to index an aggregate object of the specified size. Normally only used internally within Groovy but useful if adding range indexing support for your own aggregates. @param size the size of the aggregate being indexed @return the calculated range information (with 1 added to the to value, ready for providing to subList
[ "public RangeInfo subListBorders(int size) {\n if (inclusive == null) throw new IllegalStateException(\"Should not call subListBorders on a non-inclusive aware IntRange\");\n int tempFrom = from;\n if (tempFrom < 0) {\n tempFrom += size;\n }\n int tempTo = to;\n if (tempTo < 0) {\n tempTo += size;\n }\n if (tempFrom > tempTo) {\n return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true);\n }\n return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false);\n }" ]
[ "public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }", "private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) {\n final List<File> processed = new ArrayList<File>();\n List<File> reenabled = Collections.emptyList();\n List<File> disabled = Collections.emptyList();\n try {\n try {\n // Update the state to invalidate and process module resources\n if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n // Only invalidate modules when applying patches; on rollback files are immediately restored\n for (final File invalidation : moduleInvalidations) {\n processed.add(invalidation);\n PatchModuleInvalidationUtils.processFile(this, invalidation, mode);\n }\n if (!modulesToReenable.isEmpty()) {\n reenabled = new ArrayList<File>(modulesToReenable.size());\n for (final File path : modulesToReenable) {\n reenabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK);\n }\n }\n } else if(mode == PatchingTaskContext.Mode.ROLLBACK) {\n if (!modulesToDisable.isEmpty()) {\n disabled = new ArrayList<File>(modulesToDisable.size());\n for (final File path : modulesToDisable) {\n disabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY);\n }\n }\n }\n\n }\n modification.complete();\n callback.completed(this);\n state = State.COMPLETED;\n } catch (Exception e) {\n this.moduleInvalidations.clear();\n this.moduleInvalidations.addAll(processed);\n this.modulesToReenable.clear();\n this.modulesToReenable.addAll(reenabled);\n this.modulesToDisable.clear();\n this.moduleInvalidations.addAll(disabled);\n throw new RuntimeException(e);\n }\n } finally {\n if (state != State.COMPLETED) {\n try {\n modification.cancel();\n } finally {\n try {\n undoChanges();\n } finally {\n callback.operationCancelled(this);\n }\n }\n } else {\n try {\n if (checkForGarbageOnRestart) {\n final File cleanupMarker = new File(installedImage.getInstallationMetadata(), \"cleanup-patching-dirs\");\n cleanupMarker.createNewFile();\n }\n storeFailedRenaming();\n } catch (IOException e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to create cleanup marker\");\n }\n }\n }\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 File curDir() {\n File file = session().attribute(ATTR_PWD);\n if (null == file) {\n file = new File(System.getProperty(\"user.dir\"));\n session().attribute(ATTR_PWD, file);\n }\n return file;\n }", "public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }", "public Map<String, Attribute> getAttributes() {\n Map<String, Attribute> result = new HashMap<>();\n DataSourceAttribute datasourceAttribute = new DataSourceAttribute();\n Map<String, Attribute> dsResult = new HashMap<>();\n dsResult.put(MAP_KEY, this.mapAttribute);\n datasourceAttribute.setAttributes(dsResult);\n result.put(\"datasource\", datasourceAttribute);\n return result;\n }", "private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }", "@Override\n public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename,\n long startOffsetBytes, long timeoutMillis) {\n Preconditions.checkArgument(startOffsetBytes >= 0, \"%s: offset must be non-negative: %s\", this,\n startOffsetBytes);\n final int n = dst.remaining();\n Preconditions.checkArgument(n > 0, \"%s: dst full: %s\", this, dst);\n final int want = Math.min(READ_LIMIT_BYTES, n);\n\n final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);\n req.setHeader(\n new HTTPHeader(RANGE, \"bytes=\" + startOffsetBytes + \"-\" + (startOffsetBytes + want - 1)));\n final HTTPRequestInfo info = new HTTPRequestInfo(req);\n return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {\n @Override\n protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {\n long totalLength;\n switch (resp.getResponseCode()) {\n case 200:\n totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);\n break;\n case 206:\n totalLength = getLengthFromContentRange(resp);\n break;\n case 404:\n throw new FileNotFoundException(\"Could not find: \" + filename);\n case 416:\n throw new BadRangeException(\"Requested Range not satisfiable; perhaps read past EOF? \"\n + URLFetchUtils.describeRequestAndResponse(info, resp));\n default:\n throw HttpErrorHandler.error(info, resp);\n }\n byte[] content = resp.getContent();\n Preconditions.checkState(content.length <= want, \"%s: got %s > wanted %s\", this,\n content.length, want);\n dst.put(content);\n return getMetadataFromResponse(filename, resp, totalLength);\n }\n\n @Override\n protected Throwable convertException(Throwable e) {\n return OauthRawGcsService.convertException(info, e);\n }\n };\n }", "public void addWord(MtasCQLParserWordFullCondition w) throws ParseException {\n assert w.getCondition()\n .not() == false : \"condition word should be positive in sentence definition\";\n if (!simplified) {\n partList.add(w);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }" ]
Returns the active logged in user.
[ "@Nullable\n public StitchUserT getUser() {\n authLock.readLock().lock();\n try {\n return activeUser;\n } finally {\n authLock.readLock().unlock();\n }\n }" ]
[ "public static String getURL(String sourceURI) {\n String retval = sourceURI;\n int qPos = sourceURI.indexOf(\"?\");\n if (qPos != -1) {\n retval = retval.substring(0, qPos);\n }\n\n return retval;\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 }", "protected org.apache.log4j.helpers.PatternParser createPatternParser(final String pattern) {\n\t\treturn new FoundationLoggingPatternParser(pattern);\n\t}", "private List<Row> createExceptionAssignmentRowList(String exceptionData)\n {\n List<Row> list = new ArrayList<Row>();\n String[] exceptions = exceptionData.split(\",|:\");\n int index = 1;\n while (index < exceptions.length)\n {\n Date startDate = DatatypeConverter.parseEpochTimestamp(exceptions[index + 0]);\n Date endDate = DatatypeConverter.parseEpochTimestamp(exceptions[index + 1]);\n //Integer exceptionTypeID = Integer.valueOf(exceptions[index + 2]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"STARU_DATE\", startDate);\n map.put(\"ENE_DATE\", endDate);\n\n list.add(new MapRow(map));\n\n index += 3;\n }\n\n return list;\n }", "public Collection<V> put(K key, Collection<V> collection) {\r\n return map.put(key, collection);\r\n }", "public Map<InetSocketAddress, ServerPort> activePorts() {\n final Server server = this.server;\n if (server != null) {\n return server.activePorts();\n } else {\n return Collections.emptyMap();\n }\n }", "public List<Long> getOffsets(OffsetRequest offsetRequest) {\n ILog log = getLog(offsetRequest.topic, offsetRequest.partition);\n if (log != null) {\n return log.getOffsetsBefore(offsetRequest);\n }\n return ILog.EMPTY_OFFSETS;\n }", "public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedInsert == null) {\n\t\t\tmappedInsert = MappedCreate.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}", "private void setResourceInformation() {\n\n String sitePath = m_cms.getSitePath(m_resource);\n int pathEnd = sitePath.lastIndexOf('/') + 1;\n String baseName = sitePath.substring(pathEnd);\n m_sitepath = sitePath.substring(0, pathEnd);\n switch (CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())) {\n case PROPERTY:\n String localeSuffix = CmsStringUtil.getLocaleSuffixForName(baseName);\n if ((null != localeSuffix) && !localeSuffix.isEmpty()) {\n baseName = baseName.substring(\n 0,\n baseName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));\n m_locale = CmsLocaleManager.getLocale(localeSuffix);\n }\n if ((null == m_locale) || !m_locales.contains(m_locale)) {\n m_switchedLocaleOnOpening = true;\n m_locale = m_locales.iterator().next();\n }\n break;\n case XML:\n m_locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(\n m_cms,\n m_resource,\n m_xmlBundle);\n break;\n case DESCRIPTOR:\n m_basename = baseName.substring(\n 0,\n baseName.length() - CmsMessageBundleEditorTypes.Descriptor.POSTFIX.length());\n m_locale = new Locale(\"en\");\n break;\n default:\n throw new IllegalArgumentException(\n Messages.get().container(\n Messages.ERR_UNSUPPORTED_BUNDLE_TYPE_1,\n CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())).toString());\n }\n m_basename = baseName;\n\n }" ]
Check that the scope type is allowed by the stereotypes on the bean and the bean type
[ "protected void checkScopeAllowed() {\n if (ejbDescriptor.isStateless() && !isDependent()) {\n throw BeanLogger.LOG.scopeNotAllowedOnStatelessSessionBean(getScope(), getType());\n }\n if (ejbDescriptor.isSingleton() && !(isDependent() || getScope().equals(ApplicationScoped.class))) {\n throw BeanLogger.LOG.scopeNotAllowedOnSingletonBean(getScope(), getType());\n }\n }" ]
[ "@Override\n public void run() {\n ExecutorService executorService = Executors.newFixedThreadPool(maxClients);\n try {\n serverSocket = new ServerSocket(port, maxClients);\n while (!shuttingDown) {\n try {\n Socket socket = serverSocket.accept();\n debugConnection = new DebugConnection(socket);\n executorService.submit(debugConnection);\n } catch (SocketException e) {\n // closed\n debugConnection = null;\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n debugConnection = null;\n serverSocket.close();\n } catch (Exception e) {\n }\n executorService.shutdownNow();\n }\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 boolean hasInstance(Scriptable instance) {\n // Default for JS objects (other than Function) is to do prototype\n // chasing.\n Scriptable proto = instance.getPrototype();\n while (proto != null) {\n if (proto.equals(this)) return true;\n proto = proto.getPrototype();\n }\n return false;\n }", "public static String getAt(String text, IntRange range) {\n return getAt(text, (Range) range);\n }", "public void createEnablement() {\n GlobalEnablementBuilder builder = beanManager.getServices().get(GlobalEnablementBuilder.class);\n ModuleEnablement enablement = builder.createModuleEnablement(this);\n beanManager.setEnabled(enablement);\n\n if (BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.enabledAlternatives(this.beanManager, WeldCollections.toMultiRowString(enablement.getAllAlternatives()));\n BootstrapLogger.LOG.enabledDecorators(this.beanManager, WeldCollections.toMultiRowString(enablement.getDecorators()));\n BootstrapLogger.LOG.enabledInterceptors(this.beanManager, WeldCollections.toMultiRowString(enablement.getInterceptors()));\n }\n }", "protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {\r\n Map<String, AbstractServer> srvc = new HashMap<>();\r\n for (ServerSetup setup : config) {\r\n if (srvc.containsKey(setup.getProtocol())) {\r\n throw new IllegalArgumentException(\"Server '\" + setup.getProtocol() + \"' was found at least twice in the array\");\r\n }\r\n final String protocol = setup.getProtocol();\r\n if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {\r\n srvc.put(protocol, new SmtpServer(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {\r\n srvc.put(protocol, new Pop3Server(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {\r\n srvc.put(protocol, new ImapServer(setup, mgr));\r\n }\r\n }\r\n return srvc;\r\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 }", "private void readCalendars(Project project) throws MPXJException\n {\n Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n for (net.sf.mpxj.planner.schema.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, null);\n }\n\n Integer defaultCalendarID = getInteger(project.getCalendar());\n m_defaultCalendar = m_projectFile.getCalendarByUniqueID(defaultCalendarID);\n if (m_defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(m_defaultCalendar.getName());\n }\n }\n }", "public void addDependencyGraph(DAGraph<DataT, NodeT> dependencyGraph) {\n this.rootNode.addDependency(dependencyGraph.rootNode.key());\n Map<String, NodeT> sourceNodeTable = dependencyGraph.nodeTable;\n Map<String, NodeT> targetNodeTable = this.nodeTable;\n this.merge(sourceNodeTable, targetNodeTable);\n dependencyGraph.parentDAGs.add(this);\n if (this.hasParents()) {\n this.bubbleUpNodeTable(this, new LinkedList<String>());\n }\n }" ]
Most complete output
[ "public void setAll() {\n\tshowAttributes = true;\n\tshowEnumerations = true;\n\tshowEnumConstants = true;\n\tshowOperations = true;\n\tshowConstructors = true;\n\tshowVisibility = true;\n\tshowType = true;\n }" ]
[ "public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\n }", "public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "public static double computeTauAndDivide(final int j, final int numRows ,\n final double[] u , final double max) {\n double tau = 0;\n// double div_max = 1.0/max;\n// if( Double.isInfinite(div_max)) {\n for( int i = j; i < numRows; i++ ) {\n double d = u[i] /= max;\n tau += d*d;\n }\n// } else {\n// for( int i = j; i < numRows; i++ ) {\n// double d = u[i] *= div_max;\n// tau += d*d;\n// }\n// }\n tau = Math.sqrt(tau);\n\n if( u[j] < 0 )\n tau = -tau;\n\n return tau;\n }", "public Replication queryParams(Map<String, Object> queryParams) {\r\n this.replication = replication.queryParams(queryParams);\r\n return this;\r\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 }", "protected void checkObserverMethods() {\n Collection<EnhancedAnnotatedMethod<?, ? super T>> observerMethods = BeanMethods.getObserverMethods(this.getEnhancedAnnotated());\n Collection<EnhancedAnnotatedMethod<?, ? super T>> asyncObserverMethods = BeanMethods.getAsyncObserverMethods(this.getEnhancedAnnotated());\n checkObserverMethods(observerMethods);\n checkObserverMethods(asyncObserverMethods);\n }", "final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }", "public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "private 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 }" ]
Checks the status of one or more asynchronous photo upload tickets. This method does not require authentication. @param tickets a set of ticket ids (Strings) or {@link Ticket} objects containing ids @return a list of {@link Ticket} objects. @throws FlickrException
[ "public List<Ticket> checkTickets(Set<String> tickets) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CHECK_TICKETS);\r\n\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = tickets.iterator();\r\n while (it.hasNext()) {\r\n if (sb.length() > 0) {\r\n sb.append(\",\");\r\n }\r\n Object obj = it.next();\r\n if (obj instanceof Ticket) {\r\n sb.append(((Ticket) obj).getTicketId());\r\n } else {\r\n sb.append(obj);\r\n }\r\n }\r\n parameters.put(\"tickets\", sb.toString());\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n // <uploader>\r\n // <ticket id=\"128\" complete=\"1\" photoid=\"2995\" />\r\n // <ticket id=\"129\" complete=\"0\" />\r\n // <ticket id=\"130\" complete=\"2\" />\r\n // <ticket id=\"131\" invalid=\"1\" />\r\n // </uploader>\r\n\r\n List<Ticket> list = new ArrayList<Ticket>();\r\n Element uploaderElement = response.getPayload();\r\n NodeList ticketNodes = uploaderElement.getElementsByTagName(\"ticket\");\r\n int n = ticketNodes.getLength();\r\n for (int i = 0; i < n; i++) {\r\n Element ticketElement = (Element) ticketNodes.item(i);\r\n String id = ticketElement.getAttribute(\"id\");\r\n String complete = ticketElement.getAttribute(\"complete\");\r\n boolean invalid = \"1\".equals(ticketElement.getAttribute(\"invalid\"));\r\n String photoId = ticketElement.getAttribute(\"photoid\");\r\n Ticket info = new Ticket();\r\n info.setTicketId(id);\r\n info.setInvalid(invalid);\r\n info.setStatus(Integer.parseInt(complete));\r\n info.setPhotoId(photoId);\r\n list.add(info);\r\n }\r\n return list;\r\n }" ]
[ "protected void init(DMatrixRMaj A ) {\n UBV = A;\n\n m = UBV.numRows;\n n = UBV.numCols;\n\n min = Math.min(m,n);\n int max = Math.max(m,n);\n\n if( b.length < max+1 ) {\n b = new double[ max+1 ];\n u = new double[ max+1 ];\n }\n if( gammasU.length < m ) {\n gammasU = new double[ m ];\n }\n if( gammasV.length < n ) {\n gammasV = new double[ n ];\n }\n }", "public void deleteRedirect(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n } catch (Exception e) {\n e.printStackTrace();\n }\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 }", "String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }", "public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }", "public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {\r\n\t\treturn new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),\r\n\t\t\t\tgetBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}", "private Point parsePoint(String point) {\n int comma = point.indexOf(',');\n if (comma == -1)\n return null;\n\n float lat = Float.valueOf(point.substring(0, comma));\n float lng = Float.valueOf(point.substring(comma + 1));\n return spatialctx.makePoint(lng, lat);\n }", "public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }", "protected void updateForNewConfiguration(CmsGitConfiguration gitConfig) {\n\n if (!m_checkinBean.setCurrentConfiguration(gitConfig)) {\n Notification.show(\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_0),\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_DESC_0),\n Type.ERROR_MESSAGE);\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n return;\n }\n\n resetSelectableModules();\n for (final String moduleName : gitConfig.getConfiguredModules()) {\n addSelectableModule(moduleName);\n }\n updateNewModuleSelector();\n m_pullFirst.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullBefore()));\n m_pullAfterCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullAfter()));\n m_addAndCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoCommit()));\n m_pushAutomatically.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPush()));\n m_commitMessage.setValue(Strings.nullToEmpty(gitConfig.getDefaultCommitMessage()));\n m_copyAndUnzip.setValue(Boolean.valueOf(gitConfig.getDefaultCopyAndUnzip()));\n m_excludeLib.setValue(Boolean.valueOf(gitConfig.getDefaultExcludeLibs()));\n m_ignoreUnclean.setValue(Boolean.valueOf(gitConfig.getDefaultIngoreUnclean()));\n m_userField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserName()));\n m_emailField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserEmail()));\n\n }" ]
Singleton of MetaClassRegistry. @param includeExtension @return the registry
[ "public static MetaClassRegistry getInstance(int includeExtension) {\n if (includeExtension != DONT_LOAD_DEFAULT) {\n if (instanceInclude == null) {\n instanceInclude = new MetaClassRegistryImpl();\n }\n return instanceInclude;\n } else {\n if (instanceExclude == null) {\n instanceExclude = new MetaClassRegistryImpl(DONT_LOAD_DEFAULT);\n }\n return instanceExclude;\n }\n }" ]
[ "private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }", "public static base_responses add(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 addresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsip6();\n\t\t\t\taddresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\taddresources[i].scope = resources[i].scope;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].nd = resources[i].nd;\n\t\t\t\taddresources[i].icmp = resources[i].icmp;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t\taddresources[i].telnet = resources[i].telnet;\n\t\t\t\taddresources[i].ftp = resources[i].ftp;\n\t\t\t\taddresources[i].gui = resources[i].gui;\n\t\t\t\taddresources[i].ssh = resources[i].ssh;\n\t\t\t\taddresources[i].snmp = resources[i].snmp;\n\t\t\t\taddresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\taddresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\taddresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\taddresources[i].hostroute = resources[i].hostroute;\n\t\t\t\taddresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\taddresources[i].metric = resources[i].metric;\n\t\t\t\taddresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\taddresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\taddresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].map = resources[i].map;\n\t\t\t\taddresources[i].ownernode = resources[i].ownernode;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static Command newGetGlobal(String identifier,\n String outIdentifier) {\n return getCommandFactoryProvider().newGetGlobal( identifier,\n outIdentifier );\n }", "public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());\n }", "public static base_response delete(nitro_service client, String ciphergroupname) throws Exception {\n\t\tsslcipher deleteresource = new sslcipher();\n\t\tdeleteresource.ciphergroupname = ciphergroupname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, String jobId) {\n return requestJobV3(cloudFoundryClient, jobId)\n .filter(job -> JobState.PROCESSING != job.getState())\n .repeatWhenEmpty(exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout))\n .filter(job -> JobState.FAILED == job.getState())\n .flatMap(JobUtils::getError);\n }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }", "public static String getHotPartitionsDueToContiguity(final Cluster cluster,\n int hotContiguityCutoff) {\n StringBuilder sb = new StringBuilder();\n\n for(int zoneId: cluster.getZoneIds()) {\n Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId);\n for(Integer initialPartitionId: idToRunLength.keySet()) {\n int runLength = idToRunLength.get(initialPartitionId);\n if(runLength < hotContiguityCutoff)\n continue;\n\n int hotPartitionId = (initialPartitionId + runLength)\n % cluster.getNumberOfPartitions();\n Node hotNode = cluster.getNodeForPartitionId(hotPartitionId);\n sb.append(\"\\tNode \" + hotNode.getId() + \" (\" + hotNode.getHost()\n + \") has hot primary partition \" + hotPartitionId\n + \" that follows contiguous run of length \" + runLength + Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }", "public String login(Authentication authentication) {\n\t\tString token = getToken();\n\t\treturn login(token, authentication);\n\t}" ]
Consumes the version field from the given input and raises an exception if the record is in a newer version, written by a newer version of Hibernate OGM. @param input the input to read from @param supportedVersion the type version supported by this version of OGM @param externalizedType the type to be unmarshalled @throws IOException if an error occurs while reading the input
[ "public static void readAndCheckVersion(ObjectInput input, int supportedVersion, Class<?> externalizedType) throws IOException {\n\t\tint version = input.readInt();\n\n\t\tif ( version != supportedVersion ) {\n\t\t\tthrow LOG.unexpectedKeyVersion( externalizedType, version, supportedVersion );\n\t\t}\n\t}" ]
[ "public ValueContainer[] getCurrentLockingValues(Object o) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = new ValueContainer(fields[i].getPersistentField().get(o), fields[i].getJdbcType());\r\n }\r\n return result;\r\n }", "private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)\n {\n for (Filter field : filters)\n {\n final Filter f = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n return f.getName();\n }\n };\n parentNode.add(childNode);\n }\n }", "private static void parseOutgoings(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"outgoing\")) {\n ArrayList<Shape> outgoings = new ArrayList<Shape>();\n JSONArray outgoingObject = modelJSON.getJSONArray(\"outgoing\");\n for (int i = 0; i < outgoingObject.length(); i++) {\n Shape out = getShapeWithId(outgoingObject.getJSONObject(i).getString(\"resourceId\"),\n shapes);\n outgoings.add(out);\n out.addIncoming(current);\n }\n if (outgoings.size() > 0) {\n current.setOutgoings(outgoings);\n }\n }\n }", "public static boolean isDelayedQueue(final Jedis jedis, final String key) {\n return ZSET.equalsIgnoreCase(jedis.type(key));\n }", "public static boolean queryHasResult(Statement stmt, String sql) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n return rs.next();\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }", "public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }", "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }", "public static BMatrixRMaj elementLessThan(DMatrixRMaj A , double value , BMatrixRMaj output )\n {\n if( output == null ) {\n output = new BMatrixRMaj(A.numRows,A.numCols);\n }\n\n output.reshape(A.numRows, A.numCols);\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n output.data[i] = A.data[i] < value;\n }\n\n return output;\n }", "public static boolean isAvailable() throws Exception {\n try {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n return true;\n } catch (Exception e) {\n return false;\n }\n }" ]
Use this API to fetch a rewriteglobal_binding resource .
[ "public static rewriteglobal_binding get(nitro_service service) throws Exception{\n\t\trewriteglobal_binding obj = new rewriteglobal_binding();\n\t\trewriteglobal_binding response = (rewriteglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static <T> String listToString(List<T> list, final boolean justValue) {\r\n return listToString(list, justValue, null);\r\n }", "public static void registerParams(DynamicJasperDesign jd, Map _parameters) {\n for (Object key : _parameters.keySet()) {\n if (key instanceof String) {\n try {\n Object value = _parameters.get(key);\n if (jd.getParametersMap().get(key) != null) {\n log.warn(\"Parameter \\\"\" + key + \"\\\" already registered, skipping this one: \" + value);\n continue;\n }\n\n JRDesignParameter parameter = new JRDesignParameter();\n\n if (value == null) //There are some Map implementations that allows nulls values, just go on\n continue;\n\n//\t\t\t\t\tparameter.setValueClassName(value.getClass().getCanonicalName());\n Class clazz = value.getClass().getComponentType();\n if (clazz == null)\n clazz = value.getClass();\n parameter.setValueClass(clazz); //NOTE this is very strange\n //when using an array as subreport-data-source, I must pass the parameter class name like this: value.getClass().getComponentType()\n parameter.setName((String) key);\n jd.addParameter(parameter);\n } catch (JRException e) {\n //nothing to do\n }\n }\n\n }\n\n }", "void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }", "public static boolean isDelayedQueue(final Jedis jedis, final String key) {\n return ZSET.equalsIgnoreCase(jedis.type(key));\n }", "protected boolean isItemAccepted(byte[] key) {\n boolean entryAccepted = false;\n if (!fetchOrphaned) {\n if (isKeyNeeded(key)) {\n entryAccepted = true;\n }\n } else {\n if (!StoreRoutingPlan.checkKeyBelongsToNode(key, nodeId, initialCluster, storeDef)) {\n entryAccepted = true;\n }\n }\n return entryAccepted;\n }", "private void processCalendars() throws IOException\n {\n CalendarReader reader = new CalendarReader(m_data.getTableData(\"Calendars\"));\n reader.read();\n\n for (MapRow row : reader.getRows())\n {\n processCalendar(row);\n }\n\n m_project.setDefaultCalendar(m_calendarMap.get(reader.getDefaultCalendarUUID()));\n }", "public static base_response update(nitro_service client, cacheselector resource) throws Exception {\n\t\tcacheselector updateresource = new cacheselector();\n\t\tupdateresource.selectorname = resource.selectorname;\n\t\tupdateresource.rule = resource.rule;\n\t\treturn updateresource.update_resource(client);\n\t}", "public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }", "public static rnatip_stats get(nitro_service service, String Rnatip) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\tobj.set_Rnatip(Rnatip);\n\t\trnatip_stats response = (rnatip_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
Given a cluster and a node id checks if the node exists @param nodeId The node id to search for @return True if cluster contains the node id, else false
[ "public boolean hasNodeWithId(int nodeId) {\n Node node = nodesById.get(nodeId);\n if(node == null) {\n return false;\n }\n return true;\n }" ]
[ "public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}", "private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }", "public String getDynamicValue(String attribute) {\n\n return null == m_dynamicValues ? null : m_dynamicValues.get(attribute);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<PaxDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<PaxDate>) super.localDateTime(temporal);\n }", "public void close()\n {\n if (transac_open)\n {\n try\n {\n this._cnx.rollback();\n }\n catch (Exception e)\n {\n // Ignore.\n }\n }\n\n for (Statement s : toClose)\n {\n closeQuietly(s);\n }\n toClose.clear();\n\n closeQuietly(_cnx);\n _cnx = null;\n }", "public void addNamespace(final MongoNamespace namespace) {\n this.instanceLock.writeLock().lock();\n try {\n if (this.nsStreamers.containsKey(namespace)) {\n return;\n }\n final NamespaceChangeStreamListener streamer =\n new NamespaceChangeStreamListener(\n namespace,\n instanceConfig.getNamespaceConfig(namespace),\n service,\n networkMonitor,\n authMonitor,\n getLockForNamespace(namespace));\n this.nsStreamers.put(namespace, streamer);\n } finally {\n this.instanceLock.writeLock().unlock();\n }\n }", "public Object getProxyTarget(){\r\n\t\ttry {\r\n\t\t\treturn Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod(\"getProxyTarget\"), null);\r\n\t\t} catch (Throwable t) {\r\n\t\t\tthrow new RuntimeException(\"BoneCP: Internal error - transaction replay log is not turned on?\", t);\r\n\t\t}\r\n\t}", "void setPaused(final boolean isPaused) {\n docLock.writeLock().lock();\n try {\n docsColl.updateOne(\n getDocFilter(namespace, documentId),\n new BsonDocument(\"$set\",\n new BsonDocument(\n ConfigCodec.Fields.IS_PAUSED,\n new BsonBoolean(isPaused))));\n this.isPaused = isPaused;\n } catch (IllegalStateException e) {\n // eat this\n } finally {\n docLock.writeLock().unlock();\n }\n }", "public static DMatrixRMaj symmetricWithEigenvalues(int num, Random rand , double ...eigenvalues ) {\n DMatrixRMaj V = RandomMatrices_DDRM.orthogonal(num,num,rand);\n DMatrixRMaj D = CommonOps_DDRM.diag(eigenvalues);\n\n DMatrixRMaj temp = new DMatrixRMaj(num,num);\n\n CommonOps_DDRM.mult(V,D,temp);\n CommonOps_DDRM.multTransB(temp,V,D);\n\n return D;\n }" ]
Sets the response context. @param responseContext the response context @return the parallel task builder
[ "public ParallelTaskBuilder setResponseContext(\n Map<String, Object> responseContext) {\n if (responseContext != null)\n this.responseContext = responseContext;\n else\n logger.error(\"context cannot be null. skip set.\");\n return this;\n }" ]
[ "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 }", "private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }", "public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {\n List<Versioned<V>> versionedValues;\n\n validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());\n boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;\n String keyHexString = \"\";\n if(!hasVersion) {\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"DELETE without version requested for key: \" + keyHexString\n + \" , for store: \" + this.storeName + \" at time(in ms): \"\n + startTimeInMs + \" . Nested GET and DELETE requests to follow ---\");\n }\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent delete might be faster all the\n // steps might finish within the allotted time\n deleteRequestObject.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(deleteRequestObject);\n Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),\n null,\n versionedValues);\n\n if(versioned == null) {\n return false;\n }\n\n long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()\n - (System.currentTimeMillis() - startTimeInMs);\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n if(timeLeft < 0) {\n throw new StoreTimeoutException(\"DELETE request timed out\");\n }\n\n // Update the version and the new timeout\n deleteRequestObject.setVersion(versioned.getVersion());\n deleteRequestObject.setRoutingTimeoutInMs(timeLeft);\n\n }\n long deleteVersionStartTimeInNs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n keyHexString);\n }\n boolean result = store.delete(deleteRequestObject);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n if(!hasVersion && logger.isDebugEnabled()) {\n logger.debug(\"DELETE without version response received for key: \" + keyHexString\n + \", for store: \" + this.storeName + \" at time(in ms): \"\n + System.currentTimeMillis());\n }\n return result;\n }", "public PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }", "private void processTask(ChildTaskContainer parent, MapRow row) throws IOException\n {\n Task task = parent.addTask();\n task.setName(row.getString(\"NAME\"));\n task.setGUID(row.getUUID(\"UUID\"));\n task.setText(1, row.getString(\"ID\"));\n task.setDuration(row.getDuration(\"PLANNED_DURATION\"));\n task.setRemainingDuration(row.getDuration(\"REMAINING_DURATION\"));\n task.setHyperlink(row.getString(\"URL\"));\n task.setPercentageComplete(row.getDouble(\"PERCENT_COMPLETE\"));\n task.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n task.setMilestone(task.getDuration().getDuration() == 0);\n\n ProjectCalendar calendar = m_calendarMap.get(row.getUUID(\"CALENDAR_UUID\"));\n if (calendar != m_project.getDefaultCalendar())\n {\n task.setCalendar(calendar);\n }\n\n switch (row.getInteger(\"STATUS\").intValue())\n {\n case 1: // Planned\n {\n task.setStart(row.getDate(\"PLANNED_START\"));\n task.setFinish(task.getEffectiveCalendar().getDate(task.getStart(), task.getDuration(), false));\n break;\n }\n\n case 2: // Started\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setStart(task.getActualStart());\n task.setFinish(row.getDate(\"ESTIMATED_FINISH\"));\n if (task.getFinish() == null)\n {\n task.setFinish(row.getDate(\"PLANNED_FINISH\"));\n }\n break;\n }\n\n case 3: // Finished\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setActualFinish(row.getDate(\"ACTUAL_FINISH\"));\n task.setPercentageComplete(Double.valueOf(100.0));\n task.setStart(task.getActualStart());\n task.setFinish(task.getActualFinish());\n break;\n }\n }\n\n setConstraints(task, row);\n\n processChildTasks(task, row);\n\n m_taskMap.put(task.getGUID(), task);\n\n List<MapRow> predecessors = row.getRows(\"PREDECESSORS\");\n if (predecessors != null && !predecessors.isEmpty())\n {\n m_predecessorMap.put(task, predecessors);\n }\n\n List<MapRow> resourceAssignmnets = row.getRows(\"RESOURCE_ASSIGNMENTS\");\n if (resourceAssignmnets != null && !resourceAssignmnets.isEmpty())\n {\n processResourceAssignments(task, resourceAssignmnets);\n }\n }", "public int addKey(String key) {\n JdkUtils.requireNonNull(key);\n int nextIndex = keys.size();\n final Integer mapIndex = JdkUtils.putIfAbsent(keys, key, nextIndex);\n return mapIndex == null ? nextIndex : mapIndex;\n }", "public boolean removeKey(long key) {\r\n\tint i = indexOfKey(key);\r\n\tif (i<0) return false; // key not contained\r\n\r\n\tthis.state[i]=REMOVED;\r\n\tthis.values[i]=0; // delta\r\n\tthis.distinct--;\r\n\r\n\tif (this.distinct < this.lowWaterMark) {\r\n\t\tint newCapacity = chooseShrinkCapacity(this.distinct,this.minLoadFactor, this.maxLoadFactor);\r\n\t\trehash(newCapacity);\r\n\t}\r\n\t\r\n\treturn true;\t\r\n}", "public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable, final ServiceCallback<T> callback) {\n final ServiceFuture<T> serviceFuture = new ServiceFuture<>();\n serviceFuture.subscription = observable\n .last()\n .subscribe(new Action1<ServiceResponse<T>>() {\n @Override\n public void call(ServiceResponse<T> t) {\n if (callback != null) {\n callback.success(t.body());\n }\n serviceFuture.set(t.body());\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n if (callback != null) {\n callback.failure(throwable);\n }\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }", "protected void AddLODSceneObject(GVRSceneObject currentSceneObject) {\n if (this.transformLODSceneObject != null) {\n GVRSceneObject levelOfDetailSceneObject = null;\n if ( currentSceneObject.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = currentSceneObject;\n }\n else {\n GVRSceneObject lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_TRANSLATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_ROTATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_SCALE_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n\n }\n if ( levelOfDetailSceneObject != null) {\n final GVRLODGroup lodGroup = (GVRLODGroup) this.transformLODSceneObject.getComponent(GVRLODGroup.getComponentType());\n lodGroup.addRange(this.getMinRange(), levelOfDetailSceneObject);\n this.increment();\n }\n }\n }" ]
Use this API to fetch a tmglobal_binding resource .
[ "public static tmglobal_binding get(nitro_service service) throws Exception{\n\t\ttmglobal_binding obj = new tmglobal_binding();\n\t\ttmglobal_binding response = (tmglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "@Override\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }", "public static base_response add(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver addresource = new ntpserver();\n\t\taddresource.serverip = resource.serverip;\n\t\taddresource.servername = resource.servername;\n\t\taddresource.minpoll = resource.minpoll;\n\t\taddresource.maxpoll = resource.maxpoll;\n\t\taddresource.autokey = resource.autokey;\n\t\taddresource.key = resource.key;\n\t\treturn addresource.add_resource(client);\n\t}", "public static final String removeAmpersands(String name)\n {\n if (name != null)\n {\n if (name.indexOf('&') != -1)\n {\n StringBuilder sb = new StringBuilder();\n int index = 0;\n char c;\n\n while (index < name.length())\n {\n c = name.charAt(index);\n if (c != '&')\n {\n sb.append(c);\n }\n ++index;\n }\n\n name = sb.toString();\n }\n }\n\n return (name);\n }", "public X509Certificate getMappedCertificateForHostname(String hostname) throws CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException\n\t{\n\t\tString subject = getSubjectForHostname(hostname);\n\n\t\tString thumbprint = _subjectMap.get(subject);\n\n\t\tif(thumbprint == null) {\n\n\t\t\tKeyPair kp = getRSAKeyPair();\n\n\t\t\tX509Certificate newCert = CertificateCreator.generateStdSSLServerCertificate(kp.getPublic(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t getSigningCert(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t getSigningPrivateKey(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t subject);\n\n\t\t\taddCertAndPrivateKey(hostname, newCert, kp.getPrivate());\n\n\t\t\tthumbprint = ThumbprintUtil.getThumbprint(newCert);\n\n\t\t\t_subjectMap.put(subject, thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\n\t\t\treturn newCert;\n\n\t\t}\n return getCertificateByAlias(thumbprint);\n\n\n\t}", "private void readRelationships()\n {\n for (MapRow row : m_tables.get(\"REL\"))\n {\n Task predecessor = m_activityMap.get(row.getString(\"PREDECESSOR_ACTIVITY_ID\"));\n Task successor = m_activityMap.get(row.getString(\"SUCCESSOR_ACTIVITY_ID\"));\n if (predecessor != null && successor != null)\n {\n Duration lag = row.getDuration(\"LAG_VALUE\");\n RelationType type = row.getRelationType(\"LAG_TYPE\");\n\n successor.addPredecessor(predecessor, type, lag);\n }\n }\n }", "private static boolean equalAsInts(Vec2d a, Vec2d b) {\n return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y);\n }", "private FieldType getActivityIDField(Map<FieldType, String> map)\n {\n FieldType result = null;\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n if (entry.getValue().equals(\"task_code\"))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }", "public static rnatip_stats[] get(nitro_service service, options option) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\trnatip_stats[] response = (rnatip_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}" ]
Handles Multi Instance Report message. Handles Report on the number of instances for the command class. @param serialMessage the serial message to process. @param offset the offset at which to start procesing.
[ "private void handleMultiInstanceReportResponse(SerialMessage serialMessage,\r\n\t\t\tint offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Report\");\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint instances = serialMessage.getMessagePayloadByte(offset + 1);\r\n\r\n\t\tif (instances == 0) {\r\n\t\t\tsetInstances(1);\r\n\t\t} else \r\n\t\t{\r\n\t\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\t\r\n\t\t\tif (commandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\t\r\n\t\t\tif (zwaveCommandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tzwaveCommandClass.setInstances(instances);\r\n\t\t\tlogger.debug(String.format(\"Node %d Instances = %d, number of instances set.\", this.getNode().getNodeId(), instances));\r\n\t\t}\r\n\t\t\r\n\t\tfor (ZWaveCommandClass zwaveCommandClass : this.getNode().getCommandClasses())\r\n\t\t\tif (zwaveCommandClass.getInstances() == 0) // still waiting for an instance report of another command class. \r\n\t\t\t\treturn;\r\n\t\t\r\n\t\t// advance node stage.\r\n\t\tthis.getNode().advanceNodeStage();\r\n\t}" ]
[ "public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }", "private void persistDisabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n try {\n disabledMarker.createNewFile();\n } catch (IOException e) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain disabled only until the next restart.\", e);\n }\n }", "protected NodeData createRectangleStyle(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformLength((float) getGraphicsState().getLineWidth());\n float lw = (lineWidth < 1f) ? 1f : lineWidth;\n float wcor = stroke ? lw : 0.0f;\n \n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"absolute\")));\n ret.push(createDeclaration(\"left\", tf.createLength(x, unit)));\n ret.push(createDeclaration(\"top\", tf.createLength(y, unit)));\n ret.push(createDeclaration(\"width\", tf.createLength(width - wcor, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(height - wcor, unit)));\n \n if (stroke)\n {\n ret.push(createDeclaration(\"border-width\", tf.createLength(lw, unit)));\n ret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n String color = colorString(getGraphicsState().getStrokingColor());\n ret.push(createDeclaration(\"border-color\", tf.createColor(color)));\n }\n \n if (fill)\n {\n String color = colorString(getGraphicsState().getNonStrokingColor());\n if (color != null)\n ret.push(createDeclaration(\"background-color\", tf.createColor(color)));\n }\n\n return ret;\n }", "public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }", "@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}", "private void processDumpFileContentsRecovery(InputStream inputStream)\n\t\t\tthrows IOException {\n\t\tJsonDumpFileProcessor.logger\n\t\t\t\t.warn(\"Entering recovery mode to parse rest of file. This might be slightly slower.\");\n\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(\n\t\t\t\tinputStream));\n\n\t\tString line = br.readLine();\n\t\tif (line == null) { // can happen if iterator already has consumed all\n\t\t\t\t\t\t\t// the stream\n\t\t\treturn;\n\t\t}\n\t\tif (line.length() >= 100) {\n\t\t\tline = line.substring(0, 100) + \"[...]\"\n\t\t\t\t\t+ line.substring(line.length() - 50);\n\t\t}\n\t\tJsonDumpFileProcessor.logger.warn(\"Skipping rest of current line: \"\n\t\t\t\t+ line);\n\n\t\tline = br.readLine();\n\t\twhile (line != null && line.length() > 1) {\n\t\t\ttry {\n\t\t\t\tEntityDocument document;\n\t\t\t\tif (line.charAt(line.length() - 1) == ',') {\n\t\t\t\t\tdocument = documentReader.readValue(line.substring(0,\n\t\t\t\t\t\t\tline.length() - 1));\n\t\t\t\t} else {\n\t\t\t\t\tdocument = documentReader.readValue(line);\n\t\t\t\t}\n\t\t\t\thandleDocument(document);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tlogJsonProcessingException(e);\n\t\t\t\tJsonDumpFileProcessor.logger.error(\"Problematic line was: \"\n\t\t\t\t\t\t+ line.substring(0, Math.min(50, line.length()))\n\t\t\t\t\t\t+ \"...\");\n\t\t\t}\n\n\t\t\tline = br.readLine();\n\t\t}\n\t}", "protected void layoutGroupFooterLabels(DJGroup djgroup, JRDesignGroup jgroup, int x, int y, int width, int height) {\n\t\t//List footerVariables = djgroup.getFooterVariables();\n\t\tDJGroupLabel label = djgroup.getFooterLabel();\n\n\t\t//if (label == null || footerVariables.isEmpty())\n\t\t\t//return;\n\n\t\t//PropertyColumn col = djgroup.getColumnToGroupBy();\n\t\tJRDesignBand band = LayoutUtils.getBandFromSection((JRDesignSection) jgroup.getGroupFooterSection());\n\n//\t\tlog.debug(\"Adding footer group label for group \" + djgroup);\n\n\t\t/*DJGroupVariable lmvar = findLeftMostColumn(footerVariables);\n\t\tAbstractColumn lmColumn = lmvar.getColumnToApplyOperation();\n\t\tint width = lmColumn.getPosX().intValue() - col.getPosX().intValue();\n\n\t\tint yOffset = findYOffsetForGroupLabel(band);*/\n\n\t\tJRDesignExpression labelExp;\n\t\tif (label.isJasperExpression()) //a text with things like \"$F{myField}\"\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(label.getText());\n\t\telse if (label.getLabelExpression() != null){\n\t\t\tlabelExp = ExpressionUtils.createExpression(jgroup.getName() + \"_labelExpression\", label.getLabelExpression(), true);\n\t\t} else //a simple text\n\t\t\t//labelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ Utils.escapeTextForExpression(label.getText())+ \"\\\"\");\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ label.getText() + \"\\\"\");\n\t\tJRDesignTextField labelTf = new JRDesignTextField();\n\t\tlabelTf.setExpression(labelExp);\n\t\tlabelTf.setWidth(width);\n\t\tlabelTf.setHeight(height);\n\t\tlabelTf.setX(x);\n\t\tlabelTf.setY(y);\n\t\t//int yOffsetGlabel = labelTf.getHeight();\n\t\tlabelTf.setPositionType( PositionTypeEnum.FIX_RELATIVE_TO_TOP );\n\t\tapplyStyleToElement(label.getStyle(), labelTf);\n\t\tband.addElement(labelTf);\n\t}", "@SafeVarargs\n\tpublic static <T> Set<T> asSet(T... ts) {\n\t\tif ( ts == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse if ( ts.length == 0 ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\tSet<T> set = new HashSet<T>( getInitialCapacityFromExpectedSize( ts.length ) );\n\t\t\tCollections.addAll( set, ts );\n\t\t\treturn Collections.unmodifiableSet( set );\n\t\t}\n\t}", "@Override\n public void perform(Rewrite event, EvaluationContext context)\n {\n perform((GraphRewrite) event, context);\n }" ]
Color waveforms are represented by a series of sixteen bit integers into which color and height information are packed. This function returns the integer corresponding to a particular half-frame in the waveform. @param waveBytes the raw data making up the waveform @param segment the index of hte half-frame of interest @return the sixteen-bit number encoding the height and RGB values of that segment
[ "private int getColorWaveformBits(final ByteBuffer waveBytes, final int segment) {\n final int base = (segment * 2);\n final int big = Util.unsign(waveBytes.get(base));\n final int small = Util.unsign(waveBytes.get(base + 1));\n return big * 256 + small;\n }" ]
[ "public void loadClassifier(String loadPath, Properties props) throws ClassCastException, IOException, ClassNotFoundException {\r\n InputStream is;\r\n // ms, 10-04-2010: check first is this path exists in our CLASSPATH. This\r\n // takes priority over the file system.\r\n if ((is = loadStreamFromClasspath(loadPath)) != null) {\r\n Timing.startDoing(\"Loading classifier from \" + loadPath);\r\n loadClassifier(is);\r\n is.close();\r\n Timing.endDoing();\r\n } else {\r\n loadClassifier(new File(loadPath), props);\r\n }\r\n }", "public List<ChannelInfo> getChannels(String connectionName) {\n final URI uri = uriWithPath(\"./connections/\" + encodePathSegment(connectionName) + \"/channels/\");\n return Arrays.asList(this.rt.getForObject(uri, ChannelInfo[].class));\n }", "public CollectionRequest<Task> findByProject(String projectId) {\n \n String path = String.format(\"/projects/%s/tasks\", projectId);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "protected CmsAccessControlEntry getImportAccessControlEntry(\n CmsResource res,\n String id,\n String allowed,\n String denied,\n String flags) {\n\n return new CmsAccessControlEntry(\n res.getResourceId(),\n new CmsUUID(id),\n Integer.parseInt(allowed),\n Integer.parseInt(denied),\n Integer.parseInt(flags));\n }", "public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\n }", "@Nonnull\n\tpublic static InterfaceAnalysis analyze(@Nonnull final String code) {\n\t\tCheck.notNull(code, \"code\");\n\n\t\tfinal CompilationUnit unit = Check.notNull(SourceCodeReader.parse(code), \"compilationUnit\");\n\t\tfinal List<TypeDeclaration> types = Check.notEmpty(unit.getTypes(), \"typeDeclarations\");\n\t\tCheck.stateIsTrue(types.size() == 1, \"only one interface declaration per analysis is supported\");\n\n\t\tfinal ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) types.get(0);\n\n\t\tfinal Imports imports = SourceCodeReader.findImports(unit.getImports());\n\t\tfinal Package pkg = unit.getPackage() != null ? new Package(unit.getPackage().getName().toString()) : Package.UNDEFINED;\n\t\tfinal List<Annotation> annotations = SourceCodeReader.findAnnotations(type.getAnnotations(), imports);\n\t\tfinal List<Method> methods = SourceCodeReader.findMethods(type.getMembers(), imports);\n\t\tCheck.stateIsTrue(!hasPossibleMutatingMethods(methods), \"The passed interface '%s' seems to have mutating methods\", type.getName());\n\t\tfinal List<Interface> extendsInterfaces = SourceCodeReader.findExtends(type);\n\t\tfinal String interfaceName = type.getName();\n\t\treturn new ImmutableInterfaceAnalysis(annotations, extendsInterfaces, imports.asList(), interfaceName, methods, pkg);\n\t}", "String buildProjectEndpoint(DatastoreOptions options) {\n if (options.getProjectEndpoint() != null) {\n return options.getProjectEndpoint();\n }\n // DatastoreOptions ensures either project endpoint or project ID is set.\n String projectId = checkNotNull(options.getProjectId());\n if (options.getHost() != null) {\n return validateUrl(String.format(\"https://%s/%s/projects/%s\",\n options.getHost(), VERSION, projectId));\n } else if (options.getLocalHost() != null) {\n return validateUrl(String.format(\"http://%s/%s/projects/%s\",\n options.getLocalHost(), VERSION, projectId));\n }\n return validateUrl(String.format(\"%s/%s/projects/%s\",\n DEFAULT_HOST, VERSION, projectId));\n }", "public void initialize(BinaryPackageControlFile packageControlFile) {\n set(\"Binary\", packageControlFile.get(\"Package\"));\n set(\"Source\", Utils.defaultString(packageControlFile.get(\"Source\"), packageControlFile.get(\"Package\")));\n set(\"Architecture\", packageControlFile.get(\"Architecture\"));\n set(\"Version\", packageControlFile.get(\"Version\"));\n set(\"Maintainer\", packageControlFile.get(\"Maintainer\"));\n set(\"Changed-By\", packageControlFile.get(\"Maintainer\"));\n set(\"Distribution\", packageControlFile.get(\"Distribution\"));\n\n for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {\n set(entry.getKey(), entry.getValue());\n }\n\n StringBuilder description = new StringBuilder();\n description.append(packageControlFile.get(\"Package\"));\n if (packageControlFile.get(\"Description\") != null) {\n description.append(\" - \");\n description.append(packageControlFile.getShortDescription());\n }\n set(\"Description\", description.toString());\n }", "private static EventEnumType convertEventType(org.talend.esb.sam.common.event.EventTypeEnum eventType) {\n if (eventType == null) {\n return null;\n }\n return EventEnumType.valueOf(eventType.name());\n }" ]