query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
crops the srcBmp with the canvasView bounds and returns the cropped bitmap
[ "private static Bitmap crop(Bitmap srcBmp, View canvasView, int downsampling) {\n float scale = 1f / downsampling;\n return Bitmap.createBitmap(\n srcBmp,\n (int) Math.floor((ViewCompat.getX(canvasView)) * scale),\n (int) Math.floor((ViewCompat.getY(canvasView)) * scale),\n (int) Math.floor((canvasView.getWidth()) * scale),\n (int) Math.floor((canvasView.getHeight()) * scale)\n );\n }" ]
[ "protected boolean inViewPort(final int dataIndex) {\n boolean inViewPort = true;\n\n for (Layout layout: mLayouts) {\n inViewPort = inViewPort && (layout.inViewPort(dataIndex) || !layout.isClippingEnabled());\n }\n return inViewPort;\n }", "@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }", "private SortedProperties getLocalization(Locale locale) throws IOException, CmsException {\n\n if (null == m_localizations.get(locale)) {\n switch (m_bundleType) {\n case PROPERTY:\n loadLocalizationFromPropertyBundle(locale);\n break;\n case XML:\n loadLocalizationFromXmlBundle(locale);\n break;\n case DESCRIPTOR:\n return null;\n default:\n break;\n }\n }\n return m_localizations.get(locale);\n }", "public TopicList<Topic> getTopicsList(String groupId, int perPage, int page) throws FlickrException {\r\n TopicList<Topic> topicList = new TopicList<Topic>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_TOPICS_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element topicElements = response.getPayload();\r\n topicList.setPage(topicElements.getAttribute(\"page\"));\r\n topicList.setPages(topicElements.getAttribute(\"pages\"));\r\n topicList.setPerPage(topicElements.getAttribute(\"perpage\"));\r\n topicList.setTotal(topicElements.getAttribute(\"total\"));\r\n topicList.setGroupId(topicElements.getAttribute(\"group_id\"));\r\n topicList.setIconServer(Integer.parseInt(topicElements.getAttribute(\"iconserver\")));\r\n topicList.setIconFarm(Integer.parseInt(topicElements.getAttribute(\"iconfarm\")));\r\n topicList.setName(topicElements.getAttribute(\"name\"));\r\n topicList.setMembers(Integer.parseInt(topicElements.getAttribute(\"members\")));\r\n topicList.setPrivacy(Integer.parseInt(topicElements.getAttribute(\"privacy\")));\r\n topicList.setLanguage(topicElements.getAttribute(\"lang\"));\r\n topicList.setIsPoolModerated(\"1\".equals(topicElements.getAttribute(\"ispoolmoderated\")));\r\n\r\n NodeList topicNodes = topicElements.getElementsByTagName(\"topic\");\r\n for (int i = 0; i < topicNodes.getLength(); i++) {\r\n Element element = (Element) topicNodes.item(i);\r\n topicList.add(parseTopic(element));\r\n }\r\n return topicList;\r\n }", "public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }", "public int count(String key) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = registry.get(key);\n return null == bag ? 0 : bag.size();\n }", "public Path getParent() {\n\t\tif (!isAbsolute())\n\t\t\tthrow new IllegalStateException(\"path is not absolute: \" + toString());\n\t\tif (segments.isEmpty())\n\t\t\treturn null;\n\t\treturn new Path(segments.subList(0, segments.size()-1), true);\n\t}", "public Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\n }", "private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) {\n if (!update.playing) {\n return update.milliseconds;\n }\n long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000;\n long moved = Math.round(update.pitch * elapsedMillis);\n if (update.reverse) {\n return update.milliseconds - moved;\n }\n return update.milliseconds + moved;\n }" ]
add various getAt and setAt methods for primitive arrays @param receiver the receiver class @param name the name of the method @param args the argument classes
[ "private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }" ]
[ "protected void appendHavingClause(StringBuffer having, Criteria crit, StringBuffer stmt)\r\n {\r\n if (having.length() == 0)\r\n {\r\n having = null;\r\n }\r\n\r\n if (having != null || crit != null)\r\n {\r\n stmt.append(\" HAVING \");\r\n appendClause(having, crit, stmt);\r\n }\r\n }", "public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }", "public long[] append(MessageSet messages) throws IOException {\n checkMutable();\n long written = 0L;\n while (written < messages.getSizeInBytes())\n written += messages.writeTo(channel, 0, messages.getSizeInBytes());\n long beforeOffset = setSize.getAndAdd(written);\n return new long[]{written, beforeOffset};\n }", "public URL buildWithQuery(String base, String queryString, Object... values) {\n String urlString = String.format(base + this.template, values) + queryString;\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n assert false : \"An invalid URL template indicates a bug in the SDK.\";\n }\n\n return url;\n }", "public void setHeader(String header) {\n headerLabel.getElement().setInnerSafeHtml(SafeHtmlUtils.fromString(header));\n addStyleName(CssName.WITH_HEADER);\n ListItem item = new ListItem(headerLabel);\n UiHelper.addMousePressedHandlers(item);\n item.setStyleName(CssName.COLLECTION_HEADER);\n insert(item, 0);\n }", "public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }", "protected float getStartingOffset(final float totalSize) {\n final float axisSize = getViewPortSize(getOrientationAxis());\n float startingOffset = 0;\n\n switch (getGravityInternal()) {\n case LEFT:\n case FILL:\n case TOP:\n case FRONT:\n startingOffset = -axisSize / 2;\n break;\n case RIGHT:\n case BOTTOM:\n case BACK:\n startingOffset = (axisSize / 2 - totalSize);\n break;\n case CENTER:\n startingOffset = -totalSize / 2;\n break;\n default:\n Log.w(TAG, \"Cannot calculate starting offset: \" +\n \"gravity %s is not supported!\", mGravity);\n break;\n\n }\n\n Log.d(LAYOUT, TAG, \"getStartingOffset(): totalSize: %5.4f, dimension: %5.4f, startingOffset: %5.4f\",\n totalSize, axisSize, startingOffset);\n\n return startingOffset;\n }", "public Date getNextWorkStart(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToNextWorkStart(cal);\n return cal.getTime();\n }", "public static boolean compareAnnotatedParameters(AnnotatedParameter<?> p1, AnnotatedParameter<?> p2) {\n return compareAnnotatedCallable(p1.getDeclaringCallable(), p2.getDeclaringCallable()) && p1.getPosition() == p2.getPosition() && compareAnnotated(p1, p2);\n }" ]
Delete all backups asynchronously
[ "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 }" ]
[ "public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }", "public boolean isConnectionHandleAlive(ConnectionHandle connection) {\r\n\t\tStatement stmt = null;\r\n\t\tboolean result = false;\r\n\t\tboolean logicallyClosed = connection.logicallyClosed.get();\r\n\t\ttry {\r\n\t\t\tconnection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed.\r\n\t\t\tString testStatement = this.config.getConnectionTestStatement();\r\n\t\t\tResultSet rs = null;\r\n\r\n\t\t\tif (testStatement == null) {\r\n\t\t\t\t// Make a call to fetch the metadata instead of a dummy query.\r\n\t\t\t\trs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE );\r\n\t\t\t} else {\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(testStatement);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (rs != null) {\r\n\t\t\t\trs.close();\r\n\t\t\t}\r\n\r\n\t\t\tresult = true;\r\n\t\t} catch (SQLException e) {\r\n\t\t\t// connection must be broken!\r\n\t\t\tresult = false;\r\n\t\t} finally {\r\n\t\t\tconnection.logicallyClosed.set(logicallyClosed);\r\n\t\t\tconnection.setConnectionLastResetInMs(System.currentTimeMillis());\r\n\t\t\tresult = closeStatement(stmt, result);\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "public static int[] toInt(double[] array) {\n int[] n = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (int) array[i];\n }\n return n;\n }", "private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }", "public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }", "protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}", "public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n if (creationalContext != null) {\n T instance = contextual.create(creationalContext);\n if (creationalContext instanceof WeldCreationalContext<?>) {\n addDependentInstance(instance, contextual, (WeldCreationalContext<T>) creationalContext);\n }\n return instance;\n } else {\n return null;\n }\n }", "public static int readInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16)\n | ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff));\n }" ]
Retrieves a field type from a location in a data block. @param data data block @param offset offset into data block @return field type
[ "private FieldType getFieldType(byte[] data, int offset)\n {\n int fieldIndex = MPPUtility.getInt(data, offset);\n return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex));\n }" ]
[ "void successfulBoot() throws ConfigurationPersistenceException {\n synchronized (this) {\n if (doneBootup.get()) {\n return;\n }\n final File copySource;\n if (!interactionPolicy.isReadOnly()) {\n copySource = mainFile;\n } else {\n\n if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) {\n copySource = new File(mainFile.getParentFile(), mainFile.getName() + \".boot\");\n } else{\n copySource = new File(configurationDir, mainFile.getName() + \".boot\");\n }\n\n FilePersistenceUtils.deleteFile(copySource);\n }\n\n try {\n if (!bootFile.equals(copySource)) {\n FilePersistenceUtils.copyFile(bootFile, copySource);\n }\n\n createHistoryDirectory();\n\n final File historyBase = new File(historyRoot, mainFile.getName());\n lastFile = addSuffixToFile(historyBase, LAST);\n final File boot = addSuffixToFile(historyBase, BOOT);\n final File initial = addSuffixToFile(historyBase, INITIAL);\n\n if (!initial.exists()) {\n FilePersistenceUtils.copyFile(copySource, initial);\n }\n\n FilePersistenceUtils.copyFile(copySource, lastFile);\n FilePersistenceUtils.copyFile(copySource, boot);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile);\n } finally {\n if (interactionPolicy.isReadOnly()) {\n //Delete the temporary file\n try {\n FilePersistenceUtils.deleteFile(copySource);\n } catch (Exception ignore) {\n }\n }\n }\n doneBootup.set(true);\n }\n }", "public int getXForBeat(int beat) {\n BeatGrid grid = beatGrid.get();\n if (grid != null) {\n return millisecondsToX(grid.getTimeWithinTrack(beat));\n }\n return 0;\n }", "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 static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) {\n for(StoreDefinition def: list)\n if(def.getName().equals(name))\n return def;\n return null;\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 }", "private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }", "private void populateMilestone(Row row, Task task)\n {\n task.setMilestone(true);\n //PROJID\n task.setUniqueID(row.getInteger(\"MILESTONEID\"));\n task.setStart(row.getDate(\"GIVEN_DATE_TIME\"));\n task.setFinish(row.getDate(\"GIVEN_DATE_TIME\"));\n //PROGREST_PERIOD\n //SYMBOL_APPEARANCE\n //MILESTONE_TYPE\n //PLACEMENU\n task.setPercentageComplete(row.getBoolean(\"COMPLETED\") ? COMPLETE : INCOMPLETE);\n //INTERRUPTIBLE_X\n //ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n //ACTUAL_DURATIONHOURS\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //EFFORT_BUDGET\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n //OVERALL_PERCENV_COMPLETE\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n //NOTET\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n //STARZ\n //ENJ\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n task.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }", "public Set<ConstraintViolation> validate(int record) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int ds = 0; ds < 250; ++ds) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds));\r\n\t\t\t\terrors.addAll(validate(dataSetInfo));\r\n\t\t\t} catch (InvalidDataSetException ignored) {\r\n\t\t\t\t// DataSetFactory doesn't know about this ds, so will skip it\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn errors;\r\n\t}", "public static void main(String[] args) throws IOException, ClassNotFoundException {\r\n CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter();\r\n f.init(new SeqClassifierFlags());\r\n int numDocs = 0;\r\n int numTokens = 0;\r\n int numEntities = 0;\r\n String lastAnsBase = \"\";\r\n for (Iterator<List<CoreLabel>> it = f.getIterator(new FileReader(args[0])); it.hasNext(); ) {\r\n List<CoreLabel> doc = it.next();\r\n numDocs++;\r\n for (CoreLabel fl : doc) {\r\n // System.out.println(\"FL \" + (++i) + \" was \" + fl);\r\n if (fl.word().equals(BOUNDARY)) {\r\n continue;\r\n }\r\n String ans = fl.get(AnswerAnnotation.class);\r\n String ansBase;\r\n String ansPrefix;\r\n String[] bits = ans.split(\"-\");\r\n if (bits.length == 1) {\r\n ansBase = bits[0];\r\n ansPrefix = \"\";\r\n } else {\r\n ansBase = bits[1];\r\n ansPrefix = bits[0];\r\n }\r\n numTokens++;\r\n if (ansBase.equals(\"O\")) {\r\n } else if (ansBase.equals(lastAnsBase)) {\r\n if (ansPrefix.equals(\"B\")) {\r\n numEntities++;\r\n }\r\n } else {\r\n numEntities++;\r\n }\r\n }\r\n }\r\n System.out.println(\"File \" + args[0] + \" has \" + numDocs + \" documents, \" +\r\n numTokens + \" (non-blank line) tokens and \" +\r\n numEntities + \" entities.\");\r\n }" ]
Notifies that multiple header items are changed. @param positionStart the position. @param itemCount the item count.
[ "public final void notifyHeaderItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart, itemCount);\n }" ]
[ "public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }", "private void resetStoreDefinitions(Set<String> storeNamesToDelete) {\n // Clear entries in the metadata cache\n for(String storeName: storeNamesToDelete) {\n this.metadataCache.remove(storeName);\n this.storeDefinitionsStorageEngine.delete(storeName, null);\n this.storeNames.remove(storeName);\n }\n }", "public base_response login(String username, String password, Long timeout) throws Exception\n\t{\n\t\tthis.set_credential(username, password);\n\t\tthis.set_timeout(timeout);\n\t\treturn this.login();\n\t}", "public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }", "public AT_Row setPaddingRightChar(Character paddingRightChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {\n MultipartContent.Part part = new MultipartContent.Part()\n .setContent(new InputStreamContent(fileType, fileContent))\n .setHeaders(new HttpHeaders().set(\n \"Content-Disposition\",\n String.format(\"form-data; name=\\\"file\\\"; filename=\\\"%s\\\"\", fileName) // TODO: escape fileName?\n ));\n MultipartContent content = new MultipartContent()\n .setMediaType(new HttpMediaType(\"multipart/form-data\").setParameter(\"boundary\", UUID.randomUUID().toString()))\n .addPart(part);\n\n String path = String.format(\"/tasks/%s/attachments\", task);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"POST\")\n .data(content);\n }", "public String getSample(int line, int column, Janitor janitor) {\n String sample = null;\n String text = source.getLine(line, janitor);\n\n if (text != null) {\n if (column > 0) {\n String marker = Utilities.repeatString(\" \", column - 1) + \"^\";\n\n if (column > 40) {\n int start = column - 30 - 1;\n int end = (column + 10 > text.length() ? text.length() : column + 10 - 1);\n sample = \" \" + text.substring(start, end) + Utilities.eol() + \" \" +\n marker.substring(start, marker.length());\n } else {\n sample = \" \" + text + Utilities.eol() + \" \" + marker;\n }\n } else {\n sample = text;\n }\n }\n\n return sample;\n }", "private void sendEvents(final List<Event> events) {\n if (null != handlers) {\n for (EventHandler current : handlers) {\n for (Event event : events) {\n current.handleEvent(event);\n }\n }\n }\n\n LOG.info(\"Put events(\" + events.size() + \") to Monitoring Server.\");\n\n try {\n if (sendToEventadmin) {\n EventAdminPublisher.publish(events);\n } else {\n monitoringServiceClient.putEvents(events);\n }\n } catch (MonitoringException e) {\n throw e;\n } catch (Exception e) {\n throw new MonitoringException(\"002\",\n \"Unknown error while execute put events to Monitoring Server\", e);\n }\n\n }", "public Collection<QName> getPortComponentQNames()\n {\n //TODO:Check if there is just one QName that drives all portcomponents\n //or each port component can have a distinct QName (namespace/prefix)\n //Maintain uniqueness of the QName\n Map<String, QName> map = new HashMap<String, QName>();\n for (PortComponentMetaData pcm : portComponents)\n {\n QName qname = pcm.getWsdlPort();\n map.put(qname.getPrefix(), qname);\n }\n return map.values();\n }" ]
Sort and order steps to avoid unwanted generation
[ "public ModelNode buildExecutableRequest(CommandContext ctx) throws Exception {\n try {\n for (FailureDescProvider h : providers) {\n effectiveProviders.add(h);\n }\n // In case some key-store needs to be persisted\n for (String ks : ksToStore) {\n composite.get(Util.STEPS).add(ElytronUtil.storeKeyStore(ctx, ks));\n effectiveProviders.add(new FailureDescProvider() {\n @Override\n public String stepFailedDescription() {\n return \"Storing the key-store \" + ksToStore;\n }\n });\n }\n // Final steps\n for (int i = 0; i < finalSteps.size(); i++) {\n composite.get(Util.STEPS).add(finalSteps.get(i));\n effectiveProviders.add(finalProviders.get(i));\n }\n return composite;\n } catch (Exception ex) {\n try {\n failureOccured(ctx, null);\n } catch (Exception ex2) {\n ex.addSuppressed(ex2);\n }\n throw ex;\n }\n }" ]
[ "private static char[] buildTable() {\n char[] table = new char[26];\n for (int ix = 0; ix < table.length; ix++)\n table[ix] = '0';\n table['B' - 'A'] = '1';\n table['P' - 'A'] = '1';\n table['F' - 'A'] = '1';\n table['V' - 'A'] = '1';\n table['C' - 'A'] = '2';\n table['S' - 'A'] = '2';\n table['K' - 'A'] = '2';\n table['G' - 'A'] = '2';\n table['J' - 'A'] = '2';\n table['Q' - 'A'] = '2';\n table['X' - 'A'] = '2';\n table['Z' - 'A'] = '2';\n table['D' - 'A'] = '3';\n table['T' - 'A'] = '3';\n table['L' - 'A'] = '4';\n table['M' - 'A'] = '5';\n table['N' - 'A'] = '5';\n table['R' - 'A'] = '6';\n return table;\n }", "public void info(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.INFO, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public CmsSolrQuery getQuery(CmsObject cms) {\n\n final CmsSolrQuery query = new CmsSolrQuery();\n\n // set categories\n query.setCategories(m_categories);\n\n // set container types\n if (null != m_containerTypes) {\n query.addFilterQuery(CmsSearchField.FIELD_CONTAINER_TYPES, m_containerTypes, false, false);\n }\n\n // Set date created time filter\n query.addFilterQuery(\n CmsSearchUtil.getDateCreatedTimeRangeFilterQuery(\n CmsSearchField.FIELD_DATE_CREATED,\n getDateCreatedRange().m_startTime,\n getDateCreatedRange().m_endTime));\n\n // Set date last modified time filter\n query.addFilterQuery(\n CmsSearchUtil.getDateCreatedTimeRangeFilterQuery(\n CmsSearchField.FIELD_DATE_LASTMODIFIED,\n getDateLastModifiedRange().m_startTime,\n getDateLastModifiedRange().m_endTime));\n\n // set scope / folders to search in\n m_foldersToSearchIn = new ArrayList<String>();\n addFoldersToSearchIn(m_folders);\n addFoldersToSearchIn(m_galleries);\n setSearchFolders(cms);\n query.addFilterQuery(\n CmsSearchField.FIELD_PARENT_FOLDERS,\n new ArrayList<String>(m_foldersToSearchIn),\n false,\n true);\n\n if (!m_ignoreSearchExclude) {\n // Reference for the values: CmsGallerySearchIndex.java, field EXCLUDE_PROPERTY_VALUES\n query.addFilterQuery(\n \"-\" + CmsSearchField.FIELD_SEARCH_EXCLUDE,\n Arrays.asList(\n new String[] {\n A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_ALL,\n A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_GALLERY}),\n false,\n true);\n }\n\n // set matches per page\n query.setRows(new Integer(m_matchesPerPage));\n\n // set resource types\n if (null != m_resourceTypes) {\n List<String> resourceTypes = new ArrayList<>(m_resourceTypes);\n if (m_resourceTypes.contains(CmsResourceTypeFunctionConfig.TYPE_NAME)\n && !m_resourceTypes.contains(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION)) {\n resourceTypes.add(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION);\n }\n query.setResourceTypes(resourceTypes);\n }\n\n // set result page\n query.setStart(new Integer((m_resultPage - 1) * m_matchesPerPage));\n\n // set search locale\n if (null != m_locale) {\n query.setLocales(CmsLocaleManager.getLocale(m_locale));\n }\n\n // set search words\n if (null != m_words) {\n query.setQuery(m_words);\n }\n\n // set sort order\n query.setSort(getSort().getFirst(), getSort().getSecond());\n\n // set result collapsing by id\n query.addFilterQuery(\"{!collapse field=id}\");\n\n query.setFields(CmsGallerySearchResult.getRequiredSolrFields());\n\n if ((m_allowedFunctions != null) && !m_allowedFunctions.isEmpty()) {\n String functionFilter = \"((-type:(\"\n + CmsXmlDynamicFunctionHandler.TYPE_FUNCTION\n + \" OR \"\n + CmsResourceTypeFunctionConfig.TYPE_NAME\n + \")) OR (id:(\";\n Iterator<CmsUUID> it = m_allowedFunctions.iterator();\n while (it.hasNext()) {\n CmsUUID id = it.next();\n functionFilter += id.toString();\n if (it.hasNext()) {\n functionFilter += \" OR \";\n }\n }\n functionFilter += \")))\";\n query.addFilterQuery(functionFilter);\n }\n\n return query;\n }", "public <T> Observable<ServiceResponse<T>> getPutOrPatchResultAsync(Observable<Response<ResponseBody>> observable, final Type resourceType) {\n return this.<T>beginPutOrPatchAsync(observable, resourceType)\n .toObservable()\n .flatMap(new Func1<PollingState<T>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(PollingState<T> pollingState) {\n return pollPutOrPatchAsync(pollingState, resourceType);\n }\n })\n .last()\n .map(new Func1<PollingState<T>, ServiceResponse<T>>() {\n @Override\n public ServiceResponse<T> call(PollingState<T> pollingState) {\n return new ServiceResponse<>(pollingState.resource(), pollingState.response());\n }\n });\n }", "public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }", "public FieldType getFieldTypeFromVarDataKey(Integer key)\n {\n FieldType result = null;\n for (Entry<FieldType, FieldMap.FieldItem> entry : m_map.entrySet())\n {\n if (entry.getValue().getFieldLocation() == FieldLocation.VAR_DATA && entry.getValue().getVarDataKey().equals(key))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (pixelPerUnitBased) {\n\t\t\t//\tCalculate numerator and denominator\n\t\t\tif (pixelPerUnit > PIXEL_PER_METER) {\n\t\t\t\tthis.numerator = pixelPerUnit / conversionFactor;\n\t\t\t\tthis.denominator = 1;\n\t\t\t} else {\n\t\t\t\tthis.numerator = 1;\n\t\t\t\tthis.denominator = PIXEL_PER_METER / pixelPerUnit;\n\t\t\t}\n\t\t\tsetPixelPerUnitBased(false);\n\t\t} else {\n\t\t\t// Calculate PPU\n\t\t\tthis.pixelPerUnit = numerator / denominator * conversionFactor;\n\t\t\tsetPixelPerUnitBased(true);\n\t\t}\n\t}", "public static MarvinImage rgbToBinary(MarvinImage img, int threshold) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_BINARY);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n int gray = (int) ((img.getIntComponent0(x, y) * 0.3) + (img.getIntComponent1(x, y) * 0.59) + (img.getIntComponent2(x, y) * 0.11));\n\n if (gray <= threshold) {\n resultImage.setBinaryColor(x, y, true);\n } else {\n resultImage.setBinaryColor(x, y, false);\n }\n }\n }\n return resultImage;\n }", "public void removeLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference serviceReference : declaration.getStatus().getServiceReferencesBounded()) {\n // FIXME : In case of multiples Linker, we will remove the link of all the ServiceReference\n // FIXME : event the ones which dun know nothing about\n linkerManagement.unlink(declaration, serviceReference);\n }\n }" ]
Unpause the server, allowing it to resume normal operations
[ "@Override\n public synchronized void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n while (!taskQueue.isEmpty() && (activeRequestCount < maxRequestCount || maxRequestCount < 0)) {\n runQueuedTask(false);\n }\n }" ]
[ "VersionExcludeData getVersionIgnoreData(int major, int minor, int micro) {\n VersionExcludeData result = registry.get(new VersionKey(major, minor, micro));\n if (result == null) {\n result = registry.get(new VersionKey(major, minor, null));\n }\n return result;\n }", "public final static int readUntil(final StringBuilder out, final String in, final int start, final char end)\n {\n int pos = start;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n if (ch == end)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public static Cluster cloneCluster(Cluster cluster) {\n // Could add a better .clone() implementation that clones the derived\n // data structures. The constructor invoked by this clone implementation\n // can be slow for large numbers of partitions. Probably faster to copy\n // all the maps and stuff.\n return new Cluster(cluster.getName(),\n new ArrayList<Node>(cluster.getNodes()),\n new ArrayList<Zone>(cluster.getZones()));\n /*-\n * Historic \"clone\" code being kept in case this, for some reason, was the \"right\" way to be doing this.\n ClusterMapper mapper = new ClusterMapper();\n return mapper.readCluster(new StringReader(mapper.writeCluster(cluster)));\n */\n }", "public void put(@NotNull final PersistentStoreTransaction txn,\n final long localId,\n @NotNull final ByteIterable value,\n @Nullable final ByteIterable oldValue,\n final int propertyId,\n @NotNull final ComparableValueType type) {\n final Store valueIdx = getOrCreateValueIndex(txn, propertyId);\n final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));\n final Transaction envTxn = txn.getEnvironmentTransaction();\n primaryStore.put(envTxn, key, value);\n final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);\n boolean success;\n if (oldValue == null) {\n success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);\n } else {\n success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));\n }\n if (success) {\n for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {\n valueIdx.put(envTxn, secondaryKey, secondaryValue);\n }\n }\n checkStatus(success, \"Failed to put\");\n }", "public Set<DeviceAnnouncement> findUnreachablePlayers() {\n ensureRunning();\n Set<DeviceAnnouncement> result = new HashSet<DeviceAnnouncement>();\n for (DeviceAnnouncement candidate: DeviceFinder.getInstance().getCurrentDevices()) {\n if (!Util.sameNetwork(matchedAddress.getNetworkPrefixLength(), matchedAddress.getAddress(), candidate.getAddress())) {\n result.add(candidate);\n }\n }\n return Collections.unmodifiableSet(result);\n }", "public void start() {\n if (TransitionConfig.isDebug()) {\n getTransitionStateHolder().start();\n }\n\n mLastProgress = Float.MIN_VALUE;\n\n TransitionController transitionController;\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n transitionController = mTransitionControls.get(i);\n if (mInterpolator != null) {\n transitionController.setInterpolator(mInterpolator);\n }\n //required for ViewPager transitions to work\n if (mTarget != null) {\n transitionController.setTarget(mTarget);\n }\n transitionController.setUpdateStateAfterUpdateProgress(mUpdateStateAfterUpdateProgress);\n transitionController.start();\n }\n }", "private void writeAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n Project.Assignments.Assignment.ExtendedAttribute attrib;\n List<Project.Assignments.Assignment.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (AssignmentField mpxFieldID : getAllAssignmentExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPAssignmentField.getID(mpxFieldID) | MPPAssignmentField.ASSIGNMENT_FIELD_BASE);\n\n attrib = m_factory.createProjectAssignmentsAssignmentExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }", "public void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }", "@VisibleForTesting\n protected static int getBarSize(final ScaleBarRenderSettings settings) {\n if (settings.getParams().barSize != null) {\n return settings.getParams().barSize;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().height / 4;\n } else {\n return settings.getMaxSize().width / 4;\n }\n }\n }" ]
Process start. @param endpoint the endpoint @param eventType the event type
[ "protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n queue.add(event);\n }" ]
[ "public DbLicense getLicense(final String name) {\n final DbLicense license = repoHandler.getLicense(name);\n\n if (license == null) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"License \" + name + \" does not exist.\").build());\n }\n\n return license;\n }", "private void pushRight( int row ) {\n if( isOffZero(row))\n return;\n\n// B = createB();\n// B.print();\n rotatorPushRight(row);\n int end = N-2-row;\n for( int i = 0; i < end && bulge != 0; i++ ) {\n rotatorPushRight2(row,i+2);\n }\n// }\n }", "public static tmtrafficaction[] get(nitro_service service) throws Exception{\n\t\ttmtrafficaction obj = new tmtrafficaction();\n\t\ttmtrafficaction[] response = (tmtrafficaction[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private static void addFormatInfoEval(byte[] eval, int size, EccLevel ecc_level, int pattern) {\n\n int format = pattern;\n int seq;\n int i;\n\n switch(ecc_level) {\n case L: format += 0x08; break;\n case Q: format += 0x18; break;\n case H: format += 0x10; break;\n }\n\n seq = QR_ANNEX_C[format];\n\n for (i = 0; i < 6; i++) {\n eval[(i * size) + 8] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 8; i++) {\n eval[(8 * size) + (size - i - 1)] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 6; i++) {\n eval[(8 * size) + (5 - i)] = (byte) ((((seq >> (i + 9)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 7; i++) {\n eval[(((size - 7) + i) * size) + 8] = (byte) ((((seq >> (i + 8)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n eval[(7 * size) + 8] = (byte) ((((seq >> 6) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 8] = (byte) ((((seq >> 7) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 7] = (byte) ((((seq >> 8) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }", "static void merge(Map<ConfigurationKey, Object> original, Map<ConfigurationKey, Object> toMerge, String mergedSourceDescription) {\n for (Entry<ConfigurationKey, Object> entry : toMerge.entrySet()) {\n Object existing = original.get(entry.getKey());\n if (existing != null) {\n ConfigurationLogger.LOG.configurationKeyAlreadySet(entry.getKey().get(), existing, entry.getValue(), mergedSourceDescription);\n } else {\n original.put(entry.getKey(), entry.getValue());\n }\n }\n }", "public static systemeventhistory[] get(nitro_service service, systemeventhistory_args args) throws Exception{\n\t\tsystemeventhistory obj = new systemeventhistory();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystemeventhistory[] response = (systemeventhistory[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "private int read() {\n int curByte = 0;\n try {\n curByte = rawData.get() & 0xFF;\n } catch (Exception e) {\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n return curByte;\n }", "public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }", "public static boolean isPortletEnvSupported() {\n if (enabled == null) {\n synchronized (PortletSupport.class) {\n if (enabled == null) {\n try {\n PortletSupport.class.getClassLoader().loadClass(\"javax.portlet.PortletContext\");\n enabled = true;\n } catch (Throwable ignored) {\n enabled = false;\n }\n }\n }\n }\n return enabled;\n }" ]
Iterates over all the documents, adding each to the given target. @param target the collection to insert into @param <A> the collection type @return the target
[ "public <A extends Collection<? super ResultT>> A into(final A target) {\n forEach(new Block<ResultT>() {\n @Override\n public void apply(@Nonnull final ResultT t) {\n target.add(t);\n }\n });\n return target;\n }" ]
[ "private String getFullUrl(String url) {\n return url.startsWith(\"https://\") || url.startsWith(\"http://\") ? url : transloadit.getHostUrl() + url;\n }", "private boolean detectWSAddressingFeature(InterceptorProvider provider, Bus bus) {\n //detect on the bus level\n if (bus.getFeatures() != null) {\n Iterator<Feature> busFeatures = bus.getFeatures().iterator();\n while (busFeatures.hasNext()) {\n Feature busFeature = busFeatures.next();\n if (busFeature instanceof WSAddressingFeature) {\n return true;\n }\n }\n }\n\n //detect on the endpoint/client level\n Iterator<Interceptor<? extends Message>> interceptors = provider.getInInterceptors().iterator();\n while (interceptors.hasNext()) {\n Interceptor<? extends Message> ic = interceptors.next();\n if (ic instanceof MAPAggregator) {\n return true;\n }\n }\n\n return false;\n }", "@Override\n\tpublic EmbeddedBrowser get() {\n\t\tLOGGER.debug(\"Setting up a Browser\");\n\t\t// Retrieve the config values used\n\t\tImmutableSortedSet<String> filterAttributes =\n\t\t\t\tconfiguration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();\n\t\tlong crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();\n\t\tlong crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();\n\n\t\t// Determine the requested browser type\n\t\tEmbeddedBrowser browser = null;\n\t\tEmbeddedBrowser.BrowserType browserType =\n\t\t\t\tconfiguration.getBrowserConfig().getBrowserType();\n\t\ttry {\n\t\t\tswitch (browserType) {\n\t\t\t\tcase CHROME:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHROME_HEADLESS:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload,\n\t\t\t\t\t\t\tcrawlWaitEvent, true);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX_HEADLESS:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOTE:\n\t\t\t\t\tbrowser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(\n\t\t\t\t\t\t\tconfiguration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,\n\t\t\t\t\t\t\tcrawlWaitEvent, crawlWaitReload);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHANTOMJS:\n\t\t\t\t\tbrowser =\n\t\t\t\t\t\t\tnewPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unrecognized browser type \"\n\t\t\t\t\t\t\t+ configuration.getBrowserConfig().getBrowserType());\n\t\t\t}\n\t\t} catch (IllegalStateException e) {\n\t\t\tLOGGER.error(\"Crawling with {} failed: \" + e.getMessage(), browserType.toString());\n\t\t\tthrow e;\n\t\t}\n\n\t\t/* for Retina display. */\n\t\tif (browser instanceof WebDriverBackedEmbeddedBrowser) {\n\t\t\tint pixelDensity =\n\t\t\t\t\tthis.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();\n\t\t\tif (pixelDensity != -1)\n\t\t\t\t((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);\n\t\t}\n\n\t\tplugins.runOnBrowserCreatedPlugins(browser);\n\t\treturn browser;\n\t}", "public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }", "private 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 }", "public void setDiffuseIntensity(float r, float g, float b, float a) {\n setVec4(\"diffuse_intensity\", r, g, b, a);\n }", "@SuppressWarnings(\"unchecked\") public final List<MapRow> getRows(String name)\n {\n return (List<MapRow>) getObject(name);\n }", "public static void loadCubemapTexture(final GVRContext context,\n ResourceCache<GVRImage> textureCache,\n final TextureCallback callback,\n final GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap)\n throws IllegalArgumentException\n {\n validatePriorityCallbackParameters(context, callback, resource,\n priority);\n final GVRImage cached = textureCache == null\n ? null\n : (GVRImage) textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Texture: %s loaded from cache\", cached.getFileName());\n context.runOnGlThread(new Runnable()\n {\n @Override\n public void run()\n {\n callback.loaded(cached, resource);\n }\n });\n }\n else\n {\n TextureCallback actualCallback = (textureCache == null) ? callback\n : ResourceCache.wrapCallback(textureCache, callback);\n AsyncCubemapTexture.loadTexture(context,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, actualCallback),\n resource, priority, faceIndexMap);\n }\n }", "public StateVertex crawlIndex() {\n\t\tLOG.debug(\"Setting up vertex of the index page\");\n\n\t\tif (basicAuthUrl != null) {\n\t\t\tbrowser.goToUrl(basicAuthUrl);\n\t\t}\n\n\t\tbrowser.goToUrl(url);\n\n\t\t// Run url first load plugin to clear the application state\n\t\tplugins.runOnUrlFirstLoadPlugins(context);\n\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tStateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),\n\t\t\t\tstateComparator.getStrippedDom(browser), browser);\n\t\tPreconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,\n\t\t\t\t\"It seems some the index state is crawled more than once.\");\n\n\t\tLOG.debug(\"Parsing the index for candidate elements\");\n\t\tImmutableList<CandidateElement> extract = candidateExtractor.extract(index);\n\n\t\tplugins.runPreStateCrawlingPlugins(context, extract, index);\n\n\t\tcandidateActionCache.addActions(extract, index);\n\n\t\treturn index;\n\n\t}" ]
Handle interval change. @param event the change event.
[ "@UiHandler(\"m_everyDay\")\r\n void onEveryDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setInterval(m_everyDay.getFormValueAsString());\r\n }\r\n\r\n }" ]
[ "public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }", "protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}", "public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {\n\t\tif (clazz1 == null) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tif (clazz2 == null) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz1.isAssignableFrom(clazz2)) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz2.isAssignableFrom(clazz1)) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tClass<?> ancestor = clazz1;\n\t\tdo {\n\t\t\tancestor = ancestor.getSuperclass();\n\t\t\tif (ancestor == null || Object.class.equals(ancestor)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\twhile (!ancestor.isAssignableFrom(clazz2));\n\t\treturn ancestor;\n\t}", "@SuppressWarnings(\"deprecation\")\n public BUILDER addAccessConstraint(final AccessConstraintDefinition accessConstraint) {\n if (accessConstraints == null) {\n accessConstraints = new AccessConstraintDefinition[] {accessConstraint};\n } else {\n accessConstraints = Arrays.copyOf(accessConstraints, accessConstraints.length + 1);\n accessConstraints[accessConstraints.length - 1] = accessConstraint;\n }\n return (BUILDER) this;\n }", "private int deleteSegments(Log log, List<LogSegment> segments) {\n int total = 0;\n for (LogSegment segment : segments) {\n boolean deleted = false;\n try {\n try {\n segment.getMessageSet().close();\n } catch (IOException e) {\n logger.warn(e.getMessage(), e);\n }\n if (!segment.getFile().delete()) {\n deleted = true;\n } else {\n total += 1;\n }\n } finally {\n logger.warn(String.format(\"DELETE_LOG[%s] %s => %s\", log.name, segment.getFile().getAbsolutePath(),\n deleted));\n }\n }\n return total;\n }", "public String getUncPath() {\n getUncPath0();\n if( share == null ) {\n return \"\\\\\\\\\" + url.getHost();\n }\n return \"\\\\\\\\\" + url.getHost() + canon.replace( '/', '\\\\' );\n }", "public static policydataset[] get(nitro_service service) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tpolicydataset[] response = (policydataset[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public WebSocketContext sendToPeers(String message, boolean excludeSelf) {\n return sendToConnections(message, url, manager.urlRegistry(), excludeSelf);\n }", "public static bridgetable[] get(nitro_service service) throws Exception{\n\t\tbridgetable obj = new bridgetable();\n\t\tbridgetable[] response = (bridgetable[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Verify the given job types are all valid. @param jobTypes the given job types @throws IllegalArgumentException if any of the job types are invalid @see #checkJobType(String, Class)
[ "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 static boolean hasAnnotation(AnnotatedNode node, String name) {\r\n return AstUtil.getAnnotation(node, name) != null;\r\n }", "public static String analyzeInvalidMetadataRate(final Cluster currentCluster,\n List<StoreDefinition> currentStoreDefs,\n final Cluster finalCluster,\n List<StoreDefinition> finalStoreDefs) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Dump of invalid metadata rates per zone\").append(Utils.NEWLINE);\n\n HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs);\n\n for(StoreDefinition currentStoreDef: uniqueStores.keySet()) {\n sb.append(\"Store exemplar: \" + currentStoreDef.getName())\n .append(Utils.NEWLINE)\n .append(\"\\tThere are \" + uniqueStores.get(currentStoreDef) + \" other similar stores.\")\n .append(Utils.NEWLINE);\n\n StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef);\n StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs,\n currentStoreDef.getName());\n StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef);\n\n // Only care about existing zones\n for(int zoneId: currentCluster.getZoneIds()) {\n int zonePrimariesCount = 0;\n int invalidMetadata = 0;\n\n // Examine nodes in current cluster in existing zone.\n for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) {\n // For every zone-primary in current cluster\n for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) {\n zonePrimariesCount++;\n // Determine if original zone-primary node is still some\n // form of n-ary in final cluster. If not,\n // InvalidMetadataException will fire.\n if(!finalSRP.getZoneNAryPartitionIds(nodeId)\n .contains(zonePrimaryPartitionId)) {\n invalidMetadata++;\n }\n }\n }\n float rate = invalidMetadata / (float) zonePrimariesCount;\n sb.append(\"\\tZone \" + zoneId)\n .append(\" : total zone primaries \" + zonePrimariesCount)\n .append(\", # that trigger invalid metadata \" + invalidMetadata)\n .append(\" => \" + rate)\n .append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }", "public int size(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t// existence check on inner map1\n\t\tfinal HashMap<K3, V> innerMap2 = innerMap1.get(secondKey);\n\t\tif( innerMap2 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap2.size();\n\t}", "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }", "ModelNode toModelNode() {\n ModelNode result = null;\n if (map != null) {\n result = new ModelNode();\n for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) {\n ModelNode item = new ModelNode();\n PathAddress pa = entry.getKey();\n item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode());\n ResourceData rd = entry.getValue();\n item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode());\n ModelNode attrs = new ModelNode().setEmptyList();\n if (rd.attributes != null) {\n for (String attr : rd.attributes) {\n attrs.add(attr);\n }\n }\n if (attrs.asInt() > 0) {\n item.get(FILTERED_ATTRIBUTES).set(attrs);\n }\n ModelNode children = new ModelNode().setEmptyList();\n if (rd.children != null) {\n for (PathElement pe : rd.children) {\n children.add(new Property(pe.getKey(), new ModelNode(pe.getValue())));\n }\n }\n if (children.asInt() > 0) {\n item.get(UNREADABLE_CHILDREN).set(children);\n }\n ModelNode childTypes = new ModelNode().setEmptyList();\n if (rd.childTypes != null) {\n Set<String> added = new HashSet<String>();\n for (PathElement pe : rd.childTypes) {\n if (added.add(pe.getKey())) {\n childTypes.add(pe.getKey());\n }\n }\n }\n if (childTypes.asInt() > 0) {\n item.get(FILTERED_CHILDREN_TYPES).set(childTypes);\n }\n result.add(item);\n }\n }\n return result;\n }", "public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }", "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {\n ResourceRootIndexer.indexResourceRoot(resourceRoot);\n }\n }", "public static <T> PollingState<T> create(Response<ResponseBody> response, LongRunningOperationOptions lroOptions, int defaultRetryTimeout, Type resourceType, SerializerAdapter<?> serializerAdapter) throws IOException {\n PollingState<T> pollingState = new PollingState<>();\n pollingState.initialHttpMethod = response.raw().request().method();\n pollingState.defaultRetryTimeout = defaultRetryTimeout;\n pollingState.withResponse(response);\n pollingState.resourceType = resourceType;\n pollingState.serializerAdapter = serializerAdapter;\n pollingState.loggingContext = response.raw().request().header(LOGGING_HEADER);\n pollingState.finalStateVia = lroOptions.finalStateVia();\n\n String responseContent = null;\n PollingResource resource = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n if (responseContent != null && !responseContent.isEmpty()) {\n pollingState.resource = serializerAdapter.deserialize(responseContent, resourceType);\n resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n }\n final int statusCode = pollingState.response.code();\n if (resource != null && resource.properties != null\n && resource.properties.provisioningState != null) {\n pollingState.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n switch (statusCode) {\n case 202:\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n break;\n case 204:\n case 201:\n case 200:\n pollingState.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n break;\n default:\n pollingState.withStatus(AzureAsyncOperation.FAILED_STATUS, statusCode);\n }\n }\n return pollingState;\n }", "private void addNewGenderName(EntityIdValue entityIdValue, String name) {\n\t\tthis.genderNames.put(entityIdValue, name);\n\t\tthis.genderNamesList.add(entityIdValue);\n\t}" ]
Retrieves state and metrics information for all channels on individual connection. @param connectionName the connection name to retrieve channels @return list of channels on the connection
[ "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 }" ]
[ "private void handleChange(Object propertyId) {\n\n if (!m_saveBtn.isEnabled()) {\n m_saveBtn.setEnabled(true);\n m_saveExitBtn.setEnabled(true);\n }\n m_model.handleChange(propertyId);\n\n }", "public List<com.groupon.odo.proxylib.models.Method> getMethodsNotInGroup(int groupId) throws Exception {\n List<com.groupon.odo.proxylib.models.Method> allMethods = getAllMethods();\n List<com.groupon.odo.proxylib.models.Method> methodsNotInGroup = new ArrayList<com.groupon.odo.proxylib.models.Method>();\n List<com.groupon.odo.proxylib.models.Method> methodsInGroup = editService.getMethodsFromGroupId(groupId, null);\n\n for (int i = 0; i < allMethods.size(); i++) {\n boolean add = true;\n String methodName = allMethods.get(i).getMethodName();\n String className = allMethods.get(i).getClassName();\n\n for (int j = 0; j < methodsInGroup.size(); j++) {\n if ((methodName.equals(methodsInGroup.get(j).getMethodName())) &&\n (className.equals(methodsInGroup.get(j).getClassName()))) {\n add = false;\n }\n }\n if (add) {\n methodsNotInGroup.add(allMethods.get(i));\n }\n }\n return methodsNotInGroup;\n }", "public GVRAnimationChannel findChannel(String boneName)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n return mBoneChannels[boneId];\n }\n return null;\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 }", "public static String format(Flags flags) {\r\n StringBuilder buf = new StringBuilder();\r\n buf.append('(');\r\n if (flags.contains(Flags.Flag.ANSWERED)) {\r\n buf.append(\"\\\\Answered \");\r\n }\r\n if (flags.contains(Flags.Flag.DELETED)) {\r\n buf.append(\"\\\\Deleted \");\r\n }\r\n if (flags.contains(Flags.Flag.DRAFT)) {\r\n buf.append(\"\\\\Draft \");\r\n }\r\n if (flags.contains(Flags.Flag.FLAGGED)) {\r\n buf.append(\"\\\\Flagged \");\r\n }\r\n if (flags.contains(Flags.Flag.RECENT)) {\r\n buf.append(\"\\\\Recent \");\r\n }\r\n if (flags.contains(Flags.Flag.SEEN)) {\r\n buf.append(\"\\\\Seen \");\r\n }\r\n String[] userFlags = flags.getUserFlags();\r\n if(null!=userFlags) {\r\n for(String uf: userFlags) {\r\n buf.append(uf).append(' ');\r\n }\r\n }\r\n // Remove the trailing space, if necessary.\r\n if (buf.length() > 1) {\r\n buf.setLength(buf.length() - 1);\r\n }\r\n buf.append(')');\r\n return buf.toString();\r\n }", "void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }", "public static Authentication build(String crypt) throws IllegalArgumentException {\n if(crypt == null) {\n return new PlainAuth(null);\n }\n String[] value = crypt.split(\":\");\n \n if(value.length == 2 ) {\n String type = value[0].trim();\n String password = value[1].trim();\n if(password!=null&&password.length()>0) {\n if(\"plain\".equals(type)) {\n return new PlainAuth(password);\n }\n if(\"md5\".equals(type)) {\n return new Md5Auth(password);\n }\n if(\"crc32\".equals(type)) {\n return new Crc32Auth(Long.parseLong(password));\n }\n }\n }\n throw new IllegalArgumentException(\"error password: \"+crypt);\n }", "public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }", "@Api\n\tpublic void setFeatureModel(FeatureModel featureModel) throws LayerException {\n\t\tthis.featureModel = featureModel;\n\t\tif (null != getLayerInfo()) {\n\t\t\tfeatureModel.setLayerInfo(getLayerInfo());\n\t\t}\n\t\tfilterService.registerFeatureModel(featureModel);\n\t}" ]
Gets the first row for a query @param query query to execute @return result or NULL
[ "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }" ]
[ "public boolean isIdProperty(OgmEntityPersister persister, List<String> namesWithoutAlias) {\n\t\tString join = StringHelper.join( namesWithoutAlias, \".\" );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tString[] identifierColumnNames = persister.getIdentifierColumnNames();\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\tString[] embeddedColumnNames = persister.getPropertyColumnNames( join );\n\t\t\tfor ( String embeddedColumn : embeddedColumnNames ) {\n\t\t\t\tif ( !ArrayHelper.contains( identifierColumnNames, embeddedColumn ) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn ArrayHelper.contains( identifierColumnNames, join );\n\t}", "public static void endRequest() {\n final List<RequestScopedItem> result = CACHE.get();\n if (result != null) {\n CACHE.remove();\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }", "public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}", "private Class[] getInterfaces(Class clazz) {\r\n Class superClazz = clazz;\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n // clazz can be an interface itself and when getInterfaces()\r\n // is called on an interface it returns only the extending\r\n // interfaces, not the interface itself.\r\n if (clazz.isInterface()) {\r\n Class[] tempInterfaces = new Class[interfaces.length + 1];\r\n tempInterfaces[0] = clazz;\r\n\r\n System.arraycopy(interfaces, 0, tempInterfaces, 1, interfaces.length);\r\n interfaces = tempInterfaces;\r\n }\r\n\r\n // add all interfaces implemented by superclasses to the interfaces array\r\n while ((superClazz = superClazz.getSuperclass()) != null) {\r\n Class[] superInterfaces = superClazz.getInterfaces();\r\n Class[] combInterfaces = new Class[interfaces.length + superInterfaces.length];\r\n System.arraycopy(interfaces, 0, combInterfaces, 0, interfaces.length);\r\n System.arraycopy(superInterfaces, 0, combInterfaces, interfaces.length, superInterfaces.length);\r\n interfaces = combInterfaces;\r\n }\r\n\r\n /**\r\n * Must remove duplicate interfaces before calling Proxy.getProxyClass().\r\n * Duplicates can occur if a subclass re-declares that it implements\r\n * the same interface as one of its ancestor classes.\r\n **/\r\n HashMap unique = new HashMap();\r\n for (int i = 0; i < interfaces.length; i++) {\r\n unique.put(interfaces[i].getName(), interfaces[i]);\r\n }\r\n /* Add the OJBProxy interface as well */\r\n unique.put(OJBProxy.class.getName(), OJBProxy.class);\r\n\r\n interfaces = (Class[])unique.values().toArray(new Class[unique.size()]);\r\n\r\n return interfaces;\r\n }", "public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isPrimitive() && clazz != void.class? primitiveTypeToWrapperMap.get(clazz) : clazz);\n\t}", "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 }", "protected void setProperty(String propertyName, JavascriptEnum propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getEnumValue());\n }", "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 void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }" ]
Use this API to fetch the statistics of all gslbdomain_stats resources that are configured on netscaler.
[ "public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}" ]
[ "private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\n }", "private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }", "private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }", "public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }", "public GVRAnimator animate(int animIndex, float timeInSec)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n anim.animate(timeInSec);\n return anim;\n }", "public void setPickRay(float ox, float oy, float oz, float dx, float dy, float dz)\n {\n synchronized (this)\n {\n mRayOrigin.x = ox;\n mRayOrigin.y = oy;\n mRayOrigin.z = oz;\n mRayDirection.x = dx;\n mRayDirection.y = dy;\n mRayDirection.z = dz;\n }\n }", "public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }", "private static int nextIndex( String description, int defaultIndex ) {\n\n Pattern startsWithNumber = Pattern.compile( \"(\\\\d+).*\" );\n Matcher matcher = startsWithNumber.matcher( description );\n if( matcher.matches() ) {\n return Integer.parseInt( matcher.group( 1 ) ) - 1;\n }\n\n return defaultIndex;\n }", "public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }" ]
Add a collaborator to an app. @param appName App name. See {@link #listApps} for a list of apps that can be used. @param collaborator Username of the collaborator to add. This is usually in the form of "[email protected]".
[ "public void addCollaborator(String appName, String collaborator) {\n connection.execute(new SharingAdd(appName, collaborator), apiKey);\n }" ]
[ "private void doFileRoll(final File from, final File to) {\n final FileHelper fileHelper = FileHelper.getInstance();\n if (!fileHelper.deleteExisting(to)) {\n this.getAppender().getErrorHandler()\n .error(\"Unable to delete existing \" + to + \" for rename\");\n }\n final String original = from.toString();\n if (fileHelper.rename(from, to)) {\n LogLog.debug(\"Renamed \" + original + \" to \" + to);\n } else {\n this.getAppender().getErrorHandler()\n .error(\"Unable to rename \" + original + \" to \" + to);\n }\n }", "public Map<String, String> getSitePath() {\n\n if (m_sitePaths == null) {\n m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object rootPath) {\n\n if (rootPath instanceof String) {\n return getRequestContext().removeSiteRoot((String)rootPath);\n }\n return null;\n }\n });\n }\n return m_sitePaths;\n }", "public static final Double parseCurrency(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() / 100));\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\n }", "private Video generateRandomVideo() {\n Video video = new Video();\n configureFavoriteStatus(video);\n configureLikeStatus(video);\n configureLiveStatus(video);\n configureTitleAndThumbnail(video);\n return video;\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 }", "public Object doGetObjectByIdentity(Identity id) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getObjectByIdentity \" + id);\n\n // check if object is present in ObjectCache:\n Object obj = objectCache.lookup(id);\n // only perform a db lookup if necessary (object not cached yet)\n if (obj == null)\n {\n obj = getDBObject(id);\n }\n else\n {\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n // if specified in the ClassDescriptor the instance must be refreshed\n if (cld.isAlwaysRefresh())\n {\n refreshInstance(obj, id, cld);\n }\n // now refresh all references\n checkRefreshRelationships(obj, id, cld);\n }\n\n // Invoke events on PersistenceBrokerAware instances and listeners\n AFTER_LOOKUP_EVENT.setTarget(obj);\n fireBrokerEvent(AFTER_LOOKUP_EVENT);\n AFTER_LOOKUP_EVENT.setTarget(null);\n\n //logger.info(\"RETRIEVING object \" + obj);\n return obj;\n }", "public List<String> getModuleVersions(final String name, final FiltersHolder filters) {\n final List<String> versions = repositoryHandler.getModuleVersions(name, filters);\n\n if (versions.isEmpty()) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Module \" + name + \" does not exist.\").build());\n }\n\n return versions;\n }", "public static base_response update(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile updateresource = new dbdbprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.interpretquery = resource.interpretquery;\n\t\tupdateresource.stickiness = resource.stickiness;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.conmultiplex = resource.conmultiplex;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Add an element assigned with its score @param member the member to add @param score the score to assign @return <code>true</code> if the set has been changed
[ "public boolean add(final String member, final double score) {\n return doWithJedis(new JedisCallable<Boolean>() {\n @Override\n public Boolean call(Jedis jedis) {\n return jedis.zadd(getKey(), score, member) > 0;\n }\n });\n }" ]
[ "public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID,\r\n String folderID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_FOLDER).add(\"id\", folderID), null);\r\n }", "public void reverse() {\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).reverse();\n }\n }", "protected void runScript(File script) {\n if (!script.exists()) {\n JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + \" does not exist.\",\n \"Unable to run script.\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), \"Run CLI script \" + script.getName() + \"?\",\n \"Confirm run script\", JOptionPane.YES_NO_OPTION);\n if (choice != JOptionPane.YES_OPTION) return;\n\n menu.addScript(script);\n\n cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output\n output.post(\"\\n\");\n\n SwingWorker scriptRunner = new ScriptRunner(script);\n scriptRunner.execute();\n }", "public 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 void moveRectangleTo(Rectangle rect, float x, float y) {\n\t\tfloat width = rect.getWidth();\n\t\tfloat height = rect.getHeight();\n\t\trect.setLeft(x);\n\t\trect.setBottom(y);\n\t\trect.setRight(rect.getLeft() + width);\n\t\trect.setTop(rect.getBottom() + height);\n\t}", "private long lastModified(Set<File> files) {\n long result = 0;\n for (File file : files) {\n if (file.lastModified() > result)\n result = file.lastModified();\n }\n return result;\n }", "public void restore(String state) {\n JsonObject json = JsonObject.readFrom(state);\n String accessToken = json.get(\"accessToken\").asString();\n String refreshToken = json.get(\"refreshToken\").asString();\n long lastRefresh = json.get(\"lastRefresh\").asLong();\n long expires = json.get(\"expires\").asLong();\n String userAgent = json.get(\"userAgent\").asString();\n String tokenURL = json.get(\"tokenURL\").asString();\n String baseURL = json.get(\"baseURL\").asString();\n String baseUploadURL = json.get(\"baseUploadURL\").asString();\n boolean autoRefresh = json.get(\"autoRefresh\").asBoolean();\n int maxRequestAttempts = json.get(\"maxRequestAttempts\").asInt();\n\n this.accessToken = accessToken;\n this.refreshToken = refreshToken;\n this.lastRefresh = lastRefresh;\n this.expires = expires;\n this.userAgent = userAgent;\n this.tokenURL = tokenURL;\n this.baseURL = baseURL;\n this.baseUploadURL = baseUploadURL;\n this.autoRefresh = autoRefresh;\n this.maxRequestAttempts = maxRequestAttempts;\n }", "public 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 }", "private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath)\n throws IOException, TemplateException\n {\n if(templatePath == null)\n throw new WindupException(\"templatePath is null\");\n\n freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build());\n freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\\\', '/'));\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n template.process(vars, fw);\n }\n }" ]
Close all HTTP clients created by this factory @throws IOException if an I/O error occurs
[ "public void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }" ]
[ "public Bundler put(String key, Parcelable[] value) {\n delegate.putParcelableArray(key, value);\n return this;\n }", "public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}", "public static base_response unset(nitro_service client, responderpolicy resource, String[] args) throws Exception{\n\t\tresponderpolicy unsetresource = new responderpolicy();\n\t\tunsetresource.name = resource.name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static <T> DecoratorImpl<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new DecoratorImpl<T>(attributes, clazz, beanManager);\n }", "public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }", "private void checkOrderby(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String orderbySpec = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ORDERBY);\r\n\r\n if ((orderbySpec == null) || (orderbySpec.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.');\r\n ClassDescriptorDef elementClass = ((ModelDef)ownerClass.getOwner()).getClass(elementClassName);\r\n FieldDescriptorDef fieldDef;\r\n String token;\r\n String fieldName;\r\n String ordering;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(orderbySpec); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos == -1)\r\n {\r\n fieldName = token;\r\n ordering = null;\r\n }\r\n else\r\n {\r\n fieldName = token.substring(0, pos);\r\n ordering = token.substring(pos + 1);\r\n }\r\n fieldDef = elementClass.getField(fieldName);\r\n if (fieldDef == null)\r\n {\r\n throw new ConstraintException(\"The field \"+fieldName+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" hasn't been found in the element class \"+elementClass.getName());\r\n }\r\n if ((ordering != null) && (ordering.length() > 0) &&\r\n !\"ASC\".equals(ordering) && !\"DESC\".equals(ordering))\r\n {\r\n throw new ConstraintException(\"The ordering \"+ordering+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" is invalid\");\r\n }\r\n }\r\n }", "private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }", "@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }", "public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }" ]
get the result speech recognize and find match in strings file. @param speechResult
[ "public void findMatch(ArrayList<String> speechResult) {\n\n loadCadidateString();\n\n for (String matchCandidate : speechResult) {\n\n Locale localeDefault = mGvrContext.getActivity().getResources().getConfiguration().locale;\n if (volumeUp.equals(matchCandidate)) {\n startVolumeUp();\n break;\n } else if (volumeDown.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startVolumeDown();\n break;\n } else if (zoomIn.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startZoomIn();\n break;\n } else if (zoomOut.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startZoomOut();\n break;\n } else if (invertedColors.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startInvertedColors();\n break;\n } else if (talkBack.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n enableTalkBack();\n } else if (disableTalkBack.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n disableTalkBack();\n }\n }\n }" ]
[ "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 void addEvent(Event event) {\n if(event == null)\n throw new IllegalStateException(\"event must be non-null\");\n\n if(logger.isTraceEnabled())\n logger.trace(\"Adding event \" + event);\n\n eventQueue.add(event);\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 }", "public static appfwprofile_crosssitescripting_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_crosssitescripting_binding obj = new appfwprofile_crosssitescripting_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_crosssitescripting_binding response[] = (appfwprofile_crosssitescripting_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception {\n final List<PreparedTask> tasks = new ArrayList<PreparedTask>();\n final List<ContentItem> conflicts = new ArrayList<ContentItem>();\n // Identity\n prepareTasks(context.getIdentityEntry(), context, tasks, conflicts);\n // Layers\n for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) {\n prepareTasks(layer, context, tasks, conflicts);\n }\n // AddOns\n for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) {\n prepareTasks(addOn, context, tasks, conflicts);\n }\n // If there were problems report them\n if (!conflicts.isEmpty()) {\n throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts);\n }\n // Execute the tasks\n for (final PreparedTask task : tasks) {\n // Unless it's excluded by the user\n final ContentItem item = task.getContentItem();\n if (item != null && context.isExcluded(item)) {\n continue;\n }\n // Run the task\n task.execute();\n }\n return context.finalize(callback);\n }", "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 }", "protected NodeData createPageStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"relative\")));\n\t\tret.push(createDeclaration(\"border-width\", tf.createLength(1f, Unit.px)));\n\t\tret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n\t\tret.push(createDeclaration(\"border-color\", tf.createColor(0, 0, 255)));\n\t\tret.push(createDeclaration(\"margin\", tf.createLength(0.5f, Unit.em)));\n\t\t\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n ret.push(createDeclaration(\"width\", tf.createLength(w, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(h, unit)));\n }\n else\n log.warn(\"No media box found\");\n \n return ret;\n }", "public static base_responses delete(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec deleteresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new dnstxtrec();\n\t\t\t\tdeleteresources[i].domain = resources[i].domain;\n\t\t\t\tdeleteresources[i].String = resources[i].String;\n\t\t\t\tdeleteresources[i].recordid = resources[i].recordid;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public void setMaintenanceMode(String appName, boolean enable) {\n connection.execute(new AppUpdate(appName, enable), apiKey);\n }" ]
Adds new holes to the polygon. @param holes holes, must be contained in the exterior ring and must not overlap or intersect another hole @return this for chaining
[ "public GeoPolygon addHoles(List<List<GeoPoint>> holes) {\n\t\tContracts.assertNotNull( holes, \"holes\" );\n\t\tthis.rings.addAll( holes );\n\t\treturn this;\n\t}" ]
[ "public static String multiply(CharSequence self, Number factor) {\n String s = self.toString();\n int size = factor.intValue();\n if (size == 0)\n return \"\";\n else if (size < 0) {\n throw new IllegalArgumentException(\"multiply() should be called with a number of 0 or greater not: \" + size);\n }\n StringBuilder answer = new StringBuilder(s);\n for (int i = 1; i < size; i++) {\n answer.append(s);\n }\n return answer.toString();\n }", "public SqlStatement getPreparedDeleteStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement sql = sfc.getDeleteSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getDeleteProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlDeleteByPkStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setDeleteSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }", "@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }", "private void initDurationPanel() {\n\n m_durationPrefixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_PREFIX_0));\n m_durationAfterPostfixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_POSTFIX_0));\n m_seriesEndDate.setDateOnly(true);\n m_seriesEndDate.setAllowInvalidValue(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n m_seriesEndDate.getTextField().addFocusHandler(new FocusHandler() {\n\n public void onFocus(FocusEvent event) {\n\n if (handleChange()) {\n onSeriesEndDateFocus(event);\n }\n\n }\n });\n }", "public static BoxLegalHoldPolicy.Info createOngoing(BoxAPIConnection api, String name, String description) {\n URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_name\", name)\n .add(\"is_ongoing\", true);\n if (description != null) {\n requestJSON.add(\"description\", description);\n }\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldPolicy createdPolicy = new BoxLegalHoldPolicy(api, responseJSON.get(\"id\").asString());\n return createdPolicy.new Info(responseJSON);\n }", "public static authenticationtacacspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_authenticationvserver_binding obj = new authenticationtacacspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_authenticationvserver_binding response[] = (authenticationtacacspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@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 void growInternal(int amount ) {\n int tmp[] = new int[ data.length + amount ];\n\n System.arraycopy(data,0,tmp,0,data.length);\n this.data = tmp;\n }", "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }" ]
Recursively searches for formatting annotations. @param visitedTypes used to prevent an endless loop @param parameterName
[ "private StepFormatter.Formatting<?, ?> getFormatting( Annotation[] annotations, Set<Class<?>> visitedTypes,\n Annotation originalAnnotation, String parameterName ) {\n List<StepFormatter.Formatting<?, ?>> foundFormatting = Lists.newArrayList();\n Table tableAnnotation = null;\n for( Annotation annotation : annotations ) {\n try {\n if( annotation instanceof Format ) {\n Format arg = (Format) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting( ReflectionUtil.newInstance( arg.value() ), arg.args() ) );\n } else if( annotation instanceof Table ) {\n tableAnnotation = (Table) annotation;\n } else if( annotation instanceof AnnotationFormat ) {\n AnnotationFormat arg = (AnnotationFormat) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting(\n new StepFormatter.AnnotationBasedFormatter( arg.value().newInstance(), originalAnnotation ) ) );\n } else {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n if( !visitedTypes.contains( annotationType ) ) {\n visitedTypes.add( annotationType );\n StepFormatter.Formatting<?, ?> formatting = getFormatting( annotationType.getAnnotations(), visitedTypes,\n annotation, parameterName );\n if( formatting != null ) {\n foundFormatting.add( formatting );\n }\n }\n }\n } catch( Exception e ) {\n throw Throwables.propagate( e );\n }\n }\n\n if( foundFormatting.size() > 1 ) {\n Formatting<?, ?> innerFormatting = Iterables.getLast( foundFormatting );\n foundFormatting.remove( innerFormatting );\n\n ChainedFormatting<?> chainedFormatting = new StepFormatter.ChainedFormatting<Object>( (ObjectFormatter<Object>) innerFormatting );\n for( StepFormatter.Formatting<?, ?> formatting : Lists.reverse( foundFormatting ) ) {\n chainedFormatting.addFormatting( (StepFormatter.Formatting<?, String>) formatting );\n }\n\n foundFormatting.clear();\n foundFormatting.add( chainedFormatting );\n }\n\n if( tableAnnotation != null ) {\n ObjectFormatter<?> objectFormatter = foundFormatting.isEmpty()\n ? DefaultFormatter.INSTANCE\n : foundFormatting.get( 0 );\n return getTableFormatting( annotations, parameterName, tableAnnotation, objectFormatter );\n }\n\n if( foundFormatting.isEmpty() ) {\n return null;\n }\n\n return foundFormatting.get( 0 );\n }" ]
[ "protected Channel awaitChannel() throws IOException {\n Channel channel = this.channel;\n if(channel != null) {\n return channel;\n }\n synchronized (lock) {\n for(;;) {\n if(state == State.CLOSED) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n channel = this.channel;\n if(channel != null) {\n return channel;\n }\n if(state == State.CLOSING) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n try {\n lock.wait();\n } catch (InterruptedException e) {\n throw new IOException(e);\n }\n }\n }\n }", "public static sslciphersuite[] get(nitro_service service, options option) throws Exception{\n\t\tsslciphersuite obj = new sslciphersuite();\n\t\tsslciphersuite[] response = (sslciphersuite[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public String getArtifactLastVersion(final String gavc) {\n final List<String> versions = getArtifactVersions(gavc);\n\n final VersionsHandler versionHandler = new VersionsHandler(repositoryHandler);\n final String viaCompare = versionHandler.getLastVersion(versions);\n\n if (viaCompare != null) {\n return viaCompare;\n }\n\n //\n // These versions cannot be compared\n // Let's use the Collection.max() method by default, so goingo for a fallback\n // mechanism.\n //\n LOG.info(\"The versions cannot be compared\");\n return Collections.max(versions);\n\n }", "@UiThread\n public void collapseParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n collapseParent(i);\n }\n }", "private Integer getIntegerPropertyOverrideValue(String name, String key) {\n if (properties != null) {\n String propertyName = getPropertyName(name, key);\n\n String propertyOverrideValue = properties.getProperty(propertyName);\n\n if (propertyOverrideValue != null) {\n try {\n return Integer.parseInt(propertyOverrideValue);\n }\n catch (NumberFormatException e) {\n logger.error(\"Could not parse property override key={}, value={}\",\n key, propertyOverrideValue);\n }\n }\n }\n return null;\n }", "@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }", "private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }", "public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }", "public static BoxRetentionPolicy.Info createFinitePolicy(BoxAPIConnection api, String name, int length,\r\n String action, RetentionPolicyParams optionalParams) {\r\n return createRetentionPolicy(api, name, TYPE_FINITE, length, action, optionalParams);\r\n }" ]
Try to set the value from the provided Json string. @param value the value to set. @throws Exception thrown if parsing fails.
[ "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 static boolean isDouble(CharSequence self) {\n try {\n Double.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "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 }", "@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\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 <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken, Integer paginationPageSize) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>)readerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class,\n OauthToken.class, RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, paginationPageSize, false);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }", "private static boolean isDisabledHandler(final LogContext logContext, final String handlerName) {\n final Map<String, String> disableHandlers = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY);\n return disableHandlers != null && disableHandlers.containsKey(handlerName);\n }", "private List<Row> buildRowHierarchy(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)\n {\n //\n // Create a list of leaf nodes by merging the task and milestone lists\n //\n List<Row> leaves = new ArrayList<Row>();\n leaves.addAll(tasks);\n leaves.addAll(milestones);\n\n //\n // Sort the bars and the leaves\n //\n Collections.sort(bars, BAR_COMPARATOR);\n Collections.sort(leaves, LEAF_COMPARATOR);\n\n //\n // Map bar IDs to bars\n //\n Map<Integer, Row> barIdToBarMap = new HashMap<Integer, Row>();\n for (Row bar : bars)\n {\n barIdToBarMap.put(bar.getInteger(\"BARID\"), bar);\n }\n\n //\n // Merge expanded task attributes with parent bars\n // and create an expanded task ID to bar map.\n //\n Map<Integer, Row> expandedTaskIdToBarMap = new HashMap<Integer, Row>();\n for (Row expandedTask : expandedTasks)\n {\n Row bar = barIdToBarMap.get(expandedTask.getInteger(\"BAR\"));\n bar.merge(expandedTask, \"_\");\n Integer expandedTaskID = bar.getInteger(\"_EXPANDED_TASKID\");\n expandedTaskIdToBarMap.put(expandedTaskID, bar);\n }\n\n //\n // Build the hierarchy\n //\n List<Row> parentBars = new ArrayList<Row>();\n for (Row bar : bars)\n {\n Integer expandedTaskID = bar.getInteger(\"EXPANDED_TASK\");\n Row parentBar = expandedTaskIdToBarMap.get(expandedTaskID);\n if (parentBar == null)\n {\n parentBars.add(bar);\n }\n else\n {\n parentBar.addChild(bar);\n }\n }\n\n //\n // Attach the leaves\n //\n for (Row leaf : leaves)\n {\n Integer barID = leaf.getInteger(\"BAR\");\n Row bar = barIdToBarMap.get(barID);\n bar.addChild(leaf);\n }\n\n //\n // Prune any \"displaced items\" from the top level.\n // We're using a heuristic here as this is the only thing I\n // can see which differs between bars that we want to include\n // and bars that we want to exclude.\n //\n Iterator<Row> iter = parentBars.iterator();\n while (iter.hasNext())\n {\n Row bar = iter.next();\n String barName = bar.getString(\"NAMH\");\n if (barName == null || barName.isEmpty() || barName.equals(\"Displaced Items\"))\n {\n iter.remove();\n }\n }\n\n //\n // If we only have a single top level node (effectively a summary task) prune that too.\n //\n if (parentBars.size() == 1)\n {\n parentBars = parentBars.get(0).getChildRows();\n }\n\n return parentBars;\n }", "public static CmsSolrSpellchecker getInstance(CoreContainer container) {\n\n if (null == instance) {\n synchronized (CmsSolrSpellchecker.class) {\n if (null == instance) {\n @SuppressWarnings(\"resource\")\n SolrCore spellcheckCore = container.getCore(CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE);\n if (spellcheckCore == null) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SPELLCHECK_CORE_NOT_AVAILABLE_1,\n CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE));\n return null;\n }\n instance = new CmsSolrSpellchecker(container, spellcheckCore);\n }\n }\n }\n\n return instance;\n }", "public static int scale(Double factor, int pixel) {\n return rgb(\n (int) Math.round(factor * red(pixel)),\n (int) Math.round(factor * green(pixel)),\n (int) Math.round(factor * blue(pixel))\n );\n }" ]
Creates a slice for directly a raw memory address. This is inherently unsafe as it may be used to access arbitrary memory. @param address the raw memory address base @param size the size of the slice @return the unsafe slice
[ "public Slice newSlice(long address, int size)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, 0, null);\n }" ]
[ "public Bundler put(String key, Serializable value) {\n delegate.putSerializable(key, value);\n return this;\n }", "public ImmutableMap<String, String> getConfigurationTweak(String dbModuleName)\n {\n final DbInfo db = cluster.getNextDb();\n return ImmutableMap.of(\"ness.db.\" + dbModuleName + \".uri\", getJdbcUri(db),\n \"ness.db.\" + dbModuleName + \".ds.user\", db.user);\n }", "private void writePredecessors(Project.Tasks.Task xml, Task mpx)\n {\n List<Project.Tasks.Task.PredecessorLink> list = xml.getPredecessorLink();\n\n List<Relation> predecessors = mpx.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n list.add(writePredecessor(taskUniqueID, rel.getType(), rel.getLag()));\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }", "public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}", "public Sites getSitesInformation() throws IOException {\n\t\tMwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES);\n\t\tif (sitesTableDump == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Create a suitable processor for such dumps and process the file:\n\t\tMwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor();\n\t\tsitesDumpFileProcessor.processDumpFileContents(\n\t\t\t\tsitesTableDump.getDumpFileStream(), sitesTableDump);\n\n\t\treturn sitesDumpFileProcessor.getSites();\n\t}", "private void initDeactivationPanel() {\n\n m_deactivationPanel.setVisible(false);\n m_deactivationText.setText(Messages.get().key(Messages.GUI_SERIALDATE_DEACTIVE_TEXT_0));\n\n }", "public boolean getNumericBoolean(int field)\n {\n boolean result = false;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Integer.parseInt(m_fields[field]) == 1;\n }\n\n return (result);\n }", "public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "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 }" ]
Stops the currently running animation, if any. @see GVRAvatar#start(String) @see GVRAnimationEngine#stop(GVRAnimation)
[ "public void stop()\n {\n synchronized (mAnimQueue)\n {\n if (mIsRunning && (mAnimQueue.size() > 0))\n {\n mIsRunning = false;\n GVRAnimator animator = mAnimQueue.get(0);\n mAnimQueue.clear();\n animator.stop();\n }\n }\n }" ]
[ "public static final Path resolveSecurely(Path rootPath, String path) {\n Path resolvedPath;\n if(path == null || path.isEmpty()) {\n resolvedPath = rootPath.normalize();\n } else {\n String relativePath = removeSuperflousSlashes(path);\n resolvedPath = rootPath.resolve(relativePath).normalize();\n }\n if(!resolvedPath.startsWith(rootPath)) {\n throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path);\n }\n return resolvedPath;\n }", "private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n //baseline.getBCWP()\n //baseline.getBCWS()\n Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost());\n Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish());\n //baseline.getNumber()\n Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpx.setBaselineCost(cost);\n mpx.setBaselineFinish(finish);\n mpx.setBaselineStart(start);\n mpx.setBaselineWork(work);\n }\n else\n {\n mpx.setBaselineCost(number, cost);\n mpx.setBaselineWork(number, work);\n mpx.setBaselineStart(number, start);\n mpx.setBaselineFinish(number, finish);\n }\n }\n }", "private void readTaskBaselines(Project.Tasks.Task xmlTask, Task mpxjTask, TimeUnit durationFormat)\n {\n for (Project.Tasks.Task.Baseline baseline : xmlTask.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration duration = DatatypeConverter.parseDuration(m_projectFile, durationFormat, baseline.getDuration());\n Date finish = baseline.getFinish();\n Date start = baseline.getStart();\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjTask.setBaselineCost(cost);\n mpxjTask.setBaselineDuration(duration);\n mpxjTask.setBaselineFinish(finish);\n mpxjTask.setBaselineStart(start);\n mpxjTask.setBaselineWork(work);\n }\n else\n {\n mpxjTask.setBaselineCost(number, cost);\n mpxjTask.setBaselineDuration(number, duration);\n mpxjTask.setBaselineFinish(number, finish);\n mpxjTask.setBaselineStart(number, start);\n mpxjTask.setBaselineWork(number, work);\n }\n }\n }", "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getPluginInformation() {\n return pluginInformation();\n }", "public void end(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n LOG.info(\"Called end with key: \" + key + \" without ever calling begin\");\n return;\n }\n data.end();\n }", "public String toText() {\n StringBuilder sb = new StringBuilder();\n if (!description.isEmpty()) {\n sb.append(description.toText());\n sb.append(EOL);\n }\n if (!blockTags.isEmpty()) {\n sb.append(EOL);\n }\n for (JavadocBlockTag tag : blockTags) {\n sb.append(tag.toText()).append(EOL);\n }\n return sb.toString();\n }", "private Component createConvertToPropertyBundleButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.SETTINGS,\n m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n try {\n m_model.saveAsPropertyBundle();\n Notification.show(\"Conversion successful.\");\n } catch (CmsException | IOException e) {\n CmsVaadinUtils.showAlert(\"Conversion failed\", e.getLocalizedMessage(), null);\n }\n }\n });\n addDescriptorButton.setDisableOnClick(true);\n return addDescriptorButton;\n }", "public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }", "public static HttpConnection createPost(URI uri, String body, String contentType) {\n HttpConnection connection = Http.POST(uri, \"application/json\");\n if(body != null) {\n setEntity(connection, body, contentType);\n }\n return connection;\n }" ]
Main file parser. Reads GIF content blocks. Stops after reading maxFrames
[ "private void readContents(int maxFrames) {\n // Read GIF file content blocks.\n boolean done = false;\n while (!(done || err() || header.frameCount > maxFrames)) {\n int code = read();\n switch (code) {\n // Image separator.\n case 0x2C:\n // The graphics control extension is optional, but will always come first if it exists.\n // If one did\n // exist, there will be a non-null current frame which we should use. However if one\n // did not exist,\n // the current frame will be null and we must create it here. See issue #134.\n if (header.currentFrame == null) {\n header.currentFrame = new GifFrame();\n }\n readBitmap();\n break;\n // Extension.\n case 0x21:\n code = read();\n switch (code) {\n // Graphics control extension.\n case 0xf9:\n // Start a new frame.\n header.currentFrame = new GifFrame();\n readGraphicControlExt();\n break;\n // Application extension.\n case 0xff:\n readBlock();\n String app = \"\";\n for (int i = 0; i < 11; i++) {\n app += (char) block[i];\n }\n if (app.equals(\"NETSCAPE2.0\")) {\n readNetscapeExt();\n } else {\n // Don't care.\n skip();\n }\n break;\n // Comment extension.\n case 0xfe:\n skip();\n break;\n // Plain text extension.\n case 0x01:\n skip();\n break;\n // Uninteresting extension.\n default:\n skip();\n }\n break;\n // Terminator.\n case 0x3b:\n done = true;\n break;\n // Bad byte, but keep going and see what happens break;\n case 0x00:\n default:\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n }\n }" ]
[ "public AddonChange removeAddon(String appName, String addonName) {\n return connection.execute(new AddonRemove(appName, addonName), apiKey);\n }", "public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {\n\t\tThread currentThread = Thread.currentThread();\n\t\tClassLoader threadContextClassLoader = currentThread.getContextClassLoader();\n\t\tif (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {\n\t\t\tcurrentThread.setContextClassLoader(classLoaderToUse);\n\t\t\treturn threadContextClassLoader;\n\t\t}\n\t\telse {\n\t\t\treturn null;\n\t\t}\n\t}", "public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "public void deleteRebalancingState(RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n RebalancerState rebalancerState = getRebalancerState();\n\n if(!rebalancerState.remove(stealInfo))\n throw new IllegalArgumentException(\"Couldn't find \" + stealInfo + \" in \"\n + rebalancerState + \" while deleting\");\n\n if(rebalancerState.isEmpty()) {\n logger.debug(\"Cleaning all rebalancing state\");\n cleanAllRebalancingState();\n } else {\n put(REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n }\n } finally {\n writeLock.unlock();\n }\n }", "private String escapeQuotes(String value)\n {\n StringBuilder sb = new StringBuilder();\n int length = value.length();\n char c;\n\n sb.append('\"');\n for (int index = 0; index < length; index++)\n {\n c = value.charAt(index);\n sb.append(c);\n\n if (c == '\"')\n {\n sb.append('\"');\n }\n }\n sb.append('\"');\n\n return (sb.toString());\n }", "public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }", "public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, Class<T> clazz) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tClassConnectionSource key = new ClassConnectionSource(connectionSource, clazz);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) dao;\n\t\treturn castDao;\n\t}", "public static void symmetric(DMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n for( int j = i; j < length; j++ ) {\n double val = rand.nextDouble()*range + min;\n A.set(i,j,val);\n A.set(j,i,val);\n }\n }\n }", "public static final Bytes of(String s, Charset c) {\n Objects.requireNonNull(s);\n Objects.requireNonNull(c);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(c);\n return new Bytes(data);\n }" ]
k Returns a list of artifact regarding the filters @return List<DbArtifact>
[ "public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) {\n\t\tfinal DbModule module = getModule(dbArtifact);\n\t\tif(module == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tfinal String jenkinsJobUrl = module.getBuildInfo().get(\"jenkins-job-url\");\n\t\t\n\t\tif(jenkinsJobUrl == null){\n\t\t\treturn \"\";\t\t\t\n\t\t}\n\n\t\treturn jenkinsJobUrl;\n\t}" ]
[ "public static double blackScholesDigitalOptionValue(\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)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate analytic value\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 valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn valueAnalytic;\n\t\t}\n\t}", "private FieldDescriptorDef cloneField(FieldDescriptorDef fieldDef, String prefix)\r\n {\r\n FieldDescriptorDef copyFieldDef = new FieldDescriptorDef(fieldDef, prefix);\r\n\r\n copyFieldDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyFieldDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyFieldDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included field \"+\r\n copyFieldDef.getName()+\" from class \"+fieldDef.getOwner().getName()); \r\n }\r\n copyFieldDef.applyModifications(mod);\r\n }\r\n return copyFieldDef;\r\n }", "protected boolean computeOffset(final int dataIndex, CacheDataSet cache) {\n float layoutOffset = getLayoutOffset();\n int pos = cache.getPos(dataIndex);\n float startDataOffset = Float.NaN;\n float endDataOffset = Float.NaN;\n if (pos > 0) {\n int id = cache.getId(pos - 1);\n if (id != -1) {\n startDataOffset = cache.getEndDataOffset(id);\n if (!Float.isNaN(startDataOffset)) {\n endDataOffset = cache.setDataAfter(dataIndex, startDataOffset);\n }\n }\n } else if (pos == 0) {\n int id = cache.getId(pos + 1);\n if (id != -1) {\n endDataOffset = cache.getStartDataOffset(id);\n if (!Float.isNaN(endDataOffset)) {\n startDataOffset = cache.setDataBefore(dataIndex, endDataOffset);\n }\n } else {\n startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n endDataOffset = cache.setDataAfter(dataIndex, startDataOffset);\n }\n }\n\n Log.d(LAYOUT, TAG, \"computeOffset [%d, %d]: startDataOffset = %f endDataOffset = %f\",\n dataIndex, pos, startDataOffset, endDataOffset);\n\n boolean inBounds = !Float.isNaN(cache.getDataOffset(dataIndex)) &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n\n return inBounds;\n }", "private String parseRssFeed(String feed) {\n String[] result = feed.split(\"<br />\");\n String[] result2 = result[2].split(\"<BR />\");\n\n return result2[0];\n }", "public String toNormalizedString(boolean keepMixed, IPv6StringOptions params) {\n\t\tif(keepMixed && fromString != null && getAddressfromString().isMixedIPv6() && !params.makeMixed()) {\n\t\t\tparams = new IPv6StringOptions(\n\t\t\t\t\tparams.base,\n\t\t\t\t\tparams.expandSegments,\n\t\t\t\t\tparams.wildcardOption,\n\t\t\t\t\tparams.wildcards,\n\t\t\t\t\tparams.segmentStrPrefix,\n\t\t\t\t\ttrue,\n\t\t\t\t\tparams.ipv4Opts,\n\t\t\t\t\tparams.compressOptions,\n\t\t\t\t\tparams.separator,\n\t\t\t\t\tparams.zoneSeparator,\n\t\t\t\t\tparams.addrLabel,\n\t\t\t\t\tparams.addrSuffix,\n\t\t\t\t\tparams.reverse,\n\t\t\t\t\tparams.splitDigits,\n\t\t\t\t\tparams.uppercase);\n\t\t}\n\t\treturn toNormalizedString(params);\n\t}", "public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\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 }", "private void setTasks(String tasks) {\n\t\tfor (String task : tasks.split(\",\")) {\n\t\t\tif (KNOWN_TASKS.containsKey(task)) {\n\t\t\t\tthis.tasks |= KNOWN_TASKS.get(task);\n\t\t\t\tthis.taskName += (this.taskName.isEmpty() ? \"\" : \"-\") + task;\n\t\t\t} else {\n\t\t\t\tlogger.warn(\"Unsupported RDF serialization task \\\"\" + task\n\t\t\t\t\t\t+ \"\\\". Run without specifying any tasks for help.\");\n\t\t\t}\n\t\t}\n\t}", "public static final Bytes of(ByteBuffer bb) {\n Objects.requireNonNull(bb);\n if (bb.remaining() == 0) {\n return EMPTY;\n }\n byte[] data;\n if (bb.hasArray()) {\n data = Arrays.copyOfRange(bb.array(), bb.position() + bb.arrayOffset(),\n bb.limit() + bb.arrayOffset());\n } else {\n data = new byte[bb.remaining()];\n // duplicate so that it does not change position\n bb.duplicate().get(data);\n }\n return new Bytes(data);\n }" ]
Tests an observer method to see if it is transactional. @param observer The observer method @return true if the observer method is annotated as transactional
[ "public static TransactionPhase getTransactionalPhase(EnhancedAnnotatedMethod<?, ?> observer) {\n EnhancedAnnotatedParameter<?, ?> parameter = observer.getEnhancedParameters(Observes.class).iterator().next();\n return parameter.getAnnotation(Observes.class).during();\n }" ]
[ "public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) {\n Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get();\n classes.remove(descriptor.getBeanClass());\n if (classes.isEmpty()) {\n CONTEXTUAL_SESSION_BEANS.remove();\n }\n }", "@SuppressWarnings(\"WeakerAccess\")\n public static @Nullable CleverTapAPI getDefaultInstance(Context context) {\n // For Google Play Store/Android Studio tracking\n sdkVersion = BuildConfig.SDK_VERSION_STRING;\n if (defaultConfig == null) {\n ManifestInfo manifest = ManifestInfo.getInstance(context);\n String accountId = manifest.getAccountId();\n String accountToken = manifest.getAcountToken();\n String accountRegion = manifest.getAccountRegion();\n if(accountId == null || accountToken == null) {\n Logger.i(\"Account ID or Account token is missing from AndroidManifest.xml, unable to create default instance\");\n return null;\n }\n if (accountRegion == null) {\n Logger.i(\"Account Region not specified in the AndroidManifest - using default region\");\n }\n defaultConfig = CleverTapInstanceConfig.createDefaultInstance(context, accountId, accountToken, accountRegion);\n defaultConfig.setDebugLevel(getDebugLevel());\n }\n return instanceWithConfig(context, defaultConfig);\n }", "public static void main(String[] args) throws IOException, ClassNotFoundException {\r\n CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter();\r\n f.init(new SeqClassifierFlags());\r\n int numDocs = 0;\r\n int numTokens = 0;\r\n int numEntities = 0;\r\n String lastAnsBase = \"\";\r\n for (Iterator<List<CoreLabel>> it = f.getIterator(new FileReader(args[0])); it.hasNext(); ) {\r\n List<CoreLabel> doc = it.next();\r\n numDocs++;\r\n for (CoreLabel fl : doc) {\r\n // System.out.println(\"FL \" + (++i) + \" was \" + fl);\r\n if (fl.word().equals(BOUNDARY)) {\r\n continue;\r\n }\r\n String ans = fl.get(AnswerAnnotation.class);\r\n String ansBase;\r\n String ansPrefix;\r\n String[] bits = ans.split(\"-\");\r\n if (bits.length == 1) {\r\n ansBase = bits[0];\r\n ansPrefix = \"\";\r\n } else {\r\n ansBase = bits[1];\r\n ansPrefix = bits[0];\r\n }\r\n numTokens++;\r\n if (ansBase.equals(\"O\")) {\r\n } else if (ansBase.equals(lastAnsBase)) {\r\n if (ansPrefix.equals(\"B\")) {\r\n numEntities++;\r\n }\r\n } else {\r\n numEntities++;\r\n }\r\n }\r\n }\r\n System.out.println(\"File \" + args[0] + \" has \" + numDocs + \" documents, \" +\r\n numTokens + \" (non-blank line) tokens and \" +\r\n numEntities + \" entities.\");\r\n }", "public DynamicReportBuilder setQuery(String text, String language) {\n this.report.setQuery(new DJQuery(text, language));\n return this;\n }", "public Iterable<RowKey> getKeys() {\n\t\tif ( currentState.isEmpty() ) {\n\t\t\tif ( cleared ) {\n\t\t\t\t// if the association has been cleared and the currentState is empty, we consider that there are no rows.\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// otherwise, the snapshot rows are the current ones\n\t\t\t\treturn snapshot.getRowKeys();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// It may be a bit too large in case of removals, but that's fine for now\n\t\t\tSet<RowKey> keys = CollectionHelper.newLinkedHashSet( cleared ? currentState.size() : snapshot.size() + currentState.size() );\n\n\t\t\tif ( !cleared ) {\n\t\t\t\t// we add the snapshot RowKeys only if the association has not been cleared\n\t\t\t\tfor ( RowKey rowKey : snapshot.getRowKeys() ) {\n\t\t\t\t\tkeys.add( rowKey );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tkeys.add( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tkeys.remove( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn keys;\n\t\t}\n\t}", "public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\n }", "public void parseRawValue(String value)\n {\n int valueIndex = 0;\n int elementIndex = 0;\n m_elements.clear();\n while (valueIndex < value.length() && elementIndex < m_elements.size())\n {\n int elementLength = m_lengths.get(elementIndex).intValue();\n if (elementIndex > 0)\n {\n m_elements.add(m_separators.get(elementIndex - 1));\n }\n int endIndex = valueIndex + elementLength;\n if (endIndex > value.length())\n {\n endIndex = value.length();\n }\n String element = value.substring(valueIndex, endIndex);\n m_elements.add(element);\n valueIndex += elementLength;\n elementIndex++;\n }\n }", "public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }" ]
Gets the persistence broker used by this indirection handler. If no PBKey is available a runtime exception will be thrown. @return a PersistenceBroker
[ "protected TemporaryBrokerWrapper getBroker() throws PBFactoryException\r\n {\r\n PersistenceBrokerInternal broker;\r\n boolean needsClose = false;\r\n\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found, create a intern new one\r\n if ((broker == null) || broker.isClosed())\r\n {\r\n broker = (PersistenceBrokerInternal) PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n /** Specifies whether we obtained a fresh broker which we have to close after we used it */\r\n needsClose = true;\r\n }\r\n return new TemporaryBrokerWrapper(broker, needsClose);\r\n }" ]
[ "public void deleteMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n this.deleteMetadata(templateName, scope);\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException {\n return mapperFor(parameterizedType).serialize(object);\n }", "@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }", "public void check(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureElementClassRef(collDef, checkLevel);\r\n checkInheritedForeignkey(collDef, checkLevel);\r\n ensureCollectionClass(collDef, checkLevel);\r\n checkProxyPrefetchingLimit(collDef, checkLevel);\r\n checkOrderby(collDef, checkLevel);\r\n checkQueryCustomizer(collDef, checkLevel);\r\n }", "public static BoxAPIConnection getTransactionConnection(String accessToken, String scope, String resource) {\n BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken);\n\n URL url;\n try {\n url = new URL(apiConnection.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters;\n try {\n urlParameters = String.format(\"grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s\", GRANT_TYPE,\n URLEncoder.encode(accessToken, \"UTF-8\"), SUBJECT_TOKEN_TYPE, URLEncoder.encode(scope, \"UTF-8\"));\n\n if (resource != null) {\n urlParameters += \"&resource=\" + URLEncoder.encode(resource, \"UTF-8\");\n }\n } catch (UnsupportedEncodingException e) {\n throw new BoxAPIException(\n \"An error occurred while attempting to encode url parameters for a transactional token request\"\n );\n }\n\n BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n final String fileToken = responseJSON.get(\"access_token\").asString();\n BoxTransactionalAPIConnection transactionConnection = new BoxTransactionalAPIConnection(fileToken);\n transactionConnection.setExpires(responseJSON.get(\"expires_in\").asLong() * 1000);\n\n return transactionConnection;\n }", "public void retrieveProxyCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, true);\r\n }", "private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}", "private float MIN(float first, float second, float third) {\r\n\r\n float min = Integer.MAX_VALUE;\r\n if (first < min) {\r\n min = first;\r\n }\r\n if (second < min) {\r\n min = second;\r\n }\r\n if (third < min) {\r\n min = third;\r\n }\r\n return min;\r\n }", "protected boolean check(String id, List<String> includes) {\n\t\tif (null != includes) {\n\t\t\tfor (String check : includes) {\n\t\t\t\tif (check(id, check)) {\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}" ]
Use this API to flush cacheobject.
[ "public static base_response flush(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject flushresource = new cacheobject();\n\t\tflushresource.locator = resource.locator;\n\t\tflushresource.url = resource.url;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.port = resource.port;\n\t\tflushresource.groupname = resource.groupname;\n\t\tflushresource.httpmethod = resource.httpmethod;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}" ]
[ "public static ObjectName createObjectName(String domain, String type) {\n try {\n return new ObjectName(domain + \":type=\" + type);\n } catch(MalformedObjectNameException e) {\n throw new VoldemortException(e);\n }\n }", "public static void saveContentMap(Map<String, String> map, File file) throws IOException {\n\n FileWriter out = new FileWriter(file);\n for (String key : map.keySet()) {\n if (map.get(key) != null) {\n out.write(key.replace(\":\", \"#escapedtwodots#\") + \":\"\n + map.get(key).replace(\":\", \"#escapedtwodots#\") + \"\\r\\n\");\n }\n }\n out.close();\n }", "public void setDates(SortedSet<Date> dates, boolean checked) {\n\n m_checkBoxes.clear();\n for (Date date : dates) {\n CmsCheckBox cb = generateCheckBox(date, checked);\n m_checkBoxes.add(cb);\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }", "public static int cudnnActivationBackward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnActivationBackwardNative(handle, activationDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "public boolean toggleProfile(Boolean enabled) {\n // TODO: make this return values properly\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"active\", enabled.toString())\n };\n try {\n String uri = BASE_PROFILE + uriEncode(this._profileName) + \"/\" + BASE_CLIENTS + \"/\";\n if (_clientId == null) {\n uri += \"-1\";\n } else {\n uri += _clientId;\n }\n JSONObject response = new JSONObject(doPost(uri, params));\n } catch (Exception e) {\n // some sort of error\n System.out.println(e.getMessage());\n return false;\n }\n return true;\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 UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockMode lockMode,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t}", "public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) {\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n possibleState.put(action.getName(), action.getExpr());\r\n }\n\r\n return possibleStateList;\r\n }", "private String typeParameters(Options opt, ParameterizedType t) {\n\tif (t == null)\n\t return \"\";\n\tStringBuffer tp = new StringBuffer(1000).append(\"&lt;\");\n\tType args[] = t.typeArguments();\n\tfor (int i = 0; i < args.length; i++) {\n\t tp.append(type(opt, args[i], true));\n\t if (i != args.length - 1)\n\t\ttp.append(\", \");\n\t}\n\treturn tp.append(\"&gt;\").toString();\n }" ]
Converts a Map to an array of objects, adding only those entries whose key is in the nameMapping array. @param values the Map of values to convert @param nameMapping the keys to extract from the Map (elements in the target array will be added in this order) @return the array of Objects @throws NullPointerException if values or nameMapping is null
[ "public static Object[] filterMapToObjectArray(final Map<String, ?> values, final String[] nameMapping) {\n\t\t\n\t\tif( values == null ) {\n\t\t\tthrow new NullPointerException(\"values should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal Object[] targetArray = new Object[nameMapping.length];\n\t\tint i = 0;\n\t\tfor( final String name : nameMapping ) {\n\t\t\ttargetArray[i++] = values.get(name);\n\t\t}\n\t\treturn targetArray;\n\t}" ]
[ "public void process()\n {\n if (m_data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length (repeated twice)\n int length = MPPUtility.getInt(m_data, offset);\n offset += 8;\n // Then the number of custom columns\n int numberOfAliases = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n // Then the aliases themselves\n while (index < numberOfAliases && offset < length)\n {\n // Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the\n // offset to the string (4 bytes)\n\n // Get the Field ID\n int fieldID = MPPUtility.getInt(m_data, offset);\n offset += 4;\n // Get the alias offset (offset + 4 for some reason).\n int aliasOffset = MPPUtility.getInt(m_data, offset) + 4;\n offset += 4;\n // Read the alias itself\n if (aliasOffset < m_data.length)\n {\n String alias = MPPUtility.getUnicodeString(m_data, aliasOffset);\n m_fields.getCustomField(FieldTypeHelper.getInstance(fieldID)).setAlias(alias);\n }\n index++;\n }\n }\n }", "@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 Type getArrayComponentType(Type type) {\n if (type instanceof GenericArrayType) {\n return GenericArrayType.class.cast(type).getGenericComponentType();\n }\n if (type instanceof Class<?>) {\n Class<?> clazz = (Class<?>) type;\n if (clazz.isArray()) {\n return clazz.getComponentType();\n }\n }\n throw new IllegalArgumentException(\"Not an array type \" + type);\n }", "private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}", "public Map<String, String> readPropertiesFromActiveProfiles( final String prefix,\n final String... properties ) {\n if (settings == null) {\n console.debug(\"No maven setting injected\");\n return Collections.emptyMap();\n }\n\n final List<String> activeProfilesList = settings.getActiveProfiles();\n if (activeProfilesList.isEmpty()) {\n console.debug(\"No active profiles found\");\n return Collections.emptyMap();\n }\n\n final Map<String, String> map = new HashMap<String, String>();\n final Set<String> activeProfiles = new HashSet<String>(activeProfilesList);\n\n // Iterate over all active profiles in order\n for (final Profile profile : settings.getProfiles()) {\n // Check if the profile is active\n final String profileId = profile.getId();\n if (activeProfiles.contains(profileId)) {\n console.debug(\"Trying active profile \" + profileId);\n for (final String property : properties) {\n final String propKey = prefix != null ? prefix + property : property;\n final String value = profile.getProperties().getProperty(propKey);\n if (value != null) {\n console.debug(\"Found property \" + property + \" in profile \" + profileId);\n map.put(property, value);\n }\n }\n }\n }\n\n return map;\n }", "public <Result, Param extends Resource> Result execWithoutCacheClear(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\ttry {\n\t\t\tcacheAdapter.ignoreNotifications();\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tcacheAdapter.listenToNotifications();\n\t\t}\n\t}", "public void resetResendCount() {\n\t\tthis.resendCount = 0;\n\t\tif (this.initializationComplete)\n\t\t\tthis.nodeStage = NodeStage.NODEBUILDINFO_DONE;\n\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t}", "private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }", "public BufferedImage getBufferedImage(int width, int height) {\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, width, height, null);\n g2d.dispose();\n return (buf);\n }" ]
Build the Criteria using multiple ORs @param ids collection of identities @param fields @return Criteria
[ "private Criteria buildPrefetchCriteriaMultipleKeys(Collection ids, FieldDescriptor fields[])\r\n {\r\n Criteria crit = new Criteria();\r\n Iterator iter = ids.iterator();\r\n Object[] val;\r\n Identity id;\r\n\r\n while (iter.hasNext())\r\n {\r\n Criteria c = new Criteria();\r\n id = (Identity) iter.next();\r\n val = id.getPrimaryKeyValues();\r\n for (int i = 0; i < val.length; i++)\r\n {\r\n if (val[i] == null)\r\n {\r\n c.addIsNull(fields[i].getAttributeName());\r\n }\r\n else\r\n {\r\n c.addEqualTo(fields[i].getAttributeName(), val[i]);\r\n }\r\n }\r\n crit.addOrCriteria(c);\r\n }\r\n\r\n return crit;\r\n }" ]
[ "@NotNull\n private String getFQName(@NotNull final String localName, Object... params) {\n final StringBuilder builder = new StringBuilder();\n builder.append(storeName);\n builder.append('.');\n builder.append(localName);\n for (final Object param : params) {\n builder.append('#');\n builder.append(param);\n }\n //noinspection ConstantConditions\n return StringInterner.intern(builder.toString());\n }", "private void processKnownType(FieldType type)\n {\n //System.out.println(\"Header: \" + type);\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, 36, false, 16, \"\"));\n\n GraphicalIndicator indicator = m_container.getCustomField(type).getGraphicalIndicator();\n indicator.setFieldType(type);\n int flags = m_data[m_dataOffset];\n indicator.setProjectSummaryInheritsFromSummaryRows((flags & 0x08) != 0);\n indicator.setSummaryRowsInheritFromNonSummaryRows((flags & 0x04) != 0);\n indicator.setDisplayGraphicalIndicators((flags & 0x02) != 0);\n indicator.setShowDataValuesInToolTips((flags & 0x01) != 0);\n m_dataOffset += 20;\n\n int nonSummaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int summaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int projectSummaryOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int dataSize = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n //System.out.println(\"Data\");\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, dataSize, false, 16, \"\"));\n\n int maxNonSummaryRowOffset = m_dataOffset + summaryRowOffset;\n int maxSummaryRowOffset = m_dataOffset + projectSummaryOffset;\n int maxProjectSummaryOffset = m_dataOffset + dataSize;\n\n m_dataOffset += nonSummaryRowOffset;\n\n while (m_dataOffset + 2 < maxNonSummaryRowOffset)\n {\n indicator.addNonSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxSummaryRowOffset)\n {\n indicator.addSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxProjectSummaryOffset)\n {\n indicator.addProjectSummaryCriteria(processCriteria(type));\n }\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}", "InputStream openContentStream(final ContentItem item) throws IOException {\n final File file = getFile(item);\n if (file == null) {\n throw new IllegalStateException();\n }\n return new FileInputStream(file);\n }", "@Override\n public final PArray getArray(final String key) {\n PArray result = optArray(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "private <T> T getBeanOrNull(String name, Class<T> requiredType) {\n\t\tif (name == null || !applicationContext.containsBean(name)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn applicationContext.getBean(name, requiredType);\n\t\t\t} catch (BeansException be) {\n\t\t\t\tlog.error(\"Error during getBeanOrNull, not rethrown, \" + be.getMessage(), be);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}", "public Archetype parse(String adl) {\n try {\n return parse(new StringReader(adl));\n } catch (IOException e) {\n // StringReader should never throw an IOException\n throw new AssertionError(e);\n }\n }", "public Map<String, EntityDocument> wbGetEntities(\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\treturn wbGetEntities(properties.ids, properties.sites,\n\t\t\t\tproperties.titles, properties.props, properties.languages,\n\t\t\t\tproperties.sitefilter);\n\t}", "public String convertToPrefixLength() throws AddressStringException {\n\t\tIPAddress address = toAddress();\n\t\tInteger prefix;\n\t\tif(address == null) {\n\t\t\tif(isPrefixOnly()) {\n\t\t\t\tprefix = getNetworkPrefixLength();\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = address.getBlockMaskPrefixLength(true);\n\t\t\tif(prefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn IPAddressSegment.toUnsignedString(prefix, 10, \n\t\t\t\tnew StringBuilder(IPAddressSegment.toUnsignedStringLength(prefix, 10) + 1).append(IPAddress.PREFIX_LEN_SEPARATOR)).toString();\n\t}" ]
Returns a List of all of the values in the Map whose key matches an entry in the nameMapping array. @param map the map @param nameMapping the keys of the Map values to add to the List @return a List of all of the values in the Map whose key matches an entry in the nameMapping array @throws NullPointerException if map or nameMapping is null
[ "public static List<Object> filterMapToList(final Map<String, ?> map, final String[] nameMapping) {\n\t\tif( map == null ) {\n\t\t\tthrow new NullPointerException(\"map should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal List<Object> result = new ArrayList<Object>(nameMapping.length);\n\t\tfor( final String key : nameMapping ) {\n\t\t\tresult.add(map.get(key));\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public static void writeErrorResponse(MessageEvent messageEvent,\n HttpResponseStatus status,\n String message) {\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);\n response.setHeader(CONTENT_TYPE, \"text/plain; charset=UTF-8\");\n response.setContent(ChannelBuffers.copiedBuffer(\"Failure: \" + status.toString() + \". \"\n + message + \"\\r\\n\", CharsetUtil.UTF_8));\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n messageEvent.getChannel().write(response);\n }", "private boolean loadCustomErrorPage(\n CmsObject cms,\n HttpServletRequest req,\n HttpServletResponse res,\n String rootPath) {\n\n try {\n\n // get the site of the error page resource\n CmsSite errorSite = OpenCms.getSiteManager().getSiteForRootPath(rootPath);\n cms.getRequestContext().setSiteRoot(errorSite.getSiteRoot());\n String relPath = cms.getRequestContext().removeSiteRoot(rootPath);\n if (cms.existsResource(relPath)) {\n cms.getRequestContext().setUri(relPath);\n OpenCms.getResourceManager().loadResource(cms, cms.readResource(relPath), req, res);\n return true;\n } else {\n return false;\n }\n } catch (Throwable e) {\n // something went wrong log the exception and return false\n LOG.error(e.getMessage(), e);\n return false;\n }\n }", "public static String plus(Number value, String right) {\n return DefaultGroovyMethods.toString(value) + right;\n }", "static boolean killProcess(final String processName, int id) {\n int pid;\n try {\n pid = processUtils.resolveProcessId(processName, id);\n if(pid > 0) {\n try {\n Runtime.getRuntime().exec(processUtils.getKillCommand(pid));\n return true;\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to kill process '%s' with pid '%s'\", processName, pid);\n }\n }\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to resolve pid of process '%s'\", processName);\n }\n return false;\n }", "public CentralDogmaBuilder port(InetSocketAddress localAddress, SessionProtocol protocol) {\n return port(new ServerPort(localAddress, protocol));\n }", "public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }", "private String getPathSelectString() {\n String queryString = \"SELECT \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \",\" + Constants.PATH_PROFILE_PATHNAME +\n \",\" + Constants.PATH_PROFILE_ACTUAL_PATH +\n \",\" + Constants.PATH_PROFILE_BODY_FILTER +\n \",\" + Constants.PATH_PROFILE_GROUP_IDS +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.PATH_PROFILE_PROFILE_ID +\n \",\" + Constants.PATH_PROFILE_PATH_ORDER +\n \",\" + Constants.REQUEST_RESPONSE_REPEAT_NUMBER +\n \",\" + Constants.REQUEST_RESPONSE_REQUEST_ENABLED +\n \",\" + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED +\n \",\" + Constants.PATH_PROFILE_CONTENT_TYPE +\n \",\" + Constants.PATH_PROFILE_REQUEST_TYPE +\n \",\" + Constants.PATH_PROFILE_GLOBAL +\n \" FROM \" + Constants.DB_TABLE_PATH +\n \" JOIN \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" ON \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \"=\" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.REQUEST_RESPONSE_PATH_ID +\n \" AND \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID + \" = ?\";\n\n return queryString;\n }", "public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }", "protected long getRevisionIdFromResponse(JsonNode response) throws JsonMappingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"API response is null\");\n\t\t}\n\t\tJsonNode entity = null;\n\t\tif(response.has(\"entity\")) {\n\t\t\tentity = response.path(\"entity\");\n\t\t} else if(response.has(\"pageinfo\")) {\n\t\t\tentity = response.path(\"pageinfo\");\n\t\t} \n\t\tif(entity != null && entity.has(\"lastrevid\")) {\n\t\t\treturn entity.path(\"lastrevid\").asLong();\n\t\t}\n\t\tthrow new JsonMappingException(\"The last revision id could not be found in API response\");\n\t}" ]
The list of device types on which this application can run.
[ "public List<String> deviceTypes() {\n Integer count = json().size(DEVICE_FAMILIES);\n List<String> deviceTypes = new ArrayList<String>(count);\n for(int i = 0 ; i < count ; i++) {\n String familyNumber = json().stringValue(DEVICE_FAMILIES, i);\n if(familyNumber.equals(\"1\")) deviceTypes.add(\"iPhone\");\n if(familyNumber.equals(\"2\")) deviceTypes.add(\"iPad\");\n }\n return deviceTypes;\n }" ]
[ "protected void recycleChildren() {\n for (ListItemHostWidget host: getAllHosts()) {\n recycle(host);\n }\n mContent.onTransformChanged();\n mContent.requestLayout();\n }", "void update(Object feature) throws LayerException {\n\t\tSimpleFeatureSource source = getFeatureSource();\n\t\tif (source instanceof SimpleFeatureStore) {\n\t\t\tSimpleFeatureStore store = (SimpleFeatureStore) source;\n\t\t\tString featureId = getFeatureModel().getId(feature);\n\t\t\tFilter filter = filterService.createFidFilter(new String[] { featureId });\n\t\t\ttransactionSynchronization.synchTransaction(store);\n\t\t\tList<Name> names = new ArrayList<Name>();\n\t\t\tMap<String, Attribute> attrMap = getFeatureModel().getAttributes(feature);\n\t\t\tList<Object> values = new ArrayList<Object>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : attrMap.entrySet()) {\n\t\t\t\tString name = entry.getKey();\n\t\t\t\tnames.add(store.getSchema().getDescriptor(name).getName());\n\t\t\t\tvalues.add(entry.getValue().getValue());\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tstore.modifyFeatures(names.toArray(new Name[names.size()]), values.toArray(), filter);\n\t\t\t\tstore.modifyFeatures(store.getSchema().getGeometryDescriptor().getName(), getFeatureModel()\n\t\t\t\t\t\t.getGeometry(feature), filter);\n\t\t\t\tlog.debug(\"Updated feature {} in {}\", featureId, getFeatureSourceName());\n\t\t\t} catch (IOException ioe) {\n\t\t\t\tfeatureModelUsable = false;\n\t\t\t\tthrow new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);\n\t\t\t}\n\t\t} else {\n\t\t\tlog.error(\"Don't know how to create or update \" + getFeatureSourceName() + \", class \"\n\t\t\t\t\t+ source.getClass().getName() + \" does not implement SimpleFeatureStore\");\n\t\t\tthrow new LayerException(ExceptionCode.CREATE_OR_UPDATE_NOT_IMPLEMENTED, getFeatureSourceName(), source\n\t\t\t\t\t.getClass().getName());\n\t\t}\n\t}", "public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }", "public String putProperty(String key,\n String value) {\n return this.getProperties().put(key,\n value);\n }", "@Override\n public TagsInterface getTagsInterface() {\n if (tagsInterface == null) {\n tagsInterface = new TagsInterface(apiKey, sharedSecret, transport);\n }\n return tagsInterface;\n }", "private static JsonObject getFieldOperationJsonObject(FieldOperation fieldOperation) {\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"op\", fieldOperation.getOp().toString());\n\n String fieldKey = fieldOperation.getFieldKey();\n if (fieldKey != null) {\n jsonObject.add(\"fieldKey\", fieldKey);\n }\n\n Field field = fieldOperation.getData();\n if (field != null) {\n JsonObject fieldObj = new JsonObject();\n\n String type = field.getType();\n if (type != null) {\n fieldObj.add(\"type\", type);\n }\n\n String key = field.getKey();\n if (key != null) {\n fieldObj.add(\"key\", key);\n }\n\n String displayName = field.getDisplayName();\n if (displayName != null) {\n fieldObj.add(\"displayName\", displayName);\n }\n\n String description = field.getDescription();\n if (description != null) {\n fieldObj.add(\"description\", description);\n }\n\n Boolean hidden = field.getIsHidden();\n if (hidden != null) {\n fieldObj.add(\"hidden\", hidden);\n }\n\n List<String> options = field.getOptions();\n if (options != null) {\n JsonArray array = new JsonArray();\n for (String option: options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n\n fieldObj.add(\"options\", array);\n }\n\n jsonObject.add(\"data\", fieldObj);\n }\n\n List<String> fieldKeys = fieldOperation.getFieldKeys();\n if (fieldKeys != null) {\n jsonObject.add(\"fieldKeys\", getJsonArray(fieldKeys));\n }\n\n List<String> enumOptionKeys = fieldOperation.getEnumOptionKeys();\n if (enumOptionKeys != null) {\n jsonObject.add(\"enumOptionKeys\", getJsonArray(enumOptionKeys));\n }\n\n String enumOptionKey = fieldOperation.getEnumOptionKey();\n if (enumOptionKey != null) {\n jsonObject.add(\"enumOptionKey\", enumOptionKey);\n }\n\n String multiSelectOptionKey = fieldOperation.getMultiSelectOptionKey();\n if (multiSelectOptionKey != null) {\n jsonObject.add(\"multiSelectOptionKey\", multiSelectOptionKey);\n }\n\n List<String> multiSelectOptionKeys = fieldOperation.getMultiSelectOptionKeys();\n if (multiSelectOptionKeys != null) {\n jsonObject.add(\"multiSelectOptionKeys\", getJsonArray(multiSelectOptionKeys));\n }\n\n return jsonObject;\n }", "public static void divideElementsCol(final int blockLength ,\n final DSubmatrixD1 Y , final int col , final double val ) {\n final int width = Math.min(blockLength,Y.col1-Y.col0);\n\n final double dataY[] = Y.original.data;\n\n for( int i = Y.row0; i < Y.row1; i += blockLength ) {\n int height = Math.min( blockLength , Y.row1 - i );\n\n int index = i*Y.original.numCols + height*Y.col0 + col;\n\n if( i == Y.row0 ) {\n index += width*(col+1);\n\n for( int k = col+1; k < height; k++ , index += width ) {\n dataY[index] /= val;\n }\n } else {\n int endIndex = index + width*height;\n //for( int k = 0; k < height; k++\n for( ; index != endIndex; index += width ) {\n dataY[index] /= val;\n }\n }\n }\n }", "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\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 }" ]
Populates the project header. @param record MPX record @param properties project properties @throws MPXJException
[ "private void populateProjectHeader(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setProjectTitle(record.getString(0));\n properties.setCompany(record.getString(1));\n properties.setManager(record.getString(2));\n properties.setDefaultCalendarName(record.getString(3));\n properties.setStartDate(record.getDateTime(4));\n properties.setFinishDate(record.getDateTime(5));\n properties.setScheduleFrom(record.getScheduleFrom(6));\n properties.setCurrentDate(record.getDateTime(7));\n properties.setComments(record.getString(8));\n properties.setCost(record.getCurrency(9));\n properties.setBaselineCost(record.getCurrency(10));\n properties.setActualCost(record.getCurrency(11));\n properties.setWork(record.getDuration(12));\n properties.setBaselineWork(record.getDuration(13));\n properties.setActualWork(record.getDuration(14));\n properties.setWork2(record.getPercentage(15));\n properties.setDuration(record.getDuration(16));\n properties.setBaselineDuration(record.getDuration(17));\n properties.setActualDuration(record.getDuration(18));\n properties.setPercentageComplete(record.getPercentage(19));\n properties.setBaselineStart(record.getDateTime(20));\n properties.setBaselineFinish(record.getDateTime(21));\n properties.setActualStart(record.getDateTime(22));\n properties.setActualFinish(record.getDateTime(23));\n properties.setStartVariance(record.getDuration(24));\n properties.setFinishVariance(record.getDuration(25));\n properties.setSubject(record.getString(26));\n properties.setAuthor(record.getString(27));\n properties.setKeywords(record.getString(28));\n }" ]
[ "@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }", "public static vpntrafficpolicy_aaagroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_aaagroup_binding obj = new vpntrafficpolicy_aaagroup_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_aaagroup_binding response[] = (vpntrafficpolicy_aaagroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private static JsonObject getFieldJsonObject(Field field) {\n JsonObject fieldObj = new JsonObject();\n fieldObj.add(\"type\", field.getType());\n fieldObj.add(\"key\", field.getKey());\n fieldObj.add(\"displayName\", field.getDisplayName());\n\n String fieldDesc = field.getDescription();\n if (fieldDesc != null) {\n fieldObj.add(\"description\", field.getDescription());\n }\n\n Boolean fieldIsHidden = field.getIsHidden();\n if (fieldIsHidden != null) {\n fieldObj.add(\"hidden\", field.getIsHidden());\n }\n\n JsonArray array = new JsonArray();\n List<String> options = field.getOptions();\n if (options != null && !options.isEmpty()) {\n for (String option : options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n fieldObj.add(\"options\", array);\n }\n\n return fieldObj;\n }", "public void link(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds, Object referencedObject, boolean insert)\n {\n // MBAIRD: we have 'disassociated' this object from the referenced object,\n // the object represented by the reference descriptor is now null, so set\n // the fk in the target object to null.\n // arminw: if an insert was done and ref object was null, we should allow\n // to pass FK fields of main object (maybe only the FK fields are set)\n if (referencedObject == null)\n {\n /*\n arminw:\n if update we set FK fields to 'null', because reference was disassociated\n We do nothing on insert, maybe only the FK fields of main object (without\n materialization of the reference object) are set by the user\n */\n if(!insert)\n {\n unlinkFK(targetObject, cld, rds);\n }\n }\n else\n {\n setFKField(targetObject, cld, rds, referencedObject);\n }\n }", "public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }", "public static base_response delete(nitro_service client, String domain) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = domain;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "@Override\n protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {\n final CompletableFuture<T> future = new CompletableFuture<>();\n executor.execute(() -> {\n try {\n future.complete(blockingExecute(command));\n } catch (Throwable t) {\n future.completeExceptionally(t);\n }\n });\n return future;\n }", "public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }", "public ResourceAssignmentWorkgroupFields addWorkgroupAssignment() throws MPXJException\n {\n if (m_workgroup != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n m_workgroup = new ResourceAssignmentWorkgroupFields();\n\n return (m_workgroup);\n }" ]
Parses a record containing hours and add them to a container. @param ranges hours container @param hoursRecord hours record
[ "private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }" ]
[ "private ProjectFile handleByteOrderMark(InputStream stream, int length, Charset charset) throws Exception\n {\n UniversalProjectReader reader = new UniversalProjectReader();\n reader.setSkipBytes(length);\n reader.setCharset(charset);\n return reader.read(stream);\n }", "private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException {\n\t\tList<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>();\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read next field from config file\", e);\n\t\t\t}\n\t\t\tif (line == null || line.equals(CONFIG_FILE_FIELDS_END)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader);\n\t\t\tif (fieldConfig == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfields.add(fieldConfig);\n\t\t}\n\t\tconfig.setFieldConfigs(fields);\n\t}", "public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }", "public Set<String> findResourceNames(String location, URI locationUri) throws IOException {\n String filePath = toFilePath(locationUri);\n File folder = new File(filePath);\n if (!folder.isDirectory()) {\n LOGGER.debug(\"Skipping path as it is not a directory: \" + filePath);\n return new TreeSet<>();\n }\n\n String classPathRootOnDisk = filePath.substring(0, filePath.length() - location.length());\n if (!classPathRootOnDisk.endsWith(File.separator)) {\n classPathRootOnDisk = classPathRootOnDisk + File.separator;\n }\n LOGGER.debug(\"Scanning starting at classpath root in filesystem: \" + classPathRootOnDisk);\n return findResourceNamesFromFileSystem(classPathRootOnDisk, location, folder);\n }", "public void stop() {\n syncLock.lock();\n try {\n if (syncThread == null) {\n return;\n }\n instanceChangeStreamListener.stop();\n syncThread.interrupt();\n try {\n syncThread.join();\n } catch (final InterruptedException e) {\n return;\n }\n syncThread = null;\n isRunning = false;\n } finally {\n syncLock.unlock();\n }\n }", "public static KieRuntimeLogger newFileLogger(KieRuntimeEventManager session,\n String fileName) {\n return getKnowledgeRuntimeLoggerProvider().newFileLogger( session,\n fileName );\n }", "protected void failedToCleanupDir(final File file) {\n checkForGarbageOnRestart = true;\n PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath());\n }", "private String getSignature(String sharedSecret, Map<String, String> params) {\r\n StringBuffer buffer = new StringBuffer();\r\n buffer.append(sharedSecret);\r\n for (Map.Entry<String, String> entry : params.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append(entry.getValue());\r\n }\r\n\r\n try {\r\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\r\n return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes(\"UTF-8\")));\r\n } catch (NoSuchAlgorithmException e) {\r\n throw new RuntimeException(e);\r\n } catch (UnsupportedEncodingException u) {\r\n throw new RuntimeException(u);\r\n }\r\n }", "public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }" ]
Use this API to fetch appfwpolicylabel_policybinding_binding resources of given name .
[ "public static appfwpolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_policybinding_binding obj = new appfwpolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_policybinding_binding response[] = (appfwpolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "private void readWBS()\n {\n Map<Integer, List<MapRow>> levelMap = new HashMap<Integer, List<MapRow>>();\n for (MapRow row : m_tables.get(\"STR\"))\n {\n Integer level = row.getInteger(\"LEVEL_NUMBER\");\n List<MapRow> items = levelMap.get(level);\n if (items == null)\n {\n items = new ArrayList<MapRow>();\n levelMap.put(level, items);\n }\n items.add(row);\n }\n\n int level = 1;\n while (true)\n {\n List<MapRow> items = levelMap.get(Integer.valueOf(level++));\n if (items == null)\n {\n break;\n }\n\n for (MapRow row : items)\n {\n m_wbsFormat.parseRawValue(row.getString(\"CODE_VALUE\"));\n String parentWbsValue = m_wbsFormat.getFormattedParentValue();\n String wbsValue = m_wbsFormat.getFormattedValue();\n row.setObject(\"WBS\", wbsValue);\n row.setObject(\"PARENT_WBS\", parentWbsValue);\n }\n\n final AlphanumComparator comparator = new AlphanumComparator();\n Collections.sort(items, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n return comparator.compare(o1.getString(\"WBS\"), o2.getString(\"WBS\"));\n }\n });\n\n for (MapRow row : items)\n {\n String wbs = row.getString(\"WBS\");\n if (wbs != null && !wbs.isEmpty())\n {\n ChildTaskContainer parent = m_wbsMap.get(row.getString(\"PARENT_WBS\"));\n if (parent == null)\n {\n parent = m_projectFile;\n }\n\n Task task = parent.addTask();\n String name = row.getString(\"CODE_TITLE\");\n if (name == null || name.isEmpty())\n {\n name = wbs;\n }\n task.setName(name);\n task.setWBS(wbs);\n task.setSummary(true);\n m_wbsMap.put(wbs, task);\n }\n }\n }\n }", "public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\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}", "private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }", "public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.api.getBaseURL());\n return new BoxItemIterator(this.api, url);\n }", "public static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }", "public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\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}", "public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Get the exception message using the requested locale. @param locale locale for message @return exception message
[ "public String getMessage(Locale locale) {\n\t\tif (getCause() != null) {\n\t\t\tString message = getShortMessage(locale) + \", \" + translate(\"ROOT_CAUSE\", locale) + \" \";\n\t\t\tif (getCause() instanceof GeomajasException) {\n\t\t\t\treturn message + ((GeomajasException) getCause()).getMessage(locale);\n\t\t\t}\n\t\t\treturn message + getCause().getMessage();\n\t\t} else {\n\t\t\treturn getShortMessage(locale);\n\t\t}\n\t}" ]
[ "public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }", "public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) {\n dest.clear();\n\n if (key != null) {\n dest.key = new Key(key);\n }\n\n for (int i = 0; i < timeStamps.size(); i++) {\n long time = timeStamps.get(i);\n if (timestampTest.test(time)) {\n dest.add(time, values.get(i));\n }\n }\n }", "public void useNewRESTService(String address) throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n org.customer.service.CustomerService customerService = JAXRSClientFactory\n .createFromModel(address, \n org.customer.service.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using new RESTful CustomerService with new client\");\n\n customer.v2.Customer customer = createNewCustomer(\"Smith New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith New REST\");\n printNewCustomerDetails(customer);\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 }", "public String getPrototypeName() {\n\t\tString name = getClass().getName();\n\t\tif (name.startsWith(ORG_GEOMAJAS)) {\n\t\t\tname = name.substring(ORG_GEOMAJAS.length());\n\t\t}\n\t\tname = name.replace(\".dto.\", \".impl.\");\n\t\treturn name.substring(0, name.length() - 4) + \"Impl\";\n\t}", "public void swapSubstring(BitString other, int start, int length)\n {\n assertValidIndex(start);\n other.assertValidIndex(start);\n \n int word = start / WORD_LENGTH;\n\n int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;\n if (partialWordSize > 0)\n {\n swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize));\n ++word;\n }\n\n int remainingBits = length - partialWordSize;\n int stop = remainingBits / WORD_LENGTH;\n for (int i = word; i < stop; i++)\n {\n int temp = data[i];\n data[i] = other.data[i];\n other.data[i] = temp;\n }\n\n remainingBits %= WORD_LENGTH;\n if (remainingBits > 0)\n {\n swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits));\n }\n }", "public static ConstraintType getInstance(Locale locale, String type)\n {\n int index = 0;\n\n String[] constraintTypes = LocaleData.getStringArray(locale, LocaleData.CONSTRAINT_TYPES);\n for (int loop = 0; loop < constraintTypes.length; loop++)\n {\n if (constraintTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n return (ConstraintType.getInstance(index));\n }", "public void addProcedure(ProcedureDef procDef)\r\n {\r\n procDef.setOwner(this);\r\n _procedures.put(procDef.getName(), procDef);\r\n }", "public PhotoList<Photo> getUntagged(int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UNTAGGED);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }" ]
Remove a previously registered requirement for a capability. @param requirementRegistration the requirement. Cannot be {@code null} @see #registerAdditionalCapabilityRequirement(org.jboss.as.controller.capability.registry.RuntimeRequirementRegistration)
[ "@Override\n public void removeCapabilityRequirement(RuntimeRequirementRegistration requirementRegistration) {\n // We don't know if this got registered as an runtime-only requirement or a hard one\n // so clean it from both maps\n writeLock.lock();\n try {\n removeRequirement(requirementRegistration, false);\n removeRequirement(requirementRegistration, true);\n } finally {\n writeLock.unlock();\n }\n }" ]
[ "private void clearDeckPreview(TrackMetadataUpdate update) {\n if (previewHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformPreviewUpdate(update.player, null);\n }\n }", "public void deleteModule(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.getModulePath(name, version));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"to delete module\", name, version);\n\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 }", "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 void signOff(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.keySet().removeAll(connections);\n }", "@Beta\n public MSICredentials withObjectId(String objectId) {\n this.objectId = objectId;\n this.clientId = null;\n this.identityId = null;\n return this;\n }", "public static base_responses update(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder updateresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslocspresponder();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].cache = resources[i].cache;\n\t\t\t\tupdateresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\tupdateresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\tupdateresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\tupdateresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\tupdateresources[i].respondercert = resources[i].respondercert;\n\t\t\t\tupdateresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\tupdateresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\tupdateresources[i].signingcert = resources[i].signingcert;\n\t\t\t\tupdateresources[i].usenonce = resources[i].usenonce;\n\t\t\t\tupdateresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void write(WritableByteChannel channel) throws IOException {\n logger.debug(\"Writing> {}\", this);\n for (Field field : fields) {\n field.write(channel);\n }\n }", "public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)\n {\n if (cleanBaseFileName)\n {\n baseFileName = PathUtil.cleanFileName(baseFileName);\n }\n\n if (ancestorFolders != null)\n {\n Path pathToFile = Paths.get(\"\", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);\n baseFileName = pathToFile.toString();\n }\n String filename = baseFileName + \".\" + extension;\n\n // FIXME this looks nasty\n while (usedFilenames.contains(filename))\n {\n filename = baseFileName + \".\" + index.getAndIncrement() + \".\" + extension;\n }\n usedFilenames.add(filename);\n\n return filename;\n }", "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 }" ]
Create a model mbean from an object using the description given in the Jmx annotation if present. Only operations are supported so far, no attributes, constructors, or notifications @param o The object to create an MBean for @return The ModelMBean for the given object
[ "public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\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 final void error(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.ERROR, pObject, null);\r\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 ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }", "public static DMatrixRBlock transpose(DMatrixRBlock A , DMatrixRBlock A_tran )\n {\n if( A_tran != null ) {\n if( A.numRows != A_tran.numCols || A.numCols != A_tran.numRows )\n throw new IllegalArgumentException(\"Incompatible dimensions.\");\n if( A.blockLength != A_tran.blockLength )\n throw new IllegalArgumentException(\"Incompatible block size.\");\n } else {\n A_tran = new DMatrixRBlock(A.numCols,A.numRows,A.blockLength);\n\n }\n\n for( int i = 0; i < A.numRows; i += A.blockLength ) {\n int blockHeight = Math.min( A.blockLength , A.numRows - i);\n\n for( int j = 0; j < A.numCols; j += A.blockLength ) {\n int blockWidth = Math.min( A.blockLength , A.numCols - j);\n\n int indexA = i*A.numCols + blockHeight*j;\n int indexC = j*A_tran.numCols + blockWidth*i;\n\n transposeBlock( A , A_tran , indexA , indexC , blockWidth , blockHeight );\n }\n }\n\n return A_tran;\n }", "public static Iterable<BoxFileVersionRetention.Info> getRetentions(\n final BoxAPIConnection api, QueryFilter filter, String ... fields) {\n filter.addFields(fields);\n return new BoxResourceIterable<BoxFileVersionRetention.Info>(api,\n ALL_RETENTIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), filter.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected BoxFileVersionRetention.Info factory(JsonObject jsonObject) {\n BoxFileVersionRetention retention = new BoxFileVersionRetention(api, jsonObject.get(\"id\").asString());\n return retention.new Info(jsonObject);\n }\n };\n }", "protected static PatchElement createRollbackElement(final PatchEntry entry) {\n final PatchElement patchElement = entry.element;\n final String patchId;\n final Patch.PatchType patchType = patchElement.getProvider().getPatchType();\n if (patchType == Patch.PatchType.CUMULATIVE) {\n patchId = entry.getCumulativePatchID();\n } else {\n patchId = patchElement.getId();\n }\n return createPatchElement(entry, patchId, entry.rollbackActions);\n }", "public synchronized int cancelByTag(String tagToCancel) {\n int i = 0;\n if (taskList.containsKey(tagToCancel)) {\n removeDoneTasks();\n\n for (Future<BlurWorker.Result> future : taskList.get(tagToCancel)) {\n BuilderUtil.logVerbose(Dali.getConfig().logTag, \"Canceling task with tag \" + tagToCancel, Dali.getConfig().debugMode);\n future.cancel(true);\n i++;\n }\n\n //remove all canceled tasks\n Iterator<Future<BlurWorker.Result>> iter = taskList.get(tagToCancel).iterator();\n while (iter.hasNext()) {\n if (iter.next().isCancelled()) {\n iter.remove();\n }\n }\n }\n return i;\n }", "public static nstrafficdomain_binding[] get(nitro_service service, Long td[]) throws Exception{\n\t\tif (td !=null && td.length>0) {\n\t\t\tnstrafficdomain_binding response[] = new nstrafficdomain_binding[td.length];\n\t\t\tnstrafficdomain_binding obj[] = new nstrafficdomain_binding[td.length];\n\t\t\tfor (int i=0;i<td.length;i++) {\n\t\t\t\tobj[i] = new nstrafficdomain_binding();\n\t\t\t\tobj[i].set_td(td[i]);\n\t\t\t\tresponse[i] = (nstrafficdomain_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
Hardcode a copy method as being valid. This should be used to tell Mutability Detector about a method which copies a collection, and when the copy can be wrapped in an immutable wrapper we can consider the assignment immutable. Useful for allowing Mutability Detector to correctly work with other collections frameworks such as Google Guava. Reflection is used to obtain the method's descriptor and to verify the method's existence. @param fieldType - the type of the field to which the result of the copy is assigned @param fullyQualifiedMethodName - the fully qualified method name @param argType - the type of the argument passed to the copy method @throws MutabilityAnalysisException - if the specified class or method does not exist @throws IllegalArgumentException - if any of the arguments are null
[ "protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) {\r\n if (argType==null || fieldType==null || fullyQualifiedMethodName==null) {\r\n throw new IllegalArgumentException(\"All parameters must be supplied - no nulls\");\r\n }\r\n String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(\".\"));\r\n String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(\".\")+1);\r\n\r\n \r\n String desc = null;\r\n try {\r\n if (MethodIs.aConstructor(methodName)) {\r\n Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType);\r\n desc = Type.getConstructorDescriptor(ctor);\r\n } else {\r\n Method method = Class.forName(className).getMethod(methodName, argType);\r\n desc = Type.getMethodDescriptor(method);\r\n }\r\n } catch (NoSuchMethodException e) {\r\n rethrow(\"No such method\", e);\r\n } catch (SecurityException e) {\r\n rethrow(\"Security error\", e);\r\n } catch (ClassNotFoundException e) {\r\n rethrow(\"Class not found\", e);\r\n }\r\n CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc);\r\n hardcodeValidCopyMethod(fieldType, copyMethod);\r\n }" ]
[ "public CliCommandBuilder setController(final String hostname, final int port) {\n setController(formatAddress(null, hostname, port));\n return this;\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 }", "public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\tif (key == null)\n\t\t\tthrow new NullPointerException(\"key\");\n\t\tCollections.sort(list, new KeyComparator<T, C>(key));\n\t\treturn list;\n\t}", "public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}", "public static long crc32(byte[] bytes, int offset, int size) {\n CRC32 crc = new CRC32();\n crc.update(bytes, offset, size);\n return crc.getValue();\n }", "public AT_Row setPaddingTop(int paddingTop) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}", "private static int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }", "synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }" ]
Sets the size of the matrix being decomposed, declares new memory if needed, and sets all helper functions to their initial value.
[ "public void reset( int N ) {\n this.N = N;\n\n this.diag = null;\n this.off = null;\n\n if( splits.length < N ) {\n splits = new int[N];\n }\n\n numSplits = 0;\n\n x1 = 0;\n x2 = N-1;\n\n steps = numExceptional = lastExceptional = 0;\n\n this.Q = null;\n }" ]
[ "private void reconnectFlows() {\n // create the reverse id map:\n for (Entry<Object, List<String>> entry : _outgoingFlows.entrySet()) {\n for (String flowId : entry.getValue()) {\n if (entry.getKey() instanceof SequenceFlow) { // if it is a sequence flow, we can tell its targets\n if (_idMap.get(flowId) instanceof FlowNode) {\n ((SequenceFlow) entry.getKey()).setTargetRef((FlowNode) _idMap.get(flowId));\n }\n if (_idMap.get(flowId) instanceof Association) {\n ((Association) _idMap.get(flowId)).setTargetRef((SequenceFlow) entry.getKey());\n }\n } else if (entry.getKey() instanceof Association) {\n ((Association) entry.getKey()).setTargetRef((BaseElement) _idMap.get(flowId));\n } else { // if it is a node, we can map it to its outgoing sequence flows\n if (_idMap.get(flowId) instanceof SequenceFlow) {\n ((FlowNode) entry.getKey()).getOutgoing().add((SequenceFlow) _idMap.get(flowId));\n } else if (_idMap.get(flowId) instanceof Association) {\n ((Association) _idMap.get(flowId)).setSourceRef((BaseElement) entry.getKey());\n }\n }\n }\n }\n }", "public void addRequiredBundles(String... requiredBundles) {\n\t\tString oldBundles = mainAttributes.get(REQUIRE_BUNDLE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : requiredBundles) {\n\t\t\tBundle newBundle = Bundle.fromInput(bundle);\n\t\t\tif (name != null && name.equals(newBundle.getName()))\n\t\t\t\tcontinue;\n\t\t\tresultList.mergeInto(newBundle);\n\t\t}\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(REQUIRE_BUNDLE, result);\n\t}", "static void prepareTasks(final IdentityPatchContext.PatchEntry entry, final IdentityPatchContext context, final List<PreparedTask> tasks, final List<ContentItem> conflicts) throws PatchingException {\n for (final PatchingTasks.ContentTaskDefinition definition : entry.getTaskDefinitions()) {\n final PatchingTask task = createTask(definition, context, entry);\n if(!task.isRelevant(entry)) {\n continue;\n }\n try {\n // backup and validate content\n if (!task.prepare(entry) || definition.hasConflicts()) {\n // Unless it a content item was manually ignored (or excluded)\n final ContentItem item = task.getContentItem();\n if (!context.isIgnored(item)) {\n conflicts.add(item);\n }\n }\n tasks.add(new PreparedTask(task, entry));\n } catch (IOException e) {\n throw new PatchingException(e);\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 }", "static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {\n\t\tfor (Map.Entry<String, List<String>> entry : headers.entrySet()) {\n\t\t\tString headerName = entry.getKey();\n\t\t\tif (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265\n\t\t\t\tString headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), \"; \");\n\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t}\n\t\t\telse if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) &&\n\t\t\t\t\t!HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {\n\t\t\t\tfor (String headerValue : entry.getValue()) {\n\t\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public Iterable<BoxItem.Info> getChildren(final String... fields) {\n return new Iterable<BoxItem.Info>() {\n @Override\n public Iterator<BoxItem.Info> iterator() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID());\n return new BoxItemIterator(getAPI(), url);\n }\n };\n }", "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}", "public Iterable<BoxMetadataCascadePolicy.Info> getMetadataCascadePolicies(String... fields) {\n Iterable<BoxMetadataCascadePolicy.Info> cascadePoliciesInfo =\n BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields);\n\n return cascadePoliciesInfo;\n }", "public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }" ]
Remove a part of a CharSequence by replacing the first occurrence of target within self with '' and returns the result. @param self a CharSequence @param target an object representing the part to remove @return a String containing the original minus the part to be removed @see #minus(String, Object) @since 1.8.2
[ "public static String minus(CharSequence self, Object target) {\n String s = self.toString();\n String text = DefaultGroovyMethods.toString(target);\n int index = s.indexOf(text);\n if (index == -1) return s;\n int end = index + text.length();\n if (s.length() > end) {\n return s.substring(0, index) + s.substring(end);\n }\n return s.substring(0, index);\n }" ]
[ "public static int e(ISubsystem subsystem, String tag, String msg) {\n return isEnabled(subsystem) ?\n currentLog.e(tag, getMsg(subsystem,msg)) : 0;\n }", "public boolean forall(PixelPredicate predicate) {\n return Arrays.stream(points()).allMatch(p -> predicate.test(p.x, p.y, pixel(p)));\n }", "public static Timer getNamedTimer(String timerName, int todoFlags) {\n\t\treturn getNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}", "private <FT, FID> FT createForeignShell(ConnectionSource connectionSource, Object val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tFT foreignObject = castDao.createObjectInstance();\n\t\tforeignIdField.assignField(connectionSource, foreignObject, val, false, objectCache);\n\t\treturn foreignObject;\n\t}", "public T[] toArray(T[] tArray) {\n List<T> array = new ArrayList<T>(100);\n for (Iterator<T> it = iterator(); it.hasNext();) {\n T val = it.next();\n if (val != null) array.add(val);\n }\n return array.toArray(tArray);\n }", "public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }", "protected DirectiveStatement parseDirectiveStatement(DirectiveStContext node)\r\n\t{\r\n\t\tDirectiveStContext stContext = (DirectiveStContext) node;\r\n\t\tDirectiveExpContext direExp = stContext.directiveExp();\r\n\t\tToken token = direExp.Identifier().getSymbol();\r\n\t\tString directive = token.getText().toLowerCase().intern();\r\n\t\tTerminalNode value = direExp.StringLiteral();\r\n\t\tList<TerminalNode> idNodeList = null;\r\n\t\tDirectiveExpIDListContext directExpidLisCtx = direExp.directiveExpIDList();\r\n\t\tif (directExpidLisCtx != null)\r\n\t\t{\r\n\t\t\tidNodeList = directExpidLisCtx.Identifier();\r\n\t\t}\r\n\r\n\t\tSet<String> idList = null;\r\n\t\tDirectiveStatement ds = null;\r\n\r\n\t\tif (value != null)\r\n\t\t{\r\n\t\t\tString idListValue = this.getStringValue(value.getText());\r\n\t\t\tidList = new HashSet(Arrays.asList(idListValue.split(\",\")));\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse if (idNodeList != null)\r\n\t\t{\r\n\t\t\tidList = new HashSet<String>();\r\n\t\t\tfor (TerminalNode t : idNodeList)\r\n\t\t\t{\r\n\t\t\t\tidList.add(t.getText());\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t}\r\n\r\n\t\tif (directive.equals(\"dynamic\"))\r\n\t\t{\r\n\r\n\t\t\tif (ds.getIdList().size() == 0)\r\n\t\t\t{\r\n\t\t\t\tdata.allDynamic = true;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tdata.dynamicObjectSet = ds.getIdList();\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t\t\r\n\t\t\treturn ds;\r\n\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_open\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = true;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_close\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = false;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t}", "public AsciiTable setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "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}" ]
Use this API to fetch responderpolicy_binding resource of given name .
[ "public static responderpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy_binding obj = new responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tresponderpolicy_binding response = (responderpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public VerticalLayout getEmptyLayout() {\n\n m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey());\n setVisible(size() > 0);\n m_emptyLayout.setVisible(size() == 0);\n return m_emptyLayout;\n }", "private void addCustomFields(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (CustomField field : file.getCustomFields())\n {\n final CustomField c = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n FieldType type = c.getFieldType();\n \n return type == null ? \"(unknown)\" : type.getFieldTypeClass() + \".\" + type.toString();\n }\n };\n parentNode.add(childNode);\n }\n }", "public void restoreSecurityContext(CacheContext context) {\n\t\tSavedAuthorization cached = context.get(CacheContext.SECURITY_CONTEXT_KEY, SavedAuthorization.class);\n\t\tif (cached != null) {\n\t\t\tlog.debug(\"Restoring security context {}\", cached);\n\t\t\tsecurityManager.restoreSecurityContext(cached);\n\t\t} else {\n\t\t\tsecurityManager.clearSecurityContext();\n\t\t}\n\t}", "public static crvserver_policymap_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcrvserver_policymap_binding obj = new crvserver_policymap_binding();\n\t\tobj.set_name(name);\n\t\tcrvserver_policymap_binding response[] = (crvserver_policymap_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }", "public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final CompositeGeneratorNode rootNode) {\n final GeneratorNodeProcessor.Result result = this.processor.process(rootNode);\n fsa.generateFile(path, result);\n }", "public static Integer getDurationUnits(RecurringTask recurrence)\n {\n Duration duration = recurrence.getDuration();\n Integer result = null;\n\n if (duration != null)\n {\n result = UNITS_MAP.get(duration.getUnits());\n }\n\n return (result);\n }", "public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }", "@Override\n public int add(DownloadRequest request) throws IllegalArgumentException {\n checkReleased(\"add(...) called on a released ThinDownloadManager.\");\n if (request == null) {\n throw new IllegalArgumentException(\"DownloadRequest cannot be null\");\n }\n return mRequestQueue.add(request);\n }" ]
Get a View that displays the data at the specified position in the data set. In this case, if we are at the end of the list and we are still in append mode, we ask for a pending view and return it, plus kick off the background task to append more data to the wrapped adapter. @param position Position of the item whose data we want @param convertView View to recycle, if not null @param parent ViewGroup containing the returned View
[ "@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (position == super.getCount() && isEnableRefreshing()) {\n return (mFooter);\n }\n return (super.getView(position, convertView, parent));\n }" ]
[ "public void processCalendar(Row calendarRow, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> workPatternAssignmentMap, Map<Integer, List<Row>> exceptionAssignmentMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n //\n // Create the calendar and add the default working hours\n //\n ProjectCalendar calendar = m_project.addCalendar();\n Integer dominantWorkPatternID = calendarRow.getInteger(\"DOMINANT_WORK_PATTERN\");\n calendar.setUniqueID(calendarRow.getInteger(\"CALENDARID\"));\n processWorkPattern(calendar, dominantWorkPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n calendar.setName(calendarRow.getString(\"NAMK\"));\n\n //\n // Add any additional working weeks\n //\n List<Row> rows = workPatternAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"WORK_PATTERN\");\n if (!workPatternID.equals(dominantWorkPatternID))\n {\n ProjectCalendarWeek week = calendar.addWorkWeek();\n week.setDateRange(new DateRange(row.getDate(\"START_DATE\"), row.getDate(\"END_DATE\")));\n processWorkPattern(week, workPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n }\n }\n }\n\n //\n // Add exceptions - not sure how exceptions which turn non-working days into working days are handled by Asta - if at all?\n //\n rows = exceptionAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Date startDate = row.getDate(\"STARU_DATE\");\n Date endDate = row.getDate(\"ENE_DATE\");\n calendar.addCalendarException(startDate, endDate);\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }", "private void setRequestSitefilter(WbGetEntitiesActionData properties) {\n\t\tif (this.filter.excludeAllSiteLinks()\n\t\t\t\t|| this.filter.getSiteLinkFilter() == null) {\n\t\t\treturn;\n\t\t}\n\t\tproperties.sitefilter = ApiConnection.implodeObjects(this.filter\n\t\t\t\t.getSiteLinkFilter());\n\t}", "private void deselectChildren(CmsTreeItem item) {\r\n\r\n for (String childId : m_childrens.get(item.getId())) {\r\n CmsTreeItem child = m_categories.get(childId);\r\n deselectChildren(child);\r\n child.getCheckBox().setChecked(false);\r\n if (m_selectedCategories.contains(childId)) {\r\n m_selectedCategories.remove(childId);\r\n }\r\n }\r\n }", "private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap)\n {\n Project.Resources resources = project.getResources();\n if (resources != null)\n {\n for (Project.Resources.Resource resource : resources.getResource())\n {\n readResource(resource, calendarMap);\n }\n }\n }", "public void addBasicSentence(MtasCQLParserBasicSentenceCondition s)\n throws ParseException {\n if (!simplified) {\n List<MtasCQLParserBasicSentencePartCondition> newWordList = s\n .getPartList();\n partList.addAll(newWordList);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "public PropertiesEnvelope getUserProperties(String userId, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = getUserPropertiesWithHttpInfo(userId, aid);\n return resp.getData();\n }", "public static synchronized DeckReference getDeckReference(int player, int hotCue) {\n Map<Integer, DeckReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<Integer, DeckReference>();\n instances.put(player, playerMap);\n }\n DeckReference result = playerMap.get(hotCue);\n if (result == null) {\n result = new DeckReference(player, hotCue);\n playerMap.put(hotCue, result);\n }\n return result;\n }", "public static String ptb2Text(String ptbText) {\r\n StringBuilder sb = new StringBuilder(ptbText.length()); // probably an overestimate\r\n PTB2TextLexer lexer = new PTB2TextLexer(new StringReader(ptbText));\r\n try {\r\n for (String token; (token = lexer.next()) != null; ) {\r\n sb.append(token);\r\n }\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n return sb.toString();\r\n }", "public static base_responses add(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 addresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new route6();\n\t\t\t\taddresources[i].network = resources[i].network;\n\t\t\t\taddresources[i].gateway = resources[i].gateway;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].weight = resources[i].weight;\n\t\t\t\taddresources[i].distance = resources[i].distance;\n\t\t\t\taddresources[i].cost = resources[i].cost;\n\t\t\t\taddresources[i].advertise = resources[i].advertise;\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].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}" ]
Reads the detail container resources which are connected by relations to the given resource. @param cms the current CMS context @param res the detail content @return the list of detail only container resources @throws CmsException if something goes wrong
[ "private List<CmsResource> getDetailContainerResources(CmsObject cms, CmsResource res) throws CmsException {\n\n CmsRelationFilter filter = CmsRelationFilter.relationsFromStructureId(res.getStructureId()).filterType(\n CmsRelationType.DETAIL_ONLY);\n List<CmsResource> result = Lists.newArrayList();\n List<CmsRelation> relations = cms.readRelations(filter);\n for (CmsRelation relation : relations) {\n try {\n result.add(relation.getTarget(cms, CmsResourceFilter.ALL));\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return result;\n }" ]
[ "@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\n }", "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 base_response update(nitro_service client, snmpalarm resource) throws Exception {\n\t\tsnmpalarm updateresource = new snmpalarm();\n\t\tupdateresource.trapname = resource.trapname;\n\t\tupdateresource.thresholdvalue = resource.thresholdvalue;\n\t\tupdateresource.normalvalue = resource.normalvalue;\n\t\tupdateresource.time = resource.time;\n\t\tupdateresource.state = resource.state;\n\t\tupdateresource.severity = resource.severity;\n\t\tupdateresource.logging = resource.logging;\n\t\treturn updateresource.update_resource(client);\n\t}", "public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }", "okhttp3.Response delete(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(getFullUrl(url))\n .delete(getBody(toPayload(params), null))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }", "public void remove(Identity oid)\r\n {\r\n if (oid == null) return;\r\n\r\n ObjectCache cache = getCache(oid, null, METHOD_REMOVE);\r\n if (cache != null)\r\n {\r\n cache.remove(oid);\r\n }\r\n }", "public static base_responses delete(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 deleteresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tdeleteresources[i] = new nsacl6();\n\t\t\t\tdeleteresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static double SymmetricChiSquareDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n double den = p[i] * q[i];\n if (den != 0) {\n double p1 = p[i] - q[i];\n double p2 = p[i] + q[i];\n r += (p1 * p1 * p2) / den;\n }\n }\n\n return r;\n }", "@Override\n public void onDismiss(DialogInterface dialog) {\n if (mOldDialog != null && mOldDialog == dialog) {\n // This is the callback from the old progress dialog that was already dismissed before\n // the device orientation change, so just ignore it.\n return;\n }\n super.onDismiss(dialog);\n }" ]
Gets a collection. @param collectionName the name of the collection to return @return the collection
[ "public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }" ]
[ "public AT_CellContext setPadding(int padding){\r\n\t\tif(padding>-1){\r\n\t\t\tthis.paddingTop = padding;\r\n\t\t\tthis.paddingBottom = padding;\r\n\t\t\tthis.paddingLeft = padding;\r\n\t\t\tthis.paddingRight = padding;\r\n\t\t}\r\n\t\treturn this;\r\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 }", "@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }", "public static long raiseToPower(int value, int power)\n {\n if (power < 0)\n {\n throw new IllegalArgumentException(\"This method does not support negative powers.\");\n }\n long result = 1;\n for (int i = 0; i < power; i++)\n {\n result *= value;\n }\n return result;\n }", "@SuppressWarnings(\"checkstyle:illegalcatch\")\n private boolean sendMessage(final byte[] messageToSend) {\n try {\n connectionPool.execute(new PooledObjectConsumer<TcpConnection>() {\n @Override\n public void accept(final TcpConnection tcpConnection) throws IOException {\n tcpConnection.write(messageToSend);\n }\n });\n } catch (final Exception e) {\n addError(String.format(\"Error sending message via tcp://%s:%s\",\n getGraylogHost(), getGraylogPort()), e);\n\n return false;\n }\n\n return true;\n }", "protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(message);\n return violation;\n }", "public void addFieldDescriptor(FieldDescriptor fld)\r\n {\r\n fld.setClassDescriptor(this); // BRJ\r\n if (m_FieldDescriptions == null)\r\n {\r\n m_FieldDescriptions = new FieldDescriptor[1];\r\n m_FieldDescriptions[0] = fld;\r\n }\r\n else\r\n {\r\n int size = m_FieldDescriptions.length;\r\n FieldDescriptor[] tmpArray = new FieldDescriptor[size + 1];\r\n System.arraycopy(m_FieldDescriptions, 0, tmpArray, 0, size);\r\n tmpArray[size] = fld;\r\n m_FieldDescriptions = tmpArray;\r\n // 2. Sort fields according to their getOrder() Property\r\n Arrays.sort(m_FieldDescriptions, FieldDescriptor.getComparator());\r\n }\r\n\r\n m_fieldDescriptorNameMap = null;\r\n m_PkFieldDescriptors = null;\r\n m_nonPkFieldDescriptors = null;\r\n m_lockingFieldDescriptors = null;\r\n m_RwFieldDescriptors = null;\r\n m_RwNonPkFieldDescriptors = null;\r\n }", "static void populateFileCreationRecord(Record record, ProjectProperties properties)\n {\n properties.setMpxProgramName(record.getString(0));\n properties.setMpxFileVersion(FileVersion.getInstance(record.getString(1)));\n properties.setMpxCodePage(record.getCodePage(2));\n }", "public void store(Object obj) throws PersistenceBrokerException\n {\n obj = extractObjectToStore(obj);\n // only do something if obj != null\n if(obj == null) return;\n\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n /*\n if one of the PK fields was null, we assume the objects\n was new and needs insert\n */\n boolean insert = serviceBrokerHelper().hasNullPKField(cld, obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n /*\n if PK values are set, lookup cache or db to see whether object\n needs insert or update\n */\n if (!insert)\n {\n insert = objectCache.lookup(oid) == null\n && !serviceBrokerHelper().doesExist(cld, oid, obj);\n }\n store(obj, oid, cld, insert);\n }" ]
This is needed when running on slaves.
[ "public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {\n MavenProject mavenProject = getMavenProject(f.getAbsolutePath());\n return mavenProject.getModel().getModules();\n }" ]
[ "public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }", "String getQueryString(Map<String, String> params) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\ttry {\n\t\t\tboolean first = true;\n\t\t\tfor (Map.Entry<String,String> entry : params.entrySet()) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tbuilder.append(\"&\");\n\t\t\t\t}\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getKey(), \"UTF-8\"));\n\t\t\t\tbuilder.append(\"=\");\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getValue(), \"UTF-8\"));\n\t\t\t}\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Your Java version does not support UTF-8 encoding.\");\n\t\t}\n\n\t\treturn builder.toString();\n\t}", "public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}", "private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }", "public ItemRequest<ProjectMembership> findById(String projectMembership) {\n \n String path = String.format(\"/project_memberships/%s\", projectMembership);\n return new ItemRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }", "public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }", "public static int serialize(OutputStream stream, Object obj) {\n ObjectMapper mapper = createMapperWithJaxbAnnotationInspector();\n\n try (DataOutputStream data = new DataOutputStream(stream);\n OutputStreamWriter writer = new OutputStreamWriter(data, StandardCharsets.UTF_8)) {\n mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj);\n return data.size();\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }", "public int getLeadingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong front = network ? getDivision(0).getMaxValue() : 0;\n\t\tint prefixLen = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != front) {\n\t\t\t\treturn prefixLen + seg.getLeadingBitCount(network);\n\t\t\t}\n\t\t\tprefixLen += seg.getBitCount();\n\t\t}\n\t\treturn prefixLen;\n\t}", "private static XMLStreamException unexpectedAttribute(final XMLStreamReader reader, final int index) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedAttribute(reader.getAttributeName(index), reader.getLocation());\n }" ]
Build call for getCharactersCharacterIdShip @param characterId An EVE character ID (required) @param datasource The server name you would like data from (optional, default to tranquility) @param ifNoneMatch ETag from a previous request. A 304 will be returned if this matches the current ETag (optional) @param token Access token to use if unable to set a header (optional) @param callback Callback for upload/download progress @return Call to execute @throws ApiException If fail to serialize the request body object
[ "public com.squareup.okhttp.Call getCharactersCharacterIdShipCall(Integer characterId, String datasource,\n String ifNoneMatch, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v1/characters/{character_id}/ship/\".replaceAll(\"\\\\{\" + \"character_id\" + \"\\\\}\",\n apiClient.escapeString(characterId.toString()));\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n if (ifNoneMatch != null) {\n localVarHeaderParams.put(\"If-None-Match\", apiClient.parameterToString(ifNoneMatch));\n }\n\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = { \"application/json\" };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"GET\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }" ]
[ "@RequestMapping(value = \"api/edit/disable\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);\n //TODO also need to disable custom override if there is one of those\n editService.removeCustomOverride(path_id, clientUUID);\n\n return null;\n }", "@Override\n public synchronized void start() {\n if (!started.getAndSet(true)) {\n finished.set(false);\n thread.start();\n }\n }", "public static tunnelip_stats[] get(nitro_service service) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\ttunnelip_stats[] response = (tunnelip_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "protected B fields(List<F> fields) {\n if (instance.def.fields == null) {\n instance.def.fields = new ArrayList<F>(fields.size());\n }\n instance.def.fields.addAll(fields);\n return returnThis();\n }", "public static FormValidation validateArtifactoryCombinationFilter(String value)\n throws IOException, InterruptedException {\n String url = Util.fixEmptyAndTrim(value);\n if (url == null)\n return FormValidation.error(\"Mandatory field - You don`t have any deploy matches\");\n\n return FormValidation.ok();\n }", "public void setMeta(String photoId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_META);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\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 EventType map(Event event) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(event.getTimestamp()));\n eventType.setEventType(convertEventType(event.getEventType()));\n OriginatorType origType = mapOriginator(event.getOriginator());\n eventType.setOriginator(origType);\n MessageInfoType miType = mapMessageInfo(event.getMessageInfo());\n eventType.setMessageInfo(miType);\n eventType.setCustomInfo(convertCustomInfo(event.getCustomInfo()));\n eventType.setContentCut(event.isContentCut());\n if (event.getContent() != null) {\n DataHandler datHandler = getDataHandlerForString(event);\n eventType.setContent(datHandler);\n }\n return eventType;\n }", "private void readException(ProjectCalendar bc, Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Date fromDate = exception.getTimePeriod().getFromDate();\n Date toDate = exception.getTimePeriod().getToDate();\n\n // Vico Schedule Planner seems to write start and end dates to FromTime and ToTime\n // rather than FromDate and ToDate. This is plain wrong, and appears to be ignored by MS Project\n // so we will ignore it too!\n if (fromDate != null && toDate != null)\n {\n ProjectCalendarException bce = bc.addCalendarException(fromDate, toDate);\n bce.setName(exception.getName());\n readRecurringData(bce, exception);\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = exception.getWorkingTimes();\n if (times != null)\n {\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n bce.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }", "public static Object getFieldValue(Object object, String fieldName) {\n try {\n return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }" ]
Remove custom overrides @param path_id ID of path containing custom override @param client_uuid UUID of the client @throws Exception exception
[ "public void removeCustomOverride(int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"custom_response\", \"\", getProfileIdFromPathID(path_id), client_uuid, path_id);\n }" ]
[ "public static 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 String getPrototypeName() {\n\t\tString name = getClass().getName();\n\t\tif (name.startsWith(ORG_GEOMAJAS)) {\n\t\t\tname = name.substring(ORG_GEOMAJAS.length());\n\t\t}\n\t\tname = name.replace(\".dto.\", \".impl.\");\n\t\treturn name.substring(0, name.length() - 4) + \"Impl\";\n\t}", "protected final StyleSupplier<FeatureSource> createStyleFunction(\n final Template template,\n final String styleString) {\n return new StyleSupplier<FeatureSource>() {\n @Override\n public Style load(\n final MfClientHttpRequestFactory requestFactory,\n final FeatureSource featureSource) {\n if (featureSource == null) {\n throw new IllegalArgumentException(\"Feature source cannot be null\");\n }\n\n final String geomType = featureSource.getSchema() == null ?\n Geometry.class.getSimpleName().toLowerCase() :\n featureSource.getSchema().getGeometryDescriptor().getType().getBinding()\n .getSimpleName();\n final String styleRef = styleString != null ? styleString : geomType;\n\n final StyleParser styleParser = AbstractFeatureSourceLayerPlugin.this.parser;\n return OptionalUtils.or(\n () -> template.getStyle(styleRef),\n () -> styleParser.loadStyle(template.getConfiguration(), requestFactory, styleRef))\n .orElseGet(() -> template.getConfiguration().getDefaultStyle(geomType));\n }\n };\n }", "public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }", "public ItemRequest<Workspace> addUser(String workspace) {\n \n String path = String.format(\"/workspaces/%s/addUser\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"POST\");\n }", "private void initHasMasterMode() throws CmsException {\n\n if (hasDescriptor()\n && m_cms.hasPermissions(m_desc, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {\n m_hasMasterMode = true;\n } else {\n m_hasMasterMode = false;\n }\n }", "public static byte[] copy(byte[] array, int from, int to) {\n if(to - from < 0) {\n return new byte[0];\n } else {\n byte[] a = new byte[to - from];\n System.arraycopy(array, from, a, 0, to - from);\n return a;\n }\n }", "public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }", "static Style get(final GridParam params) {\n final StyleBuilder builder = new StyleBuilder();\n\n final Symbolizer pointSymbolizer = crossSymbolizer(\"shape://plus\", builder, CROSS_SIZE,\n params.gridColor);\n final Style style = builder.createStyle(pointSymbolizer);\n final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();\n\n if (params.haloRadius > 0.0) {\n Symbolizer halo = crossSymbolizer(\"cross\", builder, CROSS_SIZE + params.haloRadius * 2.0,\n params.haloColor);\n symbolizers.add(0, halo);\n }\n\n return style;\n }" ]
Returns an iterator over the items in this folder. @return an iterator over the items in this folder.
[ "@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxFolder.this.getID());\n return new BoxItemIterator(BoxFolder.this.getAPI(), url);\n }" ]
[ "public static void main(String[] args) {\r\n TreebankLanguagePack tlp = new PennTreebankLanguagePack();\r\n System.out.println(\"Start symbol: \" + tlp.startSymbol());\r\n String start = tlp.startSymbol();\r\n System.out.println(\"Should be true: \" + (tlp.isStartSymbol(start)));\r\n String[] strs = {\"-\", \"-LLB-\", \"NP-2\", \"NP=3\", \"NP-LGS\", \"NP-TMP=3\"};\r\n for (String str : strs) {\r\n System.out.println(\"String: \" + str + \" basic: \" + tlp.basicCategory(str) + \" basicAndFunc: \" + tlp.categoryAndFunction(str));\r\n }\r\n }", "private boolean getRelative(int value)\n {\n boolean result;\n if (value < 0 || value >= RELATIVE_MAP.length)\n {\n result = false;\n }\n else\n {\n result = RELATIVE_MAP[value];\n }\n\n return result;\n }", "public static void append(File file, Object text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file, true);\n if (!file.exists()) {\n writeUTF16BomIfRequired(charset, out);\n }\n writer = new OutputStreamWriter(out, charset);\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "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 }", "public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}", "public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }", "public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }", "public BufferedImage getBufferedImage(int width, int height) {\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, width, height, null);\n g2d.dispose();\n return (buf);\n }", "private byte[] getData(List<byte[]> blocks, int length)\n {\n byte[] result;\n\n if (blocks.isEmpty() == false)\n {\n if (length < 4)\n {\n length = 4;\n }\n\n result = new byte[length];\n int offset = 0;\n byte[] data;\n\n while (offset < length)\n {\n data = blocks.remove(0);\n System.arraycopy(data, 0, result, offset, data.length);\n offset += data.length;\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }" ]
Log column data. @param column column data
[ "private void logColumn(FastTrackColumn column)\n {\n if (m_log != null)\n {\n m_log.println(\"TABLE: \" + m_currentTable.getType());\n m_log.println(column.toString());\n m_log.flush();\n }\n }" ]
[ "public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{\n DFAgentDescription dfd = new DFAgentDescription();\n ServiceDescription sd = new ServiceDescription();\n \n sd.setType(serviceType);\n sd.setName(serviceName);\n \n //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. \n // He escogido crear nombres en clave en jade.common.Definitions para este campo. \n //NOTE El serviceName es el nombre efectivo del servicio. \n // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. \n // sd.setType(agentType);\n // sd.setName(agent.getLocalName());\n \n //Add services??\n \n // Sets the agent description\n dfd.setName(agent.getAID());\n dfd.addServices(sd);\n \n // Register the agent\n DFService.register(agent, dfd);\n }", "protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }", "private void readTable(InputStream is, SynchroTable table) throws IOException\n {\n int skip = table.getOffset() - m_offset;\n if (skip != 0)\n {\n StreamHelper.skip(is, skip);\n m_offset += skip;\n }\n\n String tableName = DatatypeConverter.getString(is);\n int tableNameLength = 2 + tableName.length();\n m_offset += tableNameLength;\n\n int dataLength;\n if (table.getLength() == -1)\n {\n dataLength = is.available();\n }\n else\n {\n dataLength = table.getLength() - tableNameLength;\n }\n\n SynchroLogger.log(\"READ\", tableName);\n\n byte[] compressedTableData = new byte[dataLength];\n is.read(compressedTableData);\n m_offset += dataLength;\n\n Inflater inflater = new Inflater();\n inflater.setInput(compressedTableData);\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedTableData.length);\n byte[] buffer = new byte[1024];\n while (!inflater.finished())\n {\n int count;\n\n try\n {\n count = inflater.inflate(buffer);\n }\n catch (DataFormatException ex)\n {\n throw new IOException(ex);\n }\n outputStream.write(buffer, 0, count);\n }\n outputStream.close();\n byte[] uncompressedTableData = outputStream.toByteArray();\n\n SynchroLogger.log(uncompressedTableData);\n\n m_tableData.put(table.getName(), uncompressedTableData);\n }", "public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }", "public void checkSpecialization() {\n if (isSpecializing()) {\n boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);\n String previousSpecializedBeanName = null;\n for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {\n String name = specializedBean.getName();\n if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {\n // there may be multiple beans specialized by this bean - make sure they all share the same name\n throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);\n }\n previousSpecializedBeanName = name;\n if (isNameDefined && name != null) {\n throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());\n }\n\n // When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are\n // added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among\n // these types are NOT types of the specializing bean (that's the way java works)\n boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>\n && specializedBean.getBeanClass().getTypeParameters().length > 0\n && !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));\n for (Type specializedType : specializedBean.getTypes()) {\n if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n boolean contains = getTypes().contains(specializedType);\n if (!contains) {\n for (Type specializingType : getTypes()) {\n // In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be\n // equal in the java sense. Therefore we have to use our own equality util.\n if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {\n contains = true;\n break;\n }\n }\n }\n if (!contains) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n }\n }\n }\n }", "private void appendJoin(StringBuffer where, StringBuffer buf, Join join)\r\n {\r\n buf.append(\",\");\r\n appendTableWithJoins(join.right, where, buf);\r\n if (where.length() > 0)\r\n {\r\n where.append(\" AND \");\r\n }\r\n join.appendJoinEqualities(where);\r\n }", "public void requestNodeInfo(int nodeId) {\n\t\tSerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.RequestNodeInfo, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationUpdate, SerialMessage.SerialMessagePriority.High);\n \tbyte[] newPayload = { (byte) nodeId };\n \tnewMessage.setMessagePayload(newPayload);\n \tthis.enqueue(newMessage);\n\t}", "private void RunScript(InteractiveObject interactiveObject, String functionName, Object[] parameters) {\n boolean complete = false;\n if ( V8JavaScriptEngine) {\n GVRJavascriptV8File gvrJavascriptV8File = interactiveObject.getScriptObject().getGVRJavascriptV8File();\n String paramString = \"var params =[\";\n for (int i = 0; i < parameters.length; i++ ) {\n paramString += (parameters[i] + \", \");\n }\n paramString = paramString.substring(0, (paramString.length()-2)) + \"];\";\n\n final GVRJavascriptV8File gvrJavascriptV8FileFinal = gvrJavascriptV8File;\n final InteractiveObject interactiveObjectFinal = interactiveObject;\n final String functionNameFinal = functionName;\n final Object[] parametersFinal = parameters;\n final String paramStringFinal = paramString;\n gvrContext.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n RunScriptThread (gvrJavascriptV8FileFinal, interactiveObjectFinal, functionNameFinal, parametersFinal, paramStringFinal);\n }\n });\n } // end V8JavaScriptEngine\n else {\n // Mozilla Rhino engine\n GVRJavascriptScriptFile gvrJavascriptFile = interactiveObject.getScriptObject().getGVRJavascriptScriptFile();\n\n complete = gvrJavascriptFile.invokeFunction(functionName, parameters);\n if (complete) {\n // The JavaScript (JS) ran. Now get the return\n // values (saved as X3D data types such as SFColor)\n // stored in 'localBindings'.\n // Then call SetResultsFromScript() to set the GearVR values\n Bindings localBindings = gvrJavascriptFile.getLocalBindings();\n SetResultsFromScript(interactiveObject, localBindings);\n } else {\n Log.e(TAG, \"Error in SCRIPT node '\" + interactiveObject.getScriptObject().getName() +\n \"' running Rhino Engine JavaScript function '\" + functionName + \"'\");\n }\n }\n }", "private long getTotalTime(ProjectCalendarDateRanges exception)\n {\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd());\n }\n return (total);\n }" ]
Write a string field to the JSON file. @param fieldName field name @param value field value
[ "private void writeStringField(String fieldName, Object value) throws IOException\n {\n String val = value.toString();\n if (!val.isEmpty())\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }" ]
[ "private static I_CmsResourceBundle tryBundle(String localizedName) {\n\n I_CmsResourceBundle result = null;\n\n try {\n\n String resourceName = localizedName.replace('.', '/') + \".properties\";\n URL url = CmsResourceBundleLoader.class.getClassLoader().getResource(resourceName);\n\n I_CmsResourceBundle additionalBundle = m_permanentCache.get(localizedName);\n if (additionalBundle != null) {\n result = additionalBundle.getClone();\n } else if (url != null) {\n // the resource was found on the file system\n InputStream is = null;\n String path = CmsFileUtil.normalizePath(url);\n File file = new File(path);\n try {\n // try to load the resource bundle from a file, NOT with the resource loader first\n // this is important since using #getResourceAsStream() may return cached results,\n // for example Tomcat by default does cache all resources loaded by the class loader\n // this means a changed resource bundle file is not loaded\n is = new FileInputStream(file);\n } catch (IOException ex) {\n // this will happen if the resource is contained for example in a .jar file\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n } catch (AccessControlException acex) {\n // fixed bug #1550\n // this will happen if the resource is contained for example in a .jar file\n // and security manager is turned on.\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n }\n if (is != null) {\n result = new CmsPropertyResourceBundle(is);\n }\n }\n } catch (IOException ex) {\n // can't localized these message since this may lead to a chicken-egg problem\n MissingResourceException mre = new MissingResourceException(\n \"Failed to load bundle '\" + localizedName + \"'\",\n localizedName,\n \"\");\n mre.initCause(ex);\n throw mre;\n }\n\n return result;\n }", "public static WidgetLib init(GVRContext gvrContext, String customPropertiesAsset)\n throws InterruptedException, JSONException, NoSuchMethodException {\n if (mInstance == null) {\n // Constructor sets mInstance to ensure the initialization order\n new WidgetLib(gvrContext, customPropertiesAsset);\n }\n return mInstance.get();\n }", "public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) {\n\n\t\t/*\n\t\t * Cacluate average log returns\n\t\t */\n\t\tdouble[] averageLogReturn = new double[12];\n\t\tArrays.fill(averageLogReturn, 0.0);\n\t\tfor(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){\n\n\t\t\tint month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12));\n\n\t\t\tdouble logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]);\n\t\t\taverageLogReturn[month] += logReturn/numberOfYearsToAverage;\n\t\t}\n\n\t\t/*\n\t\t * Normalize\n\t\t */\n\t\tdouble sum = 0.0;\n\t\tfor(int index = 0; index < averageLogReturn.length; index++){\n\t\t\tsum += averageLogReturn[index];\n\t\t}\n\t\tdouble averageSeasonal = sum / averageLogReturn.length;\n\n\t\tdouble[] seasonalAdjustments = new double[averageLogReturn.length];\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal;\n\t\t}\n\n\t\t// Annualize seasonal adjustments\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = seasonalAdjustments[index] * 12;\n\t\t}\n\n\t\treturn seasonalAdjustments;\n\t}", "private String getValueFromProp(final String propValue) {\n\n String value = propValue;\n // remove quotes\n value = value.trim();\n if ((value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.substring(1, value.length() - 1);\n }\n return value;\n }", "public History[] refreshHistory(int limit, int offset) throws Exception {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"limit\", String.valueOf(limit)),\n new BasicNameValuePair(\"offset\", String.valueOf(offset))\n };\n return constructHistory(params);\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 }", "@SuppressWarnings(\"serial\")\n private Button createSaveExitButton() {\n\n Button saveExitBtn = CmsToolBar.createButton(\n FontOpenCms.SAVE_EXIT,\n m_messages.key(Messages.GUI_BUTTON_SAVE_AND_EXIT_0));\n saveExitBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n saveAction();\n closeAction();\n\n }\n });\n saveExitBtn.setEnabled(false);\n return saveExitBtn;\n }", "public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public static void acceptsUrlMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"coordinator bootstrap urls\")\n .withRequiredArg()\n .describedAs(\"url-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }" ]
An invalid reference or references. The verification of the digest of a reference failed. This can be caused by a change to the referenced data since the signature was generated. @param aInvalidReferences The indices to the invalid references. @return Result object
[ "@Nonnull\n public static XMLDSigValidationResult createReferenceErrors (@Nonnull @Nonempty final List <Integer> aInvalidReferences)\n {\n return new XMLDSigValidationResult (aInvalidReferences);\n }" ]
[ "private Collection parseCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n collection.setId(collectionElement.getAttribute(\"id\"));\n collection.setServer(collectionElement.getAttribute(\"server\"));\n collection.setSecret(collectionElement.getAttribute(\"secret\"));\n collection.setChildCount(collectionElement.getAttribute(\"child_count\"));\n collection.setIconLarge(collectionElement.getAttribute(\"iconlarge\"));\n collection.setIconSmall(collectionElement.getAttribute(\"iconsmall\"));\n collection.setDateCreated(collectionElement.getAttribute(\"datecreate\"));\n collection.setTitle(XMLUtilities.getChildValue(collectionElement, \"title\"));\n collection.setDescription(XMLUtilities.getChildValue(collectionElement, \"description\"));\n\n Element iconPhotos = XMLUtilities.getChild(collectionElement, \"iconphotos\");\n if (iconPhotos != null) {\n NodeList photoElements = iconPhotos.getElementsByTagName(\"photo\");\n for (int i = 0; i < photoElements.getLength(); i++) {\n Element photoElement = (Element) photoElements.item(i);\n collection.addPhoto(PhotoUtils.createPhoto(photoElement));\n }\n }\n\n return collection;\n }", "@RequestMapping(value = \"/api/backup\", method = RequestMethod.POST)\n public\n @ResponseBody\n Backup processBackup(@RequestParam(\"fileData\") MultipartFile fileData) throws Exception {\n // Method taken from: http://spring.io/guides/gs/uploading-files/\n if (!fileData.isEmpty()) {\n try {\n byte[] bytes = fileData.getBytes();\n BufferedOutputStream stream =\n new BufferedOutputStream(new FileOutputStream(new File(\"backup-uploaded.json\")));\n stream.write(bytes);\n stream.close();\n\n } catch (Exception e) {\n }\n }\n File f = new File(\"backup-uploaded.json\");\n BackupService.getInstance().restoreBackupData(new FileInputStream(f));\n return BackupService.getInstance().getBackupData();\n }", "public Duration getFinishVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.FINISH_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineFinish(), getFinish(), format);\n set(AssignmentField.FINISH_VARIANCE, variance);\n }\n return (variance);\n }", "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getPluginInformation() {\n return pluginInformation();\n }", "public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n\n boolean suppressLoad = false;\n ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy();\n final boolean isReloaded = environment.getRunningModeControl().isReloaded();\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) {\n throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName());\n }\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) {\n suppressLoad = true;\n }\n\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"domain\"), domainXml, domainXml, suppressLoad);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"domain\"), domainXml);\n }\n }\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }", "public ProjectCalendarWeek addWorkWeek()\n {\n ProjectCalendarWeek week = new ProjectCalendarWeek();\n week.setParent(this);\n m_workWeeks.add(week);\n m_weeksSorted = false;\n clearWorkingDateCache();\n return week;\n }", "public static BoxLegalHoldPolicy.Info createOngoing(BoxAPIConnection api, String name, String description) {\n URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_name\", name)\n .add(\"is_ongoing\", true);\n if (description != null) {\n requestJSON.add(\"description\", description);\n }\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldPolicy createdPolicy = new BoxLegalHoldPolicy(api, responseJSON.get(\"id\").asString());\n return createdPolicy.new Info(responseJSON);\n }", "public ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {\n Objects.requireNonNull(rateTypes);\n if (rateTypes.isEmpty()) {\n throw new IllegalArgumentException(\"At least one RateType is required.\");\n }\n Set<RateType> rtSet = new HashSet<>(rateTypes);\n set(ProviderContext.KEY_RATE_TYPES, rtSet);\n return this;\n }", "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}" ]
Get the ordinal value for the last of a particular override on a path @param overrideId Id of the override to check @param pathId Path the override is on @param clientUUID UUID of the client @param filters If supplied, only endpoints ending with values in filters are returned @return The integer ordinal @throws Exception
[ "public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }" ]
[ "public static sslciphersuite[] get(nitro_service service, options option) throws Exception{\n\t\tsslciphersuite obj = new sslciphersuite();\n\t\tsslciphersuite[] response = (sslciphersuite[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)\r\n {\r\n IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());\r\n\r\n if (indexDef == null)\r\n {\r\n indexDef = new IndexDef(indexDescDef.getName(),\r\n indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));\r\n tableDef.addIndex(indexDef);\r\n }\r\n\r\n try\r\n {\r\n String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n }\r\n catch (NoSuchFieldException ex)\r\n {\r\n // won't happen if we already checked the constraints\r\n }\r\n }", "public Jar setJarPrefix(Path file) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (file != null && jarPrefixStr != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixStr + \")\");\n this.jarPrefixFile = file;\n return this;\n }", "public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private boolean checkTagAndParam(XDoc doc, String tagName, String paramName, String paramValue)\r\n {\r\n if (tagName == null) {\r\n return true;\r\n }\r\n if (!doc.hasTag(tagName)) {\r\n return false;\r\n }\r\n if (paramName == null) {\r\n return true;\r\n }\r\n if (!doc.getTag(tagName).getAttributeNames().contains(paramName)) {\r\n return false;\r\n }\r\n return (paramValue == null) || paramValue.equals(doc.getTagAttributeValue(tagName, paramName));\r\n }", "public static systemcollectionparam get(nitro_service service) throws Exception{\n\t\tsystemcollectionparam obj = new systemcollectionparam();\n\t\tsystemcollectionparam[] response = (systemcollectionparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }", "public static appfwprofile_denyurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_denyurl_binding obj = new appfwprofile_denyurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_denyurl_binding response[] = (appfwprofile_denyurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void deleteObject(Object object)\r\n {\r\n PersistenceBroker broker = null;\r\n try\r\n {\r\n broker = getBroker();\r\n broker.delete(object);\r\n }\r\n finally\r\n {\r\n if (broker != null) broker.close();\r\n }\r\n }" ]
Get the deferred flag. Exchange rates can be deferred or real.time. @return the deferred flag, or {code null}.
[ "public Set<RateType> getRateTypes() {\n @SuppressWarnings(\"unchecked\")\n Set<RateType> rateSet = get(KEY_RATE_TYPES, Set.class);\n if (rateSet == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(rateSet);\n }" ]
[ "public String getMethodSignature() {\n if (method != null) {\n String methodSignature = method.toString();\n return methodSignature.replaceFirst(\"public void \", \"\");\n }\n return null;\n }", "private static int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }", "public Widget addControl(String name, int resId, Widget.OnTouchListener listener) {\n return addControl(name, resId, null, listener, -1);\n }", "public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }", "public CmsContextMenu getContextMenuForItem(Object itemId) {\n\n CmsContextMenu result = null;\n try {\n final Item item = m_container.getItem(itemId);\n Property<?> keyProp = item.getItemProperty(TableProperty.KEY);\n String key = (String)keyProp.getValue();\n if ((null != key) && !key.isEmpty()) {\n loadAllRemainingLocalizations();\n final Map<Locale, String> localesWithEntries = new HashMap<Locale, String>();\n for (Locale l : m_localizations.keySet()) {\n if (l != m_locale) {\n String value = m_localizations.get(l).getProperty(key);\n if ((null != value) && !value.isEmpty()) {\n localesWithEntries.put(l, value);\n }\n }\n }\n if (!localesWithEntries.isEmpty()) {\n result = new CmsContextMenu();\n ContextMenuItem mainItem = result.addItem(\n Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n Messages.GUI_BUNDLE_EDITOR_CONTEXT_COPY_LOCALE_0));\n for (final Locale l : localesWithEntries.keySet()) {\n\n ContextMenuItem menuItem = mainItem.addItem(l.getDisplayName(UI.getCurrent().getLocale()));\n menuItem.addItemClickListener(new ContextMenuItemClickListener() {\n\n public void contextMenuItemClicked(ContextMenuItemClickEvent event) {\n\n item.getItemProperty(TableProperty.TRANSLATION).setValue(localesWithEntries.get(l));\n\n }\n });\n }\n }\n }\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n //TODO: Improve\n }\n return result;\n }", "public void addArtifact(final Artifact artifact) {\n if (!artifacts.contains(artifact)) {\n if (promoted) {\n artifact.setPromoted(promoted);\n }\n\n artifacts.add(artifact);\n }\n }", "private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }", "protected void setProperty(String propertyName, JavascriptEnum propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getEnumValue());\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}" ]
Get the bean if it exists in the contexts. @return An instance of the bean @throws ContextNotActiveException if the context is not active @see javax.enterprise.context.spi.Context#get(BaseBean, boolean)
[ "@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 }" ]
[ "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "public static void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }", "protected void rehash(int newCapacity) {\r\n\tint oldCapacity = table.length;\r\n\t//if (oldCapacity == newCapacity) return;\r\n\t\r\n\tlong oldTable[] = table;\r\n\tint oldValues[] = values;\r\n\tbyte oldState[] = state;\r\n\r\n\tlong newTable[] = new long[newCapacity];\r\n\tint newValues[] = new int[newCapacity];\r\n\tbyte newState[] = new byte[newCapacity];\r\n\r\n\tthis.lowWaterMark = chooseLowWaterMark(newCapacity,this.minLoadFactor);\r\n\tthis.highWaterMark = chooseHighWaterMark(newCapacity,this.maxLoadFactor);\r\n\r\n\tthis.table = newTable;\r\n\tthis.values = newValues;\r\n\tthis.state = newState;\r\n\tthis.freeEntries = newCapacity-this.distinct; // delta\r\n\t\r\n\tfor (int i = oldCapacity ; i-- > 0 ;) {\r\n\t\tif (oldState[i]==FULL) {\r\n\t\t\tlong element = oldTable[i];\r\n\t\t\tint index = indexOfInsertion(element);\r\n\t\t\tnewTable[index]=element;\r\n\t\t\tnewValues[index]=oldValues[i];\r\n\t\t\tnewState[index]=FULL;\r\n\t\t}\r\n\t}\r\n}", "public <T> T convert(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\ttry {\r\n\t\t\treturn (T) multiConverter.convert(context, source, destinationType);\r\n\t\t} catch (ConverterException e) {\r\n\t\t\tthrow e;\r\n\t\t} catch (Exception e) {\r\n\t\t\t// There is a problem with one converter. This should not happen.\r\n\t\t\t// Either there is a bug in this converter or it is not properly\r\n\t\t\t// configured\r\n\t\t\tthrow new ConverterException(\r\n\t\t\t\t\tMessageFormat\r\n\t\t\t\t\t\t\t.format(\r\n\t\t\t\t\t\t\t\t\t\"Could not convert given object with class ''{0}'' to object with type signature ''{1}''\",\r\n\t\t\t\t\t\t\t\t\tsource == null ? \"null\" : source.getClass()\r\n\t\t\t\t\t\t\t\t\t\t\t.getName(), destinationType), e);\r\n\t\t}\r\n\t}", "public Excerpt typeParameters() {\n if (getTypeParameters().isEmpty()) {\n return Excerpts.EMPTY;\n } else {\n return Excerpts.add(\"<%s>\", Excerpts.join(\", \", getTypeParameters()));\n }\n }", "public <T> T find(Class<T> classType, String id, String rev) {\n assertNotEmpty(classType, \"Class\");\n assertNotEmpty(id, \"id\");\n assertNotEmpty(id, \"rev\");\n final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, \"rev\", rev);\n return couchDbClient.get(uri, classType);\n }", "public void animate(float timeInSec)\n {\n GVRSkeleton skel = getSkeleton();\n GVRPose pose = skel.getPose();\n computePose(timeInSec,pose);\n skel.poseToBones();\n skel.updateBonePose();\n skel.updateSkinPose();\n }", "public static clusterinstance get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance response = (clusterinstance) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }" ]
Use this API to add dnsview.
[ "public static base_response add(nitro_service client, dnsview resource) throws Exception {\n\t\tdnsview addresource = new dnsview();\n\t\taddresource.viewname = resource.viewname;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "@SuppressWarnings(\"unchecked\")\n\t/* @Nullable */\n\tpublic <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\t\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\treturn (T) f.get(receiver);\n\t}", "private void countCoordinateStatement(Statement statement,\n\t\t\tItemDocument itemDocument) {\n\t\tValue value = statement.getValue();\n\t\tif (!(value instanceof GlobeCoordinatesValue)) {\n\t\t\treturn;\n\t\t}\n\n\t\tGlobeCoordinatesValue coordsValue = (GlobeCoordinatesValue) value;\n\t\tif (!this.globe.equals((coordsValue.getGlobe()))) {\n\t\t\treturn;\n\t\t}\n\n\t\tint xCoord = (int) (((coordsValue.getLongitude() + 180.0) / 360.0) * this.width)\n\t\t\t\t% this.width;\n\t\tint yCoord = (int) (((coordsValue.getLatitude() + 90.0) / 180.0) * this.height)\n\t\t\t\t% this.height;\n\n\t\tif (xCoord < 0 || yCoord < 0 || xCoord >= this.width\n\t\t\t\t|| yCoord >= this.height) {\n\t\t\tSystem.out.println(\"Dropping out-of-range coordinate: \"\n\t\t\t\t\t+ coordsValue);\n\t\t\treturn;\n\t\t}\n\n\t\tcountCoordinates(xCoord, yCoord, itemDocument);\n\t\tthis.count += 1;\n\n\t\tif (this.count % 100000 == 0) {\n\t\t\treportProgress();\n\t\t\twriteImages();\n\t\t}\n\t}", "public static List<ContentRepositoryElement> listFiles(final Path rootPath, Path tempDir, final ContentFilter filter) throws IOException {\n List<ContentRepositoryElement> result = new ArrayList<>();\n if (Files.exists(rootPath)) {\n if(isArchive(rootPath)) {\n return listZipContent(rootPath, filter);\n }\n Files.walkFileTree(rootPath, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (filter.acceptFile(rootPath, file)) {\n result.add(ContentRepositoryElement.createFile(formatPath(rootPath.relativize(file)), Files.size(file)));\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n if (filter.acceptDirectory(rootPath, dir)) {\n String directoryPath = formatDirectoryPath(rootPath.relativize(dir));\n if(! \"/\".equals(directoryPath)) {\n result.add(ContentRepositoryElement.createFolder(directoryPath));\n }\n }\n return FileVisitResult.CONTINUE;\n }\n\n private String formatDirectoryPath(Path path) {\n return formatPath(path) + '/';\n }\n\n private String formatPath(Path path) {\n return path.toString().replace(File.separatorChar, '/');\n }\n });\n } else {\n Path file = getFile(rootPath);\n if(isArchive(file)) {\n Path relativePath = file.relativize(rootPath);\n Path target = createTempDirectory(tempDir, \"unarchive\");\n unzip(file, target);\n return listFiles(target.resolve(relativePath), tempDir, filter);\n } else {\n throw new FileNotFoundException(rootPath.toString());\n }\n }\n return result;\n }", "public String addPostRunDependent(FunctionalTaskItem dependent) {\n Objects.requireNonNull(dependent);\n return this.taskGroup().addPostRunDependent(dependent);\n }", "public static aaauser_vpntrafficpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_vpntrafficpolicy_binding obj = new aaauser_vpntrafficpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_vpntrafficpolicy_binding response[] = (aaauser_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public PayloadBuilder sound(final String sound) {\n if (sound != null) {\n aps.put(\"sound\", sound);\n } else {\n aps.remove(\"sound\");\n }\n return this;\n }", "private int cleanupSegmentsToMaintainSize(final Log log) throws IOException {\n if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0;\n\n List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() {\n\n long diff = log.size() - logRetentionSize;\n\n public boolean filter(LogSegment segment) {\n diff -= segment.size();\n return diff >= 0;\n }\n });\n return deleteSegments(log, toBeDeleted);\n }", "synchronized void stop(Integer timeout) {\n final InternalState required = this.requiredState;\n if(required != InternalState.STOPPED) {\n this.requiredState = InternalState.STOPPED;\n ROOT_LOGGER.stoppingServer(serverName);\n // Only send the stop operation if the server is started\n if (internalState == InternalState.SERVER_STARTED) {\n internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);\n } else {\n transition(false);\n }\n }\n }", "protected String failMsg(final Throwable thrwbl, final String queue, final Job job) throws IOException {\n final JobFailure failure = new JobFailure();\n failure.setFailedAt(new Date());\n failure.setWorker(this.name);\n failure.setQueue(queue);\n failure.setPayload(job);\n failure.setThrowable(thrwbl);\n return ObjectMapperFactory.get().writeValueAsString(failure);\n }" ]
Gets the Jaccard distance between two points. @param p A point in space. @param q A point in space. @return The Jaccard distance between x and y.
[ "public static double JaccardDistance(double[] p, double[] q) {\n double distance = 0;\n int intersection = 0, union = 0;\n\n for (int x = 0; x < p.length; x++) {\n if ((p[x] != 0) || (q[x] != 0)) {\n if (p[x] == q[x]) {\n intersection++;\n }\n\n union++;\n }\n }\n\n if (union != 0)\n distance = 1.0 - ((double) intersection / (double) union);\n else\n distance = 0;\n\n return distance;\n }" ]
[ "@Override\r\n public void putAll(Map<? extends K, ? extends V> in) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n temp.putAll(in);\r\n map = temp;\r\n }\r\n } else {\r\n synchronized (map) {\r\n map.putAll(in);\r\n }\r\n }\r\n }", "public void start() {\n syncLock.lock();\n try {\n if (!this.isConfigured) {\n return;\n }\n instanceChangeStreamListener.stop();\n if (listenersEnabled) {\n instanceChangeStreamListener.start();\n }\n\n if (syncThread == null) {\n syncThread = new Thread(\n new DataSynchronizerRunner(\n new WeakReference<>(this),\n networkMonitor,\n logger\n ),\n \"dataSynchronizerRunnerThread\"\n );\n }\n if (syncThreadEnabled && !isRunning) {\n syncThread.start();\n isRunning = true;\n }\n } finally {\n syncLock.unlock();\n }\n }", "public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }", "protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}", "public ItemRequest<Tag> update(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"PUT\");\n }", "private void readResources(Document cdp)\n {\n for (Document.Resources.Resource resource : cdp.getResources().getResource())\n {\n readResource(resource);\n }\n }", "@SafeVarargs\n public static <T> Set<T> of(T... elements) {\n Preconditions.checkNotNull(elements);\n return ImmutableSet.<T> builder().addAll(elements).build();\n }", "public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags)\n {\n boolean includeTagsEnabled = !includeTags.isEmpty();\n\n for (String tag : tags)\n {\n boolean isIncluded = includeTags.contains(tag);\n boolean isExcluded = excludeTags.contains(tag);\n\n if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded))\n {\n return true;\n }\n }\n\n return false;\n }", "public static dospolicy[] get(nitro_service service) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tdospolicy[] response = (dospolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Register an active operation with a specific operation id. @param id the operation id @param attachment the shared attachment @param callback the completed callback @return the created active operation @throws java.lang.IllegalStateException if an operation with the same id is already registered
[ "protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) {\n lock.lock();\n try {\n // Check that we still allow registration\n // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses\n // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests\n // TODO WFCORE-845 consider using an IllegalStateException for this\n //assert ! shutdown;\n final Integer operationId;\n if(id == null) {\n // If we did not get an operationId, create a new one\n operationId = operationIdManager.createBatchId();\n } else {\n // Check that the operationId is not already taken\n if(! operationIdManager.lockBatchId(id)) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id);\n }\n operationId = id;\n }\n final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this);\n final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request);\n if(existing != null) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId);\n }\n ProtocolLogger.ROOT_LOGGER.tracef(\"Registered active operation %d\", operationId);\n activeCount++; // condition.signalAll();\n return request;\n } finally {\n lock.unlock();\n }\n }" ]
[ "private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n final ResourceAssignment a = assignment;\n MpxjTreeNode childNode = new MpxjTreeNode(a)\n {\n @Override public String toString()\n {\n Resource resource = a.getResource();\n String resourceName = resource == null ? \"(unknown resource)\" : resource.getName();\n Task task = a.getTask();\n String taskName = task == null ? \"(unknown task)\" : task.getName();\n return resourceName + \"->\" + taskName;\n }\n };\n parentNode.add(childNode);\n }\n }", "public BlurBuilder contrast(float contrast) {\n data.preProcessors.add(new ContrastProcessor(data.contextWrapper.getRenderScript(), Math.max(Math.min(1500.f, contrast), -1500.f)));\n return this;\n }", "private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }", "public static FullTypeSignature getTypeSignature(String typeSignatureString,\n\t\t\tboolean useInternalFormFullyQualifiedName) {\n\t\tString key;\n\t\tif (!useInternalFormFullyQualifiedName) {\n\t\t\tkey = typeSignatureString.replace('.', '/')\n\t\t\t\t\t.replace('$', '.');\n\t\t} else {\n\t\t\tkey = typeSignatureString;\n\t\t}\n\n\t\t// we always use the internal form as a key for cache\n\t\tFullTypeSignature typeSignature = typeSignatureCache\n\t\t\t\t.get(key);\n\t\tif (typeSignature == null) {\n\t\t\tClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser(\n\t\t\t\t\ttypeSignatureString);\n\t\t\ttypeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);\n\t\t\ttypeSignature = typeSignatureParser.parseTypeSignature();\n\t\t\ttypeSignatureCache.put(typeSignatureString, typeSignature);\n\t\t}\n\t\treturn typeSignature;\n\t}", "private 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 void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData)\n {\n String notes = taskExtData.getString(TASK_NOTES);\n if (notes == null && data.length == 366)\n {\n byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362));\n if (offsetData != null && offsetData.length >= 12)\n {\n notes = taskVarData.getString(getOffset(offsetData, 8));\n \n // We do pick up some random stuff with this approach, and \n // we don't know enough about the file format to know when to ignore it\n // so we'll use a heuristic here to ignore anything that\n // doesn't look like RTF.\n if (notes != null && notes.indexOf('{') == -1)\n {\n notes = null;\n }\n }\n }\n \n if (notes != null)\n {\n if (m_reader.getPreserveNoteFormatting() == false)\n {\n notes = RtfHelper.strip(notes);\n }\n\n task.setNotes(notes);\n }\n }", "public void scaleWeights(double scale) {\r\n for (int i = 0; i < weights.length; i++) {\r\n for (int j = 0; j < weights[i].length; j++) {\r\n weights[i][j] *= scale;\r\n }\r\n }\r\n }", "public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }", "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }" ]
Returns a compact representation of all of the stories on the task. @param task The task containing the stories to get. @return Request object
[ "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }" ]
[ "public static void removeFromList(List<String> list, String value) {\n int foundIndex = -1;\n int i = 0;\n for (String id : list) {\n if (id.equalsIgnoreCase(value)) {\n foundIndex = i;\n break;\n }\n i++;\n }\n if (foundIndex != -1) {\n list.remove(foundIndex);\n }\n }", "@Override\n public int add(DownloadRequest request) throws IllegalArgumentException {\n checkReleased(\"add(...) called on a released ThinDownloadManager.\");\n if (request == null) {\n throw new IllegalArgumentException(\"DownloadRequest cannot be null\");\n }\n return mRequestQueue.add(request);\n }", "protected void aliasGeneric( Object variable , String name ) {\n if( variable.getClass() == Integer.class ) {\n alias(((Integer)variable).intValue(),name);\n } else if( variable.getClass() == Double.class ) {\n alias(((Double)variable).doubleValue(),name);\n } else if( variable.getClass() == DMatrixRMaj.class ) {\n alias((DMatrixRMaj)variable,name);\n } else if( variable.getClass() == FMatrixRMaj.class ) {\n alias((FMatrixRMaj)variable,name);\n } else if( variable.getClass() == DMatrixSparseCSC.class ) {\n alias((DMatrixSparseCSC)variable,name);\n } else if( variable.getClass() == SimpleMatrix.class ) {\n alias((SimpleMatrix) variable, name);\n } else if( variable instanceof DMatrixFixed ) {\n DMatrixRMaj M = new DMatrixRMaj(1,1);\n ConvertDMatrixStruct.convert((DMatrixFixed)variable,M);\n alias(M,name);\n } else if( variable instanceof FMatrixFixed ) {\n FMatrixRMaj M = new FMatrixRMaj(1,1);\n ConvertFMatrixStruct.convert((FMatrixFixed)variable,M);\n alias(M,name);\n } else {\n throw new RuntimeException(\"Unknown value type of \"+\n (variable.getClass().getSimpleName())+\" for variable \"+name);\n }\n }", "public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\n }", "public static csvserver_copolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_copolicy_binding obj = new csvserver_copolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_copolicy_binding response[] = (csvserver_copolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public byte[] getPacketBytes() {\n byte[] result = new byte[packetBytes.length];\n System.arraycopy(packetBytes, 0, result, 0, packetBytes.length);\n return result;\n }", "public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {\n Map<String, Object> metadata = new HashMap<String, Object>();\n metadata.put(Constants.DEVICE_ID, deviceId);\n metadata.put(Constants.DEVICE_TYPE, deviceType);\n metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);\n metadata.put(\"scope\", \"generic\");\n ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();\n\n importDeclarations.put(deviceId, declaration);\n\n registerImportDeclaration(declaration);\n }", "public MBeanOperationInfo getOperationInfo(String operationName)\n throws OperationNotFoundException, UnsupportedEncodingException {\n\n String decodedOperationName = sanitizer.urlDecode(operationName, encoding);\n Map<String, MBeanOperationInfo> operationMap = getOperationMetadata();\n if (operationMap.containsKey(decodedOperationName)) {\n return operationMap.get(decodedOperationName);\n }\n throw new OperationNotFoundException(\"Could not find operation \" + operationName + \" on MBean \" +\n objectName.getCanonicalName());\n }", "@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }" ]
Sets the HTML entity translator. It will also remove any other translator set. Nothing will happen if the argument is null. @param htmlElementTranslator translator
[ "public void setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(htmlElementTranslator!=null){\r\n\t\t\tthis.htmlElementTranslator = htmlElementTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}" ]
[ "protected static Map<Double, Double> doQuantization(double max,\n double min,\n double[] values)\n {\n double range = max - min;\n int noIntervals = 20;\n double intervalSize = range / noIntervals;\n int[] intervals = new int[noIntervals];\n for (double value : values)\n {\n int interval = Math.min(noIntervals - 1,\n (int) Math.floor((value - min) / intervalSize));\n assert interval >= 0 && interval < noIntervals : \"Invalid interval: \" + interval;\n ++intervals[interval];\n }\n Map<Double, Double> discretisedValues = new HashMap<Double, Double>();\n for (int i = 0; i < intervals.length; i++)\n {\n // Correct the value to take into account the size of the interval.\n double value = (1 / intervalSize) * (double) intervals[i];\n discretisedValues.put(min + ((i + 0.5) * intervalSize), value);\n }\n return discretisedValues;\n }", "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 GroovyFieldDoc[] properties() {\n Collections.sort(properties);\n return properties.toArray(new GroovyFieldDoc[properties.size()]);\n }", "public Session startSshSessionAndObtainSession() {\n\n Session session = null;\n try {\n\n JSch jsch = new JSch();\n if (sshMeta.getSshLoginType() == SshLoginType.KEY) {\n\n String workingDir = System.getProperty(\"user.dir\");\n String privKeyAbsPath = workingDir + \"/\"\n + sshMeta.getPrivKeyRelativePath();\n logger.debug(\"use privkey: path: \" + privKeyAbsPath);\n\n if (!PcFileNetworkIoUtils.isFileExist(privKeyAbsPath)) {\n throw new RuntimeException(\"file not found at \"\n + privKeyAbsPath);\n }\n\n if (sshMeta.isPrivKeyUsePassphrase()\n && sshMeta.getPassphrase() != null) {\n jsch.addIdentity(privKeyAbsPath, sshMeta.getPassphrase());\n } else {\n jsch.addIdentity(privKeyAbsPath);\n }\n }\n\n session = jsch.getSession(sshMeta.getUserName(), targetHost,\n sshMeta.getSshPort());\n if (sshMeta.getSshLoginType() == SshLoginType.PASSWORD) {\n session.setPassword(sshMeta.getPassword());\n }\n\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n } catch (Exception t) {\n throw new RuntimeException(t);\n }\n return session;\n }", "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}", "public static final String getString(InputStream is) throws IOException\n {\n int type = is.read();\n if (type != 1)\n {\n throw new IllegalArgumentException(\"Unexpected string format\");\n }\n\n Charset charset = CharsetHelper.UTF8;\n \n int length = is.read();\n if (length == 0xFF)\n {\n length = getShort(is);\n if (length == 0xFFFE)\n {\n charset = CharsetHelper.UTF16LE;\n length = (is.read() * 2);\n }\n }\n\n String result;\n if (length == 0)\n {\n result = null;\n }\n else\n {\n byte[] stringData = new byte[length]; \n is.read(stringData);\n result = new String(stringData, charset);\n }\n return result;\n }", "public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\n }", "public static String getArtifactoryPluginVersion() {\n String pluginsSortName = \"artifactory\";\n //Validates Jenkins existence because in some jobs the Jenkins instance is unreachable\n if (Jenkins.getInstance() != null\n && Jenkins.getInstance().getPlugin(pluginsSortName) != null\n && Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper() != null) {\n return Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper().getVersion();\n }\n return \"\";\n }", "private void setFields(Map<String, FieldType> map, MapRow row, FieldContainer container)\n {\n if (row != null)\n {\n for (Map.Entry<String, FieldType> entry : map.entrySet())\n {\n container.set(entry.getValue(), row.getObject(entry.getKey()));\n }\n }\n }" ]
Adds this vector to v1 and places the result in this vector. @param v1 right-hand vector
[ "public void add(Vector3d v1) {\n x += v1.x;\n y += v1.y;\n z += v1.z;\n }" ]
[ "public static vpnclientlessaccesspolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy_binding obj = new vpnclientlessaccesspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy_binding response = (vpnclientlessaccesspolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }", "public static boolean isSpreadSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSpreadSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSpreadSafe();\r\n }\r\n return false;\r\n }", "@Override\n\tpublic void writeValue(TimeValue value, Resource resource)\n\t\t\tthrows RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.WB_TIME_VALUE);\n\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME,\n\t\t\t\tTimeValueConverter.getTimeLiteral(value, this.rdfWriter));\n\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_PRECISION, value.getPrecision());\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_TIMEZONE,\n\t\t\t\tvalue.getTimezoneOffset());\n\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_CALENDAR_MODEL,\n\t\t\t\tvalue.getPreferredCalendarModel());\n\t}", "public static final Duration parseDurationInThousanthsOfMinutes(ProjectProperties properties, Number value, TimeUnit targetTimeUnit)\n {\n return parseDurationInFractionsOfMinutes(properties, value, targetTimeUnit, 1000);\n }", "public static lbvserver_scpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_scpolicy_binding obj = new lbvserver_scpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_scpolicy_binding response[] = (lbvserver_scpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static <T> void injectBoundFields(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends FieldInjectionPoint<?, ?>> injectableFields) {\n for (FieldInjectionPoint<?, ?> injectableField : injectableFields) {\n injectableField.inject(instance, manager, creationalContext);\n }\n }", "public static nssimpleacl[] get(nitro_service service, String aclname[]) throws Exception{\n\t\tif (aclname !=null && aclname.length>0) {\n\t\t\tnssimpleacl response[] = new nssimpleacl[aclname.length];\n\t\t\tnssimpleacl obj[] = new nssimpleacl[aclname.length];\n\t\t\tfor (int i=0;i<aclname.length;i++) {\n\t\t\t\tobj[i] = new nssimpleacl();\n\t\t\t\tobj[i].set_aclname(aclname[i]);\n\t\t\t\tresponse[i] = (nssimpleacl) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public static Iterable<BoxRetentionPolicy.Info> getAll(\r\n String name, String type, String userID, int limit, final BoxAPIConnection api, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (name != null) {\r\n queryString.appendParam(\"policy_name\", name);\r\n }\r\n if (type != null) {\r\n queryString.appendParam(\"policy_type\", type);\r\n }\r\n if (userID != null) {\r\n queryString.appendParam(\"created_by_user_id\", userID);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString());\r\n return new BoxResourceIterable<BoxRetentionPolicy.Info>(api, url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get(\"id\").asString());\r\n return policy.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }" ]
Release transaction that was acquired in a thread with specified permits.
[ "void releaseTransaction(@NotNull final Thread thread, final int permits) {\n try (CriticalSection ignored = criticalSection.enter()) {\n int currentThreadPermits = getThreadPermits(thread);\n if (permits > currentThreadPermits) {\n throw new ExodusException(\"Can't release more permits than it was acquired\");\n }\n acquiredPermits -= permits;\n currentThreadPermits -= permits;\n if (currentThreadPermits == 0) {\n threadPermits.remove(thread);\n } else {\n threadPermits.put(thread, currentThreadPermits);\n }\n notifyNextWaiters();\n }\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 }", "protected void beforeMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.beforeMaterialization(this, _id);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public Set<RateType> getRateTypes() {\n @SuppressWarnings(\"unchecked\")\n Set<RateType> rateSet = get(KEY_RATE_TYPES, Set.class);\n if (rateSet == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(rateSet);\n }", "public ProxyAuthentication getProxyAuthentication() {\n\t\t// convert authentication to layerAuthentication so we only use one\n\t\t// TODO Remove when removing deprecated authentication field.\n\t\tif (layerAuthentication == null && authentication != null) {\n\t\t\tlayerAuthentication = new LayerAuthentication();\n\t\t\tlayerAuthentication.setAuthenticationMethod(LayerAuthenticationMethod.valueOf(authentication\n\t\t\t\t\t.getAuthenticationMethod().name()));\n\t\t\tlayerAuthentication.setPassword(authentication.getPassword());\n\t\t\tlayerAuthentication.setPasswordKey(authentication.getPasswordKey());\n\t\t\tlayerAuthentication.setRealm(authentication.getRealm());\n\t\t\tlayerAuthentication.setUser(authentication.getUser());\n\t\t\tlayerAuthentication.setUserKey(authentication.getUserKey());\n\t\t}\n\t\t// TODO Remove when removing deprecated authentication field.\n\t\treturn layerAuthentication;\n\t}", "public static void generateOutputFile(Random rng,\n File outputFile) throws IOException\n {\n DataOutputStream dataOutput = null;\n try\n {\n dataOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));\n for (int i = 0; i < INT_COUNT; i++)\n {\n dataOutput.writeInt(rng.nextInt());\n }\n dataOutput.flush();\n }\n finally\n {\n if (dataOutput != null)\n {\n dataOutput.close();\n }\n }\n }", "private void doFileRoll(final File from, final File to) {\n final FileHelper fileHelper = FileHelper.getInstance();\n if (!fileHelper.deleteExisting(to)) {\n this.getAppender().getErrorHandler()\n .error(\"Unable to delete existing \" + to + \" for rename\");\n }\n final String original = from.toString();\n if (fileHelper.rename(from, to)) {\n LogLog.debug(\"Renamed \" + original + \" to \" + to);\n } else {\n this.getAppender().getErrorHandler()\n .error(\"Unable to rename \" + original + \" to \" + to);\n }\n }", "public static Double checkLatitude(String name, Double latitude) {\n if (latitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LATITUDE,\n MAX_LATITUDE,\n latitude);\n }\n return latitude;\n }", "public CliCommandBuilder setController(final String hostname, final int port) {\n setController(formatAddress(null, hostname, port));\n return this;\n }", "public Criteria copy(boolean includeGroupBy, boolean includeOrderBy, boolean includePrefetchedRelationships)\r\n {\r\n Criteria copy = new Criteria();\r\n\r\n copy.m_criteria = new Vector(this.m_criteria);\r\n copy.m_negative = this.m_negative;\r\n\r\n if (includeGroupBy)\r\n {\r\n copy.groupby = this.groupby;\r\n }\r\n if (includeOrderBy)\r\n {\r\n copy.orderby = this.orderby;\r\n }\r\n if (includePrefetchedRelationships)\r\n {\r\n copy.prefetchedRelationships = this.prefetchedRelationships;\r\n }\r\n\r\n return copy;\r\n }" ]
Encodes the given URI query with the given encoding. @param query the query to be encoded @param encoding the character encoding to encode to @return the encoded query @throws UnsupportedEncodingException when the given encoding parameter is not supported
[ "public static String encodeQuery(String query, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(query, encoding, HierarchicalUriComponents.Type.QUERY);\n\t}" ]
[ "protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }", "public static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}", "public Info changeMessage(String newMessage) {\n Info newInfo = new Info();\n newInfo.setMessage(newMessage);\n\n URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(newInfo.getPendingChanges());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonResponse = JsonObject.readFrom(response.getJSON());\n\n return new Info(jsonResponse);\n }", "public List<Task> getActiveTasks() {\n InputStream response = null;\n URI uri = new URIBase(getBaseUri()).path(\"_active_tasks\").build();\n try {\n response = couchDbClient.get(uri);\n return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS);\n } finally {\n close(response);\n }\n }", "private void readProject(Project project)\n {\n Task mpxjTask = m_projectFile.addTask();\n //project.getAuthor()\n mpxjTask.setBaselineCost(project.getBaselineCost());\n mpxjTask.setBaselineFinish(project.getBaselineFinishDate());\n mpxjTask.setBaselineStart(project.getBaselineStartDate());\n //project.getBudget();\n //project.getCompany()\n mpxjTask.setFinish(project.getFinishDate());\n //project.getGoal()\n //project.getHyperlinks()\n //project.getMarkerID()\n mpxjTask.setName(project.getName());\n mpxjTask.setNotes(project.getNote());\n mpxjTask.setPriority(project.getPriority());\n // project.getSite()\n mpxjTask.setStart(project.getStartDate());\n // project.getStyleProject()\n // project.getTask()\n // project.getTimeScale()\n // project.getViewProperties()\n\n String projectIdentifier = project.getID().toString();\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(projectIdentifier.getBytes()));\n\n //\n // Sort the tasks into the correct order\n //\n List<Document.Projects.Project.Task> tasks = new ArrayList<Document.Projects.Project.Task>(project.getTask());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(tasks, new Comparator<Document.Projects.Project.Task>()\n {\n @Override public int compare(Document.Projects.Project.Task o1, Document.Projects.Project.Task o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n Map<String, Task> map = new HashMap<String, Task>();\n map.put(\"\", mpxjTask);\n\n for (Document.Projects.Project.Task task : tasks)\n {\n readTask(projectIdentifier, map, task);\n }\n }", "public void addRebalancingState(final RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n // Move into rebalancing state\n if(ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), \"UTF-8\")\n .compareTo(VoldemortState.NORMAL_SERVER.toString()) == 0) {\n put(SERVER_STATE_KEY, VoldemortState.REBALANCING_MASTER_SERVER);\n initCache(SERVER_STATE_KEY);\n }\n\n // Add the steal information\n RebalancerState rebalancerState = getRebalancerState();\n if(!rebalancerState.update(stealInfo)) {\n throw new VoldemortException(\"Could not add steal information \" + stealInfo\n + \" since a plan for the same donor node \"\n + stealInfo.getDonorId() + \" ( \"\n + rebalancerState.find(stealInfo.getDonorId())\n + \" ) already exists\");\n }\n put(MetadataStore.REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n } finally {\n writeLock.unlock();\n }\n }", "public RedwoodConfiguration stderr(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.err();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\n }", "protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) {\n TransactionLogger oldInstance = getInstance();\n if (oldInstance == null || oldInstance.finished) {\n if(loggingKeys == null) {\n synchronized (TransactionLogger.class) {\n if (loggingKeys == null) {\n logger.info(\"Initializing 'LoggingKeysHandler' class\");\n loggingKeys = new LoggingKeysHandler(keysPropStream);\n }\n }\n }\n initInstance(instance, logger, auditor);\n setInstance(instance);\n return true;\n }\n return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case...\n }", "private static DumpContentType guessDumpContentType(String fileName) {\n\t\tString lcDumpName = fileName.toLowerCase();\n\t\tif (lcDumpName.contains(\".json.gz\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".json.bz2\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".sql.gz\")) {\n\t\t\treturn DumpContentType.SITES;\n\t\t} else if (lcDumpName.contains(\".xml.bz2\")) {\n\t\t\tif (lcDumpName.contains(\"daily\")) {\n\t\t\t\treturn DumpContentType.DAILY;\n\t\t\t} else if (lcDumpName.contains(\"current\")) {\n\t\t\t\treturn DumpContentType.CURRENT;\n\t\t\t} else {\n\t\t\t\treturn DumpContentType.FULL;\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.warn(\"Could not guess type of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to json.gz.\");\n\t\t\treturn DumpContentType.JSON;\n\t\t}\n\t}" ]
Returns the data sources belonging to a particular group of data sources. Data sources are grouped in record linkage mode, but not in deduplication mode, so only use this method in record linkage mode.
[ "public Collection<DataSource> getDataSources(int groupno) {\n if (groupno == 1)\n return group1;\n else if (groupno == 2)\n return group2;\n else\n throw new DukeConfigException(\"Invalid group number: \" + groupno);\n }" ]
[ "public static nslimitidentifier_binding get(nitro_service service, String limitidentifier) throws Exception{\n\t\tnslimitidentifier_binding obj = new nslimitidentifier_binding();\n\t\tobj.set_limitidentifier(limitidentifier);\n\t\tnslimitidentifier_binding response = (nslimitidentifier_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static onlinkipv6prefix[] get(nitro_service service, String ipv6prefix[]) throws Exception{\n\t\tif (ipv6prefix !=null && ipv6prefix.length>0) {\n\t\t\tonlinkipv6prefix response[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tonlinkipv6prefix obj[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tfor (int i=0;i<ipv6prefix.length;i++) {\n\t\t\t\tobj[i] = new onlinkipv6prefix();\n\t\t\t\tobj[i].set_ipv6prefix(ipv6prefix[i]);\n\t\t\t\tresponse[i] = (onlinkipv6prefix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }", "static public String bb2hex(byte[] bb) {\n\t\tString result = \"\";\n\t\tfor (int i=0; i<bb.length; i++) {\n\t\t\tresult = result + String.format(\"%02X \", bb[i]);\n\t\t}\n\t\treturn result;\n\t}", "public Map<String,Object> getAttributeValues()\n throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {\n\n HashSet<String> attributeSet = new HashSet<String>();\n\n for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {\n attributeSet.add(attributeInfo.getName());\n }\n\n AttributeList attributeList =\n mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));\n\n Map<String, Object> attributeValueMap = new TreeMap<String, Object>();\n for (Attribute attribute : attributeList.asList()) {\n attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));\n }\n\n return attributeValueMap;\n }", "private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)\r\n throws java.sql.SQLException\r\n {\r\n Statement result;\r\n try\r\n {\r\n // if necessary use JDBC1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n result =\r\n con.createStatement(\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result = con.createStatement();\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // if a JDBC1.0 driver is used, the signature\r\n // createStatement(int, int) is not defined.\r\n // we then call the JDBC1.0 variant createStatement()\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n result = con.createStatement();\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql.getClass().getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n FORCEJDBC1_0 = true;\r\n result = con.createStatement();\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }", "public void processCollection(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n CollectionDescriptorDef collDef = _curClassDef.getCollection(name);\r\n String attrName;\r\n\r\n if (collDef == null)\r\n {\r\n collDef = new CollectionDescriptorDef(name);\r\n _curClassDef.addCollection(collDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processCollection\", \" Processing collection \"+collDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n collDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n if (OjbMemberTagsHandler.getMemberDimension() > 0)\r\n {\r\n // we store the array-element type for later use\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n else\r\n { \r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n\r\n _curCollectionDef = collDef;\r\n generate(template);\r\n _curCollectionDef = null;\r\n }", "public void identifyClasses(final String pluginDirectory) throws Exception {\n methodInformation.clear();\n jarInformation.clear();\n try {\n new FileTraversal() {\n public void onDirectory(final File d) {\n }\n\n public void onFile(final File f) {\n try {\n // loads class files\n if (f.getName().endsWith(\".class\")) {\n // get the class name for this path\n String className = f.getAbsolutePath();\n className = className.replace(pluginDirectory, \"\");\n className = getClassNameFromPath(className);\n\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getName());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = pluginDirectory;\n classInformation.put(className, classInfo);\n } else if (f.getName().endsWith(\".jar\")) {\n // loads JAR packages\n // open up jar and discover files\n // look for anything with /proxy/ in it\n // this may discover things we don't need but that is OK\n try {\n jarInformation.add(f.getAbsolutePath());\n JarFile jarFile = new JarFile(f);\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String pluginPackageName = jarFile.getManifest().getMainAttributes().getValue(\"plugin-package\");\n if (pluginPackageName == null) {\n return;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n if (!elementName.endsWith(\".class\")) {\n continue;\n }\n\n String className = getClassNameFromPath(elementName);\n if (className.contains(pluginPackageName)) {\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getAbsolutePath());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = f.getAbsolutePath();\n classInformation.put(className, classInfo);\n }\n }\n } catch (Exception e) {\n\n }\n }\n } catch (Exception e) {\n logger.warn(\"Exception caught: {}, {}\", e.getMessage(), e.getCause());\n }\n }\n }.traverse(new File(pluginDirectory));\n } catch (IOException e) {\n throw new Exception(\"Could not identify all plugins: \" + e.getMessage());\n }\n }", "private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action) {\r\n return createRetentionPolicy(api, name, type, length, action, null);\r\n }" ]
Set HTTP headers to allow caching for the given number of seconds. @param response where to set the caching settings @param seconds number of seconds into the future that the response should be cacheable for
[ "private void configureCaching(HttpServletResponse response, int seconds) {\n\t\t// HTTP 1.0 header\n\t\tresponse.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + seconds * 1000L);\n\t\tif (seconds > 0) {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"max-age=\" + seconds);\n\t\t} else {\n\t\t\t// HTTP 1.1 header\n\t\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, \"no-cache\");\n\n\t\t}\n\t}" ]
[ "public static void close(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n try {\n if (!stmt.isClosed())\n stmt.close();\n } catch (UnsupportedOperationException e) {\n // not all JDBC drivers implement the isClosed() method.\n // ugly, but probably the only way to get around this.\n // http://stackoverflow.com/questions/12845385/duke-fast-deduplication-java-lang-unsupportedoperationexception-operation-not\n stmt.close();\n }\n if (conn != null && !conn.isClosed())\n conn.close();\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }", "public String get(final long index) {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.lindex(getKey(), index);\n }\n });\n }", "static void restoreFromHistory(final InstallationManager.MutablePatchingTarget target, final String rollbackPatchId,\n final Patch.PatchType patchType, final PatchableTarget.TargetInfo history) throws PatchingException {\n if (patchType == Patch.PatchType.CUMULATIVE) {\n assert history.getCumulativePatchID().equals(rollbackPatchId);\n target.apply(rollbackPatchId, patchType);\n // Restore one off state\n final List<String> oneOffs = new ArrayList<String>(history.getPatchIDs());\n Collections.reverse(oneOffs);\n for (final String oneOff : oneOffs) {\n target.apply(oneOff, Patch.PatchType.ONE_OFF);\n }\n }\n checkState(history, history); // Just check for tests, that rollback should restore the old state\n }", "private static int readDataBlock(String text, int offset, int length, List<byte[]> blocks)\n {\n int bytes = length / 2;\n byte[] data = new byte[bytes];\n\n for (int index = 0; index < bytes; index++)\n {\n data[index] = (byte) Integer.parseInt(text.substring(offset, offset + 2), 16);\n offset += 2;\n }\n\n blocks.add(data);\n return (offset);\n }", "protected static Map<Double, Double> doQuantization(double max,\n double min,\n double[] values)\n {\n double range = max - min;\n int noIntervals = 20;\n double intervalSize = range / noIntervals;\n int[] intervals = new int[noIntervals];\n for (double value : values)\n {\n int interval = Math.min(noIntervals - 1,\n (int) Math.floor((value - min) / intervalSize));\n assert interval >= 0 && interval < noIntervals : \"Invalid interval: \" + interval;\n ++intervals[interval];\n }\n Map<Double, Double> discretisedValues = new HashMap<Double, Double>();\n for (int i = 0; i < intervals.length; i++)\n {\n // Correct the value to take into account the size of the interval.\n double value = (1 / intervalSize) * (double) intervals[i];\n discretisedValues.put(min + ((i + 0.5) * intervalSize), value);\n }\n return discretisedValues;\n }", "public static aaauser_auditsyslogpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_auditsyslogpolicy_binding obj = new aaauser_auditsyslogpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_auditsyslogpolicy_binding response[] = (aaauser_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }", "synchronized void setServerProcessStopping() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(null, InternalState.STOPPED, InternalState.PROCESS_STOPPING);\n }", "public void renumberUniqueIDs()\n {\n int uid = firstUniqueID();\n for (T entity : this)\n {\n entity.setUniqueID(Integer.valueOf(uid++));\n }\n }" ]
Returns a raw handle to the SQLite database connection. Do not close! @param context A context, which is used to (when needed) set up a connection to the database @return The single, unique connection to the database, as is (also) used by our Cupboard instance
[ "public synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}" ]
[ "protected void updateRotator(DMatrixRMaj Q , int m, int n, double c, double s) {\n int rowA = m*Q.numCols;\n int rowB = n*Q.numCols;\n\n// for( int i = 0; i < Q.numCols; i++ ) {\n// double a = Q.get(rowA+i);\n// double b = Q.get(rowB+i);\n// Q.set( rowA+i, c*a + s*b);\n// Q.set( rowB+i, -s*a + c*b);\n// }\n// System.out.println(\"------ AFter Update Rotator \"+m+\" \"+n);\n// Q.print();\n// System.out.println();\n int endA = rowA + Q.numCols;\n for( ; rowA != endA; rowA++ , rowB++ ) {\n double a = Q.get(rowA);\n double b = Q.get(rowB);\n Q.set(rowA, c*a + s*b);\n Q.set(rowB, -s*a + c*b);\n }\n }", "private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n String concurrentDeployment = getSystemProperty(\"org.jboss.weld.bootstrap.properties.concurrentDeployment\");\n if (concurrentDeployment != null) {\n processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);\n found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));\n }\n String preloaderThreadPoolSize = getSystemProperty(\"org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize\");\n if (preloaderThreadPoolSize != null) {\n found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));\n }\n return found;\n }", "public static <T extends Comparable<? super T>> List<T> sort(Iterable<T> iterable) {\n\t\tList<T> asList = Lists.newArrayList(iterable);\n\t\tif (iterable instanceof SortedSet<?>) {\n\t\t\tif (((SortedSet<T>) iterable).comparator() == null) {\n\t\t\t\treturn asList;\n\t\t\t}\n\t\t}\n\t\treturn ListExtensions.sortInplace(asList);\n\t}", "private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }", "public DomainList getCollectionDomains(Date date, String collectionId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_COLLECTION_DOMAINS, \"collection_id\", collectionId, date, perPage, page);\n }", "public void addClass(ClassNode node) {\n node = node.redirect();\n String name = node.getName();\n ClassNode stored = classes.get(name);\n if (stored != null && stored != node) {\n // we have a duplicate class!\n // One possibility for this is, that we declared a script and a\n // class in the same file and named the class like the file\n SourceUnit nodeSource = node.getModule().getContext();\n SourceUnit storedSource = stored.getModule().getContext();\n String txt = \"Invalid duplicate class definition of class \" + node.getName() + \" : \";\n if (nodeSource == storedSource) {\n // same class in same source\n txt += \"The source \" + nodeSource.getName() + \" contains at least two definitions of the class \" + node.getName() + \".\\n\";\n if (node.isScriptBody() || stored.isScriptBody()) {\n txt += \"One of the classes is an explicit generated class using the class statement, the other is a class generated from\" +\n \" the script body based on the file name. Solutions are to change the file name or to change the class name.\\n\";\n }\n } else {\n txt += \"The sources \" + nodeSource.getName() + \" and \" + storedSource.getName() + \" each contain a class with the name \" + node.getName() + \".\\n\";\n }\n nodeSource.getErrorCollector().addErrorAndContinue(\n new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()), nodeSource)\n );\n }\n classes.put(name, node);\n\n if (classesToCompile.containsKey(name)) {\n ClassNode cn = classesToCompile.get(name);\n cn.setRedirect(node);\n classesToCompile.remove(name);\n }\n }", "public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\tif (key == null)\n\t\t\tthrow new NullPointerException(\"key\");\n\t\tCollections.sort(list, new KeyComparator<T, C>(key));\n\t\treturn list;\n\t}", "public String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}", "public void fireTaskReadEvent(Task task)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.taskRead(task);\n }\n }\n }" ]
add a foreign key field ID
[ "public void addForeignKeyField(int newId)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(new Integer(newId));\r\n }" ]
[ "private static void updateBaseCalendarNames(List<Pair<ProjectCalendar, BigInteger>> baseCalendars, HashMap<BigInteger, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, BigInteger> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n BigInteger baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n\n }", "private void registerChildInternal(IgnoreDomainResourceTypeResource child) {\n child.setParent(this);\n children.put(child.getName(), child);\n }", "public void addHeader(String key, String value) {\n if (key.equals(\"As-User\")) {\n for (int i = 0; i < this.headers.size(); i++) {\n if (this.headers.get(i).getKey().equals(\"As-User\")) {\n this.headers.remove(i);\n }\n }\n }\n if (key.equals(\"X-Box-UA\")) {\n throw new IllegalArgumentException(\"Altering the X-Box-UA header is not permitted\");\n }\n this.headers.add(new RequestHeader(key, value));\n }", "public static <T extends WindupVertexFrame> WindupVertexFrame removeTypeFromModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().removeTypeFromElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, WindupVertexFrame.class);\n }", "private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }", "private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {\n final ModelNode op = ServerOperations.createAddOperation(address);\n for (Map.Entry<String, String> prop : properties.entrySet()) {\n final String[] props = prop.getKey().split(\",\");\n if (props.length == 0) {\n throw new RuntimeException(\"Invalid property \" + prop);\n }\n ModelNode node = op;\n for (int i = 0; i < props.length - 1; ++i) {\n node = node.get(props[i]);\n }\n final String value = prop.getValue() == null ? \"\" : prop.getValue();\n if (value.startsWith(\"!!\")) {\n handleDmrString(node, props[props.length - 1], value);\n } else {\n node.get(props[props.length - 1]).set(value);\n }\n }\n return op;\n }", "public static int cudnnCTCLoss(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the\n mini batch size, A is the alphabet size) */\n Pointer probs, /** probabilities after softmax, in GPU memory */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n Pointer costs, /** the returned costs of CTC, in GPU memory */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the dimensions are T,N,A */\n Pointer gradients, /** the returned CTC gradients, in GPU memory, to compute costs only, set it to NULL */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n Pointer workspace, /** pointer to the workspace, in GPU memory */\n long workSpaceSizeInBytes)/** the workspace size needed */\n {\n return checkResult(cudnnCTCLossNative(handle, probsDesc, probs, labels, labelLengths, inputLengths, costs, gradientsDesc, gradients, algo, ctcLossDesc, workspace, workSpaceSizeInBytes));\n }", "private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }", "public static <T> DatabaseTableConfig<T> fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseTableConfig<T> config = new DatabaseTableConfig<T>();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseTableConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_FIELDS_START)) {\n\t\t\t\treadFields(reader, config);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseTableConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadTableField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}" ]
Process the standard working hours for a given day. @param mpxjCalendar MPXJ Calendar instance @param uniqueID unique ID sequence generation @param day Day instance @param typeList Planner list of days
[ "private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList)\n {\n if (isWorkingDay(mpxjCalendar, day))\n {\n ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day);\n if (mpxjHours != null)\n {\n OverriddenDayType odt = m_factory.createOverriddenDayType();\n typeList.add(odt);\n odt.setId(getIntegerString(uniqueID.next()));\n List<Interval> intervalList = odt.getInterval();\n for (DateRange mpxjRange : mpxjHours)\n {\n Date rangeStart = mpxjRange.getStart();\n Date rangeEnd = mpxjRange.getEnd();\n\n if (rangeStart != null && rangeEnd != null)\n {\n Interval interval = m_factory.createInterval();\n intervalList.add(interval);\n interval.setStart(getTimeString(rangeStart));\n interval.setEnd(getTimeString(rangeEnd));\n }\n }\n }\n }\n }" ]
[ "private void validateFilter(Filter filter) throws IllegalArgumentException {\n switch (filter.getFilterTypeCase()) {\n case COMPOSITE_FILTER:\n for (Filter subFilter : filter.getCompositeFilter().getFiltersList()) {\n validateFilter(subFilter);\n }\n break;\n case PROPERTY_FILTER:\n if (UNSUPPORTED_OPERATORS.contains(filter.getPropertyFilter().getOp())) {\n throw new IllegalArgumentException(\"Query cannot have any inequality filters.\");\n }\n break;\n default:\n throw new IllegalArgumentException(\n \"Unsupported filter type: \" + filter.getFilterTypeCase());\n }\n }", "public Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }", "protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}", "@Override\n\tpublic EmbeddedBrowser get() {\n\t\tLOGGER.debug(\"Setting up a Browser\");\n\t\t// Retrieve the config values used\n\t\tImmutableSortedSet<String> filterAttributes =\n\t\t\t\tconfiguration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();\n\t\tlong crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();\n\t\tlong crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();\n\n\t\t// Determine the requested browser type\n\t\tEmbeddedBrowser browser = null;\n\t\tEmbeddedBrowser.BrowserType browserType =\n\t\t\t\tconfiguration.getBrowserConfig().getBrowserType();\n\t\ttry {\n\t\t\tswitch (browserType) {\n\t\t\t\tcase CHROME:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHROME_HEADLESS:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload,\n\t\t\t\t\t\t\tcrawlWaitEvent, true);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX_HEADLESS:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOTE:\n\t\t\t\t\tbrowser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(\n\t\t\t\t\t\t\tconfiguration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,\n\t\t\t\t\t\t\tcrawlWaitEvent, crawlWaitReload);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHANTOMJS:\n\t\t\t\t\tbrowser =\n\t\t\t\t\t\t\tnewPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unrecognized browser type \"\n\t\t\t\t\t\t\t+ configuration.getBrowserConfig().getBrowserType());\n\t\t\t}\n\t\t} catch (IllegalStateException e) {\n\t\t\tLOGGER.error(\"Crawling with {} failed: \" + e.getMessage(), browserType.toString());\n\t\t\tthrow e;\n\t\t}\n\n\t\t/* for Retina display. */\n\t\tif (browser instanceof WebDriverBackedEmbeddedBrowser) {\n\t\t\tint pixelDensity =\n\t\t\t\t\tthis.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();\n\t\t\tif (pixelDensity != -1)\n\t\t\t\t((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);\n\t\t}\n\n\t\tplugins.runOnBrowserCreatedPlugins(browser);\n\t\treturn browser;\n\t}", "public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);\n\t}", "protected static void validateSignature(final DataInput input) throws IOException {\n final byte[] signatureBytes = new byte[4];\n input.readFully(signatureBytes);\n if (!Arrays.equals(ManagementProtocol.SIGNATURE, signatureBytes)) {\n throw ProtocolLogger.ROOT_LOGGER.invalidSignature(Arrays.toString(signatureBytes));\n }\n }", "public static wisite_farmname_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_farmname_binding obj = new wisite_farmname_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_farmname_binding response[] = (wisite_farmname_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static DMatrixSparseCSC symmetric( int N , int nz_total ,\n double min , double max , Random rand) {\n\n // compute the number of elements in the triangle, including diagonal\n int Ntriagle = (N*N+N)/2;\n // create a list of open elements\n int open[] = new int[Ntriagle];\n for (int row = 0, index = 0; row < N; row++) {\n for (int col = row; col < N; col++, index++) {\n open[index] = row*N+col;\n }\n }\n\n // perform a random draw\n UtilEjml.shuffle(open,open.length,0,nz_total,rand);\n Arrays.sort(open,0,nz_total);\n\n // construct the matrix\n DMatrixSparseTriplet A = new DMatrixSparseTriplet(N,N,nz_total*2);\n for (int i = 0; i < nz_total; i++) {\n int index = open[i];\n int row = index/N;\n int col = index%N;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n if( row == col ) {\n A.addItem(row,col,value);\n } else {\n A.addItem(row,col,value);\n A.addItem(col,row,value);\n }\n }\n\n DMatrixSparseCSC B = new DMatrixSparseCSC(N,N,A.nz_length);\n ConvertDMatrixStruct.convert(A,B);\n\n return B;\n }", "public void put(final String key, final Object value) {\n if (TASK_DIRECTORY_KEY.equals(key) && this.values.keySet().contains(TASK_DIRECTORY_KEY)) {\n // ensure that no one overwrites the task directory\n throw new IllegalArgumentException(\"Invalid key: \" + key);\n }\n\n if (value == null) {\n throw new IllegalArgumentException(\n \"A null value was attempted to be put into the values object under key: \" + key);\n }\n this.values.put(key, value);\n }" ]
Flatten a list of test suite results into a collection of results grouped by test class. This method basically strips away the TestNG way of organising tests and arranges the results by test class.
[ "private Collection<TestClassResults> flattenResults(List<ISuite> suites)\n {\n Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();\n for (ISuite suite : suites)\n {\n for (ISuiteResult suiteResult : suite.getResults().values())\n {\n // Failed and skipped configuration methods are treated as test failures.\n organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);\n // Successful configuration methods are not included.\n \n organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);\n }\n }\n return flattenedResults.values();\n }" ]
[ "public List<BoxComment.Info> getComments() {\n URL url = GET_COMMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxComment.Info> comments = new ArrayList<BoxComment.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject commentJSON = value.asObject();\n BoxComment comment = new BoxComment(this.getAPI(), commentJSON.get(\"id\").asString());\n BoxComment.Info info = comment.new Info(commentJSON);\n comments.add(info);\n }\n\n return comments;\n }", "public static Object invoke(Object object, String methodName, Object[] parameters) {\n try {\n Class[] classTypes = new Class[parameters.length];\n for (int i = 0; i < classTypes.length; i++) {\n classTypes[i] = parameters[i].getClass();\n }\n Method method = object.getClass().getMethod(methodName, classTypes);\n return method.invoke(object, parameters);\n } catch (Throwable t) {\n return InvokerHelper.invokeMethod(object, methodName, parameters);\n }\n }", "public static String pad(String str, int totalChars) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int slen = str.length();\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < totalChars - slen; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n }", "MongoCollection<BsonDocument> getLocalCollection(final MongoNamespace namespace) {\n return getLocalCollection(\n namespace,\n BsonDocument.class,\n MongoClientSettings.getDefaultCodecRegistry());\n }", "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 setInitialSequence(int[] sequence) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].setInitialSequence(sequence);\r\n return;\r\n }\r\n model1.setInitialSequence(sequence);\r\n model2.setInitialSequence(sequence);\r\n }", "VersionExcludeData getVersionIgnoreData(int major, int minor, int micro) {\n VersionExcludeData result = registry.get(new VersionKey(major, minor, micro));\n if (result == null) {\n result = registry.get(new VersionKey(major, minor, null));\n }\n return result;\n }", "public double[] getRegressionCoefficients(RandomVariable value) {\n\t\tif(basisFunctions.length == 0) {\n\t\t\treturn new double[] { };\n\t\t}\n\t\telse if(basisFunctions.length == 1) {\n\t\t\t/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */\n\t\t\treturn new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };\n\t\t}\n\t\telse if(basisFunctions.length == 2) {\n\t\t\t/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */\n\t\t\tdouble a = basisFunctions[0].squared().getAverage();\n\t\t\tdouble b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();\n\t\t\tdouble c = b;\n\t\t\tdouble d = basisFunctions[1].squared().getAverage();\n\n\t\t\tdouble determinant = (a * d - b * c);\n\t\t\tif(determinant != 0) {\n\t\t\t\tdouble x = value.mult(basisFunctions[0]).getAverage();\n\t\t\t\tdouble y = value.mult(basisFunctions[1]).getAverage();\n\n\t\t\t\tdouble alpha0 = (d * x - b * y) / determinant;\n\t\t\t\tdouble alpha1 = (a * y - c * x) / determinant;\n\n\t\t\t\treturn new double[] { alpha0, alpha1 };\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * General case\n\t\t */\n\n\t\t// Build regression matrix\n\t\tdouble[][] BTB = new double[basisFunctions.length][basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tfor(int j=0; j<=i; j++) {\n\t\t\t\tdouble covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();\n\t\t\t\tBTB[i][j] = covariance;\n\t\t\t\tBTB[j][i] = covariance;\n\t\t\t}\n\t\t}\n\n\t\tdouble[] BTX = new double[basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tdouble covariance = basisFunctions[i].mult(value).getAverage();\n\t\t\tBTX[i] = covariance;\n\t\t}\n\n\t\treturn LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);\n\t}", "@SuppressWarnings(\"unchecked\")\n public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) {\n DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId());\n this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future);\n return future;\n }" ]
Gets the file from which boot operations should be parsed. @return the file. Will not be {@code null}
[ "public File getBootFile() {\n if (bootFile == null) {\n synchronized (this) {\n if (bootFile == null) {\n if (bootFileReset) {\n //Reset the done bootup and the sequence, so that the old file we are reloading from\n // overwrites the main file on successful boot, and history is reset as when booting new\n doneBootup.set(false);\n sequence.set(0);\n }\n // If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile,\n // as that's where we persist\n if (bootFileReset && !interactionPolicy.isReadOnly() && newReloadBootFileName == null) {\n // we boot from mainFile\n bootFile = mainFile;\n } else {\n // It's either first boot, or a reload where we're not persisting our config or with a new boot file.\n // So we need to figure out which file we're meant to boot from\n\n String bootFileName = this.bootFileName;\n if (newReloadBootFileName != null) {\n //A non-null new boot file on reload takes precedence over the reloadUsingLast functionality\n //A new boot file was specified. Use that and reset the new name to null\n bootFileName = newReloadBootFileName;\n newReloadBootFileName = null;\n } else if (interactionPolicy.isReadOnly() && reloadUsingLast) {\n //If we were reloaded, and it is not a persistent configuration we want to use the last from the history\n bootFileName = LAST;\n }\n boolean usingRawFile = bootFileName.equals(rawFileName);\n if (usingRawFile) {\n bootFile = mainFile;\n } else {\n bootFile = determineBootFile(configurationDir, bootFileName);\n try {\n bootFile = bootFile.getCanonicalFile();\n } catch (IOException ioe) {\n throw ControllerLogger.ROOT_LOGGER.canonicalBootFileNotFound(ioe, bootFile);\n }\n }\n\n\n if (!bootFile.exists()) {\n if (!usingRawFile) { // TODO there's no reason usingRawFile should be an exception,\n // but the test infrastructure stuff is built around an assumption\n // that ConfigurationFile doesn't fail if test files are not\n // in the normal spot\n if (bootFileReset || interactionPolicy.isRequireExisting()) {\n throw ControllerLogger.ROOT_LOGGER.fileNotFound(bootFile.getAbsolutePath());\n }\n }\n // Create it for the NEW and DISCARD cases\n if (!bootFileReset && !interactionPolicy.isRequireExisting()) {\n createBootFile(bootFile);\n }\n } else if (!bootFileReset) {\n if (interactionPolicy.isRejectExisting() && bootFile.length() > 0) {\n throw ControllerLogger.ROOT_LOGGER.rejectEmptyConfig(bootFile.getAbsolutePath());\n } else if (interactionPolicy.isRemoveExisting() && bootFile.length() > 0) {\n if (!bootFile.delete()) {\n throw ControllerLogger.ROOT_LOGGER.cannotDelete(bootFile.getAbsoluteFile());\n }\n createBootFile(bootFile);\n }\n } // else after first boot we want the file to exist\n }\n }\n }\n }\n return bootFile;\n }" ]
[ "public static void checkRequired(OptionSet options, List<String> opts)\n throws VoldemortException {\n List<String> optCopy = Lists.newArrayList();\n for(String opt: opts) {\n if(options.has(opt)) {\n optCopy.add(opt);\n }\n }\n if(optCopy.size() < 1) {\n System.err.println(\"Please specify one of the following options:\");\n for(String opt: opts) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Missing required option.\");\n }\n if(optCopy.size() > 1) {\n System.err.println(\"Conflicting options:\");\n for(String opt: optCopy) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Conflicting options detected.\");\n }\n }", "private static char[] buildTable() {\n char[] table = new char[26];\n for (int ix = 0; ix < table.length; ix++)\n table[ix] = '0';\n table['B' - 'A'] = '1';\n table['P' - 'A'] = '1';\n table['F' - 'A'] = '1';\n table['V' - 'A'] = '1';\n table['C' - 'A'] = '2';\n table['S' - 'A'] = '2';\n table['K' - 'A'] = '2';\n table['G' - 'A'] = '2';\n table['J' - 'A'] = '2';\n table['Q' - 'A'] = '2';\n table['X' - 'A'] = '2';\n table['Z' - 'A'] = '2';\n table['D' - 'A'] = '3';\n table['T' - 'A'] = '3';\n table['L' - 'A'] = '4';\n table['M' - 'A'] = '5';\n table['N' - 'A'] = '5';\n table['R' - 'A'] = '6';\n return table;\n }", "public static int mixColors(float t, int rgb1, int rgb2) {\n\t\tint a1 = (rgb1 >> 24) & 0xff;\n\t\tint r1 = (rgb1 >> 16) & 0xff;\n\t\tint g1 = (rgb1 >> 8) & 0xff;\n\t\tint b1 = rgb1 & 0xff;\n\t\tint a2 = (rgb2 >> 24) & 0xff;\n\t\tint r2 = (rgb2 >> 16) & 0xff;\n\t\tint g2 = (rgb2 >> 8) & 0xff;\n\t\tint b2 = rgb2 & 0xff;\n\t\ta1 = lerp(t, a1, a2);\n\t\tr1 = lerp(t, r1, r2);\n\t\tg1 = lerp(t, g1, g2);\n\t\tb1 = lerp(t, b1, b2);\n\t\treturn (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;\n\t}", "public boolean doSyncPass() {\n if (!this.isConfigured || !syncLock.tryLock()) {\n return false;\n }\n try {\n if (logicalT == Long.MAX_VALUE) {\n if (logger.isInfoEnabled()) {\n logger.info(\"reached max logical time; resetting back to 0\");\n }\n logicalT = 0;\n }\n logicalT++;\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass START\",\n logicalT));\n }\n if (networkMonitor == null || !networkMonitor.isConnected()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Network disconnected\",\n logicalT));\n }\n return false;\n }\n if (authMonitor == null || !authMonitor.tryIsLoggedIn()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Logged out\",\n logicalT));\n }\n return false;\n }\n\n syncRemoteToLocal();\n syncLocalToRemote();\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END\",\n logicalT));\n }\n } catch (InterruptedException e) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass INTERRUPTED\",\n logicalT));\n }\n return false;\n } finally {\n syncLock.unlock();\n }\n return true;\n }", "public static nslimitselector[] get(nitro_service service) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tnslimitselector[] response = (nslimitselector[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void deleteArtifact(final String gavc, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactPath(gavc));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to DELETE artifact \" + gavc;\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "public static tmsessionpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\ttmsessionpolicy_binding obj = new tmsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\ttmsessionpolicy_binding response = (tmsessionpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }", "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 }" ]
Use this API to fetch sslvserver_sslciphersuite_binding resources of given name .
[ "public static sslvserver_sslciphersuite_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "protected void doSave() {\n\n List<CmsFavoriteEntry> entries = getEntries();\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }", "private CoreLabel makeCoreLabel(String line) {\r\n CoreLabel wi = new CoreLabel();\r\n // wi.line = line;\r\n String[] bits = line.split(\"\\\\s+\");\r\n switch (bits.length) {\r\n case 0:\r\n case 1:\r\n wi.setWord(BOUNDARY);\r\n wi.set(AnswerAnnotation.class, OTHER);\r\n break;\r\n case 2:\r\n wi.setWord(bits[0]);\r\n wi.set(AnswerAnnotation.class, bits[1]);\r\n break;\r\n case 3:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(AnswerAnnotation.class, bits[2]);\r\n break;\r\n case 4:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(ChunkAnnotation.class, bits[2]);\r\n wi.set(AnswerAnnotation.class, bits[3]);\r\n break;\r\n case 5:\r\n if (flags.useLemmaAsWord) {\r\n wi.setWord(bits[1]);\r\n } else {\r\n wi.setWord(bits[0]);\r\n }\r\n wi.set(LemmaAnnotation.class, bits[1]);\r\n wi.setTag(bits[2]);\r\n wi.set(ChunkAnnotation.class, bits[3]);\r\n wi.set(AnswerAnnotation.class, bits[4]);\r\n break;\r\n default:\r\n throw new RuntimeIOException(\"Unexpected input (many fields): \" + line);\r\n }\r\n wi.set(OriginalAnswerAnnotation.class, wi.get(AnswerAnnotation.class));\r\n return wi;\r\n }", "public ItemRequest<Task> addTag(String task) {\n \n String path = String.format(\"/tasks/%s/addTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }", "@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}", "public static String resolveSvnMigratedRevision(final Revision revision, final String branch) {\n if (revision == null) {\n return null;\n }\n final Pattern pattern = Pattern.compile(\"^git-svn-id: .*\" + branch + \"@([0-9]+) \", Pattern.MULTILINE);\n final Matcher matcher = pattern.matcher(revision.getMessage());\n if (matcher.find()) {\n return matcher.group(1);\n } else {\n return revision.getRevision();\n }\n }", "public static base_response update(nitro_service client, nd6ravariables resource) throws Exception {\n\t\tnd6ravariables updateresource = new nd6ravariables();\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.ceaserouteradv = resource.ceaserouteradv;\n\t\tupdateresource.sendrouteradv = resource.sendrouteradv;\n\t\tupdateresource.srclinklayeraddroption = resource.srclinklayeraddroption;\n\t\tupdateresource.onlyunicastrtadvresponse = resource.onlyunicastrtadvresponse;\n\t\tupdateresource.managedaddrconfig = resource.managedaddrconfig;\n\t\tupdateresource.otheraddrconfig = resource.otheraddrconfig;\n\t\tupdateresource.currhoplimit = resource.currhoplimit;\n\t\tupdateresource.maxrtadvinterval = resource.maxrtadvinterval;\n\t\tupdateresource.minrtadvinterval = resource.minrtadvinterval;\n\t\tupdateresource.linkmtu = resource.linkmtu;\n\t\tupdateresource.reachabletime = resource.reachabletime;\n\t\tupdateresource.retranstime = resource.retranstime;\n\t\tupdateresource.defaultlifetime = resource.defaultlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\n\t}", "public static URL getAuthorizationURL(String clientID, URI redirectUri, String state, List<String> scopes) {\n URLTemplate template = new URLTemplate(AUTHORIZATION_URL);\n QueryStringBuilder queryBuilder = new QueryStringBuilder().appendParam(\"client_id\", clientID)\n .appendParam(\"response_type\", \"code\")\n .appendParam(\"redirect_uri\", redirectUri.toString())\n .appendParam(\"state\", state);\n\n if (scopes != null && !scopes.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n int size = scopes.size() - 1;\n int i = 0;\n while (i < size) {\n builder.append(scopes.get(i));\n builder.append(\" \");\n i++;\n }\n builder.append(scopes.get(i));\n\n queryBuilder.appendParam(\"scope\", builder.toString());\n }\n\n return template.buildWithQuery(\"\", queryBuilder.toString());\n }" ]
Randomly generates matrix with the specified number of matrix elements filled with values from min to max. @param numRows Number of rows @param numCols Number of columns @param nz_total Total number of non-zero elements in the matrix @param min Minimum value @param max maximum value @param rand Random number generated @return Randomly generated matrix
[ "public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }" ]
[ "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}", "public void setOffset(float offset, final Axis axis) {\n if (!equal(mOffset.get(axis), offset)) {\n mOffset.set(offset, axis);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }", "public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) {\n\n BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection(boxConfig.getEnterpriseId(),\n boxConfig.getClientId(), boxConfig.getClientSecret(), boxConfig.getJWTEncryptionPreferences());\n\n return connection;\n }", "public static String createResource(\n CmsObject cmsObject,\n String newLink,\n Locale locale,\n String sitePath,\n String modelFileName,\n String mode,\n String postCreateHandler) {\n\n String[] newLinkParts = newLink.split(\"\\\\|\");\n String rootPath = newLinkParts[1];\n String typeName = newLinkParts[2];\n CmsFile modelFile = null;\n if (StringUtils.equalsIgnoreCase(mode, CmsEditorConstants.MODE_COPY)) {\n try {\n modelFile = cmsObject.readFile(sitePath);\n } catch (CmsException e) {\n LOG.warn(\n \"The resource at path\" + sitePath + \"could not be read. Thus it can not be used as model file.\",\n e);\n }\n }\n CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cmsObject, rootPath);\n CmsResourceTypeConfig typeConfig = adeConfig.getResourceType(typeName);\n CmsResource newElement = null;\n try {\n CmsObject cmsClone = cmsObject;\n if ((locale != null) && !cmsObject.getRequestContext().getLocale().equals(locale)) {\n // in case the content locale does not match the request context locale, use a clone cms with the appropriate locale\n cmsClone = OpenCms.initCmsObject(cmsObject);\n cmsClone.getRequestContext().setLocale(locale);\n }\n newElement = typeConfig.createNewElement(cmsClone, modelFile, rootPath);\n CmsPair<String, String> handlerParameter = I_CmsCollectorPostCreateHandler.splitClassAndConfig(\n postCreateHandler);\n I_CmsCollectorPostCreateHandler handler = A_CmsResourceCollector.getPostCreateHandler(\n handlerParameter.getFirst());\n handler.onCreate(cmsClone, cmsClone.readFile(newElement), modelFile != null, handlerParameter.getSecond());\n } catch (CmsException e) {\n LOG.error(\"Could not create resource.\", e);\n }\n return newElement == null ? null : cmsObject.getSitePath(newElement);\n }", "public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)\n\t\t\tthrows SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\treturn doCreateTable(dao, false);\n\t}", "public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }", "@Nullable\n public ByteIterable get2(@NotNull final Transaction txn, @NotNull final ByteIterable second) {\n return this.second.get(txn, second);\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 boolean accept(String str) {\r\n int k = str.length() - 1;\r\n char c = str.charAt(k);\r\n while (k >= 0 && !Character.isDigit(c)) {\r\n k--;\r\n if (k >= 0) {\r\n c = str.charAt(k);\r\n }\r\n }\r\n if (k < 0) {\r\n return false;\r\n }\r\n int j = k;\r\n c = str.charAt(j);\r\n while (j >= 0 && Character.isDigit(c)) {\r\n j--;\r\n if (j >= 0) {\r\n c = str.charAt(j);\r\n }\r\n }\r\n j++;\r\n k++;\r\n String theNumber = str.substring(j, k);\r\n int number = Integer.parseInt(theNumber);\r\n for (Pair<Integer,Integer> p : ranges) {\r\n int low = p.first().intValue();\r\n int high = p.second().intValue();\r\n if (number >= low && number <= high) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }" ]
Adds a listener to this collection. @param listener The listener to add
[ "public synchronized void addListener(CollectionProxyListener listener)\r\n {\r\n if (_listeners == null)\r\n {\r\n _listeners = new ArrayList();\r\n }\r\n // to avoid multi-add of same listener, do check\r\n if(!_listeners.contains(listener))\r\n {\r\n _listeners.add(listener);\r\n }\r\n }" ]
[ "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "public static ComplexNumber Pow(ComplexNumber z1, double n) {\r\n\r\n double norm = Math.pow(z1.getMagnitude(), n);\r\n double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real)));\r\n\r\n double common = n * angle;\r\n\r\n double r = norm * Math.cos(Math.toRadians(common));\r\n double i = norm * Math.sin(Math.toRadians(common));\r\n\r\n return new ComplexNumber(r, i);\r\n\r\n }", "public static Priority getInstance(int priority)\n {\n Priority result;\n\n if (priority >= LOWEST && priority <= DO_NOT_LEVEL && (priority % 100 == 0))\n {\n result = VALUE[(priority / 100) - 1];\n }\n else\n {\n result = new Priority(priority);\n }\n\n return (result);\n }", "public double Function2D(double x, double y) {\n return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma);\n }", "public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }", "@JmxOperation\n public String stopAsyncOperation(int requestId) {\n try {\n stopOperation(requestId);\n } catch(VoldemortException e) {\n return e.getMessage();\n }\n\n return \"Stopping operation \" + requestId;\n }", "public Constructor getZeroArgumentConstructor()\r\n {\r\n if (zeroArgumentConstructor == null && !alreadyLookedupZeroArguments)\r\n {\r\n try\r\n {\r\n zeroArgumentConstructor = getClassOfObject().getConstructor(NO_PARAMS);\r\n }\r\n catch (NoSuchMethodException e)\r\n {\r\n //no public zero argument constructor available let's try for a private/protected one\r\n try\r\n {\r\n zeroArgumentConstructor = getClassOfObject().getDeclaredConstructor(NO_PARAMS);\r\n\r\n //we found one, now let's make it accessible\r\n zeroArgumentConstructor.setAccessible(true);\r\n }\r\n catch (NoSuchMethodException e2)\r\n {\r\n //out of options, log the fact and let the method return null\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"No zero argument constructor defined for \"\r\n + this.getClassOfObject());\r\n }\r\n }\r\n\r\n alreadyLookedupZeroArguments = true;\r\n }\r\n\r\n return zeroArgumentConstructor;\r\n }", "private ProjectFile handleDatabaseInDirectory(File directory) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n if (file.isDirectory())\n {\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n int bytesRead = fis.read(buffer);\n fis.close();\n\n //\n // If the file is smaller than the buffer we are peeking into,\n // it's probably not a valid schedule file.\n //\n if (bytesRead != BUFFER_SIZE)\n {\n continue;\n }\n\n if (matchesFingerprint(buffer, BTRIEVE_FINGERPRINT))\n {\n return handleP3BtrieveDatabase(directory);\n }\n\n if (matchesFingerprint(buffer, STW_FINGERPRINT))\n {\n return handleSureTrakDatabase(directory);\n }\n }\n }\n return null;\n }", "private int getIndicatorStartPos() {\n switch (getPosition()) {\n case TOP:\n return mIndicatorClipRect.left;\n case RIGHT:\n return mIndicatorClipRect.top;\n case BOTTOM:\n return mIndicatorClipRect.left;\n default:\n return mIndicatorClipRect.top;\n }\n }" ]
Creates a Bytes object by copying the data of the CharSequence and encoding it using UTF-8.
[ "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 }" ]
[ "public void set(int i, double value) {\n switch (i) {\n case 0: {\n x = value;\n break;\n }\n case 1: {\n y = value;\n break;\n }\n case 2: {\n z = value;\n break;\n }\n default: {\n throw new ArrayIndexOutOfBoundsException(i);\n }\n }\n }", "public static String[] addStringToArray(String[] array, String str) {\n if (isEmpty(array)) {\n return new String[]{str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }", "public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }", "void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}", "public ILog getOrCreateLog(String topic, int partition) throws IOException {\n final int configPartitionNumber = getPartition(topic);\n if (partition >= configPartitionNumber) {\n throw new IOException(\"partition is bigger than the number of configuration: \" + configPartitionNumber);\n }\n boolean hasNewTopic = false;\n Pool<Integer, Log> parts = getLogPool(topic, partition);\n if (parts == null) {\n Pool<Integer, Log> found = logs.putIfNotExists(topic, new Pool<Integer, Log>());\n if (found == null) {\n hasNewTopic = true;\n }\n parts = logs.get(topic);\n }\n //\n Log log = parts.get(partition);\n if (log == null) {\n log = createLog(topic, partition);\n Log found = parts.putIfNotExists(partition, log);\n if (found != null) {\n Closer.closeQuietly(log, logger);\n log = found;\n } else {\n logger.info(format(\"Created log for [%s-%d], now create other logs if necessary\", topic, partition));\n final int configPartitions = getPartition(topic);\n for (int i = 0; i < configPartitions; i++) {\n getOrCreateLog(topic, i);\n }\n }\n }\n if (hasNewTopic && config.getEnableZookeeper()) {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n return log;\n }", "@PostConstruct\n public void loadTagDefinitions()\n {\n Map<Addon, List<URL>> addonToResourcesMap = scanner.scanForAddonMap(new FileExtensionFilter(\"tags.xml\"));\n for (Map.Entry<Addon, List<URL>> entry : addonToResourcesMap.entrySet())\n {\n for (URL resource : entry.getValue())\n {\n log.info(\"Reading tags definitions from: \" + resource.toString() + \" from addon \" + entry.getKey().getId());\n try(InputStream is = resource.openStream())\n {\n tagService.readTags(is);\n }\n catch( Exception ex )\n {\n throw new WindupException(\"Failed reading tags definition: \" + resource.toString() + \" from addon \" + entry.getKey().getId() + \":\\n\" + ex.getMessage(), ex);\n }\n }\n }\n }", "private int convertMoneyness(double moneyness) {\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\treturn (int) Math.round(moneyness * 100);\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\treturn - (int) Math.round(moneyness * 10000);\r\n\t\t} else {\r\n\t\t\treturn (int) Math.round(moneyness * 10000);\r\n\t\t}\r\n\t}", "private boolean isClockwise(Point center, Point a, Point b) {\n double cross = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);\n return cross > 0;\n }", "protected void reportWorked(int workIncrement, int currentUnitIndex) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1);\n }\n }" ]
Creates a block matrix the same size as A_inv, inverts the matrix and copies the results back onto A_inv. @param A_inv Where the inverted matrix saved. Modified.
[ "@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 static void listResources(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Resource: \" + resource.getName() + \" (Unique ID=\" + resource.getUniqueID() + \") Start=\" + resource.getStart() + \" Finish=\" + resource.getFinish());\n }\n System.out.println();\n }", "public static Context getContext()\r\n {\r\n if (ctx == null)\r\n {\r\n try\r\n {\r\n setContext(null);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Cannot instantiate the InitialContext\", e);\r\n throw new OJBRuntimeException(e);\r\n }\r\n }\r\n return ctx;\r\n }", "public InetAddress getRemoteAddress() {\n final Channel channel;\n try {\n channel = strategy.getChannel();\n } catch (IOException e) {\n return null;\n }\n final Connection connection = channel.getConnection();\n final InetSocketAddress peerAddress = connection.getPeerAddress(InetSocketAddress.class);\n return peerAddress == null ? null : peerAddress.getAddress();\n }", "public final ZoomToFeatures copy() {\n ZoomToFeatures obj = new ZoomToFeatures();\n obj.zoomType = this.zoomType;\n obj.minScale = this.minScale;\n obj.minMargin = this.minMargin;\n return obj;\n }", "private String getTypeString(Class<?> c)\n {\n String result = TYPE_MAP.get(c);\n if (result == null)\n {\n result = c.getName();\n if (!result.endsWith(\";\") && !result.startsWith(\"[\"))\n {\n result = \"L\" + result + \";\";\n }\n }\n return result;\n }", "private static FieldType getPlaceholder(final Class<?> type, final int fieldID)\n {\n return new FieldType()\n {\n @Override public FieldTypeClass getFieldTypeClass()\n {\n return FieldTypeClass.UNKNOWN;\n }\n\n @Override public String name()\n {\n return \"UNKNOWN\";\n }\n\n @Override public int getValue()\n {\n return fieldID;\n }\n\n @Override public String getName()\n {\n return \"Unknown \" + (type == null ? \"\" : type.getSimpleName() + \"(\" + fieldID + \")\");\n }\n\n @Override public String getName(Locale locale)\n {\n return getName();\n }\n\n @Override public DataType getDataType()\n {\n return null;\n }\n\n @Override public FieldType getUnitsType()\n {\n return null;\n }\n\n @Override public String toString()\n {\n return getName();\n }\n };\n }", "@Override\n public List<String> setTargetHostsFromLineByLineText(String sourcePath,\n HostsSourceType sourceType) throws TargetHostsLoadException {\n\n List<String> targetHosts = new ArrayList<String>();\n try {\n String content = getContentFromPath(sourcePath, sourceType);\n\n targetHosts = setTargetHostsFromString(content);\n\n } catch (IOException e) {\n throw new TargetHostsLoadException(\"IEException when reading \"\n + sourcePath, e);\n }\n\n return targetHosts;\n\n }", "public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }", "private Envelope getLayerEnvelope(ProxyLayerSupport layer) {\n\t\tBbox bounds = layer.getLayerInfo().getMaxExtent();\n\t\treturn new Envelope(bounds.getX(), bounds.getMaxX(), bounds.getY(), bounds.getMaxY());\n\t}" ]
Returns the aliased certificate. Certificates are aliased by their hostname. @see ThumbprintUtil @param alias @return @throws KeyStoreException @throws UnrecoverableKeyException @throws NoSuchProviderException @throws NoSuchAlgorithmException @throws CertificateException @throws SignatureException @throws CertificateNotYetValidException @throws CertificateExpiredException @throws InvalidKeyException @throws CertificateParsingException
[ "public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{\n\n\t\tString alias = _subjectMap.get(getSubjectForHostname(hostname));\n\n\t\tif(alias != null) {\n\t\t\treturn (X509Certificate)_ks.getCertificate(alias);\n\t\t}\n return getMappedCertificateForHostname(hostname);\n\t}" ]
[ "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 static final Priority parsePriority(BigInteger priority)\n {\n return (priority == null ? null : Priority.getInstance(priority.intValue()));\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal);\n }", "public Object getFieldByAlias(String alias)\n {\n return getCachedValue(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias));\n }", "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}", "static Locale getLocale(PageContext pageContext, String name) {\r\n\r\n Locale loc = null;\r\n\r\n Object obj = javax.servlet.jsp.jstl.core.Config.find(pageContext, name);\r\n if (obj != null) {\r\n if (obj instanceof Locale) {\r\n loc = (Locale)obj;\r\n } else {\r\n loc = SetLocaleSupport.parseLocale((String)obj);\r\n }\r\n }\r\n\r\n return loc;\r\n }", "public List<Tag> getRootTags()\n {\n return this.definedTags.values().stream()\n .filter(Tag::isRoot)\n .collect(Collectors.toList());\n }", "public static String multiply(CharSequence self, Number factor) {\n String s = self.toString();\n int size = factor.intValue();\n if (size == 0)\n return \"\";\n else if (size < 0) {\n throw new IllegalArgumentException(\"multiply() should be called with a number of 0 or greater not: \" + size);\n }\n StringBuilder answer = new StringBuilder(s);\n for (int i = 1; i < size; i++) {\n answer.append(s);\n }\n return answer.toString();\n }", "public GeoShapeMapper transform(GeoTransformation... transformations) {\n if (this.transformations == null) {\n this.transformations = Arrays.asList(transformations);\n } else {\n this.transformations.addAll(Arrays.asList(transformations));\n }\n return this;\n }" ]
Returns a flag represented as a String, indicating if the supplied day is a working day. @param mpxjCalendar MPXJ ProjectCalendar instance @param day Day instance @return boolean flag as a string
[ "private String getWorkingDayString(ProjectCalendar mpxjCalendar, Day day)\n {\n String result = null;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = \"0\";\n break;\n }\n\n case NON_WORKING:\n {\n result = \"1\";\n break;\n }\n\n case DEFAULT:\n {\n result = \"2\";\n break;\n }\n }\n\n return (result);\n }" ]
[ "@Override\n\tpublic void set(String headerName, String headerValue) {\n\t\tList<String> headerValues = new LinkedList<String>();\n\t\theaderValues.add(headerValue);\n\t\theaders.put(headerName, headerValues);\n\t}", "@Override\n\tpublic boolean isPrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif(getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn containsPrefixBlock(networkPrefixLength);\n\t}", "public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private 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 }", "public void setBody(String body) {\n byte[] bytes = body.getBytes(StandardCharsets.UTF_8);\n this.bodyLength = bytes.length;\n this.body = new ByteArrayInputStream(bytes);\n }", "public Tuple get(RowKey key) {\n\t\tAssociationOperation result = currentState.get( key );\n\t\tif ( result == null ) {\n\t\t\treturn cleared ? null : snapshot.get( key );\n\t\t}\n\t\telse if ( result.getType() == REMOVE ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn result.getValue();\n\t}", "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 }", "protected final ByteBuffer parseContent(ByteBuffer in) throws BaseExceptions.ParserException {\n if (contentComplete()) {\n throw new BaseExceptions.InvalidState(\"content already complete: \" + _endOfContent);\n } else {\n switch (_endOfContent) {\n case UNKNOWN_CONTENT:\n // This makes sense only for response parsing. Requests must always have\n // either Content-Length or Transfer-Encoding\n\n _endOfContent = EndOfContent.EOF_CONTENT;\n _contentLength = Long.MAX_VALUE; // Its up to the user to limit a body size\n return parseContent(in);\n\n case CONTENT_LENGTH:\n case EOF_CONTENT:\n return nonChunkedContent(in);\n\n case CHUNKED_CONTENT:\n return chunkedContent(in);\n\n default:\n throw new BaseExceptions.InvalidState(\"not implemented: \" + _endOfContent);\n }\n }\n }", "private void populateTask(Row row, Task task)\n {\n task.setUniqueID(row.getInteger(\"Z_PK\"));\n task.setName(row.getString(\"ZTITLE\"));\n task.setPriority(Priority.getInstance(row.getInt(\"ZPRIORITY\")));\n task.setMilestone(row.getBoolean(\"ZISMILESTONE\"));\n task.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n task.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n task.setNotes(row.getString(\"ZOBJECTDESCRIPTION\"));\n task.setDuration(row.getDuration(\"ZGIVENDURATION_\"));\n task.setOvertimeWork(row.getWork(\"ZGIVENWORKOVERTIME_\"));\n task.setWork(row.getWork(\"ZGIVENWORK_\"));\n task.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n task.setActualOvertimeWork(row.getWork(\"ZGIVENACTUALWORKOVERTIME_\"));\n task.setActualWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setRemainingWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setGUID(row.getUUID(\"ZUNIQUEID\"));\n\n Integer calendarID = row.getInteger(\"ZGIVENCALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n task.setCalendar(calendar);\n }\n }\n\n populateConstraints(row, task);\n\n // Percent complete is calculated bottom up from assignments and actual work vs. planned work\n\n m_eventManager.fireTaskReadEvent(task);\n }" ]
1-D Gaussian function. @param x value. @return Function's value at point x.
[ "public double Function1D(double x) {\n return Math.exp(x * x / (-2 * sqrSigma)) / (Math.sqrt(2 * Math.PI) * sigma);\n }" ]
[ "public static base_response delete(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec deleteresource = new dnsaaaarec();\n\t\tdeleteresource.hostname = resource.hostname;\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "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 }", "public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);\n return new Processor(p);\n }", "public static double J0(double x) {\r\n double ax;\r\n\r\n if ((ax = Math.abs(x)) < 8.0) {\r\n double y = x * x;\r\n double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7\r\n + y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));\r\n double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718\r\n + y * (59272.64853 + y * (267.8532712 + y * 1.0))));\r\n\r\n return ans1 / ans2;\r\n } else {\r\n double z = 8.0 / ax;\r\n double y = z * z;\r\n double xx = ax - 0.785398164;\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n - y * 0.934935152e-7)));\r\n\r\n return Math.sqrt(0.636619772 / ax) *\r\n (Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);\r\n }\r\n }", "public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }", "public static CountryList getCountries(Context context) {\n if (mCountries != null) {\n return mCountries;\n }\n mCountries = new CountryList();\n try {\n JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries));\n for (int i = 0; i < countries.length(); i++) {\n try {\n JSONObject country = (JSONObject) countries.get(i);\n mCountries.add(new Country(country.getString(\"name\"), country.getString(\"iso2\"), country.getInt(\"dialCode\")));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return mCountries;\n }", "public void setBean(String name, Object object) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\tbean = new Bean();\n\t\t\tbeans.put(name, bean);\n\t\t}\n\t\tbean.object = object;\n\t}", "public static Enum castToEnum(Object object, Class<? extends Enum> type) {\n if (object==null) return null;\n if (type.isInstance(object)) return (Enum) object;\n if (object instanceof String || object instanceof GString) {\n return Enum.valueOf(type, object.toString());\n }\n throw new GroovyCastException(object, type);\n }", "@Override\n public void invert(DMatrixRBlock A_inv) {\n int M = Math.min(QR.numRows,QR.numCols);\n if( A_inv.numRows != M || A_inv.numCols != M )\n throw new IllegalArgumentException(\"A_inv must be square an have dimension \"+M);\n\n\n // Solve for A^-1\n // Q*R*A^-1 = I\n\n // Apply householder reflectors to the identity matrix\n // y = Q^T*I = Q^T\n MatrixOps_DDRB.setIdentity(A_inv);\n decomposer.applyQTran(A_inv);\n\n // Solve using upper triangular R matrix\n // R*A^-1 = y\n // A^-1 = R^-1*y\n TriangularSolver_DDRB.solve(QR.blockLength,true,\n new DSubmatrixD1(QR,0,M,0,M),new DSubmatrixD1(A_inv),false);\n }" ]
Creates updateable version of capability registry that on publish pushes all changes to main registry this is used to create context local registry that only on completion commits changes to main registry @return writable registry
[ "CapabilityRegistry createShadowCopy() {\n CapabilityRegistry result = new CapabilityRegistry(forServer, this);\n readLock.lock();\n try {\n try {\n result.writeLock.lock();\n copy(this, result);\n } finally {\n result.writeLock.unlock();\n }\n } finally {\n readLock.unlock();\n }\n return result;\n }" ]
[ "public static String getVcsRevision(Map<String, String> env) {\n String revision = env.get(\"SVN_REVISION\");\n if (StringUtils.isBlank(revision)) {\n revision = env.get(GIT_COMMIT);\n }\n if (StringUtils.isBlank(revision)) {\n revision = env.get(\"P4_CHANGELIST\");\n }\n return revision;\n }", "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 }", "public static Date getTime(int hour, int minutes)\n {\n Calendar cal = popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hour);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, 0);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result;\n }", "@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}", "private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}", "public List<ChannelInfo> getChannels() {\n final URI uri = uriWithPath(\"./channels/\");\n return Arrays.asList(this.rt.getForObject(uri, ChannelInfo[].class));\n }", "public static sslglobal_sslpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\tsslglobal_sslpolicy_binding response[] = (sslglobal_sslpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private LoginContext getClientLoginContext() throws LoginException {\n Configuration config = new Configuration() {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name) {\n Map<String, String> options = new HashMap<String, String>();\n options.put(\"multi-threaded\", \"true\");\n options.put(\"restore-login-identity\", \"true\");\n\n AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);\n return new AppConfigurationEntry[] { clmEntry };\n }\n };\n return getLoginContext(config);\n }", "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 }" ]
This is the probability density function for the Gaussian distribution.
[ "private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }" ]
[ "public static int cudnnBatchNormalizationBackward(\n cudnnHandle handle, \n int mode, \n Pointer alphaDataDiff, \n Pointer betaDataDiff, \n Pointer alphaParamDiff, \n Pointer betaParamDiff, \n cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */\n Pointer x, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor dxDesc, \n Pointer dx, \n /** Shared tensor desc for the 4 tensors below */\n cudnnTensorDescriptor dBnScaleBiasDesc, \n Pointer bnScale, /** bnBias doesn't affect backpropagation */\n /** scale and bias diff are not backpropagated below this layer */\n Pointer dBnScaleResult, \n Pointer dBnBiasResult, \n /** Same epsilon as forward pass */\n double epsilon, \n /** Optionally cached intermediate results from\n forward pass */\n Pointer savedMean, \n Pointer savedInvVariance)\n {\n return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));\n }", "public com.cloudant.client.api.model.ReplicationResult trigger() {\r\n ReplicationResult couchDbReplicationResult = replication.trigger();\r\n com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant\r\n .client.api.model.ReplicationResult(couchDbReplicationResult);\r\n return replicationResult;\r\n }", "Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }", "void close() {\n try {\n performTeardownExchange();\n } catch (IOException e) {\n logger.warn(\"Problem reporting our intention to close the dbserver connection\", e);\n }\n try {\n channel.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output channel\", e);\n }\n try {\n os.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output stream\", e);\n }\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client input stream\", e);\n }\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client socket\", e);\n }\n }", "public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);\n\t\tDatabaseResults results = null;\n\t\ttry {\n\t\t\tresults = compiledStatement.runQuery(null);\n\t\t\tif (results.first()) {\n\t\t\t\treturn results.getLong(0);\n\t\t\t} else {\n\t\t\t\tthrow new SQLException(\"No result found in queryForLong: \" + preparedStmt.getStatement());\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(results, \"results\");\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}", "private void ensureColumn(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN))\r\n {\r\n String javaname = fieldDef.getName();\r\n\r\n if (fieldDef.isNested())\r\n { \r\n int pos = javaname.indexOf(\"::\");\r\n\r\n // we convert nested names ('_' for '::')\r\n if (pos > 0)\r\n {\r\n StringBuffer newJavaname = new StringBuffer(javaname.substring(0, pos));\r\n int lastPos = pos + 2;\r\n\r\n do\r\n {\r\n pos = javaname.indexOf(\"::\", lastPos);\r\n newJavaname.append(\"_\");\r\n if (pos > 0)\r\n { \r\n newJavaname.append(javaname.substring(lastPos, pos));\r\n lastPos = pos + 2;\r\n }\r\n else\r\n {\r\n newJavaname.append(javaname.substring(lastPos));\r\n }\r\n }\r\n while (pos > 0);\r\n javaname = newJavaname.toString();\r\n }\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN, javaname);\r\n }\r\n }", "@SuppressWarnings(\"unused\")\n public String getDevicePushToken(final PushType type) {\n switch (type) {\n case GCM:\n return getCachedGCMToken();\n case FCM:\n return getCachedFCMToken();\n default:\n return null;\n }\n }", "protected void fixIntegerPrecisions(ItemIdValue itemIdValue,\n\t\t\tString propertyId) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Get the current statements for the property we want to fix:\n\t\t\tStatementGroup editPropertyStatements = currentItemDocument\n\t\t\t\t\t.findStatementGroup(propertyId);\n\t\t\tif (editPropertyStatements == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" no longer has any statements for \" + propertyId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tPropertyIdValue property = Datamodel\n\t\t\t\t\t.makeWikidataPropertyIdValue(propertyId);\n\t\t\tList<Statement> updateStatements = new ArrayList<>();\n\t\t\tfor (Statement s : editPropertyStatements) {\n\t\t\t\tQuantityValue qv = (QuantityValue) s.getValue();\n\t\t\t\tif (qv != null && isPlusMinusOneValue(qv)) {\n\t\t\t\t\tQuantityValue exactValue = Datamodel.makeQuantityValue(\n\t\t\t\t\t\t\tqv.getNumericValue(), qv.getNumericValue(),\n\t\t\t\t\t\t\tqv.getNumericValue());\n\t\t\t\t\tStatement exactStatement = StatementBuilder\n\t\t\t\t\t\t\t.forSubjectAndProperty(itemIdValue, property)\n\t\t\t\t\t\t\t.withValue(exactValue).withId(s.getStatementId())\n\t\t\t\t\t\t\t.withQualifiers(s.getQualifiers())\n\t\t\t\t\t\t\t.withReferences(s.getReferences())\n\t\t\t\t\t\t\t.withRank(s.getRank()).build();\n\t\t\t\t\tupdateStatements.add(exactStatement);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (updateStatements.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** \" + qid + \" quantity values for \"\n\t\t\t\t\t\t+ propertyId + \" already fixed\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tupdateStatements, propertyId);\n\n\t\t\tdataEditor.updateStatements(currentItemDocument, updateStatements,\n\t\t\t\t\tCollections.<Statement> emptyList(),\n\t\t\t\t\t\"Set exact values for [[Property:\" + propertyId + \"|\"\n\t\t\t\t\t\t\t+ propertyId + \"]] integer quantities (Task MB2)\");\n\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)\n {\n boolean result = false;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = true;\n break;\n }\n\n case NON_WORKING:\n {\n result = false;\n break;\n }\n\n case DEFAULT:\n {\n if (mpxjCalendar.getParent() == null)\n {\n result = false;\n }\n else\n {\n result = isWorkingDay(mpxjCalendar.getParent(), day);\n }\n break;\n }\n }\n\n return (result);\n }" ]
Deploys application reading resources from specified classpath location @param applicationName to configure in cluster @param classpathLocations where resources are read @throws IOException
[ "public void deployApplication(String applicationName, String... classpathLocations) throws IOException {\n\n final List<URL> classpathElements = Arrays.stream(classpathLocations)\n .map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath))\n .collect(Collectors.toList());\n\n deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()]));\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 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}", "public static appfwwsdl get(nitro_service service) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tappfwwsdl[] response = (appfwwsdl[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private static boolean getSystemConnectivity(Context context) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (cm == null) {\n return false;\n }\n\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n return activeNetwork.isConnectedOrConnecting();\n } catch (Exception exception) {\n return false;\n }\n }", "private boolean isInInnerCircle(float x, float y) {\n return GearWearableUtility.isInCircle(x, y, CENTER_X, CENTER_Y, INNER_RADIUS);\n }", "public static long hash(final BsonDocument doc) {\n if (doc == null) {\n return 0L;\n }\n\n final byte[] docBytes = toBytes(doc);\n long hashValue = FNV_64BIT_OFFSET_BASIS;\n\n for (int offset = 0; offset < docBytes.length; offset++) {\n hashValue ^= (0xFF & docBytes[offset]);\n hashValue *= FNV_64BIT_PRIME;\n }\n\n return hashValue;\n }", "private static void listTaskNotes(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n String notes = task.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + task.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }", "public Task<Void> updateSyncFrequency(@NonNull final SyncFrequency syncFrequency) {\n return this.dispatcher.dispatchTask(new Callable<Void>() {\n @Override\n public Void call() throws Exception {\n SyncImpl.this.proxy.updateSyncFrequency(syncFrequency);\n return null;\n }\n });\n }", "public void processAnonymousField(Properties attributes) throws XDocletException\r\n {\r\n if (!attributes.containsKey(ATTRIBUTE_NAME))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.PARAMETER_IS_REQUIRED,\r\n new String[]{ATTRIBUTE_NAME}));\r\n }\r\n\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n fieldDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousField\", \" Processing anonymous field \"+fieldDef.getName());\r\n\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"anonymous\");\r\n }" ]
Constructs a relative path between this path and a given path. <p> Relativization is the inverse of {@link #getAbsolutePath(Path) resolution}. This method attempts to construct a {@link #isAbsolute relative} path that when {@link #getAbsolutePath(Path) resolved} against this path, yields a path that locates the same file as the given path. For example, on UNIX, if this path is {@code "/a/b"} and the given path is {@code "/a/b/c/d"} then the resulting relative path would be {@code "c/d"}. Both paths must be absolute and and either this path or the given path must be a {@link #startsWith(Path) prefix} of the other. @param other the path to relativize against this path @return the resulting relative path or null if neither of the given paths is a prefix of the other @throws IllegalArgumentException if this path and {@code other} are not both absolute or relative
[ "public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}", "protected ZipEntry getZipEntry(String filename) throws ZipException {\n\n // yes\n ZipEntry entry = getZipFile().getEntry(filename);\n // path to file might be relative, too\n if ((entry == null) && filename.startsWith(\"/\")) {\n entry = m_zipFile.getEntry(filename.substring(1));\n }\n if (entry == null) {\n throw new ZipException(\n Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_FILE_NOT_FOUND_IN_ZIP_1, filename));\n }\n return entry;\n }", "public HiveShellContainer evaluateStatement(List<? extends Script> scripts, Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable {\n container = null;\n FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault());\n try {\n LOGGER.info(\"Setting up {} in {}\", getName(), temporaryFolder.getRoot().getAbsolutePath());\n container = createHiveServerContainer(scripts, target, temporaryFolder);\n base.evaluate();\n return container;\n } finally {\n tearDown();\n }\n }", "public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, new Class[]{ type }, new Object[]{ arg });\r\n }", "private long getEndTime(ISuite suite, IInvokedMethod method)\n {\n // Find the latest end time for all tests in the suite.\n for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())\n {\n ITestContext testContext = entry.getValue().getTestContext();\n for (ITestNGMethod m : testContext.getAllTestMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n // If we can't find a matching test method it must be a configuration method.\n for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n }\n throw new IllegalStateException(\"Could not find matching end time.\");\n }", "private Collection<? extends ResourceRoot> handleClassPathItems(final DeploymentUnit deploymentUnit) {\n final Set<ResourceRoot> additionalRoots = new HashSet<ResourceRoot>();\n final ArrayDeque<ResourceRoot> toProcess = new ArrayDeque<ResourceRoot>();\n final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n toProcess.addAll(resourceRoots);\n final Set<ResourceRoot> processed = new HashSet<ResourceRoot>(resourceRoots);\n\n while (!toProcess.isEmpty()) {\n final ResourceRoot root = toProcess.pop();\n final List<ResourceRoot> classPathRoots = root.getAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS);\n for(ResourceRoot cpRoot : classPathRoots) {\n if(!processed.contains(cpRoot)) {\n additionalRoots.add(cpRoot);\n toProcess.add(cpRoot);\n processed.add(cpRoot);\n }\n }\n }\n return additionalRoots;\n }", "private List<I_CmsSearchConfigurationSortOption> getSortOptions() {\n\n final List<I_CmsSearchConfigurationSortOption> options = new ArrayList<I_CmsSearchConfigurationSortOption>();\n final CmsXmlContentValueSequence sortOptions = m_xml.getValueSequence(XML_ELEMENT_SORTOPTIONS, m_locale);\n if (sortOptions == null) {\n return null;\n } else {\n for (int i = 0; i < sortOptions.getElementCount(); i++) {\n final I_CmsSearchConfigurationSortOption option = parseSortOption(\n sortOptions.getValue(i).getPath() + \"/\");\n if (option != null) {\n options.add(option);\n }\n }\n return options;\n }\n }", "private void writeResource(Resource mpxj)\n {\n ResourceType xml = m_factory.createResourceType();\n m_apibo.getResource().add(xml);\n\n xml.setAutoComputeActuals(Boolean.TRUE);\n xml.setCalculateCostFromUnits(Boolean.TRUE);\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getResourceCalendar()));\n xml.setCurrencyObjectId(DEFAULT_CURRENCY_ID);\n xml.setDefaultUnitsPerTime(Double.valueOf(1.0));\n xml.setEmailAddress(mpxj.getEmailAddress());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(RESOURCE_ID_PREFIX + mpxj.getUniqueID());\n xml.setIsActive(Boolean.TRUE);\n xml.setMaxUnitsPerTime(getPercentage(mpxj.getMaxUnits()));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(mpxj.getParentID());\n xml.setResourceNotes(mpxj.getNotes());\n xml.setResourceType(getResourceType(mpxj));\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.RESOURCE, mpxj));\n }", "private String escapeString(String value)\n {\n m_buffer.setLength(0);\n m_buffer.append('\"');\n for (int index = 0; index < value.length(); index++)\n {\n char c = value.charAt(index);\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\\\\\"\");\n break;\n }\n\n case '\\\\':\n {\n m_buffer.append(\"\\\\\\\\\");\n break;\n }\n\n case '/':\n {\n m_buffer.append(\"\\\\/\");\n break;\n }\n\n case '\\b':\n {\n m_buffer.append(\"\\\\b\");\n break;\n }\n\n case '\\f':\n {\n m_buffer.append(\"\\\\f\");\n break;\n }\n\n case '\\n':\n {\n m_buffer.append(\"\\\\n\");\n break;\n }\n\n case '\\r':\n {\n m_buffer.append(\"\\\\r\");\n break;\n }\n\n case '\\t':\n {\n m_buffer.append(\"\\\\t\");\n break;\n }\n\n default:\n {\n // Append if it's not a control character (0x00 to 0x1f)\n if (c > 0x1f)\n {\n m_buffer.append(c);\n }\n break;\n }\n }\n }\n m_buffer.append('\"');\n return m_buffer.toString();\n }" ]
Guesses the best set to use at the specified index by looking at the surrounding sets. In general, characters in lower-numbered sets are more common, so we choose them if we can. If no good surrounding sets can be found, the default value returned is the first value from the valid set. @param index the current index @param length the maximum length to look at @param valid the valid sets for this index @return the best set to use at the specified index
[ "private int bestSurroundingSet(int index, int length, int... valid) {\r\n int option1 = set[index - 1];\r\n if (index + 1 < length) {\r\n // we have two options to check\r\n int option2 = set[index + 1];\r\n if (contains(valid, option1) && contains(valid, option2)) {\r\n return Math.min(option1, option2);\r\n } else if (contains(valid, option1)) {\r\n return option1;\r\n } else if (contains(valid, option2)) {\r\n return option2;\r\n } else {\r\n return valid[0];\r\n }\r\n } else {\r\n // we only have one option to check\r\n if (contains(valid, option1)) {\r\n return option1;\r\n } else {\r\n return valid[0];\r\n }\r\n }\r\n }" ]
[ "public static locationfile get(nitro_service service) throws Exception{\n\t\tlocationfile obj = new locationfile();\n\t\tlocationfile[] response = (locationfile[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static List<? extends Expression> getMethodArguments(ASTNode methodCall) {\r\n if (methodCall instanceof ConstructorCallExpression) {\r\n return extractExpressions(((ConstructorCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof MethodCallExpression) {\r\n return extractExpressions(((MethodCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof StaticMethodCallExpression) {\r\n return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments());\r\n } else if (respondsTo(methodCall, \"getArguments\")) {\r\n throw new RuntimeException(); // TODO: remove, should never happen\r\n }\r\n return new ArrayList<Expression>();\r\n }", "public static void extractHouseholderColumn( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU )\n {\n int indexU = (row0+offsetU)*2;\n u[indexU++] = 1;\n u[indexU++] = 0;\n\n for (int row = row0+1; row < row1; row++) {\n int indexA = A.getIndex(row,col);\n u[indexU++] = A.data[indexA];\n u[indexU++] = A.data[indexA+1];\n }\n }", "public static final GVRPickedObject[] pickVisible(GVRScene scene) {\n sFindObjectsLock.lock();\n try {\n final GVRPickedObject[] result = NativePicker.pickVisible(scene.getNative());\n return result;\n } finally {\n sFindObjectsLock.unlock();\n }\n }", "private void checkExtents(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap processedClasses = new HashMap();\r\n InheritanceHelper helper = new InheritanceHelper();\r\n ClassDescriptorDef curExtent;\r\n boolean canBeRemoved;\r\n\r\n for (Iterator it = classDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curExtent = (ClassDescriptorDef)it.next();\r\n canBeRemoved = false;\r\n if (classDef.getName().equals(curExtent.getName()))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies itself as an extent-class\");\r\n }\r\n else if (processedClasses.containsKey(curExtent))\r\n {\r\n canBeRemoved = true;\r\n }\r\n else\r\n {\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(curExtent, classDef.getName(), false))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies an extent-class \"+curExtent.getName()+\" that is not a sub-type of it\");\r\n }\r\n // now we check whether we already have an extent for a base-class of this extent-class\r\n for (Iterator processedIt = processedClasses.keySet().iterator(); processedIt.hasNext();)\r\n {\r\n if (helper.isSameOrSubTypeOf(curExtent, ((ClassDescriptorDef)processedIt.next()).getName(), false))\r\n {\r\n canBeRemoved = true;\r\n break;\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n // won't happen because we don't use lookup of the actual classes\r\n }\r\n }\r\n if (canBeRemoved)\r\n {\r\n it.remove();\r\n }\r\n processedClasses.put(curExtent, null);\r\n }\r\n }", "private void addHours(MpxjTreeNode parentNode, ProjectCalendarDateRanges hours)\n {\n for (DateRange range : hours)\n {\n final DateRange r = range;\n MpxjTreeNode rangeNode = new MpxjTreeNode(range)\n {\n @Override public String toString()\n {\n return m_timeFormat.format(r.getStart()) + \" - \" + m_timeFormat.format(r.getEnd());\n }\n };\n parentNode.add(rangeNode);\n }\n }", "private synchronized void flushData() {\n BufferedWriter writer = null;\n try {\n writer = new BufferedWriter(new FileWriter(new File(this.inputPath)));\n for(String key: this.metadataMap.keySet()) {\n writer.write(NEW_PROPERTY_SEPARATOR + key.toString() + \"]\" + NEW_LINE);\n writer.write(this.metadataMap.get(key).toString());\n writer.write(\"\" + NEW_LINE + \"\" + NEW_LINE);\n }\n writer.flush();\n } catch(IOException e) {\n logger.error(\"IO exception while flushing data to file backed storage: \"\n + e.getMessage());\n }\n\n try {\n if(writer != null)\n writer.close();\n } catch(Exception e) {\n logger.error(\"Error while flushing data to file backed storage: \" + e.getMessage());\n }\n }", "@Nullable\n public T getItem(final int position) {\n if (position < 0 || position >= mObjects.size()) {\n return null;\n }\n return mObjects.get(position);\n }", "private void normalizeSelectedCategories() {\r\n\r\n Collection<String> normalizedCategories = new ArrayList<String>(m_selectedCategories.size());\r\n for (CmsTreeItem item : m_categories.values()) {\r\n if (item.getCheckBox().isChecked()) {\r\n normalizedCategories.add(item.getId());\r\n }\r\n }\r\n m_selectedCategories = normalizedCategories;\r\n\r\n }" ]
Send the message with the given attributes and the given body using the specified SMTP settings @param to Destination address(es) @param from Sender address @param subject Message subject @param body Message content. May either be a MimeMultipart or another body that java mail recognizes @param contentType MIME content type of body @param serverSetup Server settings to use for connecting to the SMTP server
[ "public static void sendMessageBody(String to, String from, String subject, Object body, String contentType, ServerSetup serverSetup) {\r\n try {\r\n Session smtpSession = getSession(serverSetup);\r\n MimeMessage mimeMessage = new MimeMessage(smtpSession);\r\n\r\n mimeMessage.setRecipients(Message.RecipientType.TO, to);\r\n mimeMessage.setFrom(from);\r\n mimeMessage.setSubject(subject);\r\n mimeMessage.setContent(body, contentType);\r\n sendMimeMessage(mimeMessage);\r\n } catch (MessagingException e) {\r\n throw new IllegalStateException(\"Can not send message\", e);\r\n }\r\n }" ]
[ "public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }", "public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }", "public static tmsessionpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\ttmsessionpolicy_binding obj = new tmsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\ttmsessionpolicy_binding response = (tmsessionpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected static PatchElement createRollbackElement(final PatchEntry entry) {\n final PatchElement patchElement = entry.element;\n final String patchId;\n final Patch.PatchType patchType = patchElement.getProvider().getPatchType();\n if (patchType == Patch.PatchType.CUMULATIVE) {\n patchId = entry.getCumulativePatchID();\n } else {\n patchId = patchElement.getId();\n }\n return createPatchElement(entry, patchId, entry.rollbackActions);\n }", "final public Boolean checkPositionType(String type) {\n if (tokenPosition == null) {\n return false;\n } else {\n return tokenPosition.checkType(type);\n }\n }", "public boolean shouldCompress(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkSuffixes(uri, zipSuffixes);\n\t}", "public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}", "public ProjectCalendar getBaselineCalendar()\n {\n //\n // Attempt to locate the calendar normally used by baselines\n // If this isn't present, fall back to using the default\n // project calendar.\n //\n ProjectCalendar result = getCalendarByName(\"Used for Microsoft Project 98 Baseline Calendar\");\n if (result == null)\n {\n result = getDefaultCalendar();\n }\n return result;\n }", "public void moveRectangleTo(Rectangle rect, float x, float y) {\n\t\tfloat width = rect.getWidth();\n\t\tfloat height = rect.getHeight();\n\t\trect.setLeft(x);\n\t\trect.setBottom(y);\n\t\trect.setRight(rect.getLeft() + width);\n\t\trect.setTop(rect.getBottom() + height);\n\t}" ]
Returns the primary message codewords for mode 2. @param postcode the postal code @param country the country code @param service the service code @return the primary message, as codewords
[ "private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n for (int i = 0; i < postcode.length(); i++) {\r\n if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {\r\n postcode = postcode.substring(0, i);\r\n break;\r\n }\r\n }\r\n\r\n int postcodeNum = Integer.parseInt(postcode);\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNum & 0x03) << 4) | 2;\r\n primary[1] = ((postcodeNum & 0xfc) >> 2);\r\n primary[2] = ((postcodeNum & 0x3f00) >> 8);\r\n primary[3] = ((postcodeNum & 0xfc000) >> 14);\r\n primary[4] = ((postcodeNum & 0x3f00000) >> 20);\r\n primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);\r\n primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }" ]
[ "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }", "public List<TimephasedCost> getTimephasedBaselineCost(int index)\n {\n return m_timephasedBaselineCost[index] == null ? null : m_timephasedBaselineCost[index].getData();\n }", "static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }", "public Iterable<RowKey> getKeys() {\n\t\tif ( currentState.isEmpty() ) {\n\t\t\tif ( cleared ) {\n\t\t\t\t// if the association has been cleared and the currentState is empty, we consider that there are no rows.\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// otherwise, the snapshot rows are the current ones\n\t\t\t\treturn snapshot.getRowKeys();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// It may be a bit too large in case of removals, but that's fine for now\n\t\t\tSet<RowKey> keys = CollectionHelper.newLinkedHashSet( cleared ? currentState.size() : snapshot.size() + currentState.size() );\n\n\t\t\tif ( !cleared ) {\n\t\t\t\t// we add the snapshot RowKeys only if the association has not been cleared\n\t\t\t\tfor ( RowKey rowKey : snapshot.getRowKeys() ) {\n\t\t\t\t\tkeys.add( rowKey );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tkeys.add( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tkeys.remove( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn keys;\n\t\t}\n\t}", "public static Double checkLatitude(String name, Double latitude) {\n if (latitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LATITUDE,\n MAX_LATITUDE,\n latitude);\n }\n return latitude;\n }", "public static boolean nullSafeEquals(final Object obj1, final Object obj2) {\n return ((obj1 == null && obj2 == null)\n || (obj1 != null && obj2 != null && obj1.equals(obj2)));\n }", "public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }", "public static <E> void retainAll(Collection<E> elems, Filter<? super E> filter) {\r\n for (Iterator<E> iter = elems.iterator(); iter.hasNext();) {\r\n E elem = iter.next();\r\n if ( ! filter.accept(elem)) {\r\n iter.remove();\r\n }\r\n }\r\n }", "protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }" ]
Sets the category of the notification for iOS8 notification actions. See 13 minutes into "What's new in iOS Notifications" Passing {@code null} removes the category. @param category the name of the category supplied to the app when receiving the notification @return this
[ "public PayloadBuilder category(final String category) {\n if (category != null) {\n aps.put(\"category\", category);\n } else {\n aps.remove(\"category\");\n }\n return this;\n }" ]
[ "public static boolean distributeAndCheckResponse(DistributionBuilder distributionBuilder, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber, boolean dryRun) throws IOException {\n // do a dry run first\n listener.getLogger().println(\"Performing dry run distribution (no changes are made during dry run) ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, true)) {\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully\");\n if (!dryRun) {\n listener.getLogger().println(\"Performing distribution ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, false)) {\n return false;\n }\n listener.getLogger().println(\"Distribution completed successfully!\");\n }\n return true;\n }", "private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }", "public boolean assertValidPkForDelete(ClassDescriptor cld, Object obj)\r\n {\r\n if(!ProxyHelper.isProxy(obj))\r\n {\r\n FieldDescriptor fieldDescriptors[] = cld.getPkFields();\r\n int fieldDescriptorSize = fieldDescriptors.length;\r\n for(int i = 0; i < fieldDescriptorSize; i++)\r\n {\r\n FieldDescriptor fd = fieldDescriptors[i];\r\n Object pkValue = fd.getPersistentField().get(obj);\r\n if (representsNull(fd, pkValue))\r\n {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }", "public double[] getRegressionCoefficients(RandomVariable value) {\n\t\tif(basisFunctions.length == 0) {\n\t\t\treturn new double[] { };\n\t\t}\n\t\telse if(basisFunctions.length == 1) {\n\t\t\t/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */\n\t\t\treturn new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };\n\t\t}\n\t\telse if(basisFunctions.length == 2) {\n\t\t\t/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */\n\t\t\tdouble a = basisFunctions[0].squared().getAverage();\n\t\t\tdouble b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();\n\t\t\tdouble c = b;\n\t\t\tdouble d = basisFunctions[1].squared().getAverage();\n\n\t\t\tdouble determinant = (a * d - b * c);\n\t\t\tif(determinant != 0) {\n\t\t\t\tdouble x = value.mult(basisFunctions[0]).getAverage();\n\t\t\t\tdouble y = value.mult(basisFunctions[1]).getAverage();\n\n\t\t\t\tdouble alpha0 = (d * x - b * y) / determinant;\n\t\t\t\tdouble alpha1 = (a * y - c * x) / determinant;\n\n\t\t\t\treturn new double[] { alpha0, alpha1 };\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * General case\n\t\t */\n\n\t\t// Build regression matrix\n\t\tdouble[][] BTB = new double[basisFunctions.length][basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tfor(int j=0; j<=i; j++) {\n\t\t\t\tdouble covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();\n\t\t\t\tBTB[i][j] = covariance;\n\t\t\t\tBTB[j][i] = covariance;\n\t\t\t}\n\t\t}\n\n\t\tdouble[] BTX = new double[basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tdouble covariance = basisFunctions[i].mult(value).getAverage();\n\t\t\tBTX[i] = covariance;\n\t\t}\n\n\t\treturn LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);\n\t}", "private static void loadFile(String filePath) {\n final Path path = FileSystems.getDefault().getPath(filePath);\n\n try {\n data.clear();\n data.load(Files.newBufferedReader(path));\n } catch(IOException e) {\n LOG.warn(\"Exception while loading \" + path.toString(), e);\n }\n }", "static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }", "public void search(String query) {\n final Query newQuery = searcher.getQuery().setQuery(query);\n searcher.setQuery(newQuery).search();\n }", "private static Map<String, Set<String>> expand(Map<String, Set<String>> viewToPropNames) {\n\n Set<String> baseProps = viewToPropNames.get(PropertyView.BASE_VIEW);\n\n if (baseProps == null) {\n baseProps = ImmutableSet.of();\n }\n\n if (!SquigglyConfig.isFilterImplicitlyIncludeBaseFieldsInView()) {\n\n // make an exception for full view\n Set<String> fullView = viewToPropNames.get(PropertyView.FULL_VIEW);\n\n if (fullView != null) {\n fullView.addAll(baseProps);\n }\n\n return viewToPropNames;\n }\n\n for (Map.Entry<String, Set<String>> entry : viewToPropNames.entrySet()) {\n String viewName = entry.getKey();\n Set<String> propNames = entry.getValue();\n\n if (!PropertyView.BASE_VIEW.equals(viewName)) {\n propNames.addAll(baseProps);\n }\n }\n\n return viewToPropNames;\n }", "public static String getDumpFileWebDirectory(\n\t\t\tDumpContentType dumpContentType, String projectName) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\tif (\"wikidatawiki\".equals(projectName)) {\n\t\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t\t+ \"wikidata\" + \"/\";\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Wikimedia Foundation uses non-systematic directory names for this type of dump file.\"\n\t\t\t\t\t\t\t\t+ \" I don't know where to find dumps of project \"\n\t\t\t\t\t\t\t\t+ projectName);\n\t\t\t}\n\t\t} else if (WmfDumpFile.WEB_DIRECTORY.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t+ projectName + \"/\";\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}" ]
Return the list of module dependencies @param moduleName @param moduleVersion @param fullRecursive @param corporate @param thirdParty @return List<Dependency> @throws GrapesCommunicationException
[ "public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())\n .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())\n .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors \", moduleName, moduleVersion);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Dependency>>(){});\n }" ]
[ "public static 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_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void fireResourceReadEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceRead(resource);\n }\n }\n }", "static <T> boolean syncInstantiation(T objectType) {\n List<Template> templates = new ArrayList<>();\n Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);\n if (tr == null) {\n /* Default to synchronous instantiation */\n return true;\n } else {\n return tr.syncInstantiation();\n }\n }", "public static authenticationvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_stats response = (authenticationvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "protected boolean isSameSnakSet(Iterator<Snak> snaks1, Iterator<Snak> snaks2) {\n\t\tArrayList<Snak> snakList1 = new ArrayList<>(5);\n\t\twhile (snaks1.hasNext()) {\n\t\t\tsnakList1.add(snaks1.next());\n\t\t}\n\n\t\tint snakCount2 = 0;\n\t\twhile (snaks2.hasNext()) {\n\t\t\tsnakCount2++;\n\t\t\tSnak snak2 = snaks2.next();\n\t\t\tboolean found = false;\n\t\t\tfor (int i = 0; i < snakList1.size(); i++) {\n\t\t\t\tif (snak2.equals(snakList1.get(i))) {\n\t\t\t\t\tsnakList1.set(i, null);\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn snakCount2 == snakList1.size();\n\t}", "public WebhookResponse send(String url, Payload payload) throws IOException {\n SlackHttpClient httpClient = getHttpClient();\n Response httpResponse = httpClient.postJsonPostRequest(url, payload);\n String body = httpResponse.body().string();\n httpClient.runHttpResponseListeners(httpResponse, body);\n\n return WebhookResponse.builder()\n .code(httpResponse.code())\n .message(httpResponse.message())\n .body(body)\n .build();\n }", "public boolean matchesWithMask(long lowerValue, long upperValue, long mask) {\n\t\tif(lowerValue == upperValue) {\n\t\t\treturn matchesWithMask(lowerValue, mask);\n\t\t}\n\t\tif(!isMultiple()) {\n\t\t\t//we know lowerValue and upperValue are not the same, so impossible to match those two values with a single value\n\t\t\treturn false;\n\t\t}\n\t\tlong thisValue = getDivisionValue();\n\t\tlong thisUpperValue = getUpperDivisionValue();\n\t\tif(!isMaskCompatibleWithRange(thisValue, thisUpperValue, mask, getMaxValue())) {\n\t\t\treturn false;\n\t\t}\n\t\treturn lowerValue == (thisValue & mask) && upperValue == (thisUpperValue & mask);\n\t}", "public GeoPermissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // response:\r\n // <perms id=\"240935723\" ispublic=\"1\" iscontact=\"0\" isfriend=\"0\" isfamily=\"0\"/>\r\n GeoPermissions perms = new GeoPermissions();\r\n Element permsElement = response.getPayload();\r\n perms.setPublic(\"1\".equals(permsElement.getAttribute(\"ispublic\")));\r\n perms.setContact(\"1\".equals(permsElement.getAttribute(\"iscontact\")));\r\n perms.setFriend(\"1\".equals(permsElement.getAttribute(\"isfriend\")));\r\n perms.setFamily(\"1\".equals(permsElement.getAttribute(\"isfamily\")));\r\n perms.setId(permsElement.getAttribute(\"id\"));\r\n // I ignore the id attribute. should be the same as the given\r\n // photo id.\r\n return perms;\r\n }" ]
Returns PatternParser used to parse the conversion string. Subclasses may override this to return a subclass of PatternParser which recognize custom conversion characters. @since 0.9.0
[ "protected org.apache.log4j.helpers.PatternParser createPatternParser(final String pattern) {\n\t\treturn new FoundationLoggingPatternParser(pattern);\n\t}" ]
[ "@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n rendererBuilder.withParent(viewGroup);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext()));\n rendererBuilder.withViewType(viewType);\n RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder();\n if (viewHolder == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null viewHolder\");\n }\n return viewHolder;\n }", "private void processUDF(UDFTypeType udf)\n {\n FieldTypeClass fieldType = FIELD_TYPE_MAP.get(udf.getSubjectArea());\n if (fieldType != null)\n {\n UserFieldDataType dataType = UserFieldDataType.getInstanceFromXmlName(udf.getDataType());\n String name = udf.getTitle();\n FieldType field = addUserDefinedField(fieldType, dataType, name);\n if (field != null)\n {\n m_fieldTypeMap.put(udf.getObjectId(), field);\n }\n }\n }", "public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }", "public Weld property(String key, Object value) {\n properties.put(key, value);\n return this;\n }", "public static int getXPathLocation(String dom, String xpath) {\n\t\tString dom_lower = dom.toLowerCase();\n\t\tString xpath_lower = xpath.toLowerCase();\n\t\tString[] elements = xpath_lower.split(\"/\");\n\t\tint pos = 0;\n\t\tint temp;\n\t\tint number;\n\t\tfor (String element : elements) {\n\t\t\tif (!element.isEmpty() && !element.startsWith(\"@\") && !element.contains(\"()\")) {\n\t\t\t\tif (element.contains(\"[\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnumber =\n\t\t\t\t\t\t\t\tInteger.parseInt(element.substring(element.indexOf(\"[\") + 1,\n\t\t\t\t\t\t\t\t\t\telement.indexOf(\"]\")));\n\t\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnumber = 1;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < number; i++) {\n\t\t\t\t\t// find new open element\n\t\t\t\t\ttemp = dom_lower.indexOf(\"<\" + stripEndSquareBrackets(element), pos);\n\n\t\t\t\t\tif (temp > -1) {\n\t\t\t\t\t\tpos = temp + 1;\n\n\t\t\t\t\t\t// if depth>1 then goto end of current element\n\t\t\t\t\t\tif (number > 1 && i < number - 1) {\n\t\t\t\t\t\t\tpos =\n\t\t\t\t\t\t\t\t\tgetCloseElementLocation(dom_lower, pos,\n\t\t\t\t\t\t\t\t\t\t\tstripEndSquareBrackets(element));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pos - 1;\n\t}", "private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }", "private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) {\n\t\t\n\t\tS.Buffer rowBuilder = S.buffer();\n\t\tint colWidth;\n\t\t\n\t\tfor (int i = 0 ; i < colCount ; i ++) {\n\t\t\t\n\t\t\tcolWidth = colMaxLenList.get(i) + 3;\n\t\t\t\n\t\t\tfor (int j = 0; j < colWidth ; j ++) {\n\t\t\t\tif (j==0) {\n\t\t\t\t\trowBuilder.append(\"+\");\n\t\t\t\t} else if ((i+1 == colCount && j+1 == colWidth)) {//for last column close the border\n\t\t\t\t\trowBuilder.append(\"-+\");\n\t\t\t\t} else {\n\t\t\t\t\trowBuilder.append(\"-\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn rowBuilder.append(\"\\n\").toString();\n\t}", "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }", "public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
Add UDFType objects to a PM XML file. @author kmahan @date 2014-09-24 @author lsong @date 2015-7-24
[ "private void writeUserFieldDefinitions()\n {\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n if (cf.getFieldType() != null && cf.getFieldType().getDataType() != null)\n {\n UDFTypeType udf = m_factory.createUDFTypeType();\n udf.setObjectId(Integer.valueOf(FieldTypeHelper.getFieldID(cf.getFieldType())));\n\n udf.setDataType(UserFieldDataType.inferUserFieldDataType(cf.getFieldType().getDataType()));\n udf.setSubjectArea(UserFieldDataType.inferUserFieldSubjectArea(cf.getFieldType()));\n udf.setTitle(cf.getAlias());\n m_apibo.getUDFType().add(udf);\n }\n }\n }" ]
[ "public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }", "public static String getCacheDir(Context ctx) {\n return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || (!Environment.isExternalStorageRemovable() && ctx.getExternalCacheDir() != null) ?\n ctx.getExternalCacheDir().getPath() : ctx.getCacheDir().getPath();\n }", "@Override\r\n @SuppressWarnings(\"unchecked\")\r\n public V put(K key, V value) {\r\n if (value == null) {\r\n return put(key, (V)nullValue);\r\n }\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V result = deltaMap.put(key, value);\r\n if (result == null) {\r\n return originalMap.get(key);\r\n }\r\n if (result == nullValue) {\r\n return null;\r\n }\r\n if (result == removedValue) {\r\n return null;\r\n }\r\n return result;\r\n }", "protected String addPostRunDependent(TaskGroup.HasTaskGroup dependent) {\n Objects.requireNonNull(dependent);\n this.taskGroup.addPostRunDependentTaskGroup(dependent.taskGroup());\n return dependent.taskGroup().key();\n }", "private int getItemViewType(Class prototypeClass) {\n int itemViewType = -1;\n for (Renderer renderer : prototypes) {\n if (renderer.getClass().equals(prototypeClass)) {\n itemViewType = getPrototypeIndex(renderer);\n break;\n }\n }\n if (itemViewType == -1) {\n throw new PrototypeNotFoundException(\n \"Review your RendererBuilder implementation, you are returning one\"\n + \" prototype class not found in prototypes collection\");\n }\n return itemViewType;\n }", "public int getCurrentPage() {\n int currentPage = 1;\n int count = mScrollable.getScrollingItemsCount();\n if (mSupportScrollByPage && mCurrentItemIndex >= 0 &&\n mCurrentItemIndex < count) {\n currentPage = (Math.min(mCurrentItemIndex + mPageSize - 1, count - 1)/mPageSize);\n }\n return currentPage;\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 }", "public Query getCountQuery(Query aQuery)\r\n {\r\n if(aQuery instanceof QueryBySQL)\r\n {\r\n return getQueryBySqlCount((QueryBySQL) aQuery);\r\n }\r\n else if(aQuery instanceof ReportQueryByCriteria)\r\n {\r\n return getReportQueryByCriteriaCount((ReportQueryByCriteria) aQuery);\r\n }\r\n else\r\n {\r\n return getQueryByCriteriaCount((QueryByCriteria) aQuery);\r\n }\r\n }", "protected Collection loadData() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n Collection result;\r\n\r\n if (_data != null) // could be set by listener\r\n {\r\n result = _data;\r\n }\r\n else if (_size != 0)\r\n {\r\n // TODO: returned ManageableCollection should extend Collection to avoid\r\n // this cast\r\n result = (Collection) broker.getCollectionByQuery(getCollectionClass(), getQuery());\r\n }\r\n else\r\n {\r\n result = (Collection)getCollectionClass().newInstance();\r\n }\r\n return result;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }" ]
Return the equivalence class of the argument. If the argument is not contained in and equivalence class, then an empty string is returned. @param punc @return The class name if found. Otherwise, an empty string.
[ "public static String getPunctClass(String punc) {\r\n if(punc.equals(\"%\") || punc.equals(\"-PLUS-\"))//-PLUS- is an escape for \"+\" in the ATB\r\n return \"perc\";\r\n else if(punc.startsWith(\"*\"))\r\n return \"bullet\";\r\n else if(sfClass.contains(punc))\r\n return \"sf\";\r\n else if(colonClass.contains(punc) || pEllipsis.matcher(punc).matches())\r\n return \"colon\";\r\n else if(commaClass.contains(punc))\r\n return \"comma\";\r\n else if(currencyClass.contains(punc))\r\n return \"curr\";\r\n else if(slashClass.contains(punc))\r\n return \"slash\";\r\n else if(lBracketClass.contains(punc))\r\n return \"lrb\";\r\n else if(rBracketClass.contains(punc))\r\n return \"rrb\";\r\n else if(quoteClass.contains(punc))\r\n return \"quote\";\r\n \r\n return \"\";\r\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 }", "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "public void removeScript(int id) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private Key insert(Entity entity) throws DatastoreException {\n CommitRequest req = CommitRequest.newBuilder()\n\t.addMutations(Mutation.newBuilder()\n\t .setInsert(entity))\n .setMode(CommitRequest.Mode.NON_TRANSACTIONAL)\n\t.build();\n return datastore.commit(req).getMutationResults(0).getKey();\n }", "@Override\n public void setCursorDepth(float depth)\n {\n super.setCursorDepth(depth);\n if (mRayModel != null)\n {\n mRayModel.getTransform().setScaleZ(mCursorDepth);\n }\n }", "public static void checkRequired(OptionSet options, String opt1, String opt2)\n throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt1);\n opts.add(opt2);\n checkRequired(options, opts);\n }", "public int size(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t// existence check on inner map1\n\t\tfinal HashMap<K3, V> innerMap2 = innerMap1.get(secondKey);\n\t\tif( innerMap2 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap2.size();\n\t}", "public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}", "public AT_Row setTextAlignment(TextAlignment textAlignment){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
Resolve the disposal method for the given producer method. Any resolved beans will be marked as such for the purpose of validating that all disposal methods are used. For internal use. @param types the types @param qualifiers The binding types to match @param declaringBean declaring bean @return The set of matching disposal methods
[ "public <X> Set<DisposalMethod<X, ?>> resolveDisposalBeans(Set<Type> types, Set<Annotation> qualifiers, AbstractClassBean<X> declaringBean) {\n // We can always cache as this is only ever called by Weld where we avoid non-static inner classes for annotation literals\n Set<DisposalMethod<X, ?>> beans = cast(disposalMethodResolver.resolve(new ResolvableBuilder(manager).addTypes(types).addQualifiers(qualifiers).setDeclaringBean(declaringBean).create(), true));\n resolvedDisposalBeans.addAll(beans);\n return Collections.unmodifiableSet(beans);\n }" ]
[ "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 }", "@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }", "public void setColor(int n, int color) {\n\t\tint firstColor = map[0];\n\t\tint lastColor = map[256-1];\n\t\tif (n > 0)\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)i/n, firstColor, color);\n\t\tif (n < 256-1)\n\t\t\tfor (int i = n; i < 256; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)(i-n)/(256-n), color, lastColor);\n\t}", "public void seekToHoliday(String holidayString, String direction, String seekAmount) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount);\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> void serialize(E object, ParameterizedType<E> parameterizedType, OutputStream os) throws IOException {\n mapperFor(parameterizedType).serialize(object, os);\n }", "@Override public void setUniqueID(Integer uniqueID)\n {\n ProjectFile parent = getParentFile();\n\n if (m_uniqueID != null)\n {\n parent.getCalendars().unmapUniqueID(m_uniqueID);\n }\n\n parent.getCalendars().mapUniqueID(uniqueID, this);\n\n m_uniqueID = uniqueID;\n }", "public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }", "private void readCalendar(Project.Calendars.Calendar calendar, HashMap<BigInteger, ProjectCalendar> map, List<Pair<ProjectCalendar, BigInteger>> baseCalendars)\n {\n ProjectCalendar bc = m_projectFile.addCalendar();\n bc.setUniqueID(NumberHelper.getInteger(calendar.getUID()));\n bc.setName(calendar.getName());\n BigInteger baseCalendarID = calendar.getBaseCalendarUID();\n if (baseCalendarID != null)\n {\n baseCalendars.add(new Pair<ProjectCalendar, BigInteger>(bc, baseCalendarID));\n }\n\n readExceptions(calendar, bc);\n boolean readExceptionsFromDays = bc.getCalendarExceptions().isEmpty();\n\n Project.Calendars.Calendar.WeekDays days = calendar.getWeekDays();\n if (days != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay weekDay : days.getWeekDay())\n {\n readDay(bc, weekDay, readExceptionsFromDays);\n }\n }\n else\n {\n bc.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n }\n\n readWorkWeeks(calendar, bc);\n\n map.put(calendar.getUID(), bc);\n\n m_eventManager.fireCalendarReadEvent(bc);\n }", "private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}" ]
Connects to a child JVM process @param p the process to which to connect @param startAgent whether to installed the JMX agent in the target process if not already in place @return an {@link MBeanServerConnection} to the process's MBean server
[ "public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) {\n try {\n final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent);\n final JMXConnector connector = JMXConnectorFactory.connect(serviceURL);\n final MBeanServerConnection mbsc = connector.getMBeanServerConnection();\n return mbsc;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public static void convolveHV(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) {\n\t\tint index = 0;\n\t\tfloat[] matrix = kernel.getKernelData( null );\n\t\tint rows = kernel.getHeight();\n\t\tint cols = kernel.getWidth();\n\t\tint rows2 = rows/2;\n\t\tint cols2 = cols/2;\n\n\t\tfor (int y = 0; y < height; y++) {\n\t\t\tfor (int x = 0; x < width; x++) {\n\t\t\t\tfloat r = 0, g = 0, b = 0, a = 0;\n\n\t\t\t\tfor (int row = -rows2; row <= rows2; row++) {\n\t\t\t\t\tint iy = y+row;\n\t\t\t\t\tint ioffset;\n\t\t\t\t\tif (0 <= iy && iy < height)\n\t\t\t\t\t\tioffset = iy*width;\n\t\t\t\t\telse if ( edgeAction == CLAMP_EDGES )\n\t\t\t\t\t\tioffset = y*width;\n\t\t\t\t\telse if ( edgeAction == WRAP_EDGES )\n\t\t\t\t\t\tioffset = ((iy+height) % height) * width;\n\t\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tint moffset = cols*(row+rows2)+cols2;\n\t\t\t\t\tfor (int col = -cols2; col <= cols2; col++) {\n\t\t\t\t\t\tfloat f = matrix[moffset+col];\n\n\t\t\t\t\t\tif (f != 0) {\n\t\t\t\t\t\t\tint ix = x+col;\n\t\t\t\t\t\t\tif (!(0 <= ix && ix < width)) {\n\t\t\t\t\t\t\t\tif ( edgeAction == CLAMP_EDGES )\n\t\t\t\t\t\t\t\t\tix = x;\n\t\t\t\t\t\t\t\telse if ( edgeAction == WRAP_EDGES )\n\t\t\t\t\t\t\t\t\tix = (x+width) % width;\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tint rgb = inPixels[ioffset+ix];\n\t\t\t\t\t\t\ta += f * ((rgb >> 24) & 0xff);\n\t\t\t\t\t\t\tr += f * ((rgb >> 16) & 0xff);\n\t\t\t\t\t\t\tg += f * ((rgb >> 8) & 0xff);\n\t\t\t\t\t\t\tb += f * (rgb & 0xff);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tint ia = alpha ? PixelUtils.clamp((int)(a+0.5)) : 0xff;\n\t\t\t\tint ir = PixelUtils.clamp((int)(r+0.5));\n\t\t\t\tint ig = PixelUtils.clamp((int)(g+0.5));\n\t\t\t\tint ib = PixelUtils.clamp((int)(b+0.5));\n\t\t\t\toutPixels[index++] = (ia << 24) | (ir << 16) | (ig << 8) | ib;\n\t\t\t}\n\t\t}\n\t}", "public synchronized void start() {\n\t\tif ((todoFlags & RECORD_CPUTIME) != 0) {\n\t\t\tcurrentStartCpuTime = getThreadCpuTime(threadId);\n\t\t} else {\n\t\t\tcurrentStartCpuTime = -1;\n\t\t}\n\t\tif ((todoFlags & RECORD_WALLTIME) != 0) {\n\t\t\tcurrentStartWallTime = System.nanoTime();\n\t\t} else {\n\t\t\tcurrentStartWallTime = -1;\n\t\t}\n\t\tisRunning = true;\n\t}", "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 }", "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }", "public static sslservicegroup_sslcertkey_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tsslservicegroup_sslcertkey_binding obj = new sslservicegroup_sslcertkey_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tsslservicegroup_sslcertkey_binding response[] = (sslservicegroup_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void handleDirectory(final Predicate<String> filter, final File rootDir, final List<String> discoveredFiles)\n {\n try\n {\n new DirectoryWalker<String>()\n {\n private Path startDir;\n\n public void walk() throws IOException\n {\n this.startDir = rootDir.toPath();\n this.walk(rootDir, discoveredFiles);\n }\n\n @Override\n protected void handleFile(File file, int depth, Collection<String> discoveredFiles) throws IOException\n {\n String newPath = startDir.relativize(file.toPath()).toString();\n if (filter.accept(newPath))\n discoveredFiles.add(newPath);\n }\n\n }.walk();\n }\n catch (IOException ex)\n {\n LOG.log(Level.SEVERE, \"Error reading Furnace addon directory\", ex);\n }\n }", "public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }", "public static void init() {\n reports.clear();\n Reflections reflections = new Reflections(REPORTS_PACKAGE);\n final Set<Class<? extends Report>> reportClasses = reflections.getSubTypesOf(Report.class);\n\n for(Class<? extends Report> c : reportClasses) {\n LOG.info(\"Report class: \" + c.getName());\n try {\n reports.add(c.newInstance());\n } catch (IllegalAccessException | InstantiationException e) {\n LOG.error(\"Error while loading report implementation classes\", e);\n }\n }\n\n if(LOG.isInfoEnabled()) {\n LOG.info(String.format(\"Detected %s reports\", reports.size()));\n }\n }", "public BoxGroupMembership.Info addMembership(BoxUser user, Role role) {\n BoxAPIConnection api = this.getAPI();\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"user\", new JsonObject().add(\"id\", user.getID()));\n requestJSON.add(\"group\", new JsonObject().add(\"id\", this.getID()));\n if (role != null) {\n requestJSON.add(\"role\", role.toJSONString());\n }\n\n URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get(\"id\").asString());\n return membership.new Info(responseJSON);\n }" ]
Get the root build which triggered the current build. The build root is considered to be the one furthest one away from the current build which has the isPassIdentifiedDownstream active, if no parent build exists, check that the current build needs an upstream identifier, if it does return it. @param currentBuild The current build. @return The root build with isPassIdentifiedDownstream active. Null if no upstream or non is found.
[ "public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }" ]
[ "public void setMaintenanceMode(String appName, boolean enable) {\n connection.execute(new AppUpdate(appName, enable), apiKey);\n }", "public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) {\n\n String result = configOptions.get(optionKey);\n return null != result ? result : defaultValue;\n }", "@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\tthis.attributes = (Map) attributes;\n\t}", "public static final int findValueInListBox(ListBox list, String value) {\n\tfor (int i=0; i<list.getItemCount(); i++) {\n\t if (value.equals(list.getValue(i))) {\n\t\treturn i;\n\t }\n\t}\n\treturn -1;\n }", "public static systemuser get(nitro_service service, String username) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tobj.set_username(username);\n\t\tsystemuser response = (systemuser) obj.get_resource(service);\n\t\treturn response;\n\t}", "@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 boolean measureAll(List<Widget> measuredChildren) {\n boolean changed = false;\n for (int i = 0; i < mContainer.size(); ++i) {\n\n if (!isChildMeasured(i)) {\n Widget child = measureChild(i, false);\n if (child != null) {\n if (measuredChildren != null) {\n measuredChildren.add(child);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n postMeasurement();\n }\n return changed;\n }", "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}", "private static void bodyWithBuilder(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename,\n Predicate<PropertyCodeGenerator> isOptional) {\n Variable result = new Variable(\"result\");\n\n code.add(\" %1$s %2$s = new %1$s(\\\"%3$s{\", StringBuilder.class, result, typename);\n boolean midStringLiteral = true;\n boolean midAppends = true;\n boolean prependCommas = false;\n\n PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values()\n .stream()\n .filter(isOptional)\n .reduce((first, second) -> second)\n .get();\n\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n if (isOptional.test(generator)) {\n if (midStringLiteral) {\n code.add(\"\\\")\");\n }\n if (midAppends) {\n code.add(\";%n \");\n }\n code.add(\"if (\");\n if (generator.initialState() == Initially.OPTIONAL) {\n generator.addToStringCondition(code);\n } else {\n code.add(\"!%s.contains(%s.%s)\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n }\n code.add(\") {%n %s.append(\\\"\", result);\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), property.getField());\n if (!prependCommas) {\n code.add(\".append(\\\", \\\")\");\n }\n code.add(\";%n }%n \");\n if (generator.equals(lastOptionalGenerator)) {\n code.add(\"return %s.append(\\\"\", result);\n midStringLiteral = true;\n midAppends = true;\n } else {\n midStringLiteral = false;\n midAppends = false;\n }\n } else {\n if (!midAppends) {\n code.add(\"%s\", result);\n }\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), (Excerpt) generator::addToStringValue);\n midStringLiteral = false;\n midAppends = true;\n prependCommas = true;\n }\n }\n\n checkState(prependCommas, \"Unexpected state at end of toString method\");\n checkState(midAppends, \"Unexpected state at end of toString method\");\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n code.add(\"}\\\").toString();%n\", result);\n }" ]
Features are only cacheable when not converted lazily as lazy features are incomplete, it would put detached objects in the cache. @return true when features are not converted lazily
[ "private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}" ]
[ "public Response getTemplate(String id) throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/templates/\" + id));\n }", "public DesignDocument get(String id) {\r\n assertNotEmpty(id, \"id\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id));\r\n }", "BeatGrid getBeatGrid(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.BEAT_GRID_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.BEAT_GRID) {\n return new BeatGrid(new DataReference(slot, rekordboxId), response);\n }\n logger.error(\"Unexpected response type when requesting beat grid: {}\", response);\n return null;\n }", "private void writeResources() throws IOException\n {\n writeAttributeTypes(\"resource_types\", ResourceField.values());\n\n m_writer.writeStartList(\"resources\");\n for (Resource resource : m_projectFile.getResources())\n {\n writeFields(null, resource, ResourceField.values());\n }\n m_writer.writeEndList();\n }", "public static AT_Row createContentRow(Object[] content, TableRowStyle style){\r\n\t\tValidate.notNull(content);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\tLinkedList<AT_Cell> cells = new LinkedList<AT_Cell>();\r\n\t\tfor(Object o : content){\r\n\t\t\tcells.add(new AT_Cell(o));\r\n\t\t}\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn TableRowType.CONTENT;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic LinkedList<AT_Cell> getCells(){\r\n\t\t\t\treturn cells;\r\n\t\t\t}\r\n\t\t};\r\n\t}", "public final PJsonObject toJSON() {\n try {\n JSONObject json = new JSONObject();\n for (String key: this.obj.keySet()) {\n Object opt = opt(key);\n if (opt instanceof PYamlObject) {\n opt = ((PYamlObject) opt).toJSON().getInternalObj();\n } else if (opt instanceof PYamlArray) {\n opt = ((PYamlArray) opt).toJSON().getInternalArray();\n }\n json.put(key, opt);\n }\n return new PJsonObject(json, this.getContextName());\n } catch (Throwable e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public static int brightnessNTSC(int rgb) {\n\t\tint r = (rgb >> 16) & 0xff;\n\t\tint g = (rgb >> 8) & 0xff;\n\t\tint b = rgb & 0xff;\n\t\treturn (int)(r*0.299f + g*0.587f + b*0.114f);\n\t}", "public static base_response update(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 updateresource = new nsip6();\n\t\tupdateresource.ipv6address = resource.ipv6address;\n\t\tupdateresource.td = resource.td;\n\t\tupdateresource.nd = resource.nd;\n\t\tupdateresource.icmp = resource.icmp;\n\t\tupdateresource.vserver = resource.vserver;\n\t\tupdateresource.telnet = resource.telnet;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.gui = resource.gui;\n\t\tupdateresource.ssh = resource.ssh;\n\t\tupdateresource.snmp = resource.snmp;\n\t\tupdateresource.mgmtaccess = resource.mgmtaccess;\n\t\tupdateresource.restrictaccess = resource.restrictaccess;\n\t\tupdateresource.state = resource.state;\n\t\tupdateresource.map = resource.map;\n\t\tupdateresource.dynamicrouting = resource.dynamicrouting;\n\t\tupdateresource.hostroute = resource.hostroute;\n\t\tupdateresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\tupdateresource.metric = resource.metric;\n\t\tupdateresource.vserverrhilevel = resource.vserverrhilevel;\n\t\tupdateresource.ospf6lsatype = resource.ospf6lsatype;\n\t\tupdateresource.ospfarea = resource.ospfarea;\n\t\treturn updateresource.update_resource(client);\n\t}", "void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }" ]
Sets the bottom padding character for all cells in the table. @param paddingBottomChar new padding character, ignored if null @return this to allow chaining
[ "public AsciiTable setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "private void checkForCycles(DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph)\n {\n CycleDetector<RuleProvider, DefaultEdge> cycleDetector = new CycleDetector<>(graph);\n\n if (cycleDetector.detectCycles())\n {\n // if we have cycles, then try to throw an exception with some usable data\n Set<RuleProvider> cycles = cycleDetector.findCycles();\n StringBuilder errorSB = new StringBuilder();\n for (RuleProvider cycle : cycles)\n {\n errorSB.append(\"Found dependency cycle involving: \" + cycle.getMetadata().getID()).append(System.lineSeparator());\n Set<RuleProvider> subCycleSet = cycleDetector.findCyclesContainingVertex(cycle);\n for (RuleProvider subCycle : subCycleSet)\n {\n errorSB.append(\"\\tSubcycle: \" + subCycle.getMetadata().getID()).append(System.lineSeparator());\n }\n }\n throw new RuntimeException(\"Dependency cycles detected: \" + errorSB.toString());\n }\n }", "public void addAll(@NonNull final Collection<T> collection) {\n final int length = collection.size();\n if (length == 0) {\n return;\n }\n synchronized (mLock) {\n final int position = getItemCount();\n mObjects.addAll(collection);\n notifyItemRangeInserted(position, length);\n }\n }", "private void changeClusterAndStores(String clusterKey,\n final Cluster cluster,\n String storesKey,\n final List<StoreDefinition> storeDefs) {\n metadataStore.writeLock.lock();\n try {\n VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock));\n\n // now put new stores\n updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock));\n\n } catch(Exception e) {\n logger.info(\"Error while changing cluster to \" + cluster + \"for key \" + clusterKey);\n throw new VoldemortException(e);\n } finally {\n metadataStore.writeLock.unlock();\n }\n }", "public static URL codeLocationFromURL(String url) {\n try {\n return new URL(url);\n } catch (Exception e) {\n throw new InvalidCodeLocation(url);\n }\n }", "protected Boolean checkBoolean(Object val, Boolean def) {\n return (val == null) ? def : (Boolean) val;\n }", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }", "public static String getInputValueName(\n @Nullable final String inputPrefix,\n @Nonnull final BiMap<String, String> inputMapper,\n @Nonnull final String field) {\n String name = inputMapper == null ? null : inputMapper.inverse().get(field);\n if (name == null) {\n if (inputMapper != null && inputMapper.containsKey(field)) {\n throw new RuntimeException(\"field in keys\");\n }\n final String[] defaultValues = {\n Values.TASK_DIRECTORY_KEY, Values.CLIENT_HTTP_REQUEST_FACTORY_KEY,\n Values.TEMPLATE_KEY, Values.PDF_CONFIG_KEY, Values.SUBREPORT_DIR_KEY,\n Values.OUTPUT_FORMAT_KEY, Values.JOB_ID_KEY\n };\n if (inputPrefix == null || Arrays.asList(defaultValues).contains(field)) {\n name = field;\n } else {\n name = inputPrefix.trim() +\n Character.toUpperCase(field.charAt(0)) +\n field.substring(1);\n }\n }\n return name;\n }", "public int size() {\n\t\tint size = cleared ? 0 : snapshot.size();\n\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\tcase PUT:\n\t\t\t\t\tif ( cleared || !snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize++;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tif ( !cleared && snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn size;\n\t}", "protected void processResourceBaseline(Row row)\n {\n Integer id = row.getInteger(\"RES_UID\");\n Resource resource = m_project.getResourceByUniqueID(id);\n if (resource != null)\n {\n int index = row.getInt(\"RB_BASE_NUM\");\n\n resource.setBaselineWork(index, row.getDuration(\"RB_BASE_WORK\"));\n resource.setBaselineCost(index, row.getCurrency(\"RB_BASE_COST\"));\n }\n }" ]
Retrieve the correct index for the supplied Table instance. @param table Table instance @return index
[ "private Map<String, Table> getIndex(Table table)\n {\n Map<String, Table> result;\n\n if (!table.getResourceFlag())\n {\n result = m_taskTablesByName;\n }\n else\n {\n result = m_resourceTablesByName;\n }\n return result;\n }" ]
[ "protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }", "public static ComplexNumber Add(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real + scalar, z1.imaginary);\r\n }", "@SuppressWarnings({})\n public synchronized void removeStoreFromSession(List<String> storeNameToRemove) {\n\n logger.info(\"closing the Streaming session for a few stores\");\n\n commitToVoldemort(storeNameToRemove);\n cleanupSessions(storeNameToRemove);\n\n }", "public static List<int[]> createList( int N )\n {\n int data[] = new int[ N ];\n for( int i = 0; i < data.length; i++ ) {\n data[i] = -1;\n }\n\n List<int[]> ret = new ArrayList<int[]>();\n\n createList(data,0,-1,ret);\n\n return ret;\n }", "protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }", "protected void recycleChildren() {\n for (ListItemHostWidget host: getAllHosts()) {\n recycle(host);\n }\n mContent.onTransformChanged();\n mContent.requestLayout();\n }", "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\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 }", "@Override\n public EnvironmentConfig setSetting(@NotNull final String key, @NotNull final Object value) {\n return (EnvironmentConfig) super.setSetting(key, value);\n }" ]
Lists the buildpacks installed on an app @param appName See {@link #listApps} for a list of apps that can be used.
[ "public List<BuildpackInstallation> listBuildpackInstallations(String appName) {\n return connection.execute(new BuildpackInstallationList(appName), apiKey);\n }" ]
[ "public void recordServerResult(ServerIdentity server, ModelNode response) {\n\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n boolean serverFailed = response.has(FAILURE_DESCRIPTION);\n\n\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recording server result for '%s': failed = %s\",\n server, server);\n\n synchronized (this) {\n int previousFailed = failureCount;\n if (serverFailed) {\n failureCount++;\n }\n else {\n successCount++;\n }\n if (previousFailed <= maxFailed) {\n if (!serverFailed && (successCount + failureCount) == servers.size()) {\n // All results are in; notify parent of success\n parent.recordServerGroupResult(serverGroupName, false);\n }\n else if (serverFailed && failureCount > maxFailed) {\n parent.recordServerGroupResult(serverGroupName, true);\n }\n }\n }\n }", "public static final int getInt(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Integer.parseInt(value));\n }", "public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }", "public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }", "private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }", "public void addPartialFieldAssignment(\n SourceBuilder code, Excerpt finalField, String builder) {\n addFinalFieldAssignment(code, finalField, builder);\n }", "public DbOrganization getMatchingOrganization(final DbModule dbModule) {\n if(dbModule.getOrganization() != null\n && !dbModule.getOrganization().isEmpty()){\n return getOrganization(dbModule.getOrganization());\n }\n\n for(final DbOrganization organization: repositoryHandler.getAllOrganizations()){\n final CorporateFilter corporateFilter = new CorporateFilter(organization);\n if(corporateFilter.matches(dbModule)){\n return organization;\n }\n }\n\n return null;\n }", "public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}", "protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }" ]
Returns the number of vertex indices for a single face. @param face the face @return the number of indices
[ "public int getFaceNumIndices(int face) {\n if (null == m_faceOffsets) {\n if (face >= m_numFaces || face < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + face + \n \", Size: \" + m_numFaces);\n }\n return 3;\n }\n else {\n /* \n * no need to perform bound checks here as the array access will\n * throw IndexOutOfBoundsExceptions if the index is invalid\n */\n \n if (face == m_numFaces - 1) {\n return m_faces.capacity() / 4 - m_faceOffsets.getInt(face * 4);\n }\n \n return m_faceOffsets.getInt((face + 1) * 4) - \n m_faceOffsets.getInt(face * 4);\n }\n }" ]
[ "int read(InputStream is, int contentLength) {\n if (is != null) {\n try {\n int capacity = (contentLength > 0) ? (contentLength + 4096) : 16384;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream(capacity);\n int nRead;\n byte[] data = new byte[16384];\n while ((nRead = is.read(data, 0, data.length)) != -1) {\n buffer.write(data, 0, nRead);\n }\n buffer.flush();\n\n read(buffer.toByteArray());\n } catch (IOException e) {\n Logger.d(TAG, \"Error reading data from stream\", e);\n }\n } else {\n status = STATUS_OPEN_ERROR;\n }\n\n try {\n if (is != null) {\n is.close();\n }\n } catch (IOException e) {\n Logger.d(TAG, \"Error closing stream\", e);\n }\n\n return status;\n }", "public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }", "private void checkTexRange(AiTextureType type, int index) {\n if (index < 0 || index > m_numTextures.get(type)) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size: \" +\n m_numTextures.get(type));\n }\n }", "public JsonNode wbSetClaim(String statement,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statement,\n\t\t\t\t\"Statement parameter cannot be null when adding or changing a statement\");\n\t\t\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", statement);\n\t\t\n\t\treturn performAPIAction(\"wbsetclaim\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}", "public static Predicate is(final String sql) {\n return new Predicate() {\n public String toSql() {\n return sql;\n }\n public void init(AbstractSqlCreator creator) {\n }\n };\n }", "public static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }", "public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}", "public Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\n }", "public void removeAt(int index) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.remove(index);\n } else {\n mObjects.remove(index);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }" ]
Returns all known Java installations @return a map from the version strings to their respective paths of the Java installations.
[ "@SuppressWarnings(\"unchecked\")\n public static Map<String, List<Path>> findJavaHomes() {\n try {\n return (Map<String, List<Path>>) accessible(Class.forName(CAPSULE_CLASS_NAME).getDeclaredMethod(\"getJavaHomes\")).invoke(null);\n } catch (ReflectiveOperationException e) {\n throw new AssertionError(e);\n }\n }" ]
[ "public String getTitle(Locale locale)\n {\n String result = null;\n\n if (m_title != null)\n {\n result = m_title;\n }\n else\n {\n if (m_fieldType != null)\n {\n result = m_project.getCustomFields().getCustomField(m_fieldType).getAlias();\n if (result == null)\n {\n result = m_fieldType.getName(locale);\n }\n }\n }\n\n return (result);\n }", "public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) {\n return new EnumStringConverter<E>(enumType);\n }", "private void readBlock(int blockIndex, int startIndex, int blockLength) throws Exception\n {\n logBlock(blockIndex, startIndex, blockLength);\n\n if (blockLength < 128)\n {\n readTableBlock(startIndex, blockLength);\n }\n else\n {\n readColumnBlock(startIndex, blockLength);\n }\n }", "private void writeCalendar(ProjectCalendar mpxj)\n {\n CalendarType xml = m_factory.createCalendarType();\n m_apibo.getCalendar().add(xml);\n String type = mpxj.getResource() == null ? \"Global\" : \"Resource\";\n\n xml.setBaseCalendarObjectId(getCalendarUniqueID(mpxj.getParent()));\n xml.setIsPersonal(mpxj.getResource() == null ? Boolean.FALSE : Boolean.TRUE);\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setType(type);\n\n StandardWorkWeek xmlStandardWorkWeek = m_factory.createCalendarTypeStandardWorkWeek();\n xml.setStandardWorkWeek(xmlStandardWorkWeek);\n\n for (Day day : EnumSet.allOf(Day.class))\n {\n StandardWorkHours xmlHours = m_factory.createCalendarTypeStandardWorkWeekStandardWorkHours();\n xmlStandardWorkWeek.getStandardWorkHours().add(xmlHours);\n xmlHours.setDayOfWeek(getDayName(day));\n\n for (DateRange range : mpxj.getHours(day))\n {\n WorkTimeType xmlWorkTime = m_factory.createWorkTimeType();\n xmlHours.getWorkTime().add(xmlWorkTime);\n\n xmlWorkTime.setStart(range.getStart());\n xmlWorkTime.setFinish(getEndTime(range.getEnd()));\n }\n }\n\n HolidayOrExceptions xmlExceptions = m_factory.createCalendarTypeHolidayOrExceptions();\n xml.setHolidayOrExceptions(xmlExceptions);\n\n if (!mpxj.getCalendarExceptions().isEmpty())\n {\n Calendar calendar = DateHelper.popCalendar();\n for (ProjectCalendarException mpxjException : mpxj.getCalendarExceptions())\n {\n calendar.setTime(mpxjException.getFromDate());\n while (calendar.getTimeInMillis() < mpxjException.getToDate().getTime())\n {\n HolidayOrException xmlException = m_factory.createCalendarTypeHolidayOrExceptionsHolidayOrException();\n xmlExceptions.getHolidayOrException().add(xmlException);\n\n xmlException.setDate(calendar.getTime());\n\n for (DateRange range : mpxjException)\n {\n WorkTimeType xmlHours = m_factory.createWorkTimeType();\n xmlException.getWorkTime().add(xmlHours);\n\n xmlHours.setStart(range.getStart());\n\n if (range.getEnd() != null)\n {\n xmlHours.setFinish(getEndTime(range.getEnd()));\n }\n }\n calendar.add(Calendar.DAY_OF_YEAR, 1);\n }\n }\n DateHelper.pushCalendar(calendar);\n }\n }", "@Override\n public final int getInt(final int i) {\n int val = this.array.optInt(i, Integer.MIN_VALUE);\n if (val == Integer.MIN_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\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}", "public double getBearing(LatLong end) {\n if (this.equals(end)) {\n return 0;\n }\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n double lat2 = end.latToRadians();\n double lon2 = end.longToRadians();\n\n double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),\n Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)\n * Math.cos(lat2) * Math.cos(lon1 - lon2));\n\n if (angle < 0.0) {\n angle += Math.PI * 2.0;\n }\n if (angle > Math.PI) {\n angle -= Math.PI * 2.0;\n }\n\n return Math.toDegrees(angle);\n }", "public List<Addon> listAppAddons(String appName) {\n return connection.execute(new AppAddonsList(appName), apiKey);\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 }" ]
Configures the player whose current track waveforms and status will automatically be reflected. Whenever a new track is loaded on that player, the waveform and metadata will be updated, and the current playback position and state of the player will be reflected by the component. @param player the player number to monitor, or zero if monitoring should stop
[ "public synchronized void setMonitoredPlayer(final int player) {\n if (player < 0) {\n throw new IllegalArgumentException(\"player cannot be negative\");\n }\n clearPlaybackState();\n monitoredPlayer.set(player);\n if (player > 0) { // Start monitoring the specified player\n setPlaybackState(player, 0, false); // Start with default values for required simple state.\n VirtualCdj.getInstance().addUpdateListener(updateListener);\n MetadataFinder.getInstance().addTrackMetadataListener(metadataListener);\n cueList.set(null); // Assume the worst, but see if we have one available next.\n if (MetadataFinder.getInstance().isRunning()) {\n TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n if (metadata != null) {\n cueList.set(metadata.getCueList());\n }\n }\n WaveformFinder.getInstance().addWaveformListener(waveformListener);\n if (WaveformFinder.getInstance().isRunning() && WaveformFinder.getInstance().isFindingDetails()) {\n waveform.set(WaveformFinder.getInstance().getLatestDetailFor(player));\n } else {\n waveform.set(null);\n }\n BeatGridFinder.getInstance().addBeatGridListener(beatGridListener);\n if (BeatGridFinder.getInstance().isRunning()) {\n beatGrid.set(BeatGridFinder.getInstance().getLatestBeatGridFor(player));\n } else {\n beatGrid.set(null);\n }\n try {\n TimeFinder.getInstance().start();\n if (!animating.getAndSet(true)) {\n // Create the thread to update our position smoothly as the track plays\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (animating.get()) {\n try {\n Thread.sleep(33); // Animate at 30 fps\n } catch (InterruptedException e) {\n logger.warn(\"Waveform animation thread interrupted; ending\");\n animating.set(false);\n }\n setPlaybackPosition(TimeFinder.getInstance().getTimeFor(getMonitoredPlayer()));\n }\n }\n }).start();\n }\n } catch (Exception e) {\n logger.error(\"Unable to start the TimeFinder to animate the waveform detail view\");\n animating.set(false);\n }\n } else { // Stop monitoring any player\n animating.set(false);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n cueList.set(null);\n waveform.set(null);\n beatGrid.set(null);\n }\n if (!autoScroll.get()) {\n invalidate();\n }\n repaint();\n }" ]
[ "public void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }", "PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\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 static void startTrack(final Object... args){\r\n if(isClosed){ return; }\r\n //--Create Record\r\n final int len = args.length == 0 ? 0 : args.length-1;\r\n final Object content = args.length == 0 ? \"\" : args[len];\r\n final Object[] tags = new Object[len];\r\n final StackTraceElement ste = getStackTrace();\r\n final long timestamp = System.currentTimeMillis();\r\n System.arraycopy(args,0,tags,0,len);\r\n //--Create Task\r\n final long threadID = Thread.currentThread().getId();\r\n final Runnable startTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n Record toPass = new Record(content,tags,depth,ste,timestamp);\r\n depth += 1;\r\n titleStack.push(args.length == 0 ? \"\" : args[len].toString());\r\n handlers.process(toPass, MessageType.START_TRACK, depth, toPass.timesstamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, startTrack );\r\n } else {\r\n //(case: no threading)\r\n startTrack.run();\r\n }\r\n }", "@UiThread\n public void collapseParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n collapseParent(i);\n }\n }", "public static final String printAccrueType(AccrueType value)\n {\n return (Integer.toString(value == null ? AccrueType.PRORATED.getValue() : value.getValue()));\n }", "private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }", "void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }", "@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }" ]