query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Use this API to fetch all the dnsnsecrec resources that are configured on netscaler. | [
"public static dnsnsecrec[] get(nitro_service service) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\tdnsnsecrec[] response = (dnsnsecrec[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private boolean isAllNumeric(TokenStream stream) {\n List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();\n for(Token token:tokens) {\n try {\n Integer.parseInt(token.getText());\n } catch(NumberFormatException e) {\n return false;\n }\n }\n return true;\n }",
"public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);\n }",
"public static final BigDecimal printRate(Rate rate)\n {\n BigDecimal result = null;\n if (rate != null && rate.getAmount() != 0)\n {\n result = new BigDecimal(rate.getAmount());\n }\n return result;\n }",
"public static dos_stats get(nitro_service service, options option) throws Exception{\n\t\tdos_stats obj = new dos_stats();\n\t\tdos_stats[] response = (dos_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}",
"private CmsCheckBox generateCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = new CmsCheckBox();\n cb.setText(m_dateFormat.format(date));\n cb.setChecked(checkState);\n cb.getElement().setPropertyObject(\"date\", date);\n return cb;\n\n }",
"public static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }",
"private void set(FieldType field, boolean value)\n {\n set(field, (value ? Boolean.TRUE : Boolean.FALSE));\n }",
"protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public PathAddress append(List<PathElement> additionalElements) {\n final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size());\n newList.addAll(pathAddressList);\n newList.addAll(additionalElements);\n return pathAddress(newList);\n }"
] |
Update server mapping's host header
@param serverMappingId ID of server mapping
@param hostHeader value of host header
@return updated ServerRedirect | [
"public ServerRedirect updateServerRedirectHost(int serverMappingId, String hostHeader) {\n ServerRedirect redirect = new ServerRedirect();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"hostHeader\", hostHeader),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVER + \"/\" + serverMappingId + \"/host\", params));\n redirect = getServerRedirectFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return redirect;\n }"
] | [
"public static ThreadPoolExecutor newFixedThreadPool(int threads, String groupname, int queueSize) {\n\t\treturn new ThreadPoolExecutor( threads, threads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(\n\t\t\t\tqueueSize ), new SearchThreadFactory( groupname ), new BlockPolicy() );\n\t}",
"public void setGroupsForPath(Integer[] groups, int pathId) {\n String newGroups = Arrays.toString(groups);\n newGroups = newGroups.substring(1, newGroups.length() - 1).replaceAll(\"\\\\s\", \"\");\n\n logger.info(\"adding groups={}, to pathId={}\", newGroups, pathId);\n EditService.updatePathTable(Constants.PATH_PROFILE_GROUP_IDS, newGroups, pathId);\n }",
"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}",
"@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 DbOrganization getOrganization(final String organizationId) {\n final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);\n\n if(dbOrganization == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Organization \" + organizationId + \" does not exist.\").build());\n }\n\n return dbOrganization;\n }",
"private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,\n final boolean initial) throws OperationFailedException {\n ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);\n if (resolved.recursive) {\n // Some part of expressionString resolved into a different expression.\n // So, start over, ignoring failures. Ignore failures because we don't require\n // that expressions must not resolve to something that *looks like* an expression but isn't\n return resolveExpressionStringRecursively(resolved.result, true, false);\n } else if (resolved.modified) {\n // Typical case\n return new ModelNode(resolved.result);\n } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {\n // We should only get an unmodified expression string back if there was a resolution\n // failure that we ignored.\n assert ignoreDMRResolutionFailure;\n // expressionString came from a node of type expression, so since we did nothing send it back in the same type\n return new ModelNode(new ValueExpression(expressionString));\n } else {\n // The string wasn't really an expression. Two possible cases:\n // 1) if initial == true, someone created a expression node with a non-expression string, which is legal\n // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an\n // expression but can't be resolved. We don't require that expressions must not resolve to something that\n // *looks like* an expression but isn't, so we'll just treat this as a string\n return new ModelNode(expressionString);\n }\n }",
"public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }",
"public ItemRequest<Story> findById(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"GET\");\n }",
"synchronized int storeObject(JSONObject obj, Table table) {\n if (!this.belowMemThreshold()) {\n Logger.v(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = table.getName();\n\n Cursor cursor = null;\n int count = DB_UPDATE_ERROR;\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n cursor = db.rawQuery(\"SELECT COUNT(*) FROM \" + tableName, null);\n cursor.moveToFirst();\n count = cursor.getInt(0);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n\n if (cursor != null) {\n cursor.close();\n cursor = null;\n }\n dbHelper.deleteDatabase();\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n dbHelper.close();\n }\n return count;\n }"
] |
Clones a BufferedImage.
@param image the image to clone
@return the cloned image | [
"public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}"
] | [
"public static List<Dependency> getCorporateDependencies(final Module module, final List<String> corporateFilters) {\n final List<Dependency> corporateDependencies = new ArrayList<Dependency>();\n final Pattern corporatePattern = generateCorporatePattern(corporateFilters);\n\n for(final Dependency dependency: getAllDependencies(module)){\n if(dependency.getTarget().getGavc().matches(corporatePattern.pattern())){\n corporateDependencies.add(dependency);\n }\n }\n\n return corporateDependencies;\n }",
"private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }",
"private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom)\n {\n if (projectModel.getProjectType() == null)\n return true;\n switch (projectModel.getProjectType()){\n case \"ear\":\n break;\n case \"war\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31));\n break;\n case \"ejb\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN));\n break;\n case \"ejb-client\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT));\n break;\n }\n return false;\n }",
"static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }",
"protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {\r\n\r\n try {\r\n\r\n if (file == null) {\r\n throw new IllegalArgumentException(\"File must not be null!\");\r\n }\r\n CmsLock lock = cms.getLock(file);\r\n CmsUser user = cms.getRequestContext().getCurrentUser();\r\n boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()\r\n && (lock.isOwnedBy(user) || lock.isLockableBy(user))\r\n && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);\r\n boolean isReadOnly = !canWrite;\r\n boolean isFolder = file.isFolder();\r\n boolean isRoot = file.getRootPath().length() <= 1;\r\n\r\n Set<Action> aas = new LinkedHashSet<Action>();\r\n addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);\r\n addAction(aas, Action.CAN_GET_PROPERTIES, true);\r\n addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);\r\n addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);\r\n addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);\r\n if (isFolder) {\r\n addAction(aas, Action.CAN_GET_DESCENDANTS, true);\r\n addAction(aas, Action.CAN_GET_CHILDREN, true);\r\n addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);\r\n addAction(aas, Action.CAN_GET_FOLDER_TREE, true);\r\n addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);\r\n addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);\r\n addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);\r\n } else {\r\n addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);\r\n addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);\r\n addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);\r\n }\r\n AllowableActionsImpl result = new AllowableActionsImpl();\r\n result.setAllowableActions(aas);\r\n return result;\r\n } catch (CmsException e) {\r\n handleCmsException(e);\r\n return null;\r\n }\r\n }",
"private void handleUpdate(final CdjStatus update) {\n // First see if any metadata caches need evicting or mount sets need updating.\n if (update.isLocalUsbEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalUsbLoaded()) {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT));\n }\n\n if (update.isLocalSdEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalSdLoaded()){\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT));\n }\n\n if (update.isDiscSlotEmpty()) {\n removeMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n } else {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n }\n\n // Now see if a track has changed that needs new metadata.\n if (update.getTrackType() == CdjStatus.TrackType.UNKNOWN ||\n update.getTrackType() == CdjStatus.TrackType.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.UNKNOWN ||\n update.getRekordboxId() == 0) { // We no longer have metadata for this device.\n clearDeck(update);\n } else { // We can offer metadata for this device; check if we already looked up this track.\n final TrackMetadata lastMetadata = hotCache.get(DeckReference.getDeckReference(update.getDeviceNumber(), 0));\n final DataReference trackReference = new DataReference(update.getTrackSourcePlayer(),\n update.getTrackSourceSlot(), update.getRekordboxId());\n if (lastMetadata == null || !lastMetadata.trackReference.equals(trackReference)) { // We have something new!\n // First see if we can find the new track in the hot cache as a hot cue\n for (TrackMetadata cached : hotCache.values()) {\n if (cached.trackReference.equals(trackReference)) { // Found a hot cue hit, use it.\n updateMetadata(update, cached);\n return;\n }\n }\n\n // Not in the hot cache so try actually retrieving it.\n if (activeRequests.add(update.getTrackSourcePlayer())) {\n // We had to make sure we were not already asking for this track.\n clearDeck(update); // We won't know what it is until our request completes.\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n TrackMetadata data = requestMetadataInternal(trackReference, update.getTrackType(), true);\n if (data != null) {\n updateMetadata(update, data);\n }\n } catch (Exception e) {\n logger.warn(\"Problem requesting track metadata from update\" + update, e);\n } finally {\n activeRequests.remove(update.getTrackSourcePlayer());\n }\n }\n }, \"MetadataFinder metadata request\").start();\n }\n }\n }\n }",
"public Duration getWorkVariance()\n {\n Duration variance = (Duration) getCachedValue(ResourceField.WORK_VARIANCE);\n if (variance == null)\n {\n Duration work = getWork();\n Duration baselineWork = getBaselineWork();\n if (work != null && baselineWork != null)\n {\n variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectProperties()).getDuration(), work.getUnits());\n set(ResourceField.WORK_VARIANCE, variance);\n }\n }\n return (variance);\n }",
"private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }",
"public void authenticate(String authCode) {\n URL url = null;\n try {\n url = new URL(this.tokenURL);\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 = String.format(\"grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s\",\n authCode, this.clientID, this.clientSecret);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n String json = response.getJSON();\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.accessToken = jsonObject.get(\"access_token\").asString();\n this.refreshToken = jsonObject.get(\"refresh_token\").asString();\n this.lastRefresh = System.currentTimeMillis();\n this.expires = jsonObject.get(\"expires_in\").asLong() * 1000;\n }"
] |
Uses an IdentityMap to make sure we don't recurse infinitely on the same object in a cyclic object model.
Proxies
@param obj
@return | [
"public Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\n }"
] | [
"public void publish() {\n\n CmsDirectPublishDialogAction action = new CmsDirectPublishDialogAction();\n List<CmsResource> resources = getBundleResources();\n I_CmsDialogContext context = new A_CmsDialogContext(\"\", ContextType.appToolbar, resources) {\n\n public void focus(CmsUUID structureId) {\n\n //Nothing to do.\n }\n\n public List<CmsUUID> getAllStructureIdsInView() {\n\n return null;\n }\n\n public void updateUserInfo() {\n\n //Nothing to do.\n }\n };\n action.executeAction(context);\n updateLockInformation();\n\n }",
"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 }",
"protected void reportStorageOpTime(long startNs) {\n if(streamStats != null) {\n streamStats.reportStreamingScan(operation);\n streamStats.reportStorageTime(operation,\n Utils.elapsedTimeNs(startNs, System.nanoTime()));\n }\n }",
"private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) {\n if(requestQueue != null) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n destroyRequest(resourceRequest);\n resourceRequest = requestQueue.poll();\n }\n }\n }",
"private void processActivity(Activity activity)\n {\n Task task = getParentTask(activity).addTask();\n task.setText(1, activity.getId());\n\n task.setActualDuration(activity.getActualDuration());\n task.setActualFinish(activity.getActualFinish());\n task.setActualStart(activity.getActualStart());\n //activity.getBaseunit()\n //activity.getBilled()\n //activity.getCalendar()\n //activity.getCostAccount()\n task.setCreateDate(activity.getCreationTime());\n task.setFinish(activity.getCurrentFinish());\n task.setStart(activity.getCurrentStart());\n task.setName(activity.getDescription());\n task.setDuration(activity.getDurationAtCompletion());\n task.setEarlyFinish(activity.getEarlyFinish());\n task.setEarlyStart(activity.getEarlyStart());\n task.setFreeSlack(activity.getFreeFloat());\n task.setLateFinish(activity.getLateFinish());\n task.setLateStart(activity.getLateStart());\n task.setNotes(activity.getNotes());\n task.setBaselineDuration(activity.getOriginalDuration());\n //activity.getPathFloat()\n task.setPhysicalPercentComplete(activity.getPhysicalPercentComplete());\n task.setRemainingDuration(activity.getRemainingDuration());\n task.setCost(activity.getTotalCost());\n task.setTotalSlack(activity.getTotalFloat());\n task.setMilestone(activityIsMilestone(activity));\n //activity.getUserDefined()\n task.setGUID(activity.getUuid());\n\n if (task.getMilestone())\n {\n if (activityIsStartMilestone(activity))\n {\n task.setFinish(task.getStart());\n }\n else\n {\n task.setStart(task.getFinish());\n }\n }\n\n if (task.getActualStart() == null)\n {\n task.setPercentageComplete(Integer.valueOf(0));\n }\n else\n {\n if (task.getActualFinish() != null)\n {\n task.setPercentageComplete(Integer.valueOf(100));\n }\n else\n {\n Duration remaining = activity.getRemainingDuration();\n Duration total = activity.getDurationAtCompletion();\n if (remaining != null && total != null && total.getDuration() != 0)\n {\n double percentComplete = ((total.getDuration() - remaining.getDuration()) * 100.0) / total.getDuration();\n task.setPercentageComplete(Double.valueOf(percentComplete));\n }\n }\n }\n\n m_activityMap.put(activity.getId(), task);\n }",
"private void useSearchService() throws Exception {\n\n System.out.println(\"Searching...\");\n\n WebClient wc = WebClient.create(\"http://localhost:\" + port + \"/services/personservice/search\");\n WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);\n wc.accept(MediaType.APPLICATION_XML);\n \n // Moves to \"/services/personservice/search\"\n wc.path(\"person\");\n \n SearchConditionBuilder builder = SearchConditionBuilder.instance(); \n \n System.out.println(\"Find people with the name Fred or Lorraine:\");\n \n String query = builder.is(\"name\").equalTo(\"Fred\").or()\n .is(\"name\").equalTo(\"Lorraine\")\n .query();\n findPersons(wc, query);\n \n System.out.println(\"Find all people who are no more than 30 years old\");\n query = builder.is(\"age\").lessOrEqualTo(30)\n \t\t.query();\n \n findPersons(wc, query);\n \n System.out.println(\"Find all people who are older than 28 and whose father name is John\");\n query = builder.is(\"age\").greaterThan(28)\n \t\t.and(\"fatherName\").equalTo(\"John\")\n \t\t.query();\n \n findPersons(wc, query);\n\n System.out.println(\"Find all people who have children with name Fred\");\n query = builder.is(\"childName\").equalTo(\"Fred\")\n \t\t.query();\n \n findPersons(wc, query);\n \n //Moves to \"/services/personservice/personinfo\"\n wc.reset().accept(MediaType.APPLICATION_XML);\n wc.path(\"personinfo\");\n \n System.out.println(\"Find all people younger than 40 using JPA2 Tuples\");\n query = builder.is(\"age\").lessThan(40).query();\n \n // Use URI path component to capture the query expression\n wc.path(query);\n \n \n Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);\n for (PersonInfo pi : personInfos) {\n \tSystem.out.println(\"ID : \" + pi.getId());\n }\n\n wc.close();\n }",
"public static base_responses add(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix addresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new onlinkipv6prefix();\n\t\t\t\taddresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\taddresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\taddresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\taddresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\taddresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\taddresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\taddresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"public void disableAllOverrides(int pathID, String clientUUID) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ? \" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n statement.execute();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] |
Non-blocking call
@param key
@param value
@return | [
"public Future<PutObjectResult> putAsync(String key, String value) {\n return Future.of(() -> put(key, value), this.uploadService)\n .flatMap(t->t.fold(p->Future.ofResult(p),e->Future.ofError(e)));\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 static vpnsessionaction[] get(nitro_service service) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tvpnsessionaction[] response = (vpnsessionaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private ModelNode addLocalHost(final ModelNode address, final List<ModelNode> operationList, final String hostName) {\n\n String resolvedHost = hostName != null ? hostName : defaultHostControllerName;\n\n // All further operations should modify the newly added host so the address passed in is updated.\n address.add(HOST, resolvedHost);\n\n // Add a step to setup the ManagementResourceRegistrations for the root host resource\n final ModelNode hostAddOp = new ModelNode();\n hostAddOp.get(OP).set(HostAddHandler.OPERATION_NAME);\n hostAddOp.get(OP_ADDR).set(address);\n\n operationList.add(hostAddOp);\n\n // Add a step to store the HC name\n ModelNode nameValue = hostName == null ? new ModelNode() : new ModelNode(hostName);\n final ModelNode writeName = Util.getWriteAttributeOperation(address, NAME, nameValue);\n operationList.add(writeName);\n return hostAddOp;\n }",
"@Override\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }",
"public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {\n MavenProject mavenProject = getMavenProject(f.getAbsolutePath());\n return mavenProject.getModel().getModules();\n }",
"@Nullable public GeoTarget getCanonAncestor(GeoTarget.Type type) {\n for (GeoTarget target = this; target != null; target = target.canonParent()) {\n if (target.key.type == type) {\n return target;\n }\n }\n\n return null;\n }",
"private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }",
"private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds)\r\n {\r\n Query fkQuery;\r\n QueryByCriteria fkQueryCrit;\r\n\r\n if (cds.isMtoNRelation())\r\n {\r\n fkQueryCrit = getFKQueryMtoN(obj, cld, cds);\r\n }\r\n else\r\n {\r\n fkQueryCrit = getFKQuery1toN(obj, cld, cds);\r\n }\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n fkQueryCrit.addOrderBy((FieldHelper)iter.next());\r\n }\r\n }\r\n\r\n // BRJ: customize the query\r\n if (cds.getQueryCustomizer() != null)\r\n {\r\n fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit);\r\n }\r\n else\r\n {\r\n fkQuery = fkQueryCrit;\r\n }\r\n\r\n return fkQuery;\r\n }",
"public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }"
] |
Returns all factory instances that match the query.
@param query the factory query, not null.
@return the instances found, never null. | [
"public static Collection<MonetaryAmountFactory<?>> getAmountFactories(MonetaryAmountFactoryQuery query) {\n return Optional.ofNullable(monetaryAmountsSingletonQuerySpi()).orElseThrow(() -> new MonetaryException(\n \"No MonetaryAmountsSingletonQuerySpi loaded, query functionality is not available.\"))\n .getAmountFactories(query);\n }"
] | [
"public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api, final String filterTerm,\n final String... fields) {\n return getUsersInfoForType(api, filterTerm, null, null, fields);\n }",
"static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }",
"public static sslfipskey get(nitro_service service, String fipskeyname) throws Exception{\n\t\tsslfipskey obj = new sslfipskey();\n\t\tobj.set_fipskeyname(fipskeyname);\n\t\tsslfipskey response = (sslfipskey) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Swagger read(Set<Class<?>> classes) {\n Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {\n if (class1.equals(class2)) {\n return 0;\n } else if (class1.isAssignableFrom(class2)) {\n return -1;\n } else if (class2.isAssignableFrom(class1)) {\n return 1;\n }\n return class1.getName().compareTo(class2.getName());\n });\n sortedClasses.addAll(classes);\n\n Map<Class<?>, ReaderListener> listeners = new HashMap<Class<?>, ReaderListener>();\n\n for (Class<?> cls : sortedClasses) {\n if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {\n try {\n listeners.put(cls, (ReaderListener) cls.newInstance());\n } catch (Exception e) {\n LOGGER.error(\"Failed to create ReaderListener\", e);\n }\n }\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.beforeScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking beforeScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n // process SwaggerDefinitions first - so we get tags in desired order\n for (Class<?> cls : sortedClasses) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n }\n\n for (Class<?> cls : sortedClasses) {\n read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.afterScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking afterScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n return swagger;\n }",
"public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attribute));\n }",
"protected String extractHeaderComment( File xmlFile )\n throws MojoExecutionException\n {\n\n try\n {\n SAXParser parser = SAXParserFactory.newInstance().newSAXParser();\n SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler();\n parser.setProperty( \"http://xml.org/sax/properties/lexical-handler\", handler );\n parser.parse( xmlFile, handler );\n return handler.getHeaderComment();\n }\n catch ( Exception e )\n {\n throw new MojoExecutionException( \"Failed to parse XML from \" + xmlFile, e );\n }\n }",
"public static cmppolicylabel_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tcmppolicylabel_stats[] response = (cmppolicylabel_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"private synchronized Response doAuthenticatedRequest(\n final StitchAuthRequest stitchReq,\n final AuthInfo authInfo\n ) {\n try {\n return requestClient.doRequest(prepareAuthRequest(stitchReq, authInfo));\n } catch (final StitchServiceException ex) {\n return handleAuthFailure(ex, stitchReq);\n }\n }",
"public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\n }"
] |
Calls the provided closure for a "page" of rows from the table represented by this DataSet.
A page is defined as starting at a 1-based offset, and containing a maximum number of rows.
@param offset the 1-based offset for the first row to be processed
@param maxRows the maximum number of rows to be processed
@param closure called for each row with a GroovyResultSet
@throws SQLException if a database access error occurs
@see groovy.sql.Sql#eachRow(String, java.util.List, int, int, groovy.lang.Closure) | [
"public void each(int offset, int maxRows, Closure closure) throws SQLException {\n eachRow(getSql(), getParameters(), offset, maxRows, closure);\n }"
] | [
"public static XMLGregorianCalendar convertDate(Date date) {\n if (date == null) {\n return null;\n }\n\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTimeInMillis(date.getTime());\n\n try {\n return getDatatypeFactory().newXMLGregorianCalendar(gc);\r\n } catch (DatatypeConfigurationException ex) {\n return null;\n }\n }",
"public ThumborUrlBuilder buildImage(String image) {\n if (image == null || image.length() == 0) {\n throw new IllegalArgumentException(\"Image must not be blank.\");\n }\n return new ThumborUrlBuilder(host, key, image);\n }",
"public static final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return result;\n }",
"private static final void writeJson(Writer os, //\n Object object, //\n SerializeConfig config, //\n SerializeFilter[] filters, //\n DateFormat dateFormat, //\n int defaultFeatures, //\n SerializerFeature... features) {\n SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);\n\n try {\n JSONSerializer serializer = new JSONSerializer(writer, config);\n\n if (dateFormat != null) {\n serializer.setDateFormat(dateFormat);\n serializer.config(SerializerFeature.WriteDateUseDateFormat, true);\n }\n\n if (filters != null) {\n for (SerializeFilter filter : filters) {\n serializer.addFilter(filter);\n }\n }\n serializer.write(object);\n } finally {\n writer.close();\n }\n }",
"public void start() {\n if (this.started) {\n throw new IllegalStateException(\"Cannot start the EventStream because it isn't stopped.\");\n }\n\n final long initialPosition;\n\n if (this.startingPosition == STREAM_POSITION_NOW) {\n BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), \"now\"), \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n initialPosition = jsonObject.get(\"next_stream_position\").asLong();\n } else {\n assert this.startingPosition >= 0 : \"Starting position must be non-negative\";\n initialPosition = this.startingPosition;\n }\n\n this.poller = new Poller(initialPosition);\n\n this.pollerThread = new Thread(this.poller);\n this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n EventStream.this.notifyException(e);\n }\n });\n this.pollerThread.start();\n\n this.started = true;\n }",
"public final Template getTemplate(final String name) {\n final Template template = this.templates.get(name);\n if (template != null) {\n this.accessAssertion.assertAccess(\"Configuration\", this);\n template.assertAccessible(name);\n } else {\n throw new IllegalArgumentException(String.format(\"Template '%s' does not exist. Options are: \" +\n \"%s\", name, this.templates.keySet()));\n }\n return template;\n }",
"static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}",
"public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }",
"@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }"
] |
Returns a list of all the eigenvalues | [
"public List<Complex_F64> getEigenvalues() {\n List<Complex_F64> ret = new ArrayList<Complex_F64>();\n\n if( is64 ) {\n EigenDecomposition_F64 d = (EigenDecomposition_F64)eig;\n for (int i = 0; i < eig.getNumberOfEigenvalues(); i++) {\n ret.add(d.getEigenvalue(i));\n }\n } else {\n EigenDecomposition_F32 d = (EigenDecomposition_F32)eig;\n for (int i = 0; i < eig.getNumberOfEigenvalues(); i++) {\n Complex_F32 c = d.getEigenvalue(i);\n ret.add(new Complex_F64(c.real, c.imaginary));\n }\n }\n\n return ret;\n }"
] | [
"public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }",
"public static base_response Import(nitro_service client, responderhtmlpage resource) throws Exception {\n\t\tresponderhtmlpage Importresource = new responderhtmlpage();\n\t\tImportresource.src = resource.src;\n\t\tImportresource.name = resource.name;\n\t\tImportresource.comment = resource.comment;\n\t\tImportresource.overwrite = resource.overwrite;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"@Override\n public PmdRuleSet create() {\n final SAXBuilder parser = new SAXBuilder();\n final Document dom;\n try {\n dom = parser.build(source);\n } catch (JDOMException | IOException e) {\n if (messages != null) {\n messages.addErrorText(INVALID_INPUT + \" : \" + e.getMessage());\n }\n LOG.error(INVALID_INPUT, e);\n return new PmdRuleSet();\n }\n\n final Element eltResultset = dom.getRootElement();\n final Namespace namespace = eltResultset.getNamespace();\n final PmdRuleSet result = new PmdRuleSet();\n\n final String name = eltResultset.getAttributeValue(\"name\");\n final Element descriptionElement = getChild(eltResultset, namespace);\n\n result.setName(name);\n\n if (descriptionElement != null) {\n result.setDescription(descriptionElement.getValue());\n }\n\n for (Element eltRule : getChildren(eltResultset, \"rule\", namespace)) {\n PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue(\"ref\"));\n pmdRule.setClazz(eltRule.getAttributeValue(\"class\"));\n pmdRule.setName(eltRule.getAttributeValue(\"name\"));\n pmdRule.setMessage(eltRule.getAttributeValue(\"message\"));\n parsePmdPriority(eltRule, pmdRule, namespace);\n parsePmdProperties(eltRule, pmdRule, namespace);\n result.addRule(pmdRule);\n }\n return result;\n }",
"public 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 Set<Tag> getAncestorTags(Tag tag)\n {\n Set<Tag> ancestors = new HashSet<>();\n getAncestorTags(tag, ancestors);\n return ancestors;\n }",
"public static Duration getDuration(ProjectProperties properties, Integer durationValue, Integer unitsValue)\n {\n Duration result;\n if (durationValue == null)\n {\n result = null;\n }\n else\n {\n result = Duration.getInstance(durationValue.intValue(), TimeUnit.MINUTES);\n TimeUnit units = getDurationUnits(unitsValue);\n if (result.getUnits() != units)\n {\n result = result.convertUnits(units, properties);\n }\n }\n return (result);\n }",
"public void forAllForeignkeys(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )\r\n {\r\n _curForeignkeyDef = (ForeignkeyDef)it.next();\r\n generate(template);\r\n }\r\n _curForeignkeyDef = null;\r\n }",
"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 ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) {\n assertNumericArgument(timeout, true);\n this.requestTimeout = unit.toMillis(timeout);\n return this;\n }"
] |
Adds an environment variable to the process being created.
@param key they key for the variable
@param value the value for the variable
@return the launcher | [
"public Launcher addEnvironmentVariable(final String key, final String value) {\n env.put(key, value);\n return this;\n }"
] | [
"protected EntityKey getEntityKey(Tuple tuple, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {\n\t\tObject[] columnValues = new Object[ associatedEntityKeyMetadata.getAssociationKeyColumns().length];\n\t\tint i = 0;\n\n\t\tfor ( String associationKeyColumn : associatedEntityKeyMetadata.getAssociationKeyColumns() ) {\n\t\t\tcolumnValues[i] = tuple.get( associationKeyColumn );\n\t\t\ti++;\n\t\t}\n\n\t\treturn new EntityKey( associatedEntityKeyMetadata.getEntityKeyMetadata(), columnValues );\n\t}",
"protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }",
"public static Method findDeclaredMethodByName(Class<?> clazz, String methodName) {\n for (Method method : AccessController.doPrivileged(new GetDeclaredMethodsAction(clazz))) {\n if (methodName.equals(method.getName())) {\n return method;\n }\n }\n return null;\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 List<BoxTask.Info> getTasks(String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n URL url = GET_TASKS_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), 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<BoxTask.Info> tasks = new ArrayList<BoxTask.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject taskJSON = value.asObject();\n BoxTask task = new BoxTask(this.getAPI(), taskJSON.get(\"id\").asString());\n BoxTask.Info info = task.new Info(taskJSON);\n tasks.add(info);\n }\n\n return tasks;\n }",
"public static lbvserver_rewritepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_rewritepolicy_binding obj = new lbvserver_rewritepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_rewritepolicy_binding response[] = (lbvserver_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"final public void addPosition(int position) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(position);\n } else {\n tokenPosition.add(position);\n }\n }",
"public static base_response unset(nitro_service client, systemuser resource, String[] args) throws Exception{\n\t\tsystemuser unsetresource = new systemuser();\n\t\tunsetresource.username = resource.username;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public <T> T find(Class<T> classType, String id) {\n return db.find(classType, id);\n }"
] |
Return the key if there is one else return -1 | [
"private int getCacheKey(InputDevice device, GVRControllerType controllerType) {\n if (controllerType != GVRControllerType.UNKNOWN &&\n controllerType != GVRControllerType.EXTERNAL) {\n // Sometimes a device shows up using two device ids\n // here we try to show both devices as one using the\n // product and vendor id\n\n int key = device.getVendorId();\n key = 31 * key + device.getProductId();\n key = 31 * key + controllerType.hashCode();\n\n return key;\n }\n return -1; // invalid key\n }"
] | [
"public BoxFolder.Info getFolderInfo(String folderID) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFolder folder = new BoxFolder(this.api, jsonObject.get(\"id\").asString());\n return folder.new Info(response.getJSON());\n }",
"private TreeMap<Integer, Integer> createTaskMap(FieldMap fieldMap, FixedMeta taskFixedMeta, FixedData taskFixedData, Var2Data taskVarData)\n {\n TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer>();\n int uniqueIdOffset = fieldMap.getFixedDataOffset(TaskField.UNIQUE_ID);\n Integer taskNameKey = fieldMap.getVarDataKey(TaskField.NAME);\n int itemCount = taskFixedMeta.getAdjustedItemCount();\n int uniqueID;\n Integer key;\n\n //\n // First three items are not tasks, so let's skip them\n //\n for (int loop = 3; loop < itemCount; loop++)\n {\n byte[] data = taskFixedData.getByteArrayValue(loop);\n if (data != null)\n {\n byte[] metaData = taskFixedMeta.getByteArrayValue(loop);\n\n //\n // Check for the deleted task flag\n //\n int flags = MPPUtility.getInt(metaData, 0);\n if ((flags & 0x02) != 0)\n {\n // Project stores the deleted tasks unique id's into the fixed data as well\n // and at least in one case the deleted task was listed twice in the list\n // the second time with data with it causing a phantom task to be shown.\n // See CalendarErrorPhantomTasks.mpp\n //\n // So let's add the unique id for the deleted task into the map so we don't\n // accidentally include the task later.\n //\n uniqueID = MPPUtility.getShort(data, TASK_UNIQUE_ID_FIXED_OFFSET); // Only a short stored for deleted tasks?\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, null); // use null so we can easily ignore this later\n }\n }\n else\n {\n //\n // Do we have a null task?\n //\n if (data.length == NULL_TASK_BLOCK_SIZE)\n {\n uniqueID = MPPUtility.getInt(data, TASK_UNIQUE_ID_FIXED_OFFSET);\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n else\n {\n //\n // We apply a heuristic here - if we have more than 75% of the data, we assume\n // the task is valid.\n //\n int maxSize = fieldMap.getMaxFixedDataSize(0);\n if (maxSize == 0 || ((data.length * 100) / maxSize) > 75)\n {\n uniqueID = MPPUtility.getInt(data, uniqueIdOffset);\n key = Integer.valueOf(uniqueID);\n\n // Accept this task if it does not have a deleted unique ID or it has a deleted unique ID but the name is not null\n if (!taskMap.containsKey(key) || taskVarData.getUnicodeString(key, taskNameKey) != null)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n }\n }\n }\n }\n\n return (taskMap);\n }",
"Map<String, String> packageNameMap() {\n if (packageNames == null) {\n return emptyMap();\n }\n\n Map<String, String> names = new LinkedHashMap<String, String>();\n for (PackageName name : packageNames) {\n names.put(name.getUri(), name.getPackage());\n }\n return names;\n }",
"public static byte[] hashPath(MessageDigest messageDigest, Path path) throws IOException {\n try (InputStream in = getRecursiveContentStream(path)) {\n return hashContent(messageDigest, in);\n }\n }",
"public void update(int number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];\n ByteUtils.writeInt(numberInBytes, number, 0);\n update(numberInBytes);\n }",
"public 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 }",
"public static int[][] toInt(double[][] array) {\n int[][] n = new int[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (int) array[i][j];\n }\n }\n return n;\n }",
"public void setMonth(String monthStr) {\n\n final Month month = Month.valueOf(monthStr);\n if ((m_model.getMonth() == null) || !m_model.getMonth().equals(monthStr)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setMonth(month);\n onValueChange();\n\n }\n });\n }\n }",
"public static base_responses reset(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata resetresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new appfwlearningdata();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}"
] |
Use this API to fetch appfwsignatures resource of given name . | [
"public static appfwsignatures get(nitro_service service, String name) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tobj.set_name(name);\n\t\tappfwsignatures response = (appfwsignatures) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static <GIVEN, WHEN, THEN> Scenario<GIVEN, WHEN, THEN> create( Class<GIVEN> givenClass, Class<WHEN> whenClass,\n Class<THEN> thenClass ) {\n return new Scenario<GIVEN, WHEN, THEN>( givenClass, whenClass, thenClass );\n }",
"public static base_response unset(nitro_service client, nsip6 resource, String[] args) throws Exception{\n\t\tnsip6 unsetresource = new nsip6();\n\t\tunsetresource.ipv6address = resource.ipv6address;\n\t\tunsetresource.td = resource.td;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static void timeCheck(String extra) {\n if (startCheckTime > 0) {\n long now = System.currentTimeMillis();\n long diff = now - nextCheckTime;\n nextCheckTime = now;\n Log.d(Log.SUBSYSTEM.TRACING, \"FPSCounter\", \"[%d, %d] timeCheck: %s\", now, diff, extra);\n }\n }",
"public CollectionRequest<Team> findByUser(String user) {\n \n String path = String.format(\"/users/%s/teams\", user);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception\n {\n long start = System.currentTimeMillis();\n reader.setProjectID(projectID);\n ProjectFile projectFile = reader.read();\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading database completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }",
"protected void ensureColumns(List columns, List existingColumns)\r\n {\r\n if (columns == null || columns.isEmpty())\r\n {\r\n return;\r\n }\r\n \r\n Iterator iter = columns.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n FieldHelper cf = (FieldHelper) iter.next();\r\n if (!existingColumns.contains(cf.name))\r\n {\r\n getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());\r\n }\r\n }\r\n }",
"public static PackageType resolve(final MavenProject project) {\n final String packaging = project.getPackaging().toLowerCase(Locale.ROOT);\n if (DEFAULT_TYPES.containsKey(packaging)) {\n return DEFAULT_TYPES.get(packaging);\n }\n return new PackageType(packaging);\n }",
"public String asString() throws IOException {\n long len = getContentLength();\n ByteArrayOutputStream buf;\n if (0 < len) {\n buf = new ByteArrayOutputStream((int) len);\n } else {\n buf = new ByteArrayOutputStream();\n }\n writeTo(buf);\n return decode(buf.toByteArray(), getCharacterEncoding());\n }",
"public SourceBuilder addLine(String fmt, Object... args) {\n add(fmt, args);\n source.append(LINE_SEPARATOR);\n return this;\n }"
] |
Clears the dest ColumnBuffer and inserts all entries in dest where the timestamp passes the
timestampTest.
@param dest Destination ColumnBuffer
@param timestampTest Test to determine which timestamps get added to dest | [
"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 }"
] | [
"private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }",
"public static Logger getLogger(String className) {\n\t\tif (logType == null) {\n\t\t\tlogType = findLogType();\n\t\t}\n\t\treturn new Logger(logType.createLog(className));\n\t}",
"public Integer getBlockMaskPrefixLength(boolean network) {\n\t\tInteger prefixLen;\n\t\tif(network) {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.networkMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t} else {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.hostMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setHostMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t}\n\t\tif(prefixLen < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn prefixLen;\n\t}",
"private static boolean isAssignableFrom(WildcardType type1, Type type2) {\n if (!isAssignableFrom(type1.getUpperBounds()[0], type2)) {\n return false;\n }\n if (type1.getLowerBounds().length > 0 && !isAssignableFrom(type2, type1.getLowerBounds()[0])) {\n return false;\n }\n return true;\n }",
"protected void parseNegOp(TokenList tokens, Sequence sequence) {\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n while( token != null ) {\n TokenList.Token next = token.next;\n escape:\n if( token.getSymbol() == Symbol.MINUS ) {\n if( token.previous != null && token.previous.getType() != Type.SYMBOL)\n break escape;\n if( token.previous != null && token.previous.getType() == Type.SYMBOL &&\n (token.previous.symbol == Symbol.TRANSPOSE))\n break escape;\n if( token.next == null || token.next.getType() == Type.SYMBOL)\n break escape;\n\n if( token.next.getType() != Type.VARIABLE )\n throw new RuntimeException(\"Crap bug rethink this function\");\n\n // create the operation\n Operation.Info info = Operation.neg(token.next.getVariable(),functions.getManagerTemp());\n // add the operation to the sequence\n sequence.addOperation(info.op);\n // update the token list\n TokenList.Token t = new TokenList.Token(info.output);\n tokens.insert(token.next,t);\n tokens.remove(token.next);\n tokens.remove(token);\n next = t;\n }\n token = next;\n }\n }",
"Object readResolve() throws ObjectStreamException {\n Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);\n if (bean == null) {\n throw BeanLogger.LOG.proxyDeserializationFailure(beanId);\n }\n return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);\n }",
"private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }",
"public static authenticationradiuspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_authenticationvserver_binding obj = new authenticationradiuspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_authenticationvserver_binding response[] = (authenticationradiuspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\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 }"
] |
Process the hours and exceptions for an individual calendar.
@param calendar project calendar
@param calendarData hours and exception rows for this calendar | [
"private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData)\n {\n for (ResultSetRow row : calendarData)\n {\n processCalendarData(calendar, row);\n }\n }"
] | [
"private Constructor<T> findNoArgConstructor(Class<T> dataClass) {\n\t\tConstructor<T>[] constructors;\n\t\ttry {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tConstructor<T>[] consts = (Constructor<T>[]) dataClass.getDeclaredConstructors();\n\t\t\t// i do this [grossness] to be able to move the Suppress inside the method\n\t\t\tconstructors = consts;\n\t\t} catch (Exception e) {\n\t\t\tthrow new IllegalArgumentException(\"Can't lookup declared constructors for \" + dataClass, e);\n\t\t}\n\t\tfor (Constructor<T> con : constructors) {\n\t\t\tif (con.getParameterTypes().length == 0) {\n\t\t\t\tif (!con.isAccessible()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcon.setAccessible(true);\n\t\t\t\t\t} catch (SecurityException e) {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Could not open access to constructor for \" + dataClass);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn con;\n\t\t\t}\n\t\t}\n\t\tif (dataClass.getEnclosingClass() == null) {\n\t\t\tthrow new IllegalArgumentException(\"Can't find a no-arg constructor for \" + dataClass);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Can't find a no-arg constructor for \" + dataClass + \". Missing static on inner class?\");\n\t\t}\n\t}",
"private void initKeySetForXmlBundle() {\n\n // consider only available locales\n for (Locale l : m_locales) {\n if (m_xmlBundle.hasLocale(l)) {\n Set<Object> keys = new HashSet<Object>();\n for (I_CmsXmlContentValue msg : m_xmlBundle.getValueSequence(\"Message\", l).getValues()) {\n String msgpath = msg.getPath();\n keys.add(m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", l));\n }\n m_keyset.updateKeySet(null, keys);\n }\n }\n\n }",
"protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) {\n validateGeneralBean(bean, beanManager);\n if (bean instanceof NewBean) {\n return;\n }\n if (bean instanceof DecorableBean) {\n validateDecorators(beanManager, (DecorableBean<?>) bean);\n }\n if ((bean instanceof AbstractClassBean<?>)) {\n AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean;\n // validate CDI-defined interceptors\n if (classBean.hasInterceptors()) {\n validateInterceptors(beanManager, classBean);\n }\n }\n // for each producer bean validate its disposer method\n if (bean instanceof AbstractProducerBean<?, ?, ?>) {\n AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean);\n if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) {\n AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean\n .getProducer());\n if (producer.getDisposalMethod() != null) {\n for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) {\n // pass the producer bean instead of the disposal method bean\n validateInjectionPointForDefinitionErrors(ip, null, beanManager);\n validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD);\n validateEventMetadataInjectionPoint(ip);\n validateInjectionPointForDeploymentProblems(ip, null, beanManager);\n }\n }\n }\n }\n }",
"public static boolean isTemplatePath(String string) {\n int sz = string.length();\n if (sz == 0) {\n return true;\n }\n for (int i = 0; i < sz; ++i) {\n char c = string.charAt(i);\n switch (c) {\n case ' ':\n case '\\t':\n case '\\b':\n case '<':\n case '>':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '!':\n case '@':\n case '#':\n case '*':\n case '?':\n case '%':\n case '|':\n case ',':\n case ':':\n case ';':\n case '^':\n case '&':\n return false;\n }\n }\n return true;\n }",
"public final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }",
"public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }",
"private void deleteLinks(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final LinksTable links = getLinksTable(txn, entityTypeId);\n final IntHashSet deletedLinks = new IntHashSet();\n try (Cursor cursor = links.getFirstIndexCursor(envTxn)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, 0))) != null;\n success; success = cursor.getNext()) {\n final ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final ByteIterable valueEntry = cursor.getValue();\n if (links.delete(envTxn, keyEntry, valueEntry)) {\n int linkId = key.getPropertyId();\n if (getLinkName(txn, linkId) != null) {\n deletedLinks.add(linkId);\n final LinkValue linkValue = LinkValue.entryToLinkValue(valueEntry);\n txn.linkDeleted(entity.getId(), (PersistentEntityId) linkValue.getEntityId(), linkValue.getLinkId());\n }\n }\n }\n }\n for (Integer linkId : deletedLinks) {\n links.deleteAllIndex(envTxn, linkId, entityLocalId);\n }\n }",
"private void reorder()\r\n {\r\n if(getTransaction().isOrdering() && needsCommit && mhtObjectEnvelopes.size() > 1)\r\n {\r\n ObjectEnvelopeOrdering ordering = new ObjectEnvelopeOrdering(mvOrderOfIds, mhtObjectEnvelopes);\r\n ordering.reorder();\r\n Identity[] newOrder = ordering.getOrdering();\r\n\r\n mvOrderOfIds.clear();\r\n for(int i = 0; i < newOrder.length; i++)\r\n {\r\n mvOrderOfIds.add(newOrder[i]);\r\n }\r\n }\r\n }",
"public void useOldRESTService() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using old RESTful CustomerService with old client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old REST\");\n printOldCustomerDetails(customer);\n }"
] |
This method log given exception in specified listener | [
"private void logError(LifecycleListener listener, Exception e) {\n LOGGER.error(\"Error for listener \" + listener.getClass(), e);\n }"
] | [
"public static String getRelativePathName(Path root, Path path) {\n Path relative = root.relativize(path);\n return Files.isDirectory(path) && !relative.toString().endsWith(\"/\") ? String.format(\"%s/\", relative.toString()) : relative.toString();\n }",
"@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }",
"private static Map<String, String> mapCustomInfo(CustomInfoType ciType){\n Map<String, String> customInfo = new HashMap<String, String>();\n if (ciType != null){\n for (CustomInfoType.Item item : ciType.getItem()) {\n customInfo.put(item.getKey(), item.getValue());\n }\n }\n return customInfo;\n }",
"private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\n }",
"public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }",
"public static sslvserver_sslcipher_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcipher_binding obj = new sslvserver_sslcipher_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcipher_binding response[] = (sslvserver_sslcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException {\n try {\n T result = action.call(self);\n\n Closeable temp = self;\n self = null;\n temp.close();\n\n return result;\n } finally {\n DefaultGroovyMethodsSupport.closeWithWarning(self);\n }\n }",
"String getStatusHelp(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_HELP_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_HELP_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_HELP_0);\n }\n long lastLogin = user.getLastlogin();\n return CmsVaadinUtils.getMessageText(\n Messages.GUI_USERMANAGEMENT_USER_ACTIVE_HELP_1,\n CmsDateUtil.getDateTime(new Date(lastLogin), DateFormat.SHORT, A_CmsUI.get().getLocale()));\n }",
"public void setShiftOrientation(OrientedLayout.Orientation orientation) {\n if (mShiftLayout.getOrientation() != orientation &&\n orientation != OrientedLayout.Orientation.STACK) {\n mShiftLayout.setOrientation(orientation);\n requestLayout();\n }\n }"
] |
Start the chain of execution running.
@throws IllegalStateException
if the chain of execution has already been started. | [
"public void execute() {\n State currentState = state.getAndSet(State.RUNNING);\n if (currentState == State.RUNNING) {\n throw new IllegalStateException(\n \"ExecutionChain is already running!\");\n }\n executeRunnable = new ExecuteRunnable();\n }"
] | [
"private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {\n if (cause.getMessage() == null) {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());\n } else {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + \": \" + cause.getMessage());\n }\n for (final StackTraceElement ste : cause.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (cause.getCause() != null) {\n addCauseToBacktrace(cause.getCause(), bTrace);\n }\n }",
"public static final Priority parsePriority(BigInteger priority)\n {\n return (priority == null ? null : Priority.getInstance(priority.intValue()));\n }",
"private LoginContext getClientLoginContext() throws LoginException {\n Configuration config = new Configuration() {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name) {\n Map<String, String> options = new HashMap<String, String>();\n options.put(\"multi-threaded\", \"true\");\n options.put(\"restore-login-identity\", \"true\");\n\n AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);\n return new AppConfigurationEntry[] { clmEntry };\n }\n };\n return getLoginContext(config);\n }",
"public Set<Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n for (ProcessorGraphNode<?, ?> root: this.roots) {\n for (Processor p: root.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }",
"public String getSQL92LikePattern() throws IllegalArgumentException {\n\t\tif (escape.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> escape char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardSingle.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardSingle char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardMulti.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardMulti char should be of length exactly 1\");\n\t\t}\n\t\treturn LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),\n\t\t\t\tisMatchingCase(), pattern);\n\t}",
"public UUID getUUID(FastTrackField type)\n {\n String value = getString(type);\n UUID result = null;\n if (value != null && !value.isEmpty() && value.length() >= 36)\n {\n if (value.startsWith(\"{\"))\n {\n value = value.substring(1, value.length() - 1);\n }\n if (value.length() > 16)\n {\n value = value.substring(0, 36);\n }\n result = UUID.fromString(value);\n }\n return result;\n }",
"public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }",
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }",
"protected String getIsolationLevelAsString()\r\n {\r\n if (defaultIsolationLevel == IL_READ_UNCOMMITTED)\r\n {\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_READ_COMMITTED)\r\n {\r\n return LITERAL_IL_READ_COMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_REPEATABLE_READ)\r\n {\r\n return LITERAL_IL_REPEATABLE_READ;\r\n }\r\n else if (defaultIsolationLevel == IL_SERIALIZABLE)\r\n {\r\n return LITERAL_IL_SERIALIZABLE;\r\n }\r\n else if (defaultIsolationLevel == IL_OPTIMISTIC)\r\n {\r\n return LITERAL_IL_OPTIMISTIC;\r\n }\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }"
] |
Sets the color of the drop shadow.
@param color The color of the drop shadow. | [
"public void setDropShadowColor(int color) {\n GradientDrawable.Orientation orientation = getDropShadowOrientation();\n\n final int endColor = color & 0x00FFFFFF;\n mDropShadowDrawable = new GradientDrawable(orientation,\n new int[] {\n color,\n endColor,\n });\n invalidate();\n }"
] | [
"public Where<T, ID> rawComparison(String columnName, String rawOperator, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value, rawOperator));\n\t\treturn this;\n\t}",
"public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {\n if( numRows == numCols )\n return linear(numRows);\n else\n return leastSquares(numRows,numCols);\n }",
"protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) {\n validateGeneralBean(bean, beanManager);\n if (bean instanceof NewBean) {\n return;\n }\n if (bean instanceof DecorableBean) {\n validateDecorators(beanManager, (DecorableBean<?>) bean);\n }\n if ((bean instanceof AbstractClassBean<?>)) {\n AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean;\n // validate CDI-defined interceptors\n if (classBean.hasInterceptors()) {\n validateInterceptors(beanManager, classBean);\n }\n }\n // for each producer bean validate its disposer method\n if (bean instanceof AbstractProducerBean<?, ?, ?>) {\n AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean);\n if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) {\n AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean\n .getProducer());\n if (producer.getDisposalMethod() != null) {\n for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) {\n // pass the producer bean instead of the disposal method bean\n validateInjectionPointForDefinitionErrors(ip, null, beanManager);\n validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD);\n validateEventMetadataInjectionPoint(ip);\n validateInjectionPointForDeploymentProblems(ip, null, beanManager);\n }\n }\n }\n }\n }",
"public static void append(Path self, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.defaultCharset());\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 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 }",
"public byte[] toArray() {\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return copy;\n }",
"public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }",
"@Override\n public FileModel resolvePayload(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload)\n {\n checkVariableName(event, context);\n if (payload instanceof FileReferenceModel)\n {\n return ((FileReferenceModel) payload).getFile();\n }\n if (payload instanceof FileModel)\n {\n return (FileModel) payload;\n }\n return null;\n }",
"public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }"
] |
Parses a PDF document and serializes the resulting DOM tree to an output. This requires
a DOM Level 3 capable implementation to be available. | [
"@Override\n public void writeText(PDDocument doc, Writer outputStream) throws IOException\n {\n try\n {\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation(\"LS\");\n LSSerializer writer = impl.createLSSerializer();\n LSOutput output = impl.createLSOutput();\n writer.getDomConfig().setParameter(\"format-pretty-print\", true);\n output.setCharacterStream(outputStream);\n createDOM(doc);\n writer.write(getDocument(), output);\n } catch (ClassCastException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (ClassNotFoundException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (InstantiationException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (IllegalAccessException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n }\n }"
] | [
"public FastReportBuilder addGroups(int numgroups) {\n\t\tgroupCount = numgroups;\n\t\tfor (int i = 0; i < groupCount; i++) {\n\t\t\tGroupBuilder gb = new GroupBuilder();\n\t\t\tPropertyColumn col = (PropertyColumn) report.getColumns().get(i);\n\t\t\tgb.setCriteriaColumn(col);\n\t\t\treport.getColumnsGroups().add(gb.build());\n\t\t}\n\t\treturn this;\n\t}",
"private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }",
"static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }",
"@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }",
"public void append(String str, String indentation) {\n\t\tif (indentation.isEmpty()) {\n\t\t\tappend(str);\n\t\t} else if (str != null)\n\t\t\tappend(indentation, str, segments.size());\n\t}",
"public static final Path resolveSecurely(Path rootPath, String path) {\n Path resolvedPath;\n if(path == null || path.isEmpty()) {\n resolvedPath = rootPath.normalize();\n } else {\n String relativePath = removeSuperflousSlashes(path);\n resolvedPath = rootPath.resolve(relativePath).normalize();\n }\n if(!resolvedPath.startsWith(rootPath)) {\n throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path);\n }\n return resolvedPath;\n }",
"public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\n }",
"public ItemRequest<Task> addProject(String task) {\n \n String path = String.format(\"/tasks/%s/addProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"@RequestMapping(value=\"/{subscription}\", method=GET, params=\"hub.mode=subscribe\")\n\tpublic @ResponseBody String verifySubscription(\n\t\t\t@PathVariable(\"subscription\") String subscription,\n\t\t\t@RequestParam(\"hub.challenge\") String challenge,\n\t\t\t@RequestParam(\"hub.verify_token\") String verifyToken) {\n\t\tlogger.debug(\"Received subscription verification request for '\" + subscription + \"'.\");\n\t\treturn tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : \"\";\n\t}"
] |
Deploys application reading resources from specified URLs
@param applicationName to configure in cluster
@param urls where resources are read
@return the name of the application
@throws IOException | [
"public void deployApplication(String applicationName, URL... urls) throws IOException {\n this.applicationName = applicationName;\n\n for (URL url : urls) {\n try (InputStream inputStream = url.openStream()) {\n deploy(inputStream);\n }\n }\n }"
] | [
"private WaveformPreview requestPreviewInternal(final DataReference trackReference, final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(trackReference));\n if (cache != null) {\n return cache.getWaveformPreview(null, trackReference);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(trackReference.getSlotReference());\n if (sourceDetails != null) {\n final WaveformPreview provided = MetadataFinder.getInstance().allMetadataProviders.getWaveformPreview(sourceDetails, trackReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && trackReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the preview using the dbserver protocol.\n ConnectionManager.ClientTask<WaveformPreview> task = new ConnectionManager.ClientTask<WaveformPreview>() {\n @Override\n public WaveformPreview useClient(Client client) throws Exception {\n return getWaveformPreview(trackReference.rekordboxId, SlotReference.getSlotReference(trackReference), client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(trackReference.player, task, \"requesting waveform preview\");\n } catch (Exception e) {\n logger.error(\"Problem requesting waveform preview, returning null\", e);\n }\n return null;\n }",
"public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {\r\n\t\tcheckNotRead();\r\n\t\tPreconditions.checkNotNull(tagName);\r\n\t\tExcludeByParentBuilder exclude = new ExcludeByParentBuilder(\r\n\t\t\t\ttagName.toUpperCase());\r\n\t\tcrawlParentsExcluded.add(exclude);\r\n\t\treturn exclude;\r\n\t}",
"private String trim(String line) {\n char[] chars = line.toCharArray();\n int len = chars.length;\n\n while (len > 0) {\n if (!Character.isWhitespace(chars[len - 1])) {\n break;\n }\n len--;\n }\n\n return line.substring(0, len);\n }",
"public boolean detectTierRichCss() {\r\n\r\n boolean result = false;\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n if (detectMobileQuick()) {\r\n\r\n //Exclude iPhone Tier and e-Ink Kindle devices.\r\n if (!detectTierIphone() && !detectKindle()) {\r\n\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n //Older Windows 'Mobile' isn't good enough for iPhone Tier.\r\n if (detectWebkit()\r\n || detectS60OssBrowser()\r\n || detectBlackBerryHigh()\r\n || detectWindowsMobile()\r\n || (userAgent.indexOf(engineTelecaQ) != -1)) {\r\n result = true;\r\n } // if detectWebkit()\r\n } //if !detectTierIphone()\r\n } //if detectMobileQuick()\r\n return result;\r\n }",
"public static <T> List<T> makeList(T... items) {\r\n List<T> s = new ArrayList<T>(items.length);\r\n for (int i = 0; i < items.length; i++) {\r\n s.add(items[i]);\r\n }\r\n return s;\r\n }",
"public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }",
"public static String encode(String value) throws UnsupportedEncodingException {\n if (isNullOrEmpty(value)) return value;\n return URLEncoder.encode(value, URL_ENCODING);\n }",
"protected final boolean isValidEndTypeForPattern() {\n\n if (getEndType() == null) {\n return false;\n }\n switch (getPatternType()) {\n case DAILY:\n case WEEKLY:\n case MONTHLY:\n case YEARLY:\n return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));\n case INDIVIDUAL:\n case NONE:\n return getEndType().equals(EndType.SINGLE);\n default:\n return false;\n }\n }",
"protected static Map<String, List<Statement>> addStatementToGroups(Statement statement, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newGroups = new HashMap<>(claims);\n\t\tString pid = statement.getMainSnak().getPropertyId().getId();\n\t\tif(newGroups.containsKey(pid)) {\n\t\t\tList<Statement> newGroup = new ArrayList<>(newGroups.get(pid).size());\n\t\t\tboolean statementReplaced = false;\n\t\t\tfor(Statement existingStatement : newGroups.get(pid)) {\n\t\t\t\tif(existingStatement.getStatementId().equals(statement.getStatementId()) &&\n\t\t\t\t\t\t!existingStatement.getStatementId().isEmpty()) {\n\t\t\t\t\tstatementReplaced = true;\n\t\t\t\t\tnewGroup.add(statement);\n\t\t\t\t} else {\n\t\t\t\t\tnewGroup.add(existingStatement);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!statementReplaced) {\n\t\t\t\tnewGroup.add(statement);\n\t\t\t}\n\t\t\tnewGroups.put(pid, newGroup);\n\t\t} else {\n\t\t\tnewGroups.put(pid, Collections.singletonList(statement));\n\t\t}\n\t\treturn newGroups;\n\t}"
] |
This filter uses a 9-patch to overlay the image.
@param imageUrl Watermark image URL. It is very important to understand that the same image
loader that Thumbor uses will be used here. | [
"public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }"
] | [
"public static final Integer getInteger(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return ((Integer) bundle.getObject(key));\n }",
"private void lockAndRegisterReferences(ClassDescriptor cld, Object sourceObject, int lockMode, List registeredObjects) throws LockNotGrantedException\r\n {\r\n if (implicitLocking)\r\n {\r\n Iterator i = cld.getObjectReferenceDescriptors(true).iterator();\r\n while (i.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) i.next();\r\n Object refObj = rds.getPersistentField().get(sourceObject);\r\n if (refObj != null)\r\n {\r\n boolean isProxy = ProxyHelper.isProxy(refObj);\r\n RuntimeObject rt = isProxy ? new RuntimeObject(refObj, this, false) : new RuntimeObject(refObj, this);\r\n if (!registrationList.contains(rt.getIdentity()))\r\n {\r\n lockAndRegister(rt, lockMode, registeredObjects);\r\n }\r\n }\r\n }\r\n }\r\n }",
"protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}",
"public byte[] toBytes(T object) {\n try {\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n ObjectOutputStream out = new ObjectOutputStream(stream);\n out.writeObject(object);\n return stream.toByteArray();\n } catch(IOException e) {\n throw new SerializationException(e);\n }\n }",
"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 }",
"public AiTextureInfo getTextureInfo(AiTextureType type, int index) {\n return new AiTextureInfo(type, index, getTextureFile(type, index), \n getTextureUVIndex(type, index), getBlendFactor(type, index), \n getTextureOp(type, index), getTextureMapModeW(type, index), \n getTextureMapModeW(type, index), \n getTextureMapModeW(type, index));\n }",
"private void readResourceAssignments(Project gpProject)\n {\n Allocations allocations = gpProject.getAllocations();\n if (allocations != null)\n {\n for (Allocation allocation : allocations.getAllocation())\n {\n readResourceAssignment(allocation);\n }\n }\n }",
"private void deliverFoundAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceFound(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device found announcement to listener\", t);\n }\n }\n });\n }\n }",
"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 }"
] |
Determines whether this table has a foreignkey of the given name.
@param name The name of the foreignkey
@return <code>true</code> if there is a foreignkey of that name | [
"public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }"
] | [
"public double Function2D(double x, double y) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency, y * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }",
"String generateSynopsis() {\n synopsisOptions = buildSynopsisOptions(opts, arg, domain);\n StringBuilder synopsisBuilder = new StringBuilder();\n if (parentName != null) {\n synopsisBuilder.append(parentName).append(\" \");\n }\n synopsisBuilder.append(commandName);\n if (isOperation && !opts.isEmpty()) {\n synopsisBuilder.append(\"(\");\n } else {\n synopsisBuilder.append(\" \");\n }\n boolean hasOptions = arg != null || !opts.isEmpty();\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" [\");\n }\n if (hasActions) {\n synopsisBuilder.append(\" <action>\");\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ] || [\");\n }\n SynopsisOption opt;\n while ((opt = retrieveNextOption(synopsisOptions, false)) != null) {\n String content = addSynopsisOption(opt);\n if (content != null) {\n synopsisBuilder.append(content.trim());\n if (isOperation) {\n if (!synopsisOptions.isEmpty()) {\n synopsisBuilder.append(\",\");\n } else {\n synopsisBuilder.append(\")\");\n }\n }\n synopsisBuilder.append(\" \");\n }\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ]\");\n }\n return synopsisBuilder.toString();\n }",
"private final boolean parseBoolean(String value)\n {\n return value != null && (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"y\") || value.equalsIgnoreCase(\"yes\"));\n }",
"public <T extends StatementDocument> void nullEdit(PropertyIdValue propertyId)\n\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tPropertyDocument currentDocument = (PropertyDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(propertyId.getId());\n\t\t\n\t\tnullEdit(currentDocument);\n\t}",
"public static cmppolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tobj.set_name(name);\n\t\tcmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"static Shell createTelnetConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n // Set up nvt4j; ignore the initial clear & reposition\n final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input, output) {\n private boolean cleared;\n private boolean moved;\n\n @Override\n public void clear() throws IOException {\n if (this.cleared)\n super.clear();\n this.cleared = true;\n }\n\n @Override\n public void move(int row, int col) throws IOException {\n if (this.moved)\n super.move(row, col);\n this.moved = true;\n }\n };\n nvt4jTerminal.put(nvt4j.impl.Terminal.AUTO_WRAP_ON);\n nvt4jTerminal.setCursor(true);\n\n // Have JLine do input & output through telnet terminal\n final InputStream jlineInput = new InputStream() {\n @Override\n public int read() throws IOException {\n return nvt4jTerminal.get();\n }\n };\n final OutputStream jlineOutput = new OutputStream() {\n @Override\n public void write(int value) throws IOException {\n nvt4jTerminal.put(value);\n }\n };\n\n return createTerminalConsoleShell(prompt, appName, mainHandler, jlineInput, jlineOutput);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }",
"public void copyTo(int start, int end, byte[] dest, int destPos) {\n // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object\n arraycopy(start, dest, destPos, end - start);\n }",
"public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }",
"public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver)\r\n {\r\n String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol);\r\n\r\n if (platform == null)\r\n {\r\n platform = (String)jdbcDriverToPlatform.get(jdbcDriver);\r\n }\r\n return platform;\r\n }"
] |
Creates an element that represents a single positioned box containing the specified text string.
@param data the text string to be contained in the created box.
@return the resulting DOM element | [
"protected Element createTextElement(String data, float width)\n {\n Element el = createTextElement(width);\n Text text = doc.createTextNode(data);\n el.appendChild(text);\n return el;\n }"
] | [
"private void processCalendarData(List<ProjectCalendar> calendars) throws SQLException\n {\n for (ProjectCalendar calendar : calendars)\n {\n processCalendarData(calendar, getRows(\"SELECT * FROM MSP_CALENDAR_DATA WHERE PROJ_ID=? AND CAL_UID=?\", m_projectID, calendar.getUniqueID()));\n }\n }",
"private SearchableItem buildSearchableItem(Message menuItem) {\n return new SearchableItem((int) ((NumberField) menuItem.arguments.get(1)).getValue(),\n ((StringField) menuItem.arguments.get(3)).getValue());\n }",
"private void writeExceptions(List<ProjectCalendar> records) throws IOException\n {\n for (ProjectCalendar record : records)\n {\n if (!record.getCalendarExceptions().isEmpty())\n {\n // Need to move HOLI up here and get 15 exceptions per line as per USACE spec.\n // for now, we'll write one line for each calendar exception, hope there aren't too many\n //\n // changing this would be a serious upgrade, too much coding to do today....\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n m_eventManager.fireCalendarWrittenEvent(record); // left here from MPX template, maybe not needed???\n }\n }",
"public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {\n int numSingular = Math.min(W.numRows,W.numCols);\n boolean compact = W.numRows == W.numCols;\n\n if( compact ) {\n if( U != null ) {\n if( tranU && U.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n else if( !tranU && U.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n }\n\n if( V != null ) {\n if( tranV && V.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n else if( !tranV && V.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n }\n } else {\n if( U != null && U.numRows != U.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n if( V != null && V.numRows != V.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n if( U != null && U.numRows != W.numRows )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n if( V != null && V.numRows != W.numCols )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n }\n }",
"public void handle(HttpRequest request, HttpResponder responder) {\n if (urlRewriter != null) {\n try {\n request.setUri(URI.create(request.uri()).normalize().toString());\n if (!urlRewriter.rewrite(request, responder)) {\n return;\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\",\n t.getMessage()));\n LOG.error(\"Exception thrown during rewriting of uri {}\", request.uri(), t);\n return;\n }\n }\n\n try {\n String path = URI.create(request.uri()).normalize().getPath();\n\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations\n = patternRouter.getDestinations(path);\n\n PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination =\n getMatchedDestination(routableDestinations, request.method(), path);\n\n if (matchedDestination != null) {\n //Found a httpresource route to it.\n HttpResourceModel httpResourceModel = matchedDestination.getDestination();\n\n // Call preCall method of handler hooks.\n boolean terminated = false;\n HandlerInfo info = new HandlerInfo(httpResourceModel.getMethod().getDeclaringClass().getName(),\n httpResourceModel.getMethod().getName());\n for (HandlerHook hook : handlerHooks) {\n if (!hook.preCall(request, responder, info)) {\n // Terminate further request processing if preCall returns false.\n terminated = true;\n break;\n }\n }\n\n // Call httpresource method\n if (!terminated) {\n // Wrap responder to make post hook calls.\n responder = new WrappedHttpResponder(responder, handlerHooks, request, info);\n if (httpResourceModel.handle(request, responder, matchedDestination.getGroupNameValues()).isStreaming()) {\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Body Consumer not supported for internalHttpResponder: %s\",\n request.uri()));\n }\n }\n } else if (routableDestinations.size() > 0) {\n //Found a matching resource but could not find the right HttpMethod so return 405\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n } else {\n responder.sendString(HttpResponseStatus.NOT_FOUND, String.format(\"Problem accessing: %s. Reason: Not Found\",\n request.uri()));\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\", t.getMessage()));\n LOG.error(\"Exception thrown during request processing for uri {}\", request.uri(), t);\n }\n }",
"public void unlock() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockObject = new JsonObject();\n lockObject.add(\"lock\", JsonObject.NULL);\n\n request.setBody(lockObject.toString());\n request.send();\n }",
"private void populateConstraints(Row row, Task task)\n {\n Date endDateMax = row.getTimestamp(\"ZGIVENENDDATEMAX_\");\n Date endDateMin = row.getTimestamp(\"ZGIVENENDDATEMIN_\");\n Date startDateMax = row.getTimestamp(\"ZGIVENSTARTDATEMAX_\");\n Date startDateMin = row.getTimestamp(\"ZGIVENSTARTDATEMIN_\");\n\n ConstraintType constraintType = null;\n Date constraintDate = null;\n\n if (endDateMax != null)\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = endDateMax;\n }\n\n if (endDateMin != null)\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = endDateMin;\n }\n\n if (endDateMin != null && endDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = endDateMin;\n }\n\n if (startDateMax != null)\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = startDateMax;\n }\n\n if (startDateMin != null)\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = startDateMin;\n }\n\n if (startDateMin != null && startDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = endDateMin;\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"public static <T> Observable<T> map(Observable<?> fromObservable, final T toValue) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<T>(toValue));\n } else {\n return Observable.empty();\n }\n }",
"public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n checkSchemeAndPort(scheme, port);\r\n StringBuilder buffer = new StringBuilder();\r\n if (!host.startsWith(scheme + \"://\")) {\r\n buffer.append(scheme).append(\"://\");\r\n }\r\n buffer.append(host);\r\n if (port > 0) {\r\n buffer.append(':');\r\n buffer.append(port);\r\n }\r\n if (path == null) {\r\n path = \"/\";\r\n }\r\n buffer.append(path);\r\n\r\n if (!parameters.isEmpty()) {\r\n buffer.append('?');\r\n }\r\n int size = parameters.size();\r\n for (Map.Entry<String, String> entry : parameters.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append('=');\r\n Object value = entry.getValue();\r\n if (value != null) {\r\n String string = value.toString();\r\n try {\r\n string = URLEncoder.encode(string, UTF8);\r\n } catch (UnsupportedEncodingException e) {\r\n // Should never happen, but just in case\r\n }\r\n buffer.append(string);\r\n }\r\n if (--size != 0) {\r\n buffer.append('&');\r\n }\r\n }\r\n\r\n /*\r\n * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&\r\n * !ignoreMethod(getMethod(parameters))) { buffer.append(\"&api_sig=\"); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }\r\n */\r\n\r\n return new URL(buffer.toString());\r\n }"
] |
Read a single outline code field extended attribute.
@param entityID parent entity
@param row field data | [
"protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }"
] | [
"public Result cmd(String cliCommand) {\n try {\n // The intent here is to return a Response when this is doable.\n if (ctx.isWorkflowMode() || ctx.isBatchMode()) {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx);\n if (handler.getFormat() == OperationFormat.INSTANCE) {\n ModelNode request = ctx.buildRequest(cliCommand);\n ModelNode response = ctx.execute(request, cliCommand);\n return new Result(cliCommand, request, response);\n } else {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n } catch (CommandLineException cfe) {\n throw new IllegalArgumentException(\"Error handling command: \"\n + cliCommand, cfe);\n } catch (IOException ioe) {\n throw new IllegalStateException(\"Unable to send command \"\n + cliCommand + \" to server.\", ioe);\n }\n }",
"public static DMatrixRMaj diagonal(int numRows , int numCols , double min , double max , Random rand ) {\n if( max < min )\n throw new IllegalArgumentException(\"The max must be >= the min\");\n\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int N = Math.min(numRows,numCols);\n\n double r = max-min;\n\n for( int i = 0; i < N; i++ ) {\n ret.set(i,i, rand.nextDouble()*r+min);\n }\n\n return ret;\n }",
"public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }",
"public void restartDyno(String appName, String dynoId) {\n connection.execute(new DynoRestart(appName, dynoId), apiKey);\n }",
"@Override\n public boolean accept(File file) {\n //All directories are added in the least that can be read by the Application\n if (file.isDirectory()&&file.canRead())\n { return true;\n }\n else if(properties.selection_type==DialogConfigs.DIR_SELECT)\n { /* True for files, If the selection type is Directory type, ie.\n * Only directory has to be selected from the list, then all files are\n * ignored.\n */\n return false;\n }\n else\n { /* Check whether name of the file ends with the extension. Added if it\n * does.\n */\n String name = file.getName().toLowerCase(Locale.getDefault());\n for (String ext : validExtensions) {\n if (name.endsWith(ext)) {\n return true;\n }\n }\n }\n return false;\n }",
"protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\n }",
"protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (PreparedStatement) Proxy.newProxyInstance(\n\t\t\t\tPreparedStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {PreparedStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public Iterable<V> sorted(Iterator<V> input) {\n ExecutorService executor = new ThreadPoolExecutor(this.numThreads,\n this.numThreads,\n 1000L,\n TimeUnit.MILLISECONDS,\n new SynchronousQueue<Runnable>(),\n new CallerRunsPolicy());\n final AtomicInteger count = new AtomicInteger(0);\n final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());\n while(input.hasNext()) {\n final int segmentId = count.getAndIncrement();\n final long segmentStartMs = System.currentTimeMillis();\n logger.info(\"Segment \" + segmentId + \": filling sort buffer for segment...\");\n @SuppressWarnings(\"unchecked\")\n final V[] buffer = (V[]) new Object[internalSortSize];\n int segmentSizeIter = 0;\n for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)\n buffer[segmentSizeIter] = input.next();\n final int segmentSize = segmentSizeIter;\n logger.info(\"Segment \" + segmentId + \": sort buffer filled...adding to sort queue.\");\n\n // sort and write out asynchronously\n executor.execute(new Runnable() {\n\n public void run() {\n logger.info(\"Segment \" + segmentId + \": sorting buffer.\");\n long start = System.currentTimeMillis();\n Arrays.sort(buffer, 0, segmentSize, comparator);\n long elapsed = System.currentTimeMillis() - start;\n logger.info(\"Segment \" + segmentId + \": sort completed in \" + elapsed\n + \" ms, writing to temp file.\");\n\n // write out values to a temp file\n try {\n File tempFile = File.createTempFile(\"segment-\", \".dat\", tempDir);\n tempFile.deleteOnExit();\n tempFiles.add(tempFile);\n OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),\n bufferSize);\n if(gzip)\n os = new GZIPOutputStream(os);\n DataOutputStream output = new DataOutputStream(os);\n for(int i = 0; i < segmentSize; i++)\n writeValue(output, buffer[i]);\n output.close();\n } catch(IOException e) {\n throw new VoldemortException(e);\n }\n long segmentElapsed = System.currentTimeMillis() - segmentStartMs;\n logger.info(\"Segment \" + segmentId + \": completed processing of segment in \"\n + segmentElapsed + \" ms.\");\n }\n });\n }\n\n // wait for all sorting to complete\n executor.shutdown();\n try {\n executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n // create iterator over sorted values\n return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize\n / tempFiles.size()));\n } catch(InterruptedException e) {\n throw new RuntimeException(e);\n }\n }",
"public static String normalize(final CharSequence self) {\n final String s = self.toString();\n int nx = s.indexOf('\\r');\n\n if (nx < 0) {\n return s;\n }\n\n final int len = s.length();\n final StringBuilder sb = new StringBuilder(len);\n\n int i = 0;\n\n do {\n sb.append(s, i, nx);\n sb.append('\\n');\n\n if ((i = nx + 1) >= len) break;\n\n if (s.charAt(i) == '\\n') {\n // skip the LF in CR LF\n if (++i >= len) break;\n }\n\n nx = s.indexOf('\\r', i);\n } while (nx > 0);\n\n sb.append(s, i, len);\n\n return sb.toString();\n }"
] |
Get an array of property ids.
Not all property ids need be returned. Those properties
whose ids are not returned are considered non-enumerable.
@return an array of Objects. Each entry in the array is either
a java.lang.String or a java.lang.Number | [
"public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }"
] | [
"public static inatparam get(nitro_service service) throws Exception{\n\t\tinatparam obj = new inatparam();\n\t\tinatparam[] response = (inatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static long count(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\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"private void addProperties(final PropertyDescriptor[] _properties) throws ColumnBuilderException, ClassNotFoundException {\n for (final PropertyDescriptor property : _properties) {\n if (isValidProperty(property)) {\n addColumn(getColumnTitle(property), property.getName(), property.getPropertyType().getName(), getColumnWidth(property));\n }\n }\n setUseFullPageWidth(true);\n }",
"public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }",
"private Logger createLoggerInstance(String loggerName) throws Exception\r\n {\r\n Class loggerClass = getConfiguration().getLoggerClass();\r\n Logger log = (Logger) ClassHelper.newInstance(loggerClass, String.class, loggerName);\r\n log.configure(getConfiguration());\r\n return log;\r\n }",
"public ProjectCalendar getByName(String calendarName)\n {\n ProjectCalendar calendar = null;\n\n if (calendarName != null && calendarName.length() != 0)\n {\n Iterator<ProjectCalendar> iter = iterator();\n while (iter.hasNext() == true)\n {\n calendar = iter.next();\n String name = calendar.getName();\n\n if ((name != null) && (name.equalsIgnoreCase(calendarName) == true))\n {\n break;\n }\n\n calendar = null;\n }\n }\n\n return (calendar);\n }",
"public void addExportedPackages(Set<String> packages) {\n\t\tString s = (String) getMainAttributes().get(EXPORT_PACKAGE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, packages, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(EXPORT_PACKAGE, result);\n\t}",
"public static Platform detect() throws UnsupportedPlatformException {\n String osArch = getProperty(\"os.arch\");\n String osName = getProperty(\"os.name\");\n\n for (Arch arch : Arch.values()) {\n if (arch.pattern.matcher(osArch).matches()) {\n for (OS os : OS.values()) {\n if (os.pattern.matcher(osName).matches()) {\n return new Platform(arch, os);\n }\n }\n }\n }\n\n String msg = String.format(\"Unsupported platform %s %s\", osArch, osName);\n throw new UnsupportedPlatformException(msg);\n }",
"public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }"
] |
Loads the Configuration from the properties file.
Loads the properties file, or uses defaults on failure.
@see org.apache.ojb.broker.util.configuration.impl.ConfigurationAbstractImpl#setFilename(java.lang.String) | [
"protected void load()\r\n {\r\n properties = new Properties();\r\n\r\n String filename = getFilename();\r\n \r\n try\r\n {\r\n URL url = ClassHelper.getResource(filename);\r\n\r\n if (url == null)\r\n {\r\n url = (new File(filename)).toURL();\r\n }\r\n\r\n logger.info(\"Loading OJB's properties: \" + url);\r\n\r\n URLConnection conn = url.openConnection();\r\n conn.setUseCaches(false);\r\n conn.connect();\r\n InputStream strIn = conn.getInputStream();\r\n properties.load(strIn);\r\n strIn.close();\r\n }\r\n catch (FileNotFoundException ex)\r\n {\r\n // [tomdz] If the filename is explicitly reset (null or empty string) then we'll\r\n // output an info message because the user did this on purpose\r\n // Otherwise, we'll output a warning\r\n if ((filename == null) || (filename.length() == 0))\r\n {\r\n logger.info(\"Starting OJB without a properties file. OJB is using default settings instead.\");\r\n }\r\n else\r\n {\r\n logger.warn(\"Could not load properties file '\"+filename+\"'. Using default settings!\", ex);\r\n }\r\n // [tomdz] There seems to be no use of this setting ?\r\n //properties.put(\"valid\", \"false\");\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new MetadataException(\"An error happend while loading the properties file '\"+filename+\"'\", ex);\r\n }\r\n }"
] | [
"@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > LINGER_ITERATIONS && deadPool.isEmpty() && completionKeyToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n e.printStackTrace();\n isRunning.set(false);\n }\n }",
"protected void doConfigure() {\n if (config != null) {\n for (UserBean user : config.getUsersToCreate()) {\n setUser(user.getEmail(), user.getLogin(), user.getPassword());\n }\n getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled());\n }\n }",
"public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\n }",
"public Set<String> rangeByRank(final long start, final long end) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n return jedis.zrange(getKey(), start, end);\n }\n });\n }",
"public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }",
"public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }",
"public static boolean reconnectContext(RedirectException re, CommandContext ctx) {\n boolean reconnected = false;\n try {\n ConnectionInfo info = ctx.getConnectionInfo();\n ControllerAddress address = null;\n if (info != null) {\n address = info.getControllerAddress();\n }\n if (address != null && isHttpsRedirect(re, address.getProtocol())) {\n LOG.debug(\"Trying to reconnect an http to http upgrade\");\n try {\n ctx.connectController();\n reconnected = true;\n } catch (Exception ex) {\n LOG.warn(\"Exception reconnecting\", ex);\n // Proper https redirect but error.\n // Ignoring it.\n }\n }\n } catch (URISyntaxException ex) {\n LOG.warn(\"Invalid URI: \", ex);\n // OK, invalid redirect.\n }\n return reconnected;\n }",
"synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }",
"public static HostController createHostController(String jbossHomePath, String modulePath, String[] systemPackages, String[] cmdargs) {\n if (jbossHomePath == null || jbossHomePath.isEmpty()) {\n throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath);\n }\n File jbossHomeDir = new File(jbossHomePath);\n if (!jbossHomeDir.isDirectory()) {\n throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath);\n }\n return createHostController(\n Configuration.Builder.of(jbossHomeDir)\n .setModulePath(modulePath)\n .setSystemPackages(systemPackages)\n .setCommandArguments(cmdargs)\n .build()\n );\n }"
] |
Validates bic.
@param bic to be validated.
@throws BicFormatException if bic is invalid.
UnsupportedCountryException if bic's country is not supported. | [
"public static void validate(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n try {\n validateEmpty(bic);\n validateLength(bic);\n validateCase(bic);\n validateBankCode(bic);\n validateCountryCode(bic);\n validateLocationCode(bic);\n\n if(hasBranchCode(bic)) {\n validateBranchCode(bic);\n }\n } catch (UnsupportedCountryException e) {\n throw e;\n } catch (RuntimeException e) {\n throw new BicFormatException(UNKNOWN, e.getMessage());\n }\n }"
] | [
"private synchronized void setInitializationMethod(Method newMethod)\r\n {\r\n if (newMethod != null)\r\n {\r\n // make sure it's a no argument method\r\n if (newMethod.getParameterTypes().length > 0)\r\n {\r\n throw new MetadataException(\r\n \"Initialization methods must be zero argument methods: \"\r\n + newMethod.getClass().getName()\r\n + \".\"\r\n + newMethod.getName());\r\n }\r\n\r\n // make it accessible if it's not already\r\n if (!newMethod.isAccessible())\r\n {\r\n newMethod.setAccessible(true);\r\n }\r\n }\r\n this.initializationMethod = newMethod;\r\n }",
"private Charset getCharset()\n {\n Charset result = m_charset;\n if (result == null)\n {\n // We default to CP1252 as this seems to be the most common encoding\n result = m_encoding == null ? CharsetHelper.CP1252 : Charset.forName(m_encoding);\n }\n return result;\n }",
"private void fireTreeStructureChanged()\n {\n // Guaranteed to return a non-null array\n Object[] listeners = m_listenerList.getListenerList();\n TreeModelEvent e = null;\n // Process the listeners last to first, notifying\n // those that are interested in this event\n for (int i = listeners.length - 2; i >= 0; i -= 2)\n {\n if (listeners[i] == TreeModelListener.class)\n {\n // Lazily create the event:\n if (e == null)\n {\n e = new TreeModelEvent(getRoot(), new Object[]\n {\n getRoot()\n }, null, null);\n }\n ((TreeModelListener) listeners[i + 1]).treeStructureChanged(e);\n }\n }\n }",
"public static base_response link(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey linkresource = new sslcertkey();\n\t\tlinkresource.certkey = resource.certkey;\n\t\tlinkresource.linkcertkeyname = resource.linkcertkeyname;\n\t\treturn linkresource.perform_operation(client,\"link\");\n\t}",
"public void log(Level level, Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(level, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}",
"public static appfwprofile_csrftag_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_csrftag_binding obj = new appfwprofile_csrftag_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_csrftag_binding response[] = (appfwprofile_csrftag_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean contentEqualsUnchecked(byte[] bytes, int offset, int len) {\n if (length != len) {\n return false;\n }\n\n return compareToUnchecked(bytes, offset, len) == 0;\n }",
"public void setCurrencyDigits(Integer currDigs)\n {\n if (currDigs == null)\n {\n currDigs = DEFAULT_CURRENCY_DIGITS;\n }\n set(ProjectField.CURRENCY_DIGITS, currDigs);\n }",
"protected void parseOperationsL(TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.SYMBOL && token.getSymbol() == Symbol.TRANSPOSE) {\n if( token.previous.getType() == Type.VARIABLE )\n token = insertTranspose(token.previous,tokens,sequence);\n else\n throw new ParseError(\"Expected variable before transpose\");\n }\n token = token.next;\n }\n }"
] |
Populate data for analytics. | [
"private void processAnalytics() throws SQLException\n {\n allocateConnection();\n\n try\n {\n DatabaseMetaData meta = m_connection.getMetaData();\n String productName = meta.getDatabaseProductName();\n if (productName == null || productName.isEmpty())\n {\n productName = \"DATABASE\";\n }\n else\n {\n productName = productName.toUpperCase();\n }\n\n ProjectProperties properties = m_reader.getProject().getProjectProperties();\n properties.setFileApplication(\"Primavera\");\n properties.setFileType(productName);\n }\n\n finally\n {\n releaseConnection();\n }\n }"
] | [
"protected int[] getPatternAsCodewords(int size) {\n if (size >= 10) {\n throw new IllegalArgumentException(\"Pattern groups of 10 or more digits are likely to be too large to parse as integers.\");\n }\n if (pattern == null || pattern.length == 0) {\n return new int[0];\n } else {\n int count = (int) Math.ceil(pattern[0].length() / (double) size);\n int[] codewords = new int[pattern.length * count];\n for (int i = 0; i < pattern.length; i++) {\n String row = pattern[i];\n for (int j = 0; j < count; j++) {\n int substringStart = j * size;\n int substringEnd = Math.min((j + 1) * size, row.length());\n codewords[(i * count) + j] = Integer.parseInt(row.substring(substringStart, substringEnd));\n }\n }\n return codewords;\n }\n }",
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}",
"private void stereotype(Options opt, Doc c, Align align) {\n\tfor (Tag tag : c.tags(\"stereotype\")) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 1) {\n\t\tSystem.err.println(\"@stereotype expects one field: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(align, guilWrap(opt, t[0]));\n\t}\n }",
"protected void calculateBarPositions(int _DataSize) {\n\n int dataSize = mScrollEnabled ? mVisibleBars : _DataSize;\n float barWidth = mBarWidth;\n float margin = mBarMargin;\n\n if (!mFixedBarWidth) {\n // calculate the bar width if the bars should be dynamically displayed\n barWidth = (mAvailableScreenSize / _DataSize) - margin;\n } else {\n\n if(_DataSize < mVisibleBars) {\n dataSize = _DataSize;\n }\n\n // calculate margin between bars if the bars have a fixed width\n float cumulatedBarWidths = barWidth * dataSize;\n float remainingScreenSize = mAvailableScreenSize - cumulatedBarWidths;\n\n margin = remainingScreenSize / dataSize;\n }\n\n boolean isVertical = this instanceof VerticalBarChart;\n\n int calculatedSize = (int) ((barWidth * _DataSize) + (margin * _DataSize));\n int contentWidth = isVertical ? mGraphWidth : calculatedSize;\n int contentHeight = isVertical ? calculatedSize : mGraphHeight;\n\n mContentRect = new Rect(0, 0, contentWidth, contentHeight);\n mCurrentViewport = new RectF(0, 0, mGraphWidth, mGraphHeight);\n\n calculateBounds(barWidth, margin);\n mLegend.invalidate();\n mGraph.invalidate();\n }",
"private void handleHidden(FormInput input) {\n\t\tString text = input.getInputValues().iterator().next().getValue();\n\t\tif (null == text || text.length() == 0) {\n\t\t\treturn;\n\t\t}\n\t\tWebElement inputElement = browser.getWebElement(input.getIdentification());\n\t\tJavascriptExecutor js = (JavascriptExecutor) browser.getWebDriver();\n\t\tjs.executeScript(\"arguments[0].setAttribute(arguments[1], arguments[2]);\", inputElement,\n\t\t\t\t\"value\", text);\n\t}",
"public void remove( Token token ) {\n if( token == first ) {\n first = first.next;\n }\n if( token == last ) {\n last = last.previous;\n }\n if( token.next != null ) {\n token.next.previous = token.previous;\n }\n if( token.previous != null ) {\n token.previous.next = token.next;\n }\n\n token.next = token.previous = null;\n size--;\n }",
"public static tmtrafficpolicy_tmglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_tmglobal_binding obj = new tmtrafficpolicy_tmglobal_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_tmglobal_binding response[] = (tmtrafficpolicy_tmglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"private void createPropertyVfsBundleFiles() throws CmsIllegalArgumentException, CmsLoaderException, CmsException {\n\n String bundleFileBasePath = m_sitepath + m_basename + \"_\";\n for (Locale l : m_localizations.keySet()) {\n CmsResource res = m_cms.createResource(\n bundleFileBasePath + l.toString(),\n OpenCms.getResourceManager().getResourceType(\n CmsMessageBundleEditorTypes.BundleType.PROPERTY.toString()));\n m_bundleFiles.put(l, res);\n LockedFile file = LockedFile.lockResource(m_cms, res);\n file.setCreated(true);\n m_lockedBundleFiles.put(l, file);\n m_changedTranslations.add(l);\n }\n\n }"
] |
Creates a non-binary media type with the given type, subtype, and charSet
@throws com.tngtech.jgiven.exception.JGivenWrongUsageException if any of the given arguments is {@code null} | [
"public static MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }"
] | [
"public static Observable<byte[]> downloadFileAsync(String url, Retrofit retrofit) {\n FileService service = retrofit.create(FileService.class);\n Observable<ResponseBody> response = service.download(url);\n return response.map(new Func1<ResponseBody, byte[]>() {\n @Override\n public byte[] call(ResponseBody responseBody) {\n try {\n return responseBody.bytes();\n } catch (IOException e) {\n throw Exceptions.propagate(e);\n }\n }\n });\n }",
"public static<T> Vendor<T> vendor(Func0<T> f) {\n\treturn j.vendor(f);\n }",
"public GetSingleConversationOptions filters(List<String> filters) {\n if(filters.size() == 1) { //Canvas API doesn't want the [] if it is only one value\n addSingleItem(\"filter\", filters.get(0));\n } else {\n optionsMap.put(\"filter[]\", filters);\n }\n return this;\n }",
"private String hibcProcess(String source) {\n\n // HIBC 2.6 allows up to 110 characters, not including the \"+\" prefix or the check digit\n if (source.length() > 110) {\n throw new OkapiException(\"Data too long for HIBC LIC\");\n }\n\n source = source.toUpperCase();\n if (!source.matches(\"[A-Z0-9-\\\\. \\\\$/+\\\\%]+?\")) {\n throw new OkapiException(\"Invalid characters in input\");\n }\n\n int counter = 41;\n for (int i = 0; i < source.length(); i++) {\n counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);\n }\n counter = counter % 43;\n\n char checkDigit = HIBC_CHAR_TABLE[counter];\n\n encodeInfo += \"HIBC Check Digit Counter: \" + counter + \"\\n\";\n encodeInfo += \"HIBC Check Digit: \" + checkDigit + \"\\n\";\n\n return \"+\" + source + checkDigit;\n }",
"protected Element createTextElement(float width)\n {\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"p\" + (textcnt++));\n el.setAttribute(\"class\", \"p\");\n String style = curstyle.toString();\n style += \"width:\" + width + UNIT + \";\";\n el.setAttribute(\"style\", style);\n return el;\n }",
"public <V> V getAttachment(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.get(key));\n }",
"@Override\n public boolean decompose( ZMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be square.\");\n if( A.numRows <= 0 )\n return false;\n\n QH = A;\n\n N = A.numCols;\n\n if( b.length < N*2 ) {\n b = new double[ N*2 ];\n gammas = new double[ N ];\n u = new double[ N*2 ];\n }\n return _decompose();\n }",
"public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }",
"private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }"
] |
Stop an animation. | [
"public void stopAnimation() {\n if(widget != null) {\n widget.removeStyleName(\"animated\");\n widget.removeStyleName(transition.getCssName());\n widget.removeStyleName(CssName.INFINITE);\n }\n }"
] | [
"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 }",
"public CollectionRequest<Attachment> findByTask(String task) {\n \n String path = String.format(\"/tasks/%s/attachments\", task);\n return new CollectionRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }",
"private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }",
"public 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 ProjectCalendar addDefaultBaseCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n calendar.setWorkingDay(Day.SUNDAY, false);\n calendar.setWorkingDay(Day.MONDAY, true);\n calendar.setWorkingDay(Day.TUESDAY, true);\n calendar.setWorkingDay(Day.WEDNESDAY, true);\n calendar.setWorkingDay(Day.THURSDAY, true);\n calendar.setWorkingDay(Day.FRIDAY, true);\n calendar.setWorkingDay(Day.SATURDAY, false);\n\n calendar.addDefaultCalendarHours();\n\n return (calendar);\n }",
"public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}",
"public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}",
"public void addAppenderEvent(final Category cat, final Appender appender) {\n\n\t\tupdateDefaultLayout(appender);\n\n\t\tif (appender instanceof FoundationFileRollingAppender) {\n\t\t\tfinal FoundationFileRollingAppender timeSizeRollingAppender = (FoundationFileRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\t//updateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout(); //So application state will not make any problems\n\n\t\t}else if(!(appender instanceof FoundationFileRollingAppender) && (appender instanceof TimeAndSizeRollingAppender)){ //TimeAndSizeRollingAppender\n\t\t\tfinal TimeAndSizeRollingAppender timeSizeRollingAppender = (TimeAndSizeRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\tupdateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout();\n\t\t}\n\t\tif ( ! (appender instanceof org.apache.log4j.AsyncAppender))\n initiateAsyncSupport(appender);\n\n\t}",
"public Date getNextWorkStart(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToNextWorkStart(cal);\n return cal.getTime();\n }"
] |
Produces or returns the existing proxy class. The operation is thread-safe.
@return always the class of the proxy | [
"public Class<T> getProxyClass() {\n String suffix = \"_$$_Weld\" + getProxyNameSuffix();\n String proxyClassName = getBaseProxyName();\n if (!proxyClassName.endsWith(suffix)) {\n proxyClassName = proxyClassName + suffix;\n }\n if (proxyClassName.startsWith(JAVA)) {\n proxyClassName = proxyClassName.replaceFirst(JAVA, \"org.jboss.weld\");\n }\n Class<T> proxyClass = null;\n Class<?> originalClass = bean != null ? bean.getBeanClass() : proxiedBeanType;\n BeanLogger.LOG.generatingProxyClass(proxyClassName);\n try {\n // First check to see if we already have this proxy class\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e) {\n // Create the proxy class for this instance\n try {\n proxyClass = createProxyClass(originalClass, proxyClassName);\n } catch (Throwable e1) {\n //attempt to load the class again, just in case another thread\n //defined it between the check and the create method\n try {\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e2) {\n BeanLogger.LOG.catchingDebug(e1);\n throw BeanLogger.LOG.unableToLoadProxyClass(bean, proxiedBeanType, e1);\n }\n }\n }\n return proxyClass;\n }"
] | [
"public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}",
"public <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 long removeRangeByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByLex(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }",
"public static base_response unset(nitro_service client, snmpalarm resource, String[] args) throws Exception{\n\t\tsnmpalarm unsetresource = new snmpalarm();\n\t\tunsetresource.trapname = resource.trapname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String getVersionString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.version\");\n\t\t}\n\t\treturn versionString;\n\t}",
"public static String normalizeWS(String value) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n boolean prevws = false;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (ch != ' ' && ch != '\\t' && ch != '\\n' && ch != '\\r') {\n if (prevws && pos != 0)\n tmp[pos++] = ' ';\n\n tmp[pos++] = ch;\n prevws = false;\n } else\n prevws = true;\n }\n return new String(tmp, 0, pos);\n }",
"private EditorState getMasterState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(4);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n cols.add(TableProperty.TRANSLATION);\n return new EditorState(cols, true);\n }",
"public T mapRow(ResultSet rs) throws SQLException {\n Map<String, Object> map = new HashMap<String, Object>();\n ResultSetMetaData metadata = rs.getMetaData();\n\n for (int i = 1; i <= metadata.getColumnCount(); ++i) {\n String label = metadata.getColumnLabel(i);\n\n final Object value;\n // calling getObject on a BLOB/CLOB produces weird results\n switch (metadata.getColumnType(i)) {\n case Types.BLOB:\n value = rs.getBytes(i);\n break;\n case Types.CLOB:\n value = rs.getString(i);\n break;\n default:\n value = rs.getObject(i);\n }\n\n // don't use table name extractor because we don't want aliased table name\n boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));\n String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);\n if (tableName != null && !tableName.isEmpty()) {\n String qualifiedName = tableName + \".\" + metadata.getColumnName(i);\n add(map, qualifiedName, value, overwrite);\n }\n\n add(map, label, value, overwrite);\n }\n\n return objectMapper.convertValue(map, type);\n }",
"public void declareShovel(String vhost, ShovelInfo info) {\n Map<String, Object> props = info.getDetails().getPublishProperties();\n if(props != null && props.isEmpty()) {\n throw new IllegalArgumentException(\"Shovel publish properties must be a non-empty map or null\");\n }\n final URI uri = uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(info.getName()));\n this.rt.put(uri, info);\n }"
] |
For internal use! This method creates real new PB instances | [
"protected PersistenceBrokerInternal createNewBrokerInstance(PBKey key) throws PBFactoryException\r\n {\r\n if (key == null) throw new PBFactoryException(\"Could not create new broker with PBkey argument 'null'\");\r\n // check if the given key really exists\r\n if (MetadataManager.getInstance().connectionRepository().getDescriptor(key) == null)\r\n {\r\n throw new PBFactoryException(\"Given PBKey \" + key + \" does not match in metadata configuration\");\r\n }\r\n if (log.isEnabledFor(Logger.INFO))\r\n {\r\n // only count created instances when INFO-Log-Level\r\n log.info(\"Create new PB instance for PBKey \" + key +\r\n \", already created persistence broker instances: \" + instanceCount);\r\n // useful for testing\r\n ++this.instanceCount;\r\n }\r\n\r\n PersistenceBrokerInternal instance = null;\r\n Class[] types = {PBKey.class, PersistenceBrokerFactoryIF.class};\r\n Object[] args = {key, this};\r\n try\r\n {\r\n instance = (PersistenceBrokerInternal) ClassHelper.newInstance(implementationClass, types, args);\r\n OjbConfigurator.getInstance().configure(instance);\r\n instance = (PersistenceBrokerInternal) InterceptorFactory.getInstance().createInterceptorFor(instance);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Creation of a new PB instance failed\", e);\r\n throw new PBFactoryException(\"Creation of a new PB instance failed\", e);\r\n }\r\n return instance;\r\n }"
] | [
"protected synchronized void streamingSlopPut(ByteArray key,\n Versioned<byte[]> value,\n String storeName,\n int failedNodeId) throws IOException {\n\n Slop slop = new Slop(storeName,\n Slop.Operation.PUT,\n key,\n value.getValue(),\n null,\n failedNodeId,\n new Date());\n\n ByteArray slopKey = slop.makeKey();\n Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop),\n value.getVersion());\n\n Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId);\n HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(),\n true,\n failedNode.getZoneId());\n // node Id which will receive the slop\n int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId();\n\n VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder()\n .setKey(ProtoUtils.encodeBytes(slopKey))\n .setVersioned(ProtoUtils.encodeVersioned(slopValue))\n .build();\n\n VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder()\n .setStore(SLOP_STORE)\n .setPartitionEntry(partitionEntry);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE,\n slopDestination));\n\n if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) {\n ProtoUtils.writeMessage(outputStream, updateRequest.build());\n } else {\n ProtoUtils.writeMessage(outputStream,\n VAdminProto.VoldemortAdminRequest.newBuilder()\n .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES)\n .setUpdatePartitionEntries(updateRequest)\n .build());\n outputStream.flush();\n nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true);\n\n }\n\n throttler.maybeThrottle(1);\n\n }",
"private void logOriginalResponseHistory(\n PluginResponse httpServletResponse, History history) throws URIException {\n RequestInformation requestInfo = requestInformation.get();\n if (requestInfo.handle && requestInfo.client.getIsActive()) {\n logger.info(\"Storing original response history\");\n history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setOriginalResponseContentType(httpServletResponse.getContentType());\n history.setOriginalResponseData(httpServletResponse.getContentString());\n logger.info(\"Done storing\");\n }\n }",
"private JSONArray datesToJson(Collection<Date> individualDates) {\n\n if (null != individualDates) {\n JSONArray result = new JSONArray();\n for (Date d : individualDates) {\n result.put(dateToJson(d));\n }\n return result;\n }\n return null;\n }",
"public static gslbservice_stats get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice_stats response = (gslbservice_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"@Deprecated\r\n public Location resolvePlaceId(String placeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_ID);\r\n\r\n parameters.put(\"place_id\", placeId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }",
"public static String flatten(String left, String right) {\n\t\treturn left == null || left.isEmpty() ? right : left + \".\" + right;\n\t}",
"public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static synchronized void register(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factory != null ) {\n if ( factories == null ) {\n factories = new HashMap<String, List<Callable<Class< ? >>>>();\n }\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l == null ) {\n l = new ArrayList<Callable<Class< ? >>>();\n factories.put( serviceName,\n l );\n }\n l.add( factory );\n }\n }",
"public static appfwsignatures get(nitro_service service) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tappfwsignatures[] response = (appfwsignatures[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] |
returns > 0 when o1 is more specific than o2,
returns == 0 when o1 and o2 are equal or unrelated,
returns < 0 when o2 is more specific than o1, | [
"protected int compare(MethodDesc o1, MethodDesc o2) {\n\t\tfinal Class<?>[] paramTypes1 = o1.getParameterTypes();\n\t\tfinal Class<?>[] paramTypes2 = o2.getParameterTypes();\n\n\t\t// sort by parameter types from left to right\n\t\tfor (int i = 0; i < paramTypes1.length; i++) {\n\t\t\tfinal Class<?> class1 = paramTypes1[i];\n\t\t\tfinal Class<?> class2 = paramTypes2[i];\n\n\t\t\tif (class1.equals(class2))\n\t\t\t\tcontinue;\n\t\t\tif (class1.isAssignableFrom(class2) || Void.class.equals(class2))\n\t\t\t\treturn -1;\n\t\t\tif (class2.isAssignableFrom(class1) || Void.class.equals(class1))\n\t\t\t\treturn 1;\n\t\t}\n\n\t\t// sort by declaring class (more specific comes first).\n\t\tif (!o1.getDeclaringClass().equals(o2.getDeclaringClass())) {\n\t\t\tif (o1.getDeclaringClass().isAssignableFrom(o2.getDeclaringClass()))\n\t\t\t\treturn 1;\n\t\t\tif (o2.getDeclaringClass().isAssignableFrom(o1.getDeclaringClass()))\n\t\t\t\treturn -1;\n\t\t}\n\n\t\t// sort by target\n\t\tfinal int compareTo = ((Integer) targets.indexOf(o2.target)).compareTo(targets.indexOf(o1.target));\n\t\treturn compareTo;\n\t}"
] | [
"private void checkUndefinedNotification(Notification notification) {\n String type = notification.getType();\n PathAddress source = notification.getSource();\n Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);\n if (!descriptions.keySet().contains(type)) {\n missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));\n }\n }",
"public CompositeGeneratorNode appendNewLineIfNotEmpty(final CompositeGeneratorNode parent) {\n List<IGeneratorNode> _children = parent.getChildren();\n String _lineDelimiter = this.wsConfig.getLineDelimiter();\n NewLineNode _newLineNode = new NewLineNode(_lineDelimiter, true);\n _children.add(_newLineNode);\n return parent;\n }",
"@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}",
"public static DeploymentReflectionIndex create() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(ServerPermission.CREATE_DEPLOYMENT_REFLECTION_INDEX);\n }\n return new DeploymentReflectionIndex();\n }",
"public static base_response update(nitro_service client, csparameter resource) throws Exception {\n\t\tcsparameter updateresource = new csparameter();\n\t\tupdateresource.stateupdate = resource.stateupdate;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void append(float[] newValue) {\n if ( (newValue.length % 2) == 0) {\n for (int i = 0; i < (newValue.length/2); i++) {\n value.add( new SFVec2f(newValue[i*2], newValue[i*2+1]) );\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec3f append set with array length not divisible by 2\");\n }\n }",
"public Set<String> rangeByRank(final long start, final long end) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n return jedis.zrange(getKey(), start, end);\n }\n });\n }",
"public static void validateUserStoreNamesOnNode(AdminClient adminClient,\n Integer nodeId,\n List<String> storeNames) {\n List<StoreDefinition> storeDefList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, Boolean> existingStoreNames = new HashMap<String, Boolean>();\n for(StoreDefinition storeDef: storeDefList) {\n existingStoreNames.put(storeDef.getName(), true);\n }\n for(String storeName: storeNames) {\n if(!Boolean.TRUE.equals(existingStoreNames.get(storeName))) {\n Utils.croak(\"Store \" + storeName + \" does not exist!\");\n }\n }\n }",
"public void setClasspathRef(Reference r)\r\n {\r\n createClasspath().setRefid(r);\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }"
] |
Assigned action code | [
"protected EObject forceCreateModelElementAndSet(Action action, EObject value) {\n \tEObject result = semanticModelBuilder.create(action.getType().getClassifier());\n \tsemanticModelBuilder.set(result, action.getFeature(), value, null /* ParserRule */, currentNode);\n \tinsertCompositeNode(action);\n \tassociateNodeWithAstElement(currentNode, result);\n \treturn result;\n }"
] | [
"public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException {\n\n List<CmsCategory> categories = readResourceCategories(cms, fromResource);\n for (CmsCategory category : categories) {\n addResourceToCategory(cms, toResourceSitePath, category);\n }\n }",
"public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }",
"private Iterable<PersistentNoSqlIdentifierGenerator> getPersistentGenerators() {\n\t\tMap<String, EntityPersister> entityPersisters = factory.getMetamodel().entityPersisters();\n\n\t\tSet<PersistentNoSqlIdentifierGenerator> persistentGenerators = new HashSet<PersistentNoSqlIdentifierGenerator>( entityPersisters.size() );\n\t\tfor ( EntityPersister persister : entityPersisters.values() ) {\n\t\t\tif ( persister.getIdentifierGenerator() instanceof PersistentNoSqlIdentifierGenerator ) {\n\t\t\t\tpersistentGenerators.add( (PersistentNoSqlIdentifierGenerator) persister.getIdentifierGenerator() );\n\t\t\t}\n\t\t}\n\n\t\treturn persistentGenerators;\n\t}",
"private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }",
"public static 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}",
"public static systemsession[] get(nitro_service service, Long sid[]) throws Exception{\n\t\tif (sid !=null && sid.length>0) {\n\t\t\tsystemsession response[] = new systemsession[sid.length];\n\t\t\tsystemsession obj[] = new systemsession[sid.length];\n\t\t\tfor (int i=0;i<sid.length;i++) {\n\t\t\t\tobj[i] = new systemsession();\n\t\t\t\tobj[i].set_sid(sid[i]);\n\t\t\t\tresponse[i] = (systemsession) 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 String formatAsStackTraceElement(InjectionPoint ij) {\n Member member;\n if (ij.getAnnotated() instanceof AnnotatedField) {\n AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated();\n member = annotatedField.getJavaMember();\n } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) {\n AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();\n member = annotatedParameter.getDeclaringCallable().getJavaMember();\n } else {\n // Not throwing an exception, because this method is invoked when an exception is already being thrown.\n // Throwing an exception here would hide the original exception.\n return \"-\";\n }\n return formatAsStackTraceElement(member);\n }",
"void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }",
"protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException\r\n {\r\n /*\r\n arminw:\r\n if broker isn't in PB-tx, start tx\r\n */\r\n if (!getBroker().isInTransaction())\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"call beginTransaction() on PB instance\");\r\n broker.beginTransaction();\r\n }\r\n\r\n // Notify objects of impending commits.\r\n performTransactionAwareBeforeCommit();\r\n\r\n // Now perfom the real work\r\n objectEnvelopeTable.writeObjects(isFlush);\r\n // now we have to perform the named objects\r\n namedRootsMap.performDeletion();\r\n namedRootsMap.performInsert();\r\n namedRootsMap.afterWriteCleanup();\r\n }"
] |
Set an enterprise cost value.
@param index cost index (1-30)
@param value cost value | [
"public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }"
] | [
"protected <T> T fromJsonString(String json, Class<T> clazz) {\n\t\treturn _gsonParser.fromJson(json, clazz);\n\t}",
"@Override\n protected String getToken() {\n GetAccessTokenResult token = accessToken.get();\n if (token == null || isExpired(token)\n || (isAboutToExpire(token) && refreshInProgress.compareAndSet(false, true))) {\n lock.lock();\n try {\n token = accessToken.get();\n if (token == null || isAboutToExpire(token)) {\n token = accessTokenProvider.getNewAccessToken(oauthScopes);\n accessToken.set(token);\n cacheExpirationHeadroom.set(getNextCacheExpirationHeadroom());\n }\n } finally {\n refreshInProgress.set(false);\n lock.unlock();\n }\n }\n return token.getAccessToken();\n }",
"public MembersList<Member> getList(String groupId, Set<String> memberTypes, int perPage, int page) throws FlickrException {\r\n MembersList<Member> members = new MembersList<Member>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_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 if (memberTypes != null) {\r\n parameters.put(\"membertypes\", StringUtilities.join(memberTypes, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element mElement = response.getPayload();\r\n members.setPage(mElement.getAttribute(\"page\"));\r\n members.setPages(mElement.getAttribute(\"pages\"));\r\n members.setPerPage(mElement.getAttribute(\"perpage\"));\r\n members.setTotal(mElement.getAttribute(\"total\"));\r\n\r\n NodeList mNodes = mElement.getElementsByTagName(\"member\");\r\n for (int i = 0; i < mNodes.getLength(); i++) {\r\n Element element = (Element) mNodes.item(i);\r\n members.add(parseMember(element));\r\n }\r\n return members;\r\n }",
"public static String checkRequiredProperties(Properties props,\r\n String ... requiredProps) {\r\n for (String required : requiredProps) {\r\n if (props.getProperty(required) == null) {\r\n return required;\r\n }\r\n }\r\n return null;\r\n }",
"@Deprecated\n public static RemoteProxyController create(final ManagementChannelHandler channelAssociation, final PathAddress pathAddress, final ProxyOperationAddressTranslator addressTranslator) {\n final TransactionalProtocolClient client = TransactionalProtocolHandlers.createClient(channelAssociation);\n // the remote proxy\n return create(client, pathAddress, addressTranslator, ModelVersion.CURRENT);\n }",
"public static String replaceParameters(final InputStream stream) {\n String content = IOUtil.asStringPreservingNewLines(stream);\n return resolvePlaceholders(content);\n }",
"protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException\n {\n StringBuilder pstyle = new StringBuilder(\"position:absolute;\");\n pstyle.append(\"left:\").append(x).append(UNIT).append(';');\n pstyle.append(\"top:\").append(y).append(UNIT).append(';');\n pstyle.append(\"width:\").append(width).append(UNIT).append(';');\n pstyle.append(\"height:\").append(height).append(UNIT).append(';');\n //pstyle.append(\"border:1px solid red;\");\n \n Element el = doc.createElement(\"img\");\n el.setAttribute(\"style\", pstyle.toString());\n\n String imgSrc = config.getImageHandler().handleResource(resource);\n\n if (!disableImageData && !imgSrc.isEmpty())\n el.setAttribute(\"src\", imgSrc);\n else\n el.setAttribute(\"src\", \"\");\n \n return el;\n }",
"public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedDelete == null) {\n\t\t\tmappedDelete = MappedDelete.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedDelete.delete(databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}"
] |
Get the script for a given ID
@param id ID of script
@return Script if found, otherwise null | [
"public Script getScript(int id) {\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE id = ?\"\n );\n statement.setInt(1, id);\n results = statement.executeQuery();\n if (results.next()) {\n return scriptFromSQLResult(results);\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return null;\n }"
] | [
"private void updateGhostStyle() {\n\n if (CmsStringUtil.isEmpty(m_realValue)) {\n if (CmsStringUtil.isEmpty(m_ghostValue)) {\n updateTextArea(m_realValue);\n return;\n }\n if (!m_focus) {\n setGhostStyleEnabled(true);\n updateTextArea(m_ghostValue);\n } else {\n // don't show ghost mode while focused\n setGhostStyleEnabled(false);\n }\n } else {\n setGhostStyleEnabled(false);\n updateTextArea(m_realValue);\n }\n }",
"public CollectionValuedMap<K, V> deltaClone() {\r\n CollectionValuedMap<K, V> result = new CollectionValuedMap<K, V>(null, cf, true);\r\n result.map = new DeltaMap<K, Collection<V>>(this.map);\r\n return result;\r\n }",
"public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\n }",
"public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {\n return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }",
"private boolean replaceValues(Locale locale) {\n\n try {\n SortedProperties localization = getLocalization(locale);\n if (hasDescriptor()) {\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n } else {\n m_container.removeAllItems();\n Set<Object> keyset = m_keyset.getKeySet();\n for (Object key : keyset) {\n Object itemId = m_container.addItem();\n Item item = m_container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n if (m_container.getItemIds().isEmpty()) {\n m_container.addItem();\n }\n }\n return true;\n } catch (IOException | CmsException e) {\n // The problem should typically be a problem with locking or reading the file containing the translation.\n // This should be reported in the editor, if false is returned here.\n return false;\n }\n }",
"public final double[] getDpiSuggestions() {\n if (this.dpiSuggestions == null) {\n List<Double> list = new ArrayList<>();\n for (double suggestion: DEFAULT_DPI_VALUES) {\n if (suggestion <= this.maxDpi) {\n list.add(suggestion);\n }\n }\n double[] suggestions = new double[list.size()];\n for (int i = 0; i < suggestions.length; i++) {\n suggestions[i] = list.get(i);\n }\n return suggestions;\n }\n return this.dpiSuggestions;\n }",
"public\tRandomVariableInterface[]\tgetFactorLoading(double time, double component, RandomVariableInterface[] realizationAtTimeIndex) {\n\t\tint componentIndex = liborPeriodDiscretization.getTimeIndex(component);\n\t\tif(componentIndex < 0) {\n\t\t\tcomponentIndex = -componentIndex - 2;\n\t\t}\n\t\treturn getFactorLoading(time, componentIndex, realizationAtTimeIndex);\n\t}",
"public final void notifyContentItemRemoved(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRemoved(position + headerItemCount);\n }",
"private double convertTenor(int maturityInMonths, int tenorInMonths) {\r\n\t\tSchedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths);\r\n\t\treturn schedule.getPayment(schedule.getNumberOfPeriods()-1);\r\n\t}"
] |
Sets test status. | [
"public void updateColor(TestColor color) {\n\n switch (color) {\n case green:\n m_forwardButton.setEnabled(true);\n m_confirmCheckbox.setVisible(false);\n m_status.setValue(STATUS_GREEN);\n break;\n case yellow:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_YELLOW);\n break;\n case red:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_RED);\n break;\n default:\n break;\n }\n }"
] | [
"@SuppressWarnings(\"deprecation\")\n private final void operationTimeout() {\n\n /**\n * first kill async http worker; before suicide LESSON: MUST KILL AND\n * WAIT FOR CHILDREN to reply back before kill itself.\n */\n cancelCancellable();\n if (asyncWorker != null && !asyncWorker.isTerminated()) {\n asyncWorker\n .tell(RequestWorkerMsgType.PROCESS_ON_TIMEOUT, getSelf());\n\n } else {\n logger.info(\"asyncWorker has been killed or uninitialized (null). \"\n + \"Not send PROCESS ON TIMEOUT.\\nREQ: \"\n + request.toString());\n replyErrors(PcConstants.OPERATION_TIMEOUT,\n PcConstants.OPERATION_TIMEOUT, PcConstants.NA,\n PcConstants.NA_INT);\n }\n\n }",
"private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }",
"private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }",
"public static vpnclientlessaccesspolicy[] get(nitro_service service) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String getDateCreatedTimeRangeFilterQuery(String searchField, long startTime, long endTime) {\n\n String sStartTime = null;\n String sEndTime = null;\n\n // Convert startTime to ISO 8601 format\n if ((startTime > Long.MIN_VALUE) && (startTime < Long.MAX_VALUE)) {\n sStartTime = CmsSearchUtil.getDateAsIso8601(new Date(startTime));\n }\n\n // Convert endTime to ISO 8601 format\n if ((endTime > Long.MIN_VALUE) && (endTime < Long.MAX_VALUE)) {\n sEndTime = CmsSearchUtil.getDateAsIso8601(new Date(endTime));\n }\n\n // Build Solr range string\n final String rangeString = CmsSearchUtil.getSolrRangeString(sStartTime, sEndTime);\n\n // Build Solr filter string\n return String.format(\"%s:%s\", searchField, rangeString);\n }",
"public Response save() throws RequestException, LocalOperationException {\n Map<String, Object> templateData = new HashMap<String, Object>();\n templateData.put(\"name\", name);\n\n options.put(\"steps\", steps.toMap());\n\n templateData.put(\"template\", options);\n Request request = new Request(transloadit);\n return new Response(request.post(\"/templates\", templateData));\n }",
"public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }",
"public BoxFolder.Info restoreFolder(String folderID) {\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }",
"public static String getString(byte[] bytes, String encoding) {\n try {\n return new String(bytes, encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }"
] |
Use this API to Import appfwsignatures. | [
"public static base_response Import(nitro_service client, appfwsignatures resource) throws Exception {\n\t\tappfwsignatures Importresource = new appfwsignatures();\n\t\tImportresource.src = resource.src;\n\t\tImportresource.name = resource.name;\n\t\tImportresource.xslt = resource.xslt;\n\t\tImportresource.comment = resource.comment;\n\t\tImportresource.overwrite = resource.overwrite;\n\t\tImportresource.merge = resource.merge;\n\t\tImportresource.sha1 = resource.sha1;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}"
] | [
"public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }",
"@Nonnull\n protected Payload getPayload(final String testName) {\n // Get the current bucket.\n final TestBucket testBucket = buckets.get(testName);\n\n // Lookup Payloads for this test\n if (testBucket != null) {\n final Payload payload = testBucket.getPayload();\n if (null != payload) {\n return payload;\n }\n }\n\n return Payload.EMPTY_PAYLOAD;\n }",
"public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }",
"private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) {\n if (!(flexiblePublisher instanceof FlexiblePublisher)) {\n throw new IllegalArgumentException(String.format(\"Publisher should be of type: '%s'. Found type: '%s'\",\n FlexiblePublisher.class, flexiblePublisher.getClass()));\n }\n\n List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers();\n for (ConditionalPublisher condition : conditions) {\n if (type.isInstance(condition.getPublisher())) {\n return type.cast(condition.getPublisher());\n }\n }\n\n return null;\n }",
"@VisibleForTesting\n protected static Dimension getMaxLabelSize(final ScaleBarRenderSettings settings) {\n float maxLabelHeight = 0.0f;\n float maxLabelWidth = 0.0f;\n for (final Label label: settings.getLabels()) {\n maxLabelHeight = Math.max(maxLabelHeight, label.getHeight());\n maxLabelWidth = Math.max(maxLabelWidth, label.getWidth());\n }\n return new Dimension((int) Math.ceil(maxLabelWidth), (int) Math.ceil(maxLabelHeight));\n }",
"private void processDeferredRelationship(DeferredRelationship dr) throws MPXJException\n {\n String data = dr.getData();\n Task task = dr.getTask();\n\n int length = data.length();\n\n if (length != 0)\n {\n int start = 0;\n int end = 0;\n\n while (end != length)\n {\n end = data.indexOf(m_delimiter, start);\n\n if (end == -1)\n {\n end = length;\n }\n\n populateRelation(dr.getField(), task, data.substring(start, end).trim());\n\n start = end + 1;\n }\n }\n }",
"private static boolean containsObject(Object searchFor, Object[] searchIn)\r\n {\r\n for (int i = 0; i < searchIn.length; i++)\r\n {\r\n if (searchFor == searchIn[i])\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public void removeGroup(int groupId) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_GROUPS\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, groupId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_GROUP_ID + \" = ?\"\n );\n\n statement.setInt(1, groupId);\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 removeGroupIdFromTablePaths(groupId);\n }",
"public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }"
] |
Creates a curator built using Fluo's zookeeper connection string. Root path will start at Fluo
chroot. | [
"public static CuratorFramework newFluoCurator(FluoConfiguration config) {\n return newCurator(config.getInstanceZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }"
] | [
"private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {\n if(response == null) {\n logger.warn(\"RoutingTimedout on waiting for async ops; parallelResponseToWait: \"\n + numNodesPendingResponse + \"; preferred-1: \" + (preferred - 1)\n + \"; quorumOK: \" + quorumSatisfied + \"; zoneOK: \" + zonesSatisfied);\n } else {\n numNodesPendingResponse = numNodesPendingResponse - 1;\n numResponsesGot = numResponsesGot + 1;\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handling async put error\");\n }\n if(response.getValue() instanceof QuotaExceededException) {\n /**\n * TODO Not sure if we need to count this Exception for\n * stats or silently ignore and just log a warning. While\n * QuotaExceededException thrown from other places mean the\n * operation failed, this one does not fail the operation\n * but instead stores slops. Introduce a new Exception in\n * client side to just monitor how mamy Async writes fail on\n * exceeding Quota?\n * \n */\n if(logger.isDebugEnabled()) {\n logger.debug(\"Received quota exceeded exception after a successful \"\n + pipeline.getOperation().getSimpleName() + \" call on node \"\n + response.getNode().getId() + \", store '\"\n + pipelineData.getStoreName() + \"', master-node '\"\n + pipelineData.getMaster().getId() + \"'\");\n }\n } else if(handleResponseError(response, pipeline, failureDetector)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key\n + \"} severe async put error, exiting parallel put stage\");\n }\n\n return;\n }\n if(PipelineRoutedStore.isSlopableFailure(response.getValue())\n || response.getValue() instanceof QuotaExceededException) {\n /**\n * We want to slop ParallelPuts which fail due to\n * QuotaExceededException.\n * \n * TODO Though this is not the right way of doing things, in\n * order to avoid inconsistencies and data loss, we chose to\n * slop the quota failed parallel puts.\n * \n * As a long term solution - 1) either Quota management\n * should be hidden completely in a routing layer like\n * Coordinator or 2) the Server should be able to\n * distinguish between serial and parallel puts and should\n * only quota for serial puts\n * \n */\n pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());\n }\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handled async put error\");\n }\n\n } else {\n pipelineData.incrementSuccesses();\n failureDetector.recordSuccess(response.getNode(), response.getRequestTime());\n pipelineData.getZoneResponses().add(response.getNode().getZoneId());\n }\n }\n }",
"public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }",
"public 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 void setEnterpriseNumber(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_NUMBER, index), value);\n }",
"public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }",
"static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {\n final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());\n final FlushableDataOutput output = context.writeMessage(header);\n try {\n // This is an error\n output.writeByte(DomainControllerProtocol.PARAM_ERROR);\n // send error code\n output.writeByte(errorCode);\n // error message\n if (message == null) {\n output.writeUTF(\"unknown error\");\n } else {\n output.writeUTF(message);\n }\n // response end\n output.writeByte(ManagementProtocol.RESPONSE_END);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }",
"public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}",
"public Conditionals addIfMatch(Tag tag) {\n Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));\n Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));\n List<Tag> match = new ArrayList<>(this.match);\n\n if (tag == null) {\n tag = Tag.ALL;\n }\n if (Tag.ALL.equals(tag)) {\n match.clear();\n }\n if (!match.contains(Tag.ALL)) {\n if (!match.contains(tag)) {\n match.add(tag);\n }\n }\n else {\n throw new IllegalArgumentException(\"Tag ALL already in the list\");\n }\n return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);\n }",
"public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }"
] |
Invokes a closure passing it a new Sql instance created from the given JDBC connection URL.
The created connection will be closed if required.
@param url a database url of the form
<code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
@param c the Closure to call
@see #newInstance(String)
@throws SQLException if a database access error occurs | [
"public static void withInstance(String url, Closure c) throws SQLException {\n Sql sql = null;\n try {\n sql = newInstance(url);\n c.call(sql);\n } finally {\n if (sql != null) sql.close();\n }\n }"
] | [
"public static dnstxtrec[] get(nitro_service service) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean find() {\r\n if (findIterator == null) {\r\n findIterator = root.iterator();\r\n }\r\n if (findCurrent != null && matches()) {\r\n return true;\r\n }\r\n while (findIterator.hasNext()) {\r\n findCurrent = findIterator.next();\r\n resetChildIter(findCurrent);\r\n if (matches()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static <T> List<T> makeList(T... items) {\r\n List<T> s = new ArrayList<T>(items.length);\r\n for (int i = 0; i < items.length; i++) {\r\n s.add(items[i]);\r\n }\r\n return s;\r\n }",
"public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) {\n return JavaConverters.asScalaIterableConverter(linkedList).asScala();\n }",
"@Override\n public final boolean getBool(final String key) {\n Boolean result = optBool(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"private void clearArt(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverAlbumArtUpdate(player, null); // Inform listeners that the artwork is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DataReference art : new HashSet<DataReference>(artCache.keySet())) {\n if (art.player == player) {\n artCache.remove(art);\n }\n }\n }",
"public void setDialect(String dialect) {\n String[] scripts = createScripts.get(dialect);\n createSql = scripts[0];\n createSqlInd = scripts[1];\n }",
"public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }",
"@Override\n public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,\n final ByteBuffer chunk, long timeoutMillis) {\n try {\n ensureInitialized();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n final Environment environment = ApiProxy.getCurrentEnvironment();\n return writePool.schedule(new Callable<RawGcsCreationToken>() {\n @Override\n public RawGcsCreationToken call() throws Exception {\n ApiProxy.setEnvironmentForCurrentThread(environment);\n return append(token, chunk);\n }\n }, 50, TimeUnit.MILLISECONDS);\n }"
] |
Create the exception assignment map.
@param rows calendar rows
@return exception assignment map | [
"private Map<Integer, List<Row>> createExceptionAssignmentMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String exceptions = row.getString(\"EXCEPTIONS\");\n map.put(calendarID, createExceptionAssignmentRowList(exceptions));\n }\n return map;\n }"
] | [
"private static int getContainerPort(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Port) {\n Port port = (Port) q;\n if (port.value() > 0) {\n return port.value();\n }\n }\n }\n\n ServicePort servicePort = findQualifiedServicePort(service, qualifiers);\n if (servicePort != null) {\n return servicePort.getTargetPort().getIntVal();\n }\n return 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 }",
"public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n public boolean commit() {\n final CoreRemoteMongoCollection<DocumentT> collection = getCollection();\n final List<WriteModel<DocumentT>> writeModels = getBulkWriteModels();\n\n // define success as any one operation succeeding for now\n boolean success = true;\n for (final WriteModel<DocumentT> write : writeModels) {\n if (write instanceof ReplaceOneModel) {\n final ReplaceOneModel<DocumentT> replaceModel = ((ReplaceOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(replaceModel.getFilter(), (Bson) replaceModel.getReplacement());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateOneModel) {\n final UpdateOneModel<DocumentT> updateModel = ((UpdateOneModel) write);\n final RemoteUpdateResult result =\n collection.updateOne(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n } else if (write instanceof UpdateManyModel) {\n final UpdateManyModel<DocumentT> updateModel = ((UpdateManyModel) write);\n final RemoteUpdateResult result =\n collection.updateMany(updateModel.getFilter(), updateModel.getUpdate());\n success = success\n && (result != null && result.getModifiedCount() == result.getMatchedCount());\n }\n }\n return success;\n }",
"public static boolean isFormatCorrect(String fileName, ReadOnlyStorageFormat format) {\n switch(format) {\n case READONLY_V0:\n case READONLY_V1:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n case READONLY_V2:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n default:\n throw new VoldemortException(\"Format type not supported\");\n }\n }",
"public static autoscaleprofile get(nitro_service service, String name) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tobj.set_name(name);\n\t\tautoscaleprofile response = (autoscaleprofile) obj.get_resource(service);\n\t\treturn response;\n\t}",
"protected Element createTextElement(float width)\n {\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"p\" + (textcnt++));\n el.setAttribute(\"class\", \"p\");\n String style = curstyle.toString();\n style += \"width:\" + width + UNIT + \";\";\n el.setAttribute(\"style\", style);\n return el;\n }",
"public void setLongAttribute(String name, Long value) {\n\t\tensureValue();\n\t\tAttribute attribute = new LongAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"static ChangeEvent<BsonDocument> changeEventForLocalReplace(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final BsonDocument document,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.REPLACE,\n document,\n namespace,\n new BsonDocument(\"_id\", documentId),\n null,\n writePending);\n }"
] |
Set the header names to forward from the request. Should not be defined if all is set to true
@param names the header names. | [
"public void setHeaders(final Set<String> names) {\n // transform to lower-case because header names should be case-insensitive\n Set<String> lowerCaseNames = new HashSet<>();\n for (String name: names) {\n lowerCaseNames.add(name.toLowerCase());\n }\n this.headerNames = lowerCaseNames;\n }"
] | [
"public void each(int offset, int maxRows, Closure closure) throws SQLException {\n eachRow(getSql(), getParameters(), offset, maxRows, closure);\n }",
"public static String entityToString(HttpEntity entity) throws IOException {\n if (entity != null) {\n InputStream is = entity.getContent();\n return IOUtils.toString(is, \"UTF-8\");\n }\n return \"\";\n }",
"public static OgmCollectionPersister getInverseCollectionPersister(OgmCollectionPersister mainSidePersister) {\n\t\tif ( mainSidePersister.isInverse() || !mainSidePersister.isManyToMany() || !mainSidePersister.getElementType().isEntityType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tEntityPersister inverseSidePersister = mainSidePersister.getElementPersister();\n\n\t\t// process collection-typed properties of inverse side and try to find association back to main side\n\t\tfor ( Type type : inverseSidePersister.getPropertyTypes() ) {\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( mainSidePersister.getFactory(), (CollectionType) type );\n\t\t\t\tif ( isCollectionMatching( mainSidePersister, inverseCollectionPersister ) ) {\n\t\t\t\t\treturn inverseCollectionPersister;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public static long directorySize(File self) throws IOException, IllegalArgumentException\n {\n final long[] size = {0L};\n\n eachFileRecurse(self, FileType.FILES, new Closure<Void>(null) {\n public void doCall(Object[] args) {\n size[0] += ((File) args[0]).length();\n }\n });\n\n return size[0];\n }",
"public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\n }",
"public static authenticationradiusaction[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public ListResponse listTemplates(Map<String, Object> options)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new ListResponse(request.get(\"/templates\", options));\n }",
"public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable) {\n final ServiceFuture<T> serviceFuture = new ServiceFuture<>();\n serviceFuture.subscription = observable\n .last()\n .subscribe(new Action1<ServiceResponse<T>>() {\n @Override\n public void call(ServiceResponse<T> t) {\n serviceFuture.set(t.body());\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }",
"public static Iterable<BoxRetentionPolicy.Info> getAll(final BoxAPIConnection api, String ... fields) {\r\n return getAll(null, null, null, DEFAULT_LIMIT, api, fields);\r\n }"
] |
those could be incorporated with above, but that would blurry everything. | [
"protected void checkConsecutiveAlpha() {\n\n Pattern symbolsPatter = Pattern.compile(REGEX_ALPHA_UC + \"+\");\n Matcher matcher = symbolsPatter.matcher(this.password);\n int met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n\n // alpha lower case\n\n symbolsPatter = Pattern.compile(REGEX_ALPHA_LC + \"+\");\n matcher = symbolsPatter.matcher(this.password);\n met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n }"
] | [
"private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\n }",
"public final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }",
"public static long getMaxId(PersistenceBroker brokerForClass, Class topLevel, FieldDescriptor original) throws PersistenceBrokerException\r\n {\r\n long max = 0;\r\n long tmp;\r\n ClassDescriptor cld = brokerForClass.getClassDescriptor(topLevel);\r\n\r\n // if class is not an interface / not abstract we have to search its directly mapped table\r\n if (!cld.isInterface() && !cld.isAbstract())\r\n {\r\n tmp = getMaxIdForClass(brokerForClass, cld, original);\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n // if class is an extent we have to search through its subclasses\r\n if (cld.isExtent())\r\n {\r\n Vector extentClasses = cld.getExtentClasses();\r\n for (int i = 0; i < extentClasses.size(); i++)\r\n {\r\n Class extentClass = (Class) extentClasses.get(i);\r\n if (cld.getClassOfObject().equals(extentClass))\r\n {\r\n throw new PersistenceBrokerException(\"Circular extent in \" + extentClass +\r\n \", please check the repository\");\r\n }\r\n else\r\n {\r\n // fix by Mark Rowell\r\n // Call recursive\r\n tmp = getMaxId(brokerForClass, extentClass, original);\r\n }\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n }\r\n return max;\r\n }",
"public void setIndexBuffer(GVRIndexBuffer ibuf)\n {\n mIndices = ibuf;\n NativeMesh.setIndexBuffer(getNative(), (ibuf != null) ? ibuf.getNative() : 0L);\n }",
"public static Trajectory concactTrajectorie(Trajectory a, Trajectory b){\n\t\tif(a.getDimension()!=b.getDimension()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not have the same dimension\");\n\t\t}\n\t\tTrajectory c = new Trajectory(a.getDimension());\n\t\t\n\t\tfor(int i = 0 ; i < a.size(); i++){\n\t\t\tPoint3d pos = new Point3d(a.get(i).x, \n\t\t\t\t\ta.get(i).y, \n\t\t\t\t\ta.get(i).z);\n\t\t\tc.add(pos);\n\t\t}\n\t\t\n\t\tdouble dx = a.get(a.size()-1).x - b.get(0).x;\n\t\tdouble dy = a.get(a.size()-1).y - b.get(0).y;\n\t\tdouble dz = a.get(a.size()-1).z - b.get(0).z;\n\t\t\n\t\tfor(int i = 1 ; i < b.size(); i++){\n\t\t\tPoint3d pos = new Point3d(b.get(i).x+dx, \n\t\t\t\t\tb.get(i).y+dy, \n\t\t\t\t\tb.get(i).z+dz);\n\t\t\tc.add(pos);\n\t\t}\n\t\t\n\t\treturn c;\n\t\t\n\t}",
"public void setVolume(float volume)\n {\n // Save this in case this audio source is not being played yet\n mVolume = volume;\n if (isPlaying() && (getSourceId() != GvrAudioEngine.INVALID_ID))\n {\n // This will actually work only if the sound file is being played\n mAudioListener.getAudioEngine().setSoundVolume(getSourceId(), getVolume());\n }\n }",
"private static long switchValue8(long currentHexValue, int digitCount) {\n\t\tlong result = 0x7 & currentHexValue;\n\t\tint shift = 0;\n\t\twhile(--digitCount > 0) {\n\t\t\tshift += 3;\n\t\t\tcurrentHexValue >>>= 4;\n\t\t\tresult |= (0x7 & currentHexValue) << shift;\n\t\t}\n\t\treturn result;\n\t}",
"public final void notifyHeaderItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (newHeaderItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart, itemCount);\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 }"
] |
If the Authtoken was already created in a separate program but not saved to file.
@param authToken
@param tokenSecret
@param username
@return
@throws IOException | [
"private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {\n\n Auth auth = new Auth();\n auth.setToken(authToken);\n auth.setTokenSecret(tokenSecret);\n\n // Prompt to ask what permission is needed: read, update or delete.\n auth.setPermission(Permission.fromString(\"delete\"));\n\n User user = new User();\n // Later change the following 3. Either ask user to pass on command line or read\n // from saved file.\n user.setId(nsid);\n user.setUsername((username));\n user.setRealName(\"\");\n auth.setUser(user);\n this.authStore.store(auth);\n return auth;\n }"
] | [
"@RequestMapping(value = \"/api/scripts\", method = RequestMethod.POST)\n public\n @ResponseBody\n Script addScript(Model model,\n @RequestParam(required = true) String name,\n @RequestParam(required = true) String script) throws Exception {\n\n return ScriptService.getInstance().addScript(name, script);\n }",
"public static base_responses update(nitro_service client, snmpalarm resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpalarm updateresources[] = new snmpalarm[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpalarm();\n\t\t\t\tupdateresources[i].trapname = resources[i].trapname;\n\t\t\t\tupdateresources[i].thresholdvalue = resources[i].thresholdvalue;\n\t\t\t\tupdateresources[i].normalvalue = resources[i].normalvalue;\n\t\t\t\tupdateresources[i].time = resources[i].time;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].severity = resources[i].severity;\n\t\t\t\tupdateresources[i].logging = resources[i].logging;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"protected int countedSize() throws PersistenceBrokerException\r\n {\r\n Query countQuery = getBroker().serviceBrokerHelper().getCountQuery(getQueryObject().getQuery());\r\n ResultSetAndStatement rsStmt;\r\n ClassDescriptor cld = getQueryObject().getClassDescriptor();\r\n int count = 0;\r\n\r\n // BRJ: do not use broker.getCount() because it's extent-aware\r\n // the count we need here must not include extents !\r\n if (countQuery instanceof QueryBySQL)\r\n {\r\n String countSql = ((QueryBySQL) countQuery).getSql();\r\n rsStmt = getBroker().serviceJdbcAccess().executeSQL(countSql, cld, Query.NOT_SCROLLABLE);\r\n }\r\n else\r\n {\r\n rsStmt = getBroker().serviceJdbcAccess().executeQuery(countQuery, cld);\r\n }\r\n\r\n try\r\n {\r\n if (rsStmt.m_rs.next())\r\n {\r\n count = rsStmt.m_rs.getInt(1);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n finally\r\n {\r\n rsStmt.close();\r\n }\r\n\r\n return count;\r\n }",
"public AsciiTable setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private static Iterable<BoxUser.Info> getUsersInfoForType(final BoxAPIConnection api,\n final String filterTerm, final String userType, final String externalAppUserId, final String... fields) {\n return new Iterable<BoxUser.Info>() {\n public Iterator<BoxUser.Info> iterator() {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (filterTerm != null) {\n builder.appendParam(\"filter_term\", filterTerm);\n }\n if (userType != null) {\n builder.appendParam(\"user_type\", userType);\n }\n if (externalAppUserId != null) {\n builder.appendParam(\"external_app_user_id\", externalAppUserId);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxUserIterator(api, url);\n }\n };\n }",
"private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n //baseline.getBCWP()\n //baseline.getBCWS()\n Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost());\n Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish());\n //baseline.getNumber()\n Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpx.setBaselineCost(cost);\n mpx.setBaselineFinish(finish);\n mpx.setBaselineStart(start);\n mpx.setBaselineWork(work);\n }\n else\n {\n mpx.setBaselineCost(number, cost);\n mpx.setBaselineWork(number, work);\n mpx.setBaselineStart(number, start);\n mpx.setBaselineFinish(number, finish);\n }\n }\n }",
"public static String getEncoding(CmsObject cms, CmsResource file) {\n\n CmsProperty encodingProperty = CmsProperty.getNullProperty();\n try {\n encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n return CmsEncoder.lookupEncoding(encodingProperty.getValue(\"\"), OpenCms.getSystemInfo().getDefaultEncoding());\n }",
"public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void applyMultiIconTo(Drawable icon, int iconColor, Drawable selectedIcon, int selectedIconColor, boolean tinted, ImageView imageView) {\n //if we have an icon then we want to set it\n if (icon != null) {\n //if we got a different color for the selectedIcon we need a StateList\n if (selectedIcon != null) {\n if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, selectedIcon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(UIUtils.getIconStateList(icon, selectedIcon));\n }\n } else if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(icon);\n }\n //make sure we display the icon\n imageView.setVisibility(View.VISIBLE);\n } else {\n //hide the icon\n imageView.setVisibility(View.GONE);\n }\n }"
] |
Called when the scene object gets a new parent.
@param parent New parent of this scene object. | [
"protected void onNewParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onNewOwnersParent(parent);\n }\n }"
] | [
"public void rollback()\r\n {\r\n try\r\n {\r\n Iterator iter = mvOrderOfIds.iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n if(log.isDebugEnabled())\r\n log.debug(\"rollback: \" + mod);\r\n // if the Object has been modified by transaction, mark object as dirty\r\n if(mod.hasChanged(transaction.getBroker()))\r\n {\r\n mod.setModificationState(mod.getModificationState().markDirty());\r\n }\r\n mod.getModificationState().rollback(mod);\r\n }\r\n }\r\n finally\r\n {\r\n needsCommit = false;\r\n }\r\n afterWriteCleanup();\r\n }",
"public final Iterator<AbstractTraceRegion> leafIterator() {\n\t\tif (nestedRegions == null)\n\t\t\treturn Collections.<AbstractTraceRegion> singleton(this).iterator();\n\t\treturn new LeafIterator(this);\n\t}",
"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 static void configure(Job conf, SimpleConfiguration props) {\n try {\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n props.save(baos);\n\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public static base_response clear(nitro_service client, route6 resource) throws Exception {\n\t\troute6 clearresource = new route6();\n\t\tclearresource.routetype = resource.routetype;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public static String getParameter(DbConn cnx, String key, String defaultValue)\n {\n try\n {\n return cnx.runSelectSingle(\"globalprm_select_by_key\", 3, String.class, key);\n }\n catch (NoResultException e)\n {\n return defaultValue;\n }\n }",
"public 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 sslpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tsslpolicy_lbvserver_binding obj = new sslpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tsslpolicy_lbvserver_binding response[] = (sslpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean contains(Vector3 p) {\n\t\tboolean ans = false;\n\t\tif(this.halfplane || p== null) return false;\n\n\t\tif (isCorner(p)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tPointLinePosition a12 = PointLineTest.pointLineTest(a,b,p);\n\t\tPointLinePosition a23 = PointLineTest.pointLineTest(b,c,p);\n\t\tPointLinePosition a31 = PointLineTest.pointLineTest(c,a,p);\n\n\t\tif ((a12 == PointLinePosition.LEFT && a23 == PointLinePosition.LEFT && a31 == PointLinePosition.LEFT ) ||\n\t\t\t\t(a12 == PointLinePosition.RIGHT && a23 == PointLinePosition.RIGHT && a31 == PointLinePosition.RIGHT ) ||\n\t\t\t\t(a12 == PointLinePosition.ON_SEGMENT ||a23 == PointLinePosition.ON_SEGMENT || a31 == PointLinePosition.ON_SEGMENT)) {\n\t\t\tans = true;\n\t\t}\n\n\t\treturn ans;\n\t}"
] |
Gets currently visible user.
@return List of user | [
"public List<CmsUser> getVisibleUser() {\n\n if (!m_fullyLoaded) {\n return m_users;\n }\n if (size() == m_users.size()) {\n return m_users;\n }\n List<CmsUser> directs = new ArrayList<CmsUser>();\n for (CmsUser user : m_users) {\n if (!m_indirects.contains(user)) {\n directs.add(user);\n }\n }\n return directs;\n }"
] | [
"public int getModifiers() {\n MetaMethod getter = getGetter();\n MetaMethod setter = getSetter();\n if (setter != null && getter == null) return setter.getModifiers();\n if (getter != null && setter == null) return getter.getModifiers();\n int modifiers = getter.getModifiers() | setter.getModifiers();\n int visibility = 0;\n if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC;\n if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED;\n if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE;\n int states = getter.getModifiers() & setter.getModifiers();\n states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);\n states |= visibility;\n return states;\n }",
"public void writeOutput(DataPipe cr) {\n String[] nextLine = new String[cr.getDataMap().entrySet().size()];\n\n int count = 0;\n for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) {\n nextLine[count] = entry.getValue();\n count++;\n }\n\n csvFile.writeNext(nextLine);\n }",
"private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }",
"private void deliverBeatGridUpdate(int player, BeatGrid beatGrid) {\n if (!getBeatGridListeners().isEmpty()) {\n final BeatGridUpdate update = new BeatGridUpdate(player, beatGrid);\n for (final BeatGridListener listener : getBeatGridListeners()) {\n try {\n listener.beatGridChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering beat grid update to listener\", t);\n }\n }\n }\n }",
"public static 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}",
"private void ensureNext() {\n // Check if the current scan result has more keys (i.e. the index did not reach the end of the result list)\n if (resultIndex < scanResult.getResult().size()) {\n return;\n }\n // Since the current scan result was fully iterated,\n // if there is another cursor scan it and ensure next key (recursively)\n if (!FIRST_CURSOR.equals(scanResult.getStringCursor())) {\n scanResult = scan(scanResult.getStringCursor(), scanParams);\n resultIndex = 0;\n ensureNext();\n }\n }",
"protected String sendRequestToDF(String df_service, Object msgContent) {\n\n IDFComponentDescription[] receivers = getReceivers(df_service);\n if (receivers.length > 0) {\n IMessageEvent mevent = createMessageEvent(\"send_request\");\n mevent.getParameter(SFipa.CONTENT).setValue(msgContent);\n for (int i = 0; i < receivers.length; i++) {\n mevent.getParameterSet(SFipa.RECEIVERS).addValue(\n receivers[i].getName());\n logger.info(\"The receiver is \" + receivers[i].getName());\n }\n sendMessage(mevent);\n }\n logger.info(\"Message sended to \" + df_service + \" to \"\n + receivers.length + \" receivers\");\n return (\"Message sended to \" + df_service);\n }",
"@Override\n\tpublic boolean addAll(Collection<? extends T> collection) {\n\t\tboolean changed = false;\n\t\tfor (T data : collection) {\n\t\t\ttry {\n\t\t\t\tif (addElement(data)) {\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not create data elements in dao\", e);\n\t\t\t}\n\t\t}\n\t\treturn changed;\n\t}",
"private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }"
] |
Convert an Image into a TYPE_INT_ARGB BufferedImage. If the image is already of this type, the original image is returned unchanged.
@param image the image to convert
@return the converted image | [
"public static BufferedImage convertImageToARGB( Image image ) {\n\t\tif ( image instanceof BufferedImage && ((BufferedImage)image).getType() == BufferedImage.TYPE_INT_ARGB )\n\t\t\treturn (BufferedImage)image;\n\t\tBufferedImage p = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics2D g = p.createGraphics();\n\t\tg.drawImage( image, 0, 0, null );\n\t\tg.dispose();\n\t\treturn p;\n\t}"
] | [
"private void verifyApplicationName(String name) {\n if (name == null) {\n throw new IllegalArgumentException(\"Application name cannot be null\");\n }\n if (name.isEmpty()) {\n throw new IllegalArgumentException(\"Application name length must be > 0\");\n }\n String reason = null;\n char[] chars = name.toCharArray();\n char c;\n for (int i = 0; i < chars.length; i++) {\n c = chars[i];\n if (c == 0) {\n reason = \"null character not allowed @\" + i;\n break;\n } else if (c == '/' || c == '.' || c == ':') {\n reason = \"invalid character '\" + c + \"'\";\n break;\n } else if (c > '\\u0000' && c <= '\\u001f' || c >= '\\u007f' && c <= '\\u009F'\n || c >= '\\ud800' && c <= '\\uf8ff' || c >= '\\ufff0' && c <= '\\uffff') {\n reason = \"invalid character @\" + i;\n break;\n }\n }\n if (reason != null) {\n throw new IllegalArgumentException(\n \"Invalid application name \\\"\" + name + \"\\\" caused by \" + reason);\n }\n }",
"private void readProjectHeader()\n {\n Table table = m_tables.get(\"DIR\");\n MapRow row = table.find(\"\");\n if (row != null)\n {\n setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());\n m_wbsFormat = new P3WbsFormat(row);\n }\n }",
"@AsParameterConverter\n\tpublic Trader retrieveTrader(String name) {\n\t\tfor (Trader trader : traders) {\n\t\t\tif (trader.getName().equals(name)) {\n\t\t\t\treturn trader;\n\t\t\t}\n\t\t}\n\t\treturn mockTradePersister().retrieveTrader(name);\n\t}",
"@Override\r\n public synchronized long skip(final long length) throws IOException {\r\n final long skip = super.skip(length);\r\n this.count += skip;\r\n return skip;\r\n }",
"private String getContentFromPath(String sourcePath,\n HostsSourceType sourceType) throws IOException {\n\n String res = \"\";\n\n if (sourceType == HostsSourceType.LOCAL_FILE) {\n res = PcFileNetworkIoUtils.readFileContentToString(sourcePath);\n } else if (sourceType == HostsSourceType.URL) {\n res = PcFileNetworkIoUtils.readStringFromUrlGeneric(sourcePath);\n }\n return res;\n\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic static Type getSuperclassTypeParameter(Class<?> subclass) {\n\t\tType superclass = subclass.getGenericSuperclass();\n\t\tif (superclass instanceof Class) {\n\t\t\tthrow new RuntimeException(\"Missing type parameter.\");\n\t\t}\n\t\treturn ((ParameterizedType) superclass).getActualTypeArguments()[0];\n\t}",
"public void clearSources()\n {\n synchronized (mAudioSources)\n {\n for (GVRAudioSource source : mAudioSources)\n {\n source.setListener(null);\n }\n mAudioSources.clear();\n }\n }",
"public static String encode(String component) {\n if (component != null) {\n try {\n return URLEncoder.encode(component, UTF_8.name());\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"JVM must support UTF-8\", e);\n }\n }\n return null;\n }",
"public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) {\n\t\treturn CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason });\n\t}"
] |
mark a node as blacklisted
@param nodeId Integer node id of the node to be blacklisted | [
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public void blacklistNode(int nodeId) {\n Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();\n\n if(blackListedNodes == null) {\n blackListedNodes = new ArrayList();\n }\n blackListedNodes.add(nodeId);\n\n for(Node node: nodesInCluster) {\n\n if(node.getId() == nodeId) {\n nodesToStream.remove(node);\n break;\n }\n\n }\n\n for(String store: storeNames) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n nodeId));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n }"
] | [
"private boolean isSpecial(final char chr) {\n\t\treturn ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')\n\t\t\t\t|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\\\')\n\t\t\t\t|| (chr == '&'));\n\t}",
"private void readRelationships(Storepoint phoenixProject)\n {\n for (Relationship relation : phoenixProject.getRelationships().getRelationship())\n {\n readRelation(relation);\n }\n }",
"private synchronized Response doAuthenticatedRequest(\n final StitchAuthRequest stitchReq,\n final AuthInfo authInfo\n ) {\n try {\n return requestClient.doRequest(prepareAuthRequest(stitchReq, authInfo));\n } catch (final StitchServiceException ex) {\n return handleAuthFailure(ex, stitchReq);\n }\n }",
"public void setDoubleAttribute(String name, Double value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DoubleAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}",
"private Number calculatePercentComplete(Row row)\n {\n Number result;\n switch (PercentCompleteType.getInstance(row.getString(\"complete_pct_type\")))\n {\n case UNITS:\n {\n result = calculateUnitsPercentComplete(row);\n break;\n }\n\n case DURATION:\n {\n result = calculateDurationPercentComplete(row);\n break;\n }\n\n default:\n {\n result = calculatePhysicalPercentComplete(row);\n break;\n }\n }\n\n return result;\n }",
"public String getTypeDescriptor() {\n if (typeDescriptor == null) {\n StringBuilder buf = new StringBuilder(name.length() + parameters.length * 10);\n buf.append(returnType.getName());\n buf.append(' ');\n buf.append(name);\n buf.append('(');\n for (int i = 0; i < parameters.length; i++) {\n if (i > 0) {\n buf.append(\", \");\n }\n Parameter param = parameters[i];\n buf.append(formatTypeName(param.getType()));\n }\n buf.append(')');\n typeDescriptor = buf.toString();\n }\n return typeDescriptor;\n }",
"private static Date getSentDate(MimeMessage msg, Date defaultVal) {\r\n if (msg == null) {\r\n return defaultVal;\r\n }\r\n try {\r\n Date sentDate = msg.getSentDate();\r\n if (sentDate == null) {\r\n return defaultVal;\r\n } else {\r\n return sentDate;\r\n }\r\n } catch (MessagingException me) {\r\n return new Date();\r\n }\r\n }",
"synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }",
"public static vpnclientlessaccesspolicy get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy response = (vpnclientlessaccesspolicy) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Put object to session cache.
@param oid The {@link org.apache.ojb.broker.Identity} of the object to cache
@param entry The {@link org.apache.ojb.broker.cache.ObjectCacheTwoLevelImpl.CacheEntry} of the object
@param onlyIfNew Flag, if set <em>true</em> only new objects (not already in session cache) be cached. | [
"private void putToSessionCache(Identity oid, CacheEntry entry, boolean onlyIfNew)\r\n {\r\n if(onlyIfNew)\r\n {\r\n // no synchronization needed, because session cache was used per broker instance\r\n if(!sessionCache.containsKey(oid)) sessionCache.put(oid, entry);\r\n }\r\n else\r\n {\r\n sessionCache.put(oid, entry);\r\n }\r\n }"
] | [
"public static ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,\n final DomainController domainController, final ExpressionResolver expressionResolver) {\n final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,\n hostModel, domainController, expressionResolver);\n\n\n return factory.getBootUpdates();\n }",
"public synchronized void resumeControlPoint(final String entryPoint) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getEntryPoint().equals(entryPoint)) {\n ep.resume();\n }\n }\n }",
"public void setWeekDay(String weekDayStr) {\n\n final WeekDay weekDay = WeekDay.valueOf(weekDayStr);\n if ((m_model.getWeekDay() != null) || !m_model.getWeekDay().equals(weekDay)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(weekDay);\n onValueChange();\n }\n });\n\n }\n\n }",
"@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }",
"public static void block(DMatrix1Row A , DMatrix1Row A_tran ,\n final int blockLength )\n {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int blockHeight = Math.min( blockLength , A.numRows - i);\n\n int indexSrc = i*A.numCols;\n int indexDst = i;\n\n for( int j = 0; j < A.numCols; j += blockLength ) {\n int blockWidth = Math.min( blockLength , A.numCols - j);\n\n// int indexSrc = i*A.numCols + j;\n// int indexDst = j*A_tran.numCols + i;\n\n int indexSrcEnd = indexSrc + blockWidth;\n// for( int l = 0; l < blockWidth; l++ , indexSrc++ ) {\n for( ; indexSrc < indexSrcEnd; indexSrc++ ) {\n int rowSrc = indexSrc;\n int rowDst = indexDst;\n int end = rowDst + blockHeight;\n// for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) {\n for( ; rowDst < end; rowSrc += A.numCols ) {\n // faster to write in sequence than to read in sequence\n A_tran.data[ rowDst++ ] = A.data[ rowSrc ];\n }\n indexDst += A_tran.numCols;\n }\n }\n }\n }",
"public BoneCP getPool() {\r\n\t\tFinalWrapper<BoneCP> wrapper = this.pool;\r\n\t\treturn wrapper == null ? null : wrapper.value;\r\n\t}",
"public Collection<Argument> getArguments(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return new ArrayList<>(args);\n }\n return Collections.emptyList();\n }",
"private void writeWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar)\n {\n List<ProjectCalendarWeek> weeks = mpxjCalendar.getWorkWeeks();\n if (!weeks.isEmpty())\n {\n WorkWeeks xmlWorkWeeks = m_factory.createProjectCalendarsCalendarWorkWeeks();\n xmlCalendar.setWorkWeeks(xmlWorkWeeks);\n List<WorkWeek> xmlWorkWeekList = xmlWorkWeeks.getWorkWeek();\n\n for (ProjectCalendarWeek week : weeks)\n {\n WorkWeek xmlWeek = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeek();\n xmlWorkWeekList.add(xmlWeek);\n\n xmlWeek.setName(week.getName());\n TimePeriod xmlTimePeriod = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekTimePeriod();\n xmlWeek.setTimePeriod(xmlTimePeriod);\n xmlTimePeriod.setFromDate(week.getDateRange().getStart());\n xmlTimePeriod.setToDate(week.getDateRange().getEnd());\n\n WeekDays xmlWeekDays = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDays();\n xmlWeek.setWeekDays(xmlWeekDays);\n\n List<Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay> dayList = xmlWeekDays.getWeekDay();\n\n for (int loop = 1; loop < 8; loop++)\n {\n DayType workingFlag = week.getWorkingDay(Day.getInstance(loop));\n\n if (workingFlag != DayType.DEFAULT)\n {\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BigInteger.valueOf(loop));\n day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING));\n\n if (workingFlag == DayType.WORKING)\n {\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n ProjectCalendarHours bch = week.getCalendarHours(Day.getInstance(loop));\n if (bch != null)\n {\n for (DateRange range : bch)\n {\n if (range != null)\n {\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }\n }\n }\n }\n }\n }",
"public static double calculateBoundedness(double D, int N, double timelag, double confRadius){\n\t\tdouble r = confRadius;\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble res = cov_area/(4*r*r);\n\t\treturn res;\n\t}"
] |
Returns only the leaf categories of the wrapped categories.
The method assumes that categories are ordered in the list, i.e., parents are directly followed by their children.
NOTE: In the complete category tree a leaf of the wrapped tree part may not be a leaf.
@return only the leaf categories of the wrapped categories. | [
"public List<CmsCategory> getLeafItems() {\n\n List<CmsCategory> result = new ArrayList<CmsCategory>();\n if (m_categories.isEmpty()) {\n return result;\n }\n Iterator<CmsCategory> it = m_categories.iterator();\n CmsCategory current = it.next();\n while (it.hasNext()) {\n CmsCategory next = it.next();\n if (!next.getPath().startsWith(current.getPath())) {\n result.add(current);\n }\n current = next;\n }\n result.add(current);\n return result;\n }"
] | [
"private 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 ConnectionInfo getConnection(String name) {\n final URI uri = uriWithPath(\"./connections/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ConnectionInfo.class);\n }",
"public static byte[] domainControllerDataToByteBuffer(List<DomainControllerData> data) throws Exception {\n final ByteArrayOutputStream out_stream = new ByteArrayOutputStream(512);\n byte[] result;\n try (DataOutputStream out = new DataOutputStream(out_stream)) {\n Iterator<DomainControllerData> iter = data.iterator();\n while (iter.hasNext()) {\n DomainControllerData dcData = iter.next();\n dcData.writeTo(out);\n if (iter.hasNext()) {\n S3Util.writeString(SEPARATOR, out);\n }\n }\n result = out_stream.toByteArray();\n }\n return result;\n }",
"@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }",
"public int removeChildObjectsByName(final String name) {\n int removed = 0;\n\n if (null != name && !name.isEmpty()) {\n removed = removeChildObjectsByNameImpl(name);\n }\n\n return removed;\n }",
"public static base_responses update(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat updateresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new inat();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].privateip = resources[i].privateip;\n\t\t\t\tupdateresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].tftp = resources[i].tftp;\n\t\t\t\tupdateresources[i].usip = resources[i].usip;\n\t\t\t\tupdateresources[i].usnip = resources[i].usnip;\n\t\t\t\tupdateresources[i].proxyip = resources[i].proxyip;\n\t\t\t\tupdateresources[i].mode = resources[i].mode;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n public void close(SocketDestination destination) {\n factory.setLastClosedTimestamp(destination);\n queuedPool.reset(destination);\n }",
"public void createEnablement() {\n GlobalEnablementBuilder builder = beanManager.getServices().get(GlobalEnablementBuilder.class);\n ModuleEnablement enablement = builder.createModuleEnablement(this);\n beanManager.setEnabled(enablement);\n\n if (BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.enabledAlternatives(this.beanManager, WeldCollections.toMultiRowString(enablement.getAllAlternatives()));\n BootstrapLogger.LOG.enabledDecorators(this.beanManager, WeldCollections.toMultiRowString(enablement.getDecorators()));\n BootstrapLogger.LOG.enabledInterceptors(this.beanManager, WeldCollections.toMultiRowString(enablement.getInterceptors()));\n }\n }",
"public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }"
] |
creates a shape list containing all child shapes and set it to the
current shape new shape get added to the shape array
@param shapes
@param modelJSON
@param current
@throws org.json.JSONException | [
"private static void parseChildShapes(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"childShapes\")) {\n ArrayList<Shape> childShapes = new ArrayList<Shape>();\n\n JSONArray childShapeObject = modelJSON.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapeObject.length(); i++) {\n childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString(\"resourceId\"),\n shapes));\n }\n if (childShapes.size() > 0) {\n for (Shape each : childShapes) {\n each.setParent(current);\n }\n current.setChildShapes(childShapes);\n }\n ;\n }\n }"
] | [
"private List<Entry> sortEntries(List<Entry> loadedEntries) {\n Collections.sort(loadedEntries, new Comparator<Entry>() {\n @Override\n public int compare(Entry entry1, Entry entry2) {\n int result = (int) (entry1.cuePosition - entry2.cuePosition);\n if (result == 0) {\n int h1 = (entry1.hotCueNumber != 0) ? 1 : 0;\n int h2 = (entry2.hotCueNumber != 0) ? 1 : 0;\n result = h1 - h2;\n }\n return result;\n }\n });\n return Collections.unmodifiableList(loadedEntries);\n }",
"public Object getRealValue()\r\n {\r\n if(valueRealSubject != null)\r\n {\r\n return valueRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareValueRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareValueRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise value with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return valueRealSubject;\r\n }",
"static InternationalFixedDate create(int prolepticYear, int month, int dayOfMonth) {\n YEAR_RANGE.checkValidValue(prolepticYear, ChronoField.YEAR_OF_ERA);\n MONTH_OF_YEAR_RANGE.checkValidValue(month, ChronoField.MONTH_OF_YEAR);\n DAY_OF_MONTH_RANGE.checkValidValue(dayOfMonth, ChronoField.DAY_OF_MONTH);\n\n if (dayOfMonth == DAYS_IN_LONG_MONTH && month != 6 && month != MONTHS_IN_YEAR) {\n throw new DateTimeException(\"Invalid date: \" + prolepticYear + '/' + month + '/' + dayOfMonth);\n }\n if (month == 6 && dayOfMonth == DAYS_IN_LONG_MONTH && !INSTANCE.isLeapYear(prolepticYear)) {\n throw new DateTimeException(\"Invalid Leap Day as '\" + prolepticYear + \"' is not a leap year\");\n }\n return new InternationalFixedDate(prolepticYear, month, dayOfMonth);\n }",
"public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\n }",
"public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}",
"public static final int getShort(byte[] data, int offset)\n {\n int result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"boolean processUnstable() {\n boolean change = !unstable;\n if (change) { // Only once until the process is removed. A process is unstable until removed.\n unstable = true;\n HostControllerLogger.ROOT_LOGGER.managedServerUnstable(serverName);\n }\n return change;\n }",
"private static String getEncodedInstance(String encodedResponse) {\n if (isReturnValue(encodedResponse) || isThrownException(encodedResponse)) {\n return encodedResponse.substring(4);\n }\n\n return encodedResponse;\n }",
"public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }"
] |
Print out the template information that the client needs for performing a request.
@param json the writer to write the information to. | [
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"attributes\");\n json.array();\n for (Map.Entry<String, Attribute> entry: this.attributes.entrySet()) {\n Attribute attribute = entry.getValue();\n if (attribute.getClass().getAnnotation(InternalAttribute.class) == null) {\n json.object();\n attribute.printClientConfig(json, this);\n json.endObject();\n }\n }\n json.endArray();\n }"
] | [
"public ListExternalToolsOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }",
"public void setConnection(JdbcConnectionDescriptor jcd) throws PlatformException\r\n {\r\n _jcd = jcd;\r\n\r\n String targetDatabase = (String)_dbmsToTorqueDb.get(_jcd.getDbms().toLowerCase());\r\n\r\n if (targetDatabase == null)\r\n {\r\n throw new PlatformException(\"Database \"+_jcd.getDbms()+\" is not supported by torque\");\r\n }\r\n if (!targetDatabase.equals(_targetDatabase))\r\n {\r\n _targetDatabase = targetDatabase;\r\n _creationScript = null;\r\n _initScripts.clear();\r\n }\r\n }",
"private void setResponeHeaders(HttpServletResponse response) {\n\n response.setHeader(\"Cache-Control\", \"no-store, no-cache\");\n response.setHeader(\"Pragma\", \"no-cache\");\n response.setDateHeader(\"Expires\", System.currentTimeMillis());\n response.setContentType(\"text/plain; charset=utf-8\");\n response.setCharacterEncoding(\"utf-8\");\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }",
"public static Object findResult(Object self, Object defaultResult, Closure closure) {\n Object result = findResult(self, closure);\n if (result == null) return defaultResult;\n return result;\n }",
"public static final boolean isMouseInside(NativeEvent event, Element element) {\n return isInside(event.getClientX() + Window.getScrollLeft(), event.getClientY() + Window.getScrollTop(), getBounds(element));\n }",
"private final boolean matchChildBlock(int bufferIndex)\n {\n //\n // Match the pattern we see at the start of the child block\n //\n int index = 0;\n for (byte b : CHILD_BLOCK_PATTERN)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n return false;\n }\n ++index;\n }\n\n //\n // The first step will produce false positives. To handle this, we should find\n // the name of the block next, and check to ensure that the length\n // of the name makes sense.\n //\n int nameLength = FastTrackUtility.getInt(m_buffer, bufferIndex + index);\n\n// System.out.println(\"Name length: \" + nameLength);\n// \n// if (nameLength > 0 && nameLength < 100)\n// {\n// String name = new String(m_buffer, bufferIndex+index+4, nameLength, CharsetHelper.UTF16LE);\n// System.out.println(\"Name: \" + name);\n// }\n \n return nameLength > 0 && nameLength < 100;\n }",
"private void setCalendarToLastRelativeDay(Calendar calendar)\n {\n calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n int requiredDayOfWeek = getDayOfWeek().getValue();\n int dayOfWeekOffset = 0;\n\n if (currentDayOfWeek > requiredDayOfWeek)\n {\n dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek;\n }\n else\n {\n if (currentDayOfWeek < requiredDayOfWeek)\n {\n dayOfWeekOffset = -7 + (requiredDayOfWeek - currentDayOfWeek);\n }\n }\n\n if (dayOfWeekOffset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset);\n }\n }",
"public void logError(String message, Object sender) {\n getEventManager().sendEvent(this, IErrorEvents.class, \"onError\", new Object[] { message, sender });\n }"
] |
Create a buffered image with the correct image bands etc... for the tiles being loaded.
@param imageWidth width of the image to create
@param imageHeight height of the image to create. | [
"@Nonnull\n public BufferedImage createBufferedImage(final int imageWidth, final int imageHeight) {\n return new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);\n }"
] | [
"public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }",
"public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }",
"private List<Row> getRows(String sql) throws SQLException\n {\n allocateConnection();\n\n try\n {\n List<Row> result = new LinkedList<Row>();\n\n m_ps = m_connection.prepareStatement(sql);\n m_rs = m_ps.executeQuery();\n populateMetaData();\n while (m_rs.next())\n {\n result.add(new MpdResultSetRow(m_rs, m_meta));\n }\n\n return (result);\n }\n\n finally\n {\n releaseConnection();\n }\n }",
"public List<CRFCliqueTree> getCliqueTrees(String filename, DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n List<CRFCliqueTree> cts = new ArrayList<CRFCliqueTree>();\r\n ObjectBank<List<IN>> docs = makeObjectBankFromFile(filename, readerAndWriter);\r\n for (List<IN> doc : docs) {\r\n cts.add(getCliqueTree(doc));\r\n }\r\n\r\n return cts;\r\n }",
"synchronized void storeUninstallTimestamp() {\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"There is not enough space left on the device to store data, data discarded\");\n return ;\n }\n final String tableName = Table.UNINSTALL_TS.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n\n }",
"private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }",
"public static String formatConnectionEstablishmentMessage(final String connectionName, final String host, final String connectionReason) {\n\t\treturn CON_ESTABLISHMENT_FORMAT.format(new Object[] { connectionName, host, connectionReason });\n\t}",
"public static <T> AddQuery<T> start(T query, long correlationId) {\n return start(query, correlationId, \"default\", null);\n }",
"@Override\n public boolean parseAndValidateRequest() {\n if(!super.parseAndValidateRequest()) {\n return false;\n }\n isGetVersionRequest = hasGetVersionRequestHeader();\n if(isGetVersionRequest && this.parsedKeys.size() > 1) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Get version request cannot have multiple keys\");\n return false;\n }\n return true;\n }"
] |
This method maps the resource unique identifiers to their index number
within the FixedData block.
@param fieldMap field map
@param rscFixedMeta resource fixed meta data
@param rscFixedData resource fixed data
@return map of resource IDs to resource data | [
"private TreeMap<Integer, Integer> createResourceMap(FieldMap fieldMap, FixedMeta rscFixedMeta, FixedData rscFixedData)\n {\n TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer>();\n int itemCount = rscFixedMeta.getAdjustedItemCount();\n\n for (int loop = 0; loop < itemCount; loop++)\n {\n byte[] data = rscFixedData.getByteArrayValue(loop);\n if (data == null || data.length < fieldMap.getMaxFixedDataSize(0))\n {\n continue;\n }\n\n Integer uniqueID = Integer.valueOf(MPPUtility.getShort(data, 0));\n resourceMap.put(uniqueID, Integer.valueOf(loop));\n }\n\n return (resourceMap);\n }"
] | [
"public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n String url = null;\n Boolean confirm = false;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Synchronize metadata versions across all nodes\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n System.out.println(\" node = all nodes\");\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient);\n\n Versioned<Properties> versionedProps = mergeAllVersions(adminClient);\n\n printVersions(versionedProps);\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm,\n \"do you want to synchronize metadata versions to all node\"))\n return;\n\n adminClient.metadataMgmtOps.setMetadataVersion(versionedProps);\n }",
"public static void openFavoriteDialog(CmsFileExplorer explorer) {\n\n try {\n CmsExplorerFavoriteContext context = new CmsExplorerFavoriteContext(A_CmsUI.getCmsObject(), explorer);\n CmsFavoriteDialog dialog = new CmsFavoriteDialog(context, new CmsFavoriteDAO(A_CmsUI.getCmsObject()));\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setContent(dialog);\n window.setCaption(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_FAVORITES_DIALOG_TITLE_0));\n A_CmsUI.get().addWindow(window);\n window.center();\n } catch (CmsException e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }",
"void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }",
"public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }",
"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 Class getRealClass(Object objectOrProxy)\r\n {\r\n IndirectionHandler handler;\r\n\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n handler = getIndirectionHandler(objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n handler = VirtualProxy.getIndirectionHandler((VirtualProxy) objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n else\r\n {\r\n return objectOrProxy.getClass();\r\n }\r\n }",
"private static Clique valueOfHelper(int[] relativeIndices) {\r\n // if clique already exists, return that one\r\n Clique c = new Clique();\r\n c.relativeIndices = relativeIndices;\r\n return intern(c);\r\n }",
"public static Map<FieldType, String> getDefaultWbsFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(TaskField.UNIQUE_ID, \"wbs_id\");\n map.put(TaskField.GUID, \"guid\");\n map.put(TaskField.NAME, \"wbs_name\");\n map.put(TaskField.BASELINE_COST, \"orig_cost\");\n map.put(TaskField.REMAINING_COST, \"indep_remain_total_cost\");\n map.put(TaskField.REMAINING_WORK, \"indep_remain_work_qty\");\n map.put(TaskField.DEADLINE, \"anticip_end_date\");\n map.put(TaskField.DATE1, \"suspend_date\");\n map.put(TaskField.DATE2, \"resume_date\");\n map.put(TaskField.TEXT1, \"task_code\");\n map.put(TaskField.WBS, \"wbs_short_name\");\n\n return map;\n }",
"@SuppressWarnings(\"rawtypes\")\n private void synchronousInvokeCallback(Callable call) {\n\n Future future = streamingSlopResults.submit(call);\n\n try {\n future.get();\n\n } catch(InterruptedException e1) {\n\n logger.error(\"Callback failed\", e1);\n throw new VoldemortException(\"Callback failed\");\n\n } catch(ExecutionException e1) {\n\n logger.error(\"Callback failed during execution\", e1);\n throw new VoldemortException(\"Callback failed during execution\");\n }\n\n }"
] |
Takes a date, and retrieves the next business day
@param dateString the date
@param onlyBusinessDays only business days
@return a string containing the next business day | [
"public String getNextDay(String dateString, boolean onlyBusinessDays) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(dateString).plusDays(1);\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n\n if (onlyBusinessDays) {\n if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7\n || isHoliday(date.toString().substring(0, 10))) {\n return getNextDay(date.toString().substring(0, 10), true);\n } else {\n return parser.print(date);\n }\n } else {\n return parser.print(date);\n }\n }"
] | [
"@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final K key) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Objects.equal(input, key);\n\t\t\t}\n\t\t});\n\t}",
"public PortComponentMetaData getPortComponentByWsdlPort(String name)\n {\n ArrayList<String> pcNames = new ArrayList<String>();\n for (PortComponentMetaData pc : portComponents)\n {\n String wsdlPortName = pc.getWsdlPort().getLocalPart();\n if (wsdlPortName.equals(name))\n return pc;\n\n pcNames.add(wsdlPortName);\n }\n\n Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames);\n return null;\n }",
"@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > lingerIterations && pidToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n isRunning.set(false);\n }\n }",
"public String getVertexString() {\n if (tail() != null) {\n return \"\" + tail().index + \"-\" + head().index;\n } else {\n return \"?-\" + head().index;\n }\n }",
"public static Info inviteUserToEnterprise(BoxAPIConnection api, String userLogin, String enterpriseID) {\n\n URL url = INVITE_CREATION_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n JsonObject body = new JsonObject();\n\n JsonObject enterprise = new JsonObject();\n enterprise.add(\"id\", enterpriseID);\n body.add(\"enterprise\", enterprise);\n\n JsonObject actionableBy = new JsonObject();\n actionableBy.add(\"login\", userLogin);\n body.add(\"actionable_by\", actionableBy);\n\n request.setBody(body);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxInvite invite = new BoxInvite(api, responseJSON.get(\"id\").asString());\n return invite.new Info(responseJSON);\n }",
"public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }",
"private static Set<ProjectModel> getAllApplications(GraphContext graphContext)\n {\n Set<ProjectModel> apps = new HashSet<>();\n Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);\n for (ProjectModel appProject : appProjects)\n apps.add(appProject);\n return apps;\n }",
"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 static void openLogFile(String logPath) {\n\t\tif (logPath == null) {\n\t\t\tprintStream = System.out;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tprintStream = new PrintStream(new File(logPath));\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Log file \" + logPath + \" was not found\", e);\n\t\t\t}\n\t\t}\n\t}"
] |
This method extracts calendar data from a GanttProject file.
@param ganttProject Root node of the GanttProject file | [
"private void readCalendars(Project ganttProject)\n {\n m_mpxjCalendar = m_projectFile.addCalendar();\n m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n Calendars gpCalendar = ganttProject.getCalendars();\n setWorkingDays(m_mpxjCalendar, gpCalendar);\n setExceptions(m_mpxjCalendar, gpCalendar);\n m_eventManager.fireCalendarReadEvent(m_mpxjCalendar);\n }"
] | [
"public static double J(int n, double x) {\r\n int j, m;\r\n double ax, bj, bjm, bjp, sum, tox, ans;\r\n boolean jsum;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n if (n == 0) return J0(x);\r\n if (n == 1) return J(x);\r\n\r\n ax = Math.abs(x);\r\n if (ax == 0.0) return 0.0;\r\n else if (ax > (double) n) {\r\n tox = 2.0 / ax;\r\n bjm = J0(ax);\r\n bj = J(ax);\r\n for (j = 1; j < n; j++) {\r\n bjp = j * tox * bj - bjm;\r\n bjm = bj;\r\n bj = bjp;\r\n }\r\n ans = bj;\r\n } else {\r\n tox = 2.0 / ax;\r\n m = 2 * ((n + (int) Math.sqrt(ACC * n)) / 2);\r\n jsum = false;\r\n bjp = ans = sum = 0.0;\r\n bj = 1.0;\r\n for (j = m; j > 0; j--) {\r\n bjm = j * tox * bj - bjp;\r\n bjp = bj;\r\n bj = bjm;\r\n if (Math.abs(bj) > BIGNO) {\r\n bj *= BIGNI;\r\n bjp *= BIGNI;\r\n ans *= BIGNI;\r\n sum *= BIGNI;\r\n }\r\n if (jsum) sum += bj;\r\n jsum = !jsum;\r\n if (j == n) ans = bjp;\r\n }\r\n sum = 2.0 * sum - bj;\r\n ans /= sum;\r\n }\r\n\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }",
"public static void replaceBadXmlCharactersBySpace(char[] cbuf, int off, int len) {\n for (int i = off; i < off + len; i++) {\n if (isBadXmlCharacter(cbuf[i])) {\n cbuf[i] = '\\u0020';\n }\n }\n }",
"protected T createInstance() {\n try {\n Constructor<T> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n return ctor.newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (SecurityException e) {\n throw new RuntimeException(e);\n } catch (NoSuchMethodException e) {\n throw new RuntimeException(e);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }",
"public Build getBuildInfo(String appName, String buildId) {\n return connection.execute(new BuildInfo(appName, buildId), apiKey);\n }",
"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 }",
"public InsertIntoTable addRowsFromDelimited(File file, String delimiter, Object nullValue) {\n builder.addRowsFromDelimited(file, delimiter, nullValue);\n return this;\n }",
"private OperationResponse executeForResult(final OperationExecutionContext executionContext) throws IOException {\n try {\n return execute(executionContext).get();\n } catch(Exception e) {\n throw new IOException(e);\n }\n }",
"private Map<String, Criteria> getCriterias(Map<String, String[]> params) {\n Map<String, Criteria> result = new HashMap<String, Criteria>();\n for (Map.Entry<String, String[]> param : params.entrySet()) {\n for (Criteria criteria : FILTER_CRITERIAS) {\n if (criteria.getName().equals(param.getKey())) {\n try {\n Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]);\n for (Criteria parsedCriteria : parsedCriterias) {\n result.put(parsedCriteria.getName(), parsedCriteria);\n }\n } catch (Exception e) {\n // Exception happened during paring\n LOG.log(Level.SEVERE, \"Error parsing parameter \" + param.getKey(), e);\n }\n break;\n }\n }\n }\n return result;\n }",
"static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }"
] |
set custom request for profile's default client
@param profileName profileName to modify
@param pathName friendly name of path
@param customData custom request data
@return true if success, false otherwise | [
"public static boolean setCustomRequestForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }"
] | [
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}",
"public List<MaterialSection> getSectionList() {\n List<MaterialSection> list = new LinkedList<>();\n\n for(MaterialSection section : sectionList)\n list.add(section);\n\n for(MaterialSection section : bottomSectionList)\n list.add(section);\n\n return list;\n }",
"protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }",
"private void processPredecessor(Task task, MapRow row)\n {\n Task predecessor = m_taskMap.get(row.getUUID(\"PREDECESSOR_UUID\"));\n if (predecessor != null)\n {\n task.addPredecessor(predecessor, row.getRelationType(\"RELATION_TYPE\"), row.getDuration(\"LAG\"));\n }\n }",
"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 }",
"public static sslcertkey_crldistribution_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n public Symmetry454Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public JsonObject getJsonObject() {\n\n JsonObject obj = new JsonObject();\n obj.add(\"field\", this.field);\n\n obj.add(\"value\", this.value);\n\n return obj;\n }",
"void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}"
] |
Parses an item id
@param id
the identifier of the entity, such as "Q42"
@param siteIri
the siteIRI that this value refers to
@throws IllegalArgumentException
if the id is invalid | [
"static EntityIdValue fromId(String id, String siteIri) {\n\t\tswitch (guessEntityTypeFromId(id)) {\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM:\n\t\t\t\treturn new ItemIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY:\n\t\t\t\treturn new PropertyIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_LEXEME:\n\t\t\t\treturn new LexemeIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_FORM:\n\t\t\t\treturn new FormIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_SENSE:\n\t\t\t\treturn new SenseIdValueImpl(id, siteIri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}"
] | [
"public static <IN extends CoreMap> CRFClassifier<IN> getJarClassifier(String resourceName, Properties props) {\r\n CRFClassifier<IN> crf = new CRFClassifier<IN>();\r\n crf.loadJarClassifier(resourceName, props);\r\n return crf;\r\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear();\n }",
"public static base_response unset(nitro_service client, nsdiameter resource, String[] args) throws Exception{\n\t\tnsdiameter unsetresource = new nsdiameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public final void fatal(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.FATAL, pObject, null);\r\n\t}",
"protected void unregisterDriver(){\r\n\t\tString jdbcURL = this.config.getJdbcUrl();\r\n\t\tif ((jdbcURL != null) && this.config.isDeregisterDriverOnClose()){\r\n\t\t\tlogger.info(\"Unregistering JDBC driver for : \"+jdbcURL);\r\n\t\t\ttry {\r\n\t\t\t\tDriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL));\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\tlogger.info(\"Unregistering driver failed.\", e);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public IdRange[] parseIdRange(ImapRequestLineReader request)\n throws ProtocolException {\n CharacterValidator validator = new MessageSetCharValidator();\n String nextWord = consumeWord(request, validator);\n\n int commaPos = nextWord.indexOf(',');\n if (commaPos == -1) {\n return new IdRange[]{IdRange.parseRange(nextWord)};\n }\n\n List<IdRange> rangeList = new ArrayList<>();\n int pos = 0;\n while (commaPos != -1) {\n String range = nextWord.substring(pos, commaPos);\n IdRange set = IdRange.parseRange(range);\n rangeList.add(set);\n\n pos = commaPos + 1;\n commaPos = nextWord.indexOf(',', pos);\n }\n String range = nextWord.substring(pos);\n rangeList.add(IdRange.parseRange(range));\n return rangeList.toArray(new IdRange[rangeList.size()]);\n }",
"public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}",
"@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null == baseTmsUrl) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"baseTmsUrl\");\n\t\t}\n\n\t\t// Make sure we have a base URL we can work with:\n\t\tif ((baseTmsUrl.startsWith(\"http://\") || baseTmsUrl.startsWith(\"https://\")) && !baseTmsUrl.endsWith(\"/\")) {\n\t\t\tbaseTmsUrl += \"/\";\n\t\t}\n\n\t\t// Make sure there is a correct RasterLayerInfo object:\n\t\tif (layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO) {\n\t\t\ttry {\n\t\t\t\ttileMap = configurationService.getCapabilities(this);\n\t\t\t\tversion = tileMap.getVersion();\n\t\t\t\textension = tileMap.getTileFormat().getExtension();\n\t\t\t\tlayerInfo = configurationService.asLayerInfo(tileMap);\n\t\t\t\tusable = true;\n\t\t\t} catch (TmsLayerException e) {\n\t\t\t\t// a layer needs an info object to keep the DtoConfigurationPostProcessor happy !\n\t\t\t\tlayerInfo = UNUSABLE_LAYER_INFO;\n\t\t\t\tusable = false;\n\t\t\t\tlog.warn(\"The layer could not be correctly initialized: \" + getId(), e);\n\t\t\t}\n\t\t} else if (extension == null) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"extension\");\n\t\t}\n\n\t\tif (layerInfo != null) {\n\t\t\t// Finally prepare some often needed values:\n\t\t\tstate = new TileServiceState(geoService, layerInfo);\n\t\t\t// when proxying the real url will be resolved later on, just use a simple one for now\n\t\t\tboolean proxying = useCache || useProxy || null != authentication;\n\t\t\tif (tileMap != null && !proxying) {\n\t\t\t\turlBuilder = new TileMapUrlBuilder(tileMap);\n\t\t\t} else {\n\t\t\t\turlBuilder = new SimpleTmsUrlBuilder(extension);\n\t\t\t}\n\t\t}\n\t}",
"public static File newFile(File baseDir, String... segments) {\n File f = baseDir;\n for (String segment : segments) {\n f = new File(f, segment);\n }\n return f;\n }"
] |
Polls the next ParsedWord from the stack.
@return next ParsedWord | [
"public ParsedWord pollParsedWord() {\n if(hasNextWord()) {\n //set correct next char\n if(parsedLine.words().size() > (word+1))\n character = parsedLine.words().get(word+1).lineIndex();\n else\n character = -1;\n return parsedLine.words().get(word++);\n }\n else\n return new ParsedWord(null, -1);\n }"
] | [
"public void merge(final ResourceRoot additionalResourceRoot) {\n if(!additionalResourceRoot.getRoot().equals(root)) {\n throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot());\n }\n usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource;\n if(additionalResourceRoot.getExportFilters().isEmpty()) {\n //new root has no filters, so we don't want our existing filters to break anything\n //see WFLY-1527\n this.exportFilters.clear();\n } else {\n this.exportFilters.addAll(additionalResourceRoot.getExportFilters());\n }\n }",
"public NamedStyleInfo getNamedStyleInfo(String name) {\n\t\tfor (NamedStyleInfo info : namedStyleInfos) {\n\t\t\tif (info.getName().equals(name)) {\n\t\t\t\treturn info;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"@Override\n public void finish() {\n if (started.get() && !finished.getAndSet(true)) {\n waitUntilFinished();\n super.finish();\n // recreate thread (don't start) for processor reuse\n createProcessorThread();\n clearQueues();\n started.set(false);\n }\n }",
"static File getTargetFile(final File root, final MiscContentItem item) {\n return PatchContentLoader.getMiscPath(root, item);\n }",
"public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure closure) {\n return find(self.toString(), Pattern.compile(regex.toString()), closure);\n }",
"private void handleMultiInstanceReportResponse(SerialMessage serialMessage,\r\n\t\t\tint offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Report\");\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint instances = serialMessage.getMessagePayloadByte(offset + 1);\r\n\r\n\t\tif (instances == 0) {\r\n\t\t\tsetInstances(1);\r\n\t\t} else \r\n\t\t{\r\n\t\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\t\r\n\t\t\tif (commandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\t\r\n\t\t\tif (zwaveCommandClass == null) {\r\n\t\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tzwaveCommandClass.setInstances(instances);\r\n\t\t\tlogger.debug(String.format(\"Node %d Instances = %d, number of instances set.\", this.getNode().getNodeId(), instances));\r\n\t\t}\r\n\t\t\r\n\t\tfor (ZWaveCommandClass zwaveCommandClass : this.getNode().getCommandClasses())\r\n\t\t\tif (zwaveCommandClass.getInstances() == 0) // still waiting for an instance report of another command class. \r\n\t\t\t\treturn;\r\n\t\t\r\n\t\t// advance node stage.\r\n\t\tthis.getNode().advanceNodeStage();\r\n\t}",
"private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }",
"public void setBaselineStartText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_STARTS, baselineNumber), value);\n }",
"private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) {\n if (numberClass == Integer.class) {\n buffer.addInt((Integer) value);\n } else if (numberClass == Long.class) {\n buffer.addLong((Long) value);\n } else if (numberClass == BigInteger.class) {\n buffer.addBigInteger((BigInteger) value);\n } else if (numberClass == BigDecimal.class) {\n buffer.addBigDecimal((BigDecimal) value);\n } else if (numberClass == Double.class) {\n Double doubleValue = (Double) value;\n if (doubleValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (doubleValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addDouble(doubleValue);\n } else if (numberClass == Float.class) {\n Float floatValue = (Float) value;\n if (floatValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (floatValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addFloat(floatValue);\n } else if (numberClass == Byte.class) {\n buffer.addByte((Byte) value);\n } else if (numberClass == Short.class) {\n buffer.addShort((Short) value);\n } else { // Handle other Number implementations\n buffer.addString(value.toString());\n }\n }"
] |
Build filter for the request.
@param layerFilter layer filter
@param featureIds features to include in report (null for all)
@return filter
@throws GeomajasException filter could not be parsed/created | [
"private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {\n\t\tFilter filter = null;\n\t\tif (null != layerFilter) {\n\t\t\tfilter = filterService.parseFilter(layerFilter);\n\t\t}\n\t\tif (null != featureIds) {\n\t\t\tFilter fidFilter = filterService.createFidFilter(featureIds);\n\t\t\tif (null == filter) {\n\t\t\t\tfilter = fidFilter;\n\t\t\t} else {\n\t\t\t\tfilter = filterService.createAndFilter(filter, fidFilter);\n\t\t\t}\n\t\t}\n\t\treturn filter;\n\t}"
] | [
"public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {\n Set<String> orderedChildTypes = resource.getOrderedChildTypes();\n if (orderedChildTypes.size() > 0) {\n orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());\n }\n }",
"public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }",
"public Map<String, List<Locale>> getAvailableLocales() {\n\n if (m_availableLocales == null) {\n // create lazy map only on demand\n m_availableLocales = CmsCollectionsGenericWrapper.createLazyMap(new CmsAvailableLocaleLoaderTransformer());\n }\n return m_availableLocales;\n }",
"private SortedSet<Date> filterExceptions(SortedSet<Date> dates) {\n\n SortedSet<Date> result = new TreeSet<Date>();\n for (Date d : dates) {\n if (!m_exceptions.contains(d)) {\n result.add(d);\n }\n }\n return result;\n }",
"public static void closeScope(Object name) {\n //we remove the scope first, so that other threads don't see it, and see the next snapshot of the tree\n ScopeNode scope = (ScopeNode) MAP_KEY_TO_SCOPE.remove(name);\n if (scope != null) {\n ScopeNode parentScope = scope.getParentScope();\n if (parentScope != null) {\n parentScope.removeChild(scope);\n } else {\n ConfigurationHolder.configuration.onScopeForestReset();\n }\n removeScopeAndChildrenFromMap(scope);\n }\n }",
"public List<SquigglyNode> parse(String filter) {\n filter = StringUtils.trim(filter);\n\n if (StringUtils.isEmpty(filter)) {\n return Collections.emptyList();\n }\n\n // get it from the cache if we can\n List<SquigglyNode> cachedNodes = CACHE.getIfPresent(filter);\n\n if (cachedNodes != null) {\n return cachedNodes;\n }\n\n\n SquigglyExpressionLexer lexer = ThrowingErrorListener.overwrite(new SquigglyExpressionLexer(new ANTLRInputStream(filter)));\n SquigglyExpressionParser parser = ThrowingErrorListener.overwrite(new SquigglyExpressionParser(new CommonTokenStream(lexer)));\n\n Visitor visitor = new Visitor();\n List<SquigglyNode> nodes = Collections.unmodifiableList(visitor.visit(parser.parse()));\n\n CACHE.put(filter, nodes);\n return nodes;\n }",
"private void sendAnnouncement(InetAddress broadcastAddress) {\n try {\n DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,\n broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);\n socket.get().send(announcement);\n Thread.sleep(getAnnounceInterval());\n } catch (Throwable t) {\n logger.warn(\"Unable to send announcement packet, shutting down\", t);\n stop();\n }\n }",
"private void handleMultiInstanceEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Encapsulation\");\r\n\t\tint instance = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);\r\n\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Instance = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), instance));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);\r\n\t}",
"private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }"
] |
Read hints from a file. | [
"public static Map<String,List<Long>> readHints(File hints) throws IOException {\n Map<String,List<Long>> result = new HashMap<>();\n InputStream is = new FileInputStream(hints);\n mergeHints(is, result);\n return result;\n }"
] | [
"public Collection<Exif> getExif(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_EXIF);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n List<Exif> exifs = new ArrayList<Exif>();\r\n Element photoElement = response.getPayload();\r\n NodeList exifElements = photoElement.getElementsByTagName(\"exif\");\r\n for (int i = 0; i < exifElements.getLength(); i++) {\r\n Element exifElement = (Element) exifElements.item(i);\r\n Exif exif = new Exif();\r\n exif.setTagspace(exifElement.getAttribute(\"tagspace\"));\r\n exif.setTagspaceId(exifElement.getAttribute(\"tagspaceid\"));\r\n exif.setTag(exifElement.getAttribute(\"tag\"));\r\n exif.setLabel(exifElement.getAttribute(\"label\"));\r\n exif.setRaw(XMLUtilities.getChildValue(exifElement, \"raw\"));\r\n exif.setClean(XMLUtilities.getChildValue(exifElement, \"clean\"));\r\n exifs.add(exif);\r\n }\r\n return exifs;\r\n }",
"@Override\n public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms)\n throws VoldemortException {\n // acquire write lock\n writeLock.lock();\n try {\n String key = ByteUtils.getString(keyBytes.get(), \"UTF-8\");\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n\n Versioned<Object> valueObject = convertStringToObject(key, value);\n\n this.put(key, valueObject);\n } finally {\n writeLock.unlock();\n }\n }",
"public boolean shouldIncrementVersionBasedOnResources(CmsObject cms) throws CmsException {\n\n if (m_checkpointTime == 0) {\n return true;\n }\n\n // adjust the site root, if necessary\n CmsObject cmsClone = adjustSiteRootIfNecessary(cms, this);\n\n // calculate the module resources\n List<CmsResource> moduleResources = calculateModuleResources(cmsClone, this);\n\n for (CmsResource resource : moduleResources) {\n try {\n List<CmsResource> resourcesToCheck = Lists.newArrayList();\n resourcesToCheck.add(resource);\n if (resource.isFolder()) {\n resourcesToCheck.addAll(cms.readResources(resource, CmsResourceFilter.IGNORE_EXPIRATION, true));\n }\n for (CmsResource resourceToCheck : resourcesToCheck) {\n if (resourceToCheck.getDateLastModified() > m_checkpointTime) {\n return true;\n }\n }\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n continue;\n }\n }\n return false;\n }",
"public static double blackScholesDigitalOptionVega(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate vega\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;\n\n\t\t\treturn vega;\n\t\t}\n\t}",
"public void sendLoadTrackCommand(DeviceUpdate target, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n ensureRunning();\n byte[] payload = new byte[LOAD_TRACK_PAYLOAD.length];\n System.arraycopy(LOAD_TRACK_PAYLOAD, 0, payload, 0, LOAD_TRACK_PAYLOAD.length);\n payload[0x02] = getDeviceNumber();\n payload[0x05] = getDeviceNumber();\n payload[0x09] = (byte)sourcePlayer;\n payload[0x0a] = sourceSlot.protocolValue;\n payload[0x0b] = sourceType.protocolValue;\n Util.numberToBytes(rekordboxId, payload, 0x0d, 4);\n assembleAndSendPacket(Util.PacketType.LOAD_TRACK_COMMAND, payload, target.getAddress(), UPDATE_PORT);\n }",
"@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (flatPosition == RecyclerView.NO_POSITION) {\n return flatPosition;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }",
"private boolean contentEqualsUnchecked(byte[] bytes, int offset, int len) {\n if (length != len) {\n return false;\n }\n\n return compareToUnchecked(bytes, offset, len) == 0;\n }",
"void applyFreshParticleOnScreen(\n @NonNull final Scene scene,\n final int position\n ) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n final double direction = Math.toRadians(random.nextInt(360));\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float x = random.nextInt(w);\n final float y = random.nextInt(h);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }",
"@Override\n public final boolean getBool(final String key) {\n Boolean result = optBool(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }"
] |
Provides a reverse view on the given list which is especially useful to traverse a list backwards in a for-each
loop. The list itself is not modified by calling this method.
@param list
the list whose elements should be traversed in reverse. May not be <code>null</code>.
@return a list with the same elements as the given list, in reverse | [
"@Pure\n\tpublic static <T> List<T> reverseView(List<T> list) {\n\t\treturn Lists.reverse(list);\n\t}"
] | [
"protected void postProcessing()\n {\n //\n // Update the internal structure. We'll take this opportunity to\n // generate outline numbers for the tasks as they don't appear to\n // be present in the MPP file.\n //\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoWBS(m_autoWBS);\n config.setAutoOutlineNumber(true);\n m_project.updateStructure();\n config.setAutoOutlineNumber(false);\n\n //\n // Perform post-processing to set the summary flag\n //\n for (Task task : m_project.getTasks())\n {\n task.setSummary(task.hasChildTasks());\n }\n\n //\n // Ensure that the unique ID counters are correct\n //\n config.updateUniqueCounters();\n }",
"public IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }",
"protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\n }",
"public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }",
"public void addChildTask(Task child, int childOutlineLevel)\n {\n int outlineLevel = NumberHelper.getInt(getOutlineLevel());\n\n if ((outlineLevel + 1) == childOutlineLevel)\n {\n m_children.add(child);\n setSummary(true);\n }\n else\n {\n if (m_children.isEmpty() == false)\n {\n (m_children.get(m_children.size() - 1)).addChildTask(child, childOutlineLevel);\n }\n }\n }",
"private License getLicense(final String licenseId) {\n License result = null;\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);\n\n if (matchingLicenses.isEmpty()) {\n result = DataModelFactory.createLicense(\"#\" + licenseId + \"# (to be identified)\", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);\n result.setUnknown(true);\n } else {\n if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"%s matches multiple licenses %s. \" +\n \"Please run the report showing multiple matching on licenses\",\n licenseId, matchingLicenses.toString()));\n }\n result = mapper.getLicense(matchingLicenses.iterator().next());\n\n }\n\n return result;\n }",
"Item newStringishItem(final int type, final String value) {\n key2.set(type, value, null, null);\n Item result = get(key2);\n if (result == null) {\n pool.put12(type, newUTF8(value));\n result = new Item(index++, key2);\n put(result);\n }\n return result;\n }",
"private void recordTime(Tracked op,\n long timeNS,\n long numEmptyResponses,\n long valueSize,\n long keySize,\n long getAllAggregateRequests) {\n counters.get(op).addRequest(timeNS,\n numEmptyResponses,\n valueSize,\n keySize,\n getAllAggregateRequests);\n\n if (logger.isTraceEnabled() && !storeName.contains(\"aggregate\") && !storeName.contains(\"voldsys$\"))\n logger.trace(\"Store '\" + storeName + \"' logged a \" + op.toString() + \" request taking \" +\n ((double) timeNS / voldemort.utils.Time.NS_PER_MS) + \" ms\");\n }",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n ValueContainer[] result = new ValueContainer[pkFields.length];\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n\r\n try\r\n {\r\n for(int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fd = pkFields[i];\r\n Object cv = pkValues[i];\r\n if(convertToSql)\r\n {\r\n // BRJ : apply type and value mapping\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n throw new PersistenceBrokerException(\"Can't generate primary key values for given Identity \" + oid, e);\r\n }\r\n return result;\r\n }"
] |
Use this API to fetch filtered set of lbvserver resources.
set the filter parameter values in filtervalue object. | [
"public static lbvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tlbvserver[] response = (lbvserver[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}"
] | [
"protected void reportStorageOpTime(long startNs) {\n if(streamStats != null) {\n streamStats.reportStreamingScan(operation);\n streamStats.reportStorageTime(operation,\n Utils.elapsedTimeNs(startNs, System.nanoTime()));\n }\n }",
"@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public ByteBuffer getRawData() {\n if (rawData != null) {\n rawData.rewind();\n return rawData.slice();\n }\n return null;\n }",
"public static base_response add(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite addresource = new gslbsite();\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.sitetype = resource.sitetype;\n\t\taddresource.siteipaddress = resource.siteipaddress;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.metricexchange = resource.metricexchange;\n\t\taddresource.nwmetricexchange = resource.nwmetricexchange;\n\t\taddresource.sessionexchange = resource.sessionexchange;\n\t\taddresource.triggermonitor = resource.triggermonitor;\n\t\taddresource.parentsite = resource.parentsite;\n\t\treturn addresource.add_resource(client);\n\t}",
"public AT_Row setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\n }",
"public static Attachment fromBinaryBytes( byte[] bytes, MediaType mediaType ) {\n if( !mediaType.isBinary() ) {\n throw new IllegalArgumentException( \"MediaType must be binary\" );\n }\n return new Attachment(BaseEncoding.base64().encode( bytes ), mediaType, null );\n }",
"public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\n }\n }",
"public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }"
] |
Plots the MSD curve with the trajectory t and adds the fitted model for free diffusion.
@param t
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param timelag Elapsed time between two frames.
@param diffusionCoefficient Diffusion coefficient
@param intercept | [
"public static Chart getMSDLineWithFreeModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double intercept) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = intercept + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + a\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}"
] | [
"private void checkId(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID);\r\n\r\n if ((id != null) && (id.length() > 0))\r\n {\r\n try\r\n {\r\n Integer.parseInt(id);\r\n }\r\n catch (NumberFormatException ex)\r\n {\r\n throw new ConstraintException(\"The id attribute of field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is not a valid number\");\r\n }\r\n }\r\n }",
"public String join(List<String> list) {\n\n if (list == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String s : list) {\n\n if (s == null) {\n if (convertEmptyToNull) {\n s = \"\";\n } else {\n throw new IllegalArgumentException(\"StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true).\");\n }\n }\n\n if (!first) {\n sb.append(separator);\n }\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == escapeChar || c == separator) {\n sb.append(escapeChar);\n }\n sb.append(c);\n }\n\n first = false;\n }\n return sb.toString();\n }",
"public final Object getValue(final String id, final String property) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n criteria.select(root.get(property));\n criteria.where(builder.equal(root.get(\"referenceId\"), id));\n return getSession().createQuery(criteria).uniqueResult();\n }",
"public static dnspolicy_dnsglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnsglobal_binding obj = new dnspolicy_dnsglobal_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnsglobal_binding response[] = (dnspolicy_dnsglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static BoxRetentionPolicyAssignment.Info createAssignment(BoxAPIConnection api, String policyID,\r\n JsonObject assignTo, JsonArray filter) {\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_id\", policyID)\r\n .add(\"assign_to\", assignTo);\r\n\r\n if (filter != null) {\r\n requestJSON.add(\"filter_fields\", filter);\r\n }\r\n\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicyAssignment createdAssignment\r\n = new BoxRetentionPolicyAssignment(api, responseJSON.get(\"id\").asString());\r\n return createdAssignment.new Info(responseJSON);\r\n }",
"private void processTasks() throws SQLException\n {\n //\n // Yes... we could probably read this in one query in the right order\n // using a CTE... but life's too short.\n //\n List<Row> rows = getRows(\"select * from zscheduleitem where zproject=? and zparentactivity_ is null and z_ent=? order by zorderinparentactivity\", m_projectID, m_entityMap.get(\"Activity\"));\n for (Row row : rows)\n {\n Task task = m_project.addTask();\n populateTask(row, task);\n processChildTasks(task);\n }\n }",
"public static vrid6[] get(nitro_service service) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tvrid6[] response = (vrid6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }",
"private String getSymbolName(char c)\n {\n String result = null;\n\n switch (c)\n {\n case ',':\n {\n result = \"Comma\";\n break;\n }\n\n case '.':\n {\n result = \"Period\";\n break;\n }\n }\n\n return result;\n }"
] |
Converts a string representation of an integer into an Integer object.
Silently ignores any parse exceptions and returns null.
@param value String representation of an integer
@return Integer instance | [
"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 setWeeklyDaysFromBitmap(Integer days, int[] masks)\n {\n if (days != null)\n {\n int value = days.intValue();\n for (Day day : Day.values())\n {\n setWeeklyDay(day, ((value & masks[day.getValue()]) != 0));\n }\n }\n }",
"private Project.Tasks.Task.PredecessorLink writePredecessor(Integer taskID, RelationType type, Duration lag)\n {\n Project.Tasks.Task.PredecessorLink link = m_factory.createProjectTasksTaskPredecessorLink();\n\n link.setPredecessorUID(NumberHelper.getBigInteger(taskID));\n link.setType(BigInteger.valueOf(type.getValue()));\n link.setCrossProject(Boolean.FALSE); // SF-300: required to keep P6 happy when importing MSPDI files\n\n if (lag != null && lag.getDuration() != 0)\n {\n double linkLag = lag.getDuration();\n if (lag.getUnits() != TimeUnit.PERCENT && lag.getUnits() != TimeUnit.ELAPSED_PERCENT)\n {\n linkLag = 10.0 * Duration.convertUnits(linkLag, lag.getUnits(), TimeUnit.MINUTES, m_projectFile.getProjectProperties()).getDuration();\n }\n link.setLinkLag(BigInteger.valueOf((long) linkLag));\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(lag.getUnits(), false));\n }\n else\n {\n // SF-329: default required to keep Powerproject happy when importing MSPDI files\n link.setLinkLag(BIGINTEGER_ZERO);\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(m_projectFile.getProjectProperties().getDefaultDurationUnits(), false));\n }\n\n return (link);\n }",
"public CollectionRequest<Task> projects(String task) {\n \n String path = String.format(\"/tasks/%s/projects\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private static long scanForEndSig(final File file, final FileChannel channel, final ScanContext context) throws IOException {\n\n\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n int bufferPos = actualRead - 1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && context.matches(patternPos, bb.get(bufferPos - patternPos));\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n final State state = context.state;\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord, context.getSig())) {\n if (state == State.FOUND) {\n return startEndRecord;\n } else {\n return -1;\n }\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return -1;\n }",
"private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }",
"public static void copyProperties(Object dest, Object orig){\n\t\ttry {\n\t\t\tif (orig != null && dest != null){\n\t\t\t\tBeanUtils.copyProperties(dest, orig);\n\n\t\t\t\tPropertyUtils putils = new PropertyUtils();\n\t PropertyDescriptor origDescriptors[] = putils.getPropertyDescriptors(orig);\n\n\t\t\t\tfor (PropertyDescriptor origDescriptor : origDescriptors) {\n\t\t\t\t\tString name = origDescriptor.getName();\n\t\t\t\t\tif (\"class\".equals(name)) {\n\t\t\t\t\t\tcontinue; // No point in trying to set an object's class\n\t\t\t\t\t}\n\n\t\t\t\t\tClass propertyType = origDescriptor.getPropertyType();\n\t\t\t\t\tif (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType)))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (!putils.isReadable(orig, name)) { //because of bad convention\n\t\t\t\t\t\tMethod m = orig.getClass().getMethod(\"is\" + name.substring(0, 1).toUpperCase() + name.substring(1), (Class<?>[]) null);\n\t\t\t\t\t\tObject value = m.invoke(orig, (Object[]) null);\n\n\t\t\t\t\t\tif (putils.isWriteable(dest, name)) {\n\t\t\t\t\t\t\tBeanUtilsBean.getInstance().copyProperty(dest, name, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new DJException(\"Could not copy properties for shared object: \" + orig +\", message: \" + e.getMessage(),e);\n\t\t}\n\t}",
"public static void sendMimeMessage(MimeMessage mimeMessage) {\r\n try {\r\n Transport.send(mimeMessage);\r\n } catch (MessagingException e) {\r\n throw new IllegalStateException(\"Can not send message \" + mimeMessage, e);\r\n }\r\n }",
"public void updateConfig(String appName, Map<String, String> config) {\n connection.execute(new ConfigUpdate(appName, config), apiKey);\n }",
"public static nslimitidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tobj.set_name(name);\n\t\tnslimitidentifier_stats response = (nslimitidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Load the avatar base model
@param avatarResource resource with avatar model | [
"public void loadModel(GVRAndroidResource avatarResource)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n\n mAvatarRoot.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }"
] | [
"public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException\r\n {\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n int i = 0;\r\n try\r\n {\r\n for (; i < pkValues.length; i++)\r\n {\r\n setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindDelete failed for: \" + oid.toString() + \", while set value '\" +\r\n pkValues[i] + \"' for column \" + pkFields[i].getColumnName());\r\n throw e;\r\n }\r\n }",
"public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\n }",
"public CollectionRequest<User> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/users\", workspace);\n return new CollectionRequest<User>(this, User.class, path, \"GET\");\n }",
"private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }",
"private SortedSet<Date> filterExceptions(SortedSet<Date> dates) {\n\n SortedSet<Date> result = new TreeSet<Date>();\n for (Date d : dates) {\n if (!m_exceptions.contains(d)) {\n result.add(d);\n }\n }\n return result;\n }",
"protected static <E extends LogRecordHandler> boolean removeHandler(Class<E> toRemove) {\r\n boolean rtn = false;\r\n Iterator<LogRecordHandler> iter = handlers.iterator();\r\n while(iter.hasNext()){\r\n if(iter.next().getClass().equals(toRemove)){\r\n rtn = true;\r\n iter.remove();\r\n }\r\n }\r\n return rtn;\r\n }",
"public boolean hasDeploymentSubsystemModel(final String subsystemName) {\n final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);\n final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);\n return root.hasChild(subsystem);\n }",
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"public void promote() {\n URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, \"current\");\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"type\", \"file_version\");\n jsonObject.add(\"id\", this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(jsonObject.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n this.parseJSON(JsonObject.readFrom(response.getJSON()));\n }"
] |
Returns the bounding box of the vertices.
@param corners destination array to get corners of bounding box.
The first three entries are the minimum X,Y,Z values
and the next three are the maximum X,Y,Z.
@return true if bounds are not empty, false if empty (no vertices) | [
"public boolean getBoxBound(float[] corners)\n {\n int rc;\n if ((corners == null) || (corners.length != 6) ||\n ((rc = NativeVertexBuffer.getBoundingVolume(getNative(), corners)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy box bound into array provided\");\n }\n return rc != 0;\n }"
] | [
"public Flags flagList(ImapRequestLineReader request) throws ProtocolException {\n Flags flags = new Flags();\n request.nextWordChar();\n consumeChar(request, '(');\n CharacterValidator validator = new NoopCharValidator();\n String nextWord = consumeWord(request, validator);\n while (!nextWord.endsWith(\")\")) {\n setFlag(nextWord, flags);\n nextWord = consumeWord(request, validator);\n }\n // Got the closing \")\", may be attached to a word.\n if (nextWord.length() > 1) {\n setFlag(nextWord.substring(0, nextWord.length() - 1), flags);\n }\n\n return flags;\n }",
"public static String getStringProperty(String name, Map<String, String> map, String defaultValue) {\n if (map.containsKey(name) && Strings.isNotNullOrEmpty(map.get(name))) {\n defaultValue = map.get(name);\n }\n return getPropertyOrEnvironmentVariable(name, defaultValue);\n }",
"public EventBus emit(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"private final boolean matchPattern(byte[][] patterns, int bufferIndex)\n {\n boolean match = false;\n for (byte[] pattern : patterns)\n {\n int index = 0;\n match = true;\n for (byte b : pattern)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n match = false;\n break;\n }\n ++index;\n }\n if (match)\n {\n break;\n }\n }\n return match;\n }",
"private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }",
"@AsParameterConverter\n\tpublic Trader retrieveTrader(String name) {\n\t\tfor (Trader trader : traders) {\n\t\t\tif (trader.getName().equals(name)) {\n\t\t\t\treturn trader;\n\t\t\t}\n\t\t}\n\t\treturn mockTradePersister().retrieveTrader(name);\n\t}",
"static Project convert(\n String name, com.linecorp.centraldogma.server.storage.project.Project project) {\n return new Project(name);\n }",
"public static Iterable<BoxGroup.Info> getAllGroupsByName(final BoxAPIConnection api, String name) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (name == null || name.trim().isEmpty()) {\n throw new BoxAPIException(\"Searching groups by name requires a non NULL or non empty name\");\n } else {\n builder.appendParam(\"name\", name);\n }\n\n return new Iterable<BoxGroup.Info>() {\n public Iterator<BoxGroup.Info> iterator() {\n URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxGroupIterator(api, url);\n }\n };\n }",
"public static int optionLength(String option) {\n\tint result = Standard.optionLength(option);\n\tif (result != 0)\n\t return result;\n\telse\n\t return UmlGraph.optionLength(option);\n }"
] |
Obtain a connection asynchronously by queueing a request to obtain a connection in a separate thread.
Use as follows:<p>
Future<Connection> result = pool.getAsyncConnection();<p>
... do something else in your application here ...<p>
Connection connection = result.get(); // get the connection<p>
@return A Future task returning a connection. | [
"public ListenableFuture<Connection> getAsyncConnection(){\r\n\r\n\t\treturn this.asyncExecutor.submit(new Callable<Connection>() {\r\n\r\n\t\t\tpublic Connection call() throws Exception {\r\n\t\t\t\treturn getConnection();\r\n\t\t\t}});\r\n\t}"
] | [
"protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {\n\n m_foundResources = new ArrayList<I_CmsSearchResourceBean>();\n for (final CmsSearchResource searchResult : searchResults) {\n m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));\n }\n }",
"public void setLicense(String photoId, int licenseId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_LICENSE);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"license_id\", Integer.toString(licenseId));\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty sucess response if it completes without error.\r\n\r\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 }",
"public void setBeliefValue(String agent_name, final String belief_name,\n final Object new_value, Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n bia.getBeliefbase().getBelief(belief_name)\n .setFact(new_value);\n return null;\n }\n }).get(new ThreadSuspendable());\n }",
"WaveformDetail getWaveformDetail(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n final NumberField idField = new NumberField(rekordboxId);\n\n // First try to get the NXS2-style color waveform if we are supposed to.\n if (preferColor.get()) {\n try {\n Message response = client.simpleRequest(Message.KnownType.ANLZ_TAG_REQ, Message.KnownType.ANLZ_TAG,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField,\n new NumberField(Message.ANLZ_FILE_TAG_COLOR_WAVEFORM_DETAIL), new NumberField(Message.ALNZ_FILE_TYPE_EXT));\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n } catch (Exception e) {\n logger.info(\"No color waveform available for slot \" + slot + \", id \" + rekordboxId + \"; requesting blue version.\", e);\n }\n }\n\n Message response = client.simpleRequest(Message.KnownType.WAVE_DETAIL_REQ, Message.KnownType.WAVE_DETAIL,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField, NumberField.WORD_0);\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n }",
"private static void displayAvailableFilters(ProjectFile project)\n {\n System.out.println(\"Unknown filter name supplied.\");\n System.out.println(\"Available task filters:\");\n for (Filter filter : project.getFilters().getTaskFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n System.out.println(\"Available resource filters:\");\n for (Filter filter : project.getFilters().getResourceFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n }",
"public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n // 1. handle the special cases first.\r\n if (row == 0)\r\n {\r\n return true;\r\n }\r\n\r\n if (row == 1)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n m_activeIterator.absolute(1);\r\n return true;\r\n }\r\n if (row == -1)\r\n {\r\n m_activeIteratorIndex = m_rsIterators.size();\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n m_activeIterator.absolute(-1);\r\n return true;\r\n }\r\n\r\n // now do the real work.\r\n boolean movedToAbsolute = false;\r\n boolean retval = false;\r\n setNextIterator();\r\n\r\n // row is positive, so index from beginning.\r\n if (row > 0)\r\n {\r\n int sizeCount = 0;\r\n Iterator it = m_rsIterators.iterator();\r\n OJBIterator temp = null;\r\n while (it.hasNext() && !movedToAbsolute)\r\n {\r\n temp = (OJBIterator) it.next();\r\n if (temp.size() < row)\r\n {\r\n sizeCount += temp.size();\r\n }\r\n else\r\n {\r\n // move to the offset - sizecount\r\n m_currentCursorPosition = row - sizeCount;\r\n retval = temp.absolute(m_currentCursorPosition);\r\n movedToAbsolute = true;\r\n }\r\n }\r\n\r\n }\r\n\r\n // row is negative, so index from end\r\n else if (row < 0)\r\n {\r\n int sizeCount = 0;\r\n OJBIterator temp = null;\r\n for (int i = m_rsIterators.size(); ((i >= 0) && !movedToAbsolute); i--)\r\n {\r\n temp = (OJBIterator) m_rsIterators.get(i);\r\n if (temp.size() < row)\r\n {\r\n sizeCount += temp.size();\r\n }\r\n else\r\n {\r\n // move to the offset - sizecount\r\n m_currentCursorPosition = row + sizeCount;\r\n retval = temp.absolute(m_currentCursorPosition);\r\n movedToAbsolute = true;\r\n }\r\n }\r\n }\r\n\r\n return retval;\r\n }",
"private void transform(File file, Source transformSource)\n throws TransformerConfigurationException, IOException, SAXException, TransformerException,\n ParserConfigurationException {\n\n Transformer transformer = m_transformerFactory.newTransformer(transformSource);\n transformer.setOutputProperty(OutputKeys.ENCODING, \"us-ascii\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\");\n String configDirPath = m_configDir.getAbsolutePath();\n configDirPath = configDirPath.replaceFirst(\"[/\\\\\\\\]$\", \"\");\n transformer.setParameter(\"configDir\", configDirPath);\n XMLReader reader = m_parserFactory.newSAXParser().getXMLReader();\n reader.setEntityResolver(NO_ENTITY_RESOLVER);\n\n Source source;\n\n if (file.exists()) {\n source = new SAXSource(reader, new InputSource(file.getCanonicalPath()));\n } else {\n source = new SAXSource(reader, new InputSource(new ByteArrayInputStream(DEFAULT_XML.getBytes(\"UTF-8\"))));\n }\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n Result target = new StreamResult(baos);\n transformer.transform(source, target);\n byte[] transformedConfig = baos.toByteArray();\n try (FileOutputStream output = new FileOutputStream(file)) {\n output.write(transformedConfig);\n }\n }",
"public void deletePersistent(Object object)\r\n {\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"No transaction in progress, cannot delete persistent\");\r\n }\r\n RuntimeObject rt = new RuntimeObject(object, tx);\r\n tx.deletePersistent(rt);\r\n// tx.moveToLastInOrderList(rt.getIdentity());\r\n }"
] |
Define the set of extensions.
@param extensions
@return self | [
"public Weld extensions(Extension... extensions) {\n this.extensions.clear();\n for (Extension extension : extensions) {\n addExtension(extension);\n }\n return this;\n }"
] | [
"@JsonProperty(\"paging\")\n void paging(String paging) {\n builder.paging(IndexPagingState.fromByteBuffer(ByteBufferUtils.byteBuffer(paging)));\n }",
"public static Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }",
"public ItemRequest<Task> removeFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/removeFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public void buttonClick(View v) {\n switch (v.getId()) {\n case R.id.show:\n showAppMsg();\n break;\n case R.id.cancel_all:\n AppMsg.cancelAll(this);\n break;\n default:\n return;\n }\n }",
"public static sslvserver_sslcipher_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcipher_binding obj = new sslvserver_sslcipher_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcipher_binding response[] = (sslvserver_sslcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Automaton getAutomatonById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n List<BytesRef> bytesArray = new ArrayList<>();\n Set<String> data = get(id);\n if (data != null) {\n Term term;\n for (String item : data) {\n term = new Term(\"dummy\", item);\n bytesArray.add(term.bytes());\n }\n Collections.sort(bytesArray);\n return Automata.makeStringUnion(bytesArray);\n }\n }\n return null;\n }",
"@Override\n public boolean decompose(DMatrixRMaj orig) {\n if( orig.numCols != orig.numRows )\n throw new IllegalArgumentException(\"Matrix must be square.\");\n if( orig.numCols <= 0 )\n return false;\n\n int N = orig.numRows;\n\n // compute a similar tridiagonal matrix\n if( !decomp.decompose(orig) )\n return false;\n\n if( diag == null || diag.length < N) {\n diag = new double[N];\n off = new double[N-1];\n }\n decomp.getDiagonal(diag,off);\n\n // Tell the helper to work with this matrix\n helper.init(diag,off,N);\n\n if( computeVectors ) {\n if( computeVectorsWithValues ) {\n return extractTogether();\n } else {\n return extractSeparate(N);\n }\n } else {\n return computeEigenValues();\n }\n }",
"public static appfwjsoncontenttype[] get(nitro_service service, String jsoncontenttypevalue[]) throws Exception{\n\t\tif (jsoncontenttypevalue !=null && jsoncontenttypevalue.length>0) {\n\t\t\tappfwjsoncontenttype response[] = new appfwjsoncontenttype[jsoncontenttypevalue.length];\n\t\t\tappfwjsoncontenttype obj[] = new appfwjsoncontenttype[jsoncontenttypevalue.length];\n\t\t\tfor (int i=0;i<jsoncontenttypevalue.length;i++) {\n\t\t\t\tobj[i] = new appfwjsoncontenttype();\n\t\t\t\tobj[i].set_jsoncontenttypevalue(jsoncontenttypevalue[i]);\n\t\t\t\tresponse[i] = (appfwjsoncontenttype) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"@GuardedBy(\"elementsLock\")\n\t@Override\n\tpublic boolean markChecked(CandidateElement element) {\n\t\tString generalString = element.getGeneralString();\n\t\tString uniqueString = element.getUniqueString();\n\t\tsynchronized (elementsLock) {\n\t\t\tif (elements.contains(uniqueString)) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\telements.add(generalString);\n\t\t\t\telements.add(uniqueString);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}"
] |
Finish the oauth flow after the user was redirected back.
@param code
Code returned by the Eve Online SSO
@param state
This should be some secret to prevent XRSF see
getAuthorizationUri
@throws net.troja.eve.esi.ApiException | [
"public void finishFlow(final String code, final String state) throws ApiException {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (codeVerifier == null)\n throw new IllegalArgumentException(\"code_verifier is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(\"grant_type=\");\n builder.append(encode(\"authorization_code\"));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&code=\");\n builder.append(encode(code));\n builder.append(\"&code_verifier=\");\n builder.append(encode(codeVerifier));\n update(account, builder.toString());\n }"
] | [
"public static String readTextFile(Context context, String asset) {\n try {\n InputStream inputStream = context.getAssets().open(asset);\n return org.gearvrf.utility.TextFile.readTextFile(inputStream);\n } catch (FileNotFoundException f) {\n Log.w(TAG, \"readTextFile(): asset file '%s' doesn't exist\", asset);\n } catch (IOException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"readTextFile()\");\n }\n return null;\n }",
"public static base_response restart(nitro_service client) throws Exception {\n\t\tdbsmonitors restartresource = new dbsmonitors();\n\t\treturn restartresource.perform_operation(client,\"restart\");\n\t}",
"public static void writeFlowId(Message message, String flowId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(FLOWID_HTTP_HEADER_NAME, Collections.singletonList(flowId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' set to: \" + flowId);\n }\n }",
"public static boolean reconnectContext(RedirectException re, CommandContext ctx) {\n boolean reconnected = false;\n try {\n ConnectionInfo info = ctx.getConnectionInfo();\n ControllerAddress address = null;\n if (info != null) {\n address = info.getControllerAddress();\n }\n if (address != null && isHttpsRedirect(re, address.getProtocol())) {\n LOG.debug(\"Trying to reconnect an http to http upgrade\");\n try {\n ctx.connectController();\n reconnected = true;\n } catch (Exception ex) {\n LOG.warn(\"Exception reconnecting\", ex);\n // Proper https redirect but error.\n // Ignoring it.\n }\n }\n } catch (URISyntaxException ex) {\n LOG.warn(\"Invalid URI: \", ex);\n // OK, invalid redirect.\n }\n return reconnected;\n }",
"public static Status from(Set<ServiceReference> serviceReferencesBound, Set<ServiceReference> serviceReferencesHandled) {\n if (serviceReferencesBound == null && serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\" +\n \"and serviceReferencesHandled == null\");\n } else if (serviceReferencesBound == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\");\n } else if (serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesHandled == null\");\n }\n return new Status(serviceReferencesBound, serviceReferencesHandled);\n }",
"public static sslcertlink[] get(nitro_service service) throws Exception{\n\t\tsslcertlink obj = new sslcertlink();\n\t\tsslcertlink[] response = (sslcertlink[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }"
] |
Converts an XML file to an object.
@param fileName The filename where to save it to.
@return The object.
@throws FileNotFoundException On error. | [
"public static Object xmlToObject(String fileName) throws FileNotFoundException {\r\n\t\tFileInputStream fi = new FileInputStream(fileName);\r\n\t\tXMLDecoder decoder = new XMLDecoder(fi);\r\n\t\tObject object = decoder.readObject();\r\n\t\tdecoder.close();\r\n\t\treturn object;\r\n\t}"
] | [
"public static base_response update(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable updateresource = new bridgetable();\n\t\tupdateresource.bridgeage = resource.bridgeage;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {\n return createAppUser(api, name, new CreateUserParams());\n }",
"CueList getCueList(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.CUE_LIST_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.CUE_LIST) {\n return new CueList(response);\n }\n logger.error(\"Unexpected response type when requesting cue list: {}\", response);\n return null;\n }",
"public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }",
"public static TimeZone get(String suffix) {\n if(SUFFIX_TIMEZONES.containsKey(suffix)) {\n return SUFFIX_TIMEZONES.get(suffix);\n }\n log.warn(\"Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York\", suffix);\n return SUFFIX_TIMEZONES.get(\"\");\n }",
"public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }",
"public void setDefaultCalendarName(String calendarName)\n {\n if (calendarName == null || calendarName.length() == 0)\n {\n calendarName = DEFAULT_CALENDAR_NAME;\n }\n\n set(ProjectField.DEFAULT_CALENDAR_NAME, calendarName);\n }",
"protected void refresh()\r\n {\r\n if (log.isDebugEnabled())\r\n log.debug(\"Refresh this transaction for reuse: \" + this);\r\n try\r\n {\r\n // we reuse ObjectEnvelopeTable instance\r\n objectEnvelopeTable.refresh();\r\n }\r\n catch (Exception e)\r\n {\r\n if (log.isDebugEnabled())\r\n {\r\n log.debug(\"error closing object envelope table : \" + e.getMessage());\r\n e.printStackTrace();\r\n }\r\n }\r\n cleanupBroker();\r\n // clear the temporary used named roots map\r\n // we should do that, because same tx instance\r\n // could be used several times\r\n broker = null;\r\n clearRegistrationList();\r\n unmaterializedLocks.clear();\r\n txStatus = Status.STATUS_NO_TRANSACTION;\r\n }",
"private boolean hasMultipleCostRates()\n {\n boolean result = false;\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n //\n // We assume here that if there is just one entry in the cost rate\n // table, this is an open ended rate which covers any work, it won't\n // have specific dates attached to it.\n //\n if (table.size() > 1)\n {\n //\n // If we have multiple rates in the table, see if the same rate\n // is in force at the start and the end of the aaaignment.\n //\n CostRateTableEntry startEntry = table.getEntryByDate(getStart());\n CostRateTableEntry finishEntry = table.getEntryByDate(getFinish());\n result = (startEntry != finishEntry);\n }\n }\n return result;\n }"
] |
Get the output mapper from processor. | [
"@Nonnull\n public BiMap<String, String> getOutputMapper() {\n final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();\n if (outputMapper == null) {\n return HashBiMap.create();\n }\n return outputMapper;\n }"
] | [
"public boolean isExit() {\n if (currentRow > finalRow) { //request new block of work\n String newBlock = this.sendRequestSync(\"this/request/block\");\n LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0);\n\n if (newBlock.contains(\"exit\")) {\n getExitFlag().set(true);\n makeReport(true);\n return true;\n } else {\n block.buildFromResponse(newBlock);\n }\n\n currentRow = block.getStart();\n finalRow = block.getStop();\n } else { //report the number of lines written\n makeReport(false);\n\n if (exit.get()) {\n getExitFlag().set(true);\n return true;\n }\n }\n\n return false;\n }",
"public Object get(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\treturn convertedObjects.get(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}",
"public long queryForCountStar(DatabaseConnection databaseConnection) throws SQLException {\n\t\tif (countStarQuery == null) {\n\t\t\tStringBuilder sb = new StringBuilder(64);\n\t\t\tsb.append(\"SELECT COUNT(*) FROM \");\n\t\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\t\tcountStarQuery = sb.toString();\n\t\t}\n\t\tlong count = databaseConnection.queryForLong(countStarQuery);\n\t\tlogger.debug(\"query of '{}' returned {}\", countStarQuery, count);\n\t\treturn count;\n\t}",
"private void processFile(InputStream is) throws MPXJException\n {\n try\n {\n InputStreamReader reader = new InputStreamReader(is, CharsetHelper.UTF8);\n Tokenizer tk = new ReaderTokenizer(reader)\n {\n @Override protected boolean startQuotedIsValid(StringBuilder buffer)\n {\n return buffer.length() == 1 && buffer.charAt(0) == '<';\n }\n };\n\n tk.setDelimiter(DELIMITER);\n ArrayList<String> columns = new ArrayList<String>();\n String nextTokenPrefix = null;\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n columns.clear();\n TableDefinition table = null;\n\n while (tk.nextToken() == Tokenizer.TT_WORD)\n {\n String token = tk.getToken();\n if (columns.size() == 0)\n {\n if (token.charAt(0) == '#')\n {\n int index = token.lastIndexOf(':');\n if (index != -1)\n {\n String headerToken;\n if (token.endsWith(\"-\") || token.endsWith(\"=\"))\n {\n headerToken = token;\n token = null;\n }\n else\n {\n headerToken = token.substring(0, index);\n token = token.substring(index + 1);\n }\n\n RowHeader header = new RowHeader(headerToken);\n table = m_tableDefinitions.get(header.getType());\n columns.add(header.getID());\n }\n }\n else\n {\n if (token.charAt(0) == 0)\n {\n processFileType(token);\n }\n }\n }\n\n if (table != null && token != null)\n {\n if (token.startsWith(\"<\\\"\") && !token.endsWith(\"\\\">\"))\n {\n nextTokenPrefix = token;\n }\n else\n {\n if (nextTokenPrefix != null)\n {\n token = nextTokenPrefix + DELIMITER + token;\n nextTokenPrefix = null;\n }\n\n columns.add(token);\n }\n }\n }\n\n if (table != null && columns.size() > 1)\n {\n // System.out.println(table.getName() + \" \" + columns.size());\n // ColumnDefinition[] columnDefs = table.getColumns();\n // int unknownIndex = 1;\n // for (int xx = 0; xx < columns.size(); xx++)\n // {\n // String x = columns.get(xx);\n // String columnName = xx < columnDefs.length ? (columnDefs[xx] == null ? \"UNKNOWN\" + (unknownIndex++) : columnDefs[xx].getName()) : \"?\";\n // System.out.println(columnName + \": \" + x + \", \");\n // }\n // System.out.println();\n\n TextFileRow row = new TextFileRow(table, columns, m_epochDateFormat);\n List<Row> rows = m_tables.get(table.getName());\n if (rows == null)\n {\n rows = new LinkedList<Row>();\n m_tables.put(table.getName(), rows);\n }\n rows.add(row);\n }\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n }",
"public static rnatparam get(nitro_service service) throws Exception{\n\t\trnatparam obj = new rnatparam();\n\t\trnatparam[] response = (rnatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static Logger getLogger(String className) {\n\t\tif (logType == null) {\n\t\t\tlogType = findLogType();\n\t\t}\n\t\treturn new Logger(logType.createLog(className));\n\t}",
"public Object copy(Object obj, PersistenceBroker broker)\r\n\t\t\tthrows ObjectCopyException\r\n\t{\r\n\t\tif (obj instanceof OjbCloneable)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\treturn ((OjbCloneable) obj).ojbClone();\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new ObjectCopyException(\"Object must implement OjbCloneable in order to use the\"\r\n\t\t\t\t\t\t\t\t\t\t + \" CloneableObjectCopyStrategy\");\r\n\t\t}\r\n\t}",
"public String[] getItemsSelected() {\n List<String> selected = new LinkedList<>();\n for (int i = getIndexOffset(); i < listBox.getItemCount(); i++) {\n if (listBox.isItemSelected(i)) {\n selected.add(listBox.getValue(i));\n }\n }\n return selected.toArray(new String[selected.size()]);\n }",
"private Map<String, String> mergeItem(\r\n String item,\r\n Map<String, String> localeValues,\r\n Map<String, String> resultLocaleValues) {\r\n\r\n if (resultLocaleValues.get(item) != null) {\r\n if (localeValues.get(item) != null) {\r\n localeValues.put(item, localeValues.get(item) + \" \" + resultLocaleValues.get(item));\r\n } else {\r\n localeValues.put(item, resultLocaleValues.get(item));\r\n }\r\n }\r\n\r\n return localeValues;\r\n }"
] |
Convert moneyness given as difference to par swap rate to moneyness in bp.
Uses the fixing times of the fix schedule to determine fractions.
@param moneyness as offset.
@return Moneyness in bp. | [
"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 void createSuiteList(List<ISuite> suites,\n File outputDirectory,\n boolean onlyFailures) throws Exception\n {\n VelocityContext context = createContext();\n context.put(SUITES_KEY, suites);\n context.put(ONLY_FAILURES_KEY, onlyFailures);\n generateFile(new File(outputDirectory, SUITES_FILE),\n SUITES_FILE + TEMPLATE_EXTENSION,\n context);\n }",
"@IntRange(from = 0, to = OPAQUE)\n private static int resolveLineAlpha(\n @IntRange(from = 0, to = OPAQUE) final int sceneAlpha,\n final float maxDistance,\n final float distance) {\n final float alphaPercent = 1f - distance / maxDistance;\n final int alpha = (int) ((float) OPAQUE * alphaPercent);\n return alpha * sceneAlpha / OPAQUE;\n }",
"private void processCalendars() throws Exception\n {\n List<Row> rows = getRows(\"select * from zcalendar where zproject=?\", m_projectID);\n for (Row row : rows)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n calendar.setUniqueID(row.getInteger(\"Z_PK\"));\n calendar.setName(row.getString(\"ZTITLE\"));\n processDays(calendar);\n processExceptions(calendar);\n m_eventManager.fireCalendarReadEvent(calendar);\n }\n }",
"public synchronized Widget measureChild(final int dataIndex, boolean calculateOffset) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"measureChild dataIndex = %d\", dataIndex);\n\n Widget widget = mContainer.get(dataIndex);\n if (widget != null) {\n synchronized (mMeasuredChildren) {\n mMeasuredChildren.add(dataIndex);\n }\n }\n return widget;\n }",
"private void setQR(DMatrixRMaj Q , DMatrixRMaj R , int growRows ) {\n if( Q.numRows != Q.numCols ) {\n throw new IllegalArgumentException(\"Q should be square.\");\n }\n\n this.Q = Q;\n this.R = R;\n\n m = Q.numRows;\n n = R.numCols;\n\n if( m+growRows > maxRows || n > maxCols ) {\n if( autoGrow ) {\n declareInternalData(m+growRows,n);\n } else {\n throw new IllegalArgumentException(\"Autogrow has been set to false and the maximum number of rows\" +\n \" or columns has been exceeded.\");\n }\n }\n }",
"public Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }",
"void processBeat(Beat beat) {\n if (isRunning() && beat.isTempoMaster()) {\n setMasterTempo(beat.getEffectiveTempo());\n deliverBeatAnnouncement(beat);\n }\n }",
"public String getXmlFormatted(Map<String, String> dataMap) {\r\n StringBuilder sb = new StringBuilder();\r\n for (String var : outTemplate) {\r\n sb.append(appendXmlStartTag(var));\r\n sb.append(dataMap.get(var));\r\n sb.append(appendXmlEndingTag(var));\r\n }\r\n return sb.toString();\r\n }",
"public void postLicense(final License license, 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.licenseResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST license\";\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 }"
] |
Sets the set of property filters based on the given string.
@param filters
comma-separates list of property ids, or "-" to filter all
statements | [
"private void setPropertyFilters(String filters) {\n\t\tthis.filterProperties = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tfor (String pid : filters.split(\",\")) {\n\t\t\t\tthis.filterProperties.add(Datamodel\n\t\t\t\t\t\t.makeWikidataPropertyIdValue(pid));\n\t\t\t}\n\t\t}\n\t}"
] | [
"public static base_response kill(nitro_service client, systemsession resource) throws Exception {\n\t\tsystemsession killresource = new systemsession();\n\t\tkillresource.sid = resource.sid;\n\t\tkillresource.all = resource.all;\n\t\treturn killresource.perform_operation(client,\"kill\");\n\t}",
"public static String encodePath(String path, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH);\n\t}",
"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 ParsedWord pollParsedWord() {\n if(hasNextWord()) {\n //set correct next char\n if(parsedLine.words().size() > (word+1))\n character = parsedLine.words().get(word+1).lineIndex();\n else\n character = -1;\n return parsedLine.words().get(word++);\n }\n else\n return new ParsedWord(null, -1);\n }",
"public Date getStartDate()\n {\n Date startDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date. Note that the\n // behaviour is different for milestones. The milestone end date\n // is always correct, the milestone start date may be different\n // to reflect a missed deadline.\n //\n Date taskStartDate;\n if (task.getMilestone() == true)\n {\n taskStartDate = task.getActualFinish();\n if (taskStartDate == null)\n {\n taskStartDate = task.getFinish();\n }\n }\n else\n {\n taskStartDate = task.getActualStart();\n if (taskStartDate == null)\n {\n taskStartDate = task.getStart();\n }\n }\n\n if (taskStartDate != null)\n {\n if (startDate == null)\n {\n startDate = taskStartDate;\n }\n else\n {\n if (taskStartDate.getTime() < startDate.getTime())\n {\n startDate = taskStartDate;\n }\n }\n }\n }\n\n return (startDate);\n }",
"public BlurBuilder brightness(float brightness) {\n data.preProcessors.add(new RenderscriptBrightnessProcessor(data.contextWrapper.getRenderScript(), brightness, data.contextWrapper.getResources()));\n return this;\n }",
"public static final Double parsePercent(String value)\n {\n return value == null ? null : Double.valueOf(Double.parseDouble(value) * 100.0);\n }",
"public void registerComponent(java.awt.Component c)\r\n {\r\n unregisterComponent(c);\r\n if (recognizerAbstractClass == null)\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDefaultDragGestureRecognizer(c, \r\n dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n else\r\n {\r\n hmDragGestureRecognizers.put(c, \r\n dragSource.createDragGestureRecognizer (recognizerAbstractClass,\r\n c, dragWorker.getAcceptableActions(c), dgListener)\r\n );\r\n }\r\n }",
"public final static int readMdLink(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n boolean endReached = false;\n switch (ch)\n {\n case '(':\n counter++;\n break;\n case ' ':\n if (counter == 1)\n {\n endReached = true;\n }\n break;\n case ')':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n break;\n }\n if (endReached)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }"
] |
Scans given directory for files passing given filter, adds the results into given list. | [
"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 void symmLowerToFull( DMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new MatrixDimensionException(\"Must be a square matrix\");\n\n final int cols = A.numCols;\n\n for (int row = 0; row < A.numRows; row++) {\n for (int col = row+1; col < cols; col++) {\n A.data[row*cols+col] = A.data[col*cols+row];\n }\n }\n }",
"public static String buildDynamicCapabilityName(String baseName, String dynamicNameElement) {\n return buildDynamicCapabilityName(baseName, new String[]{dynamicNameElement});\n }",
"public WebSocketContext sendToPeers(String message, boolean excludeSelf) {\n return sendToConnections(message, url, manager.urlRegistry(), excludeSelf);\n }",
"public void addJobType(final String jobName, final Class<?> jobType) {\n checkJobType(jobName, jobType);\n this.jobTypes.put(jobName, jobType);\n }",
"private void writeToFile(List<DomainControllerData> data, String domainName) throws IOException {\n if(domainName == null || data == null) {\n return;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n String key = S3Util.sanitize(domainName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n byte[] buf = S3Util.domainControllerDataToByteBuffer(data);\n S3Object val = new S3Object(buf, null);\n if (usingPreSignedUrls()) {\n Map headers = new TreeMap();\n headers.put(\"x-amz-acl\", Arrays.asList(\"public-read\"));\n conn.put(pre_signed_put_url, val, headers).connection.getResponseMessage();\n } else {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n conn.put(location, key, val, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotWriteToS3File(e.getLocalizedMessage());\n }\n }",
"public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }",
"public int nullity() {\n if( is64 ) {\n return SingularOps_DDRM.nullity((SingularValueDecomposition_F64)svd, 10.0 * UtilEjml.EPS);\n } else {\n return SingularOps_FDRM.nullity((SingularValueDecomposition_F32)svd, 5.0f * UtilEjml.F_EPS);\n }\n }",
"public void visitRequire(String module, int access, String version) {\n if (mv != null) {\n mv.visitRequire(module, access, version);\n }\n }",
"public static DoubleMatrix[] fullSVD(DoubleMatrix A) {\n int m = A.rows;\n int n = A.columns;\n\n DoubleMatrix U = new DoubleMatrix(m, m);\n DoubleMatrix S = new DoubleMatrix(min(m, n));\n DoubleMatrix V = new DoubleMatrix(n, n);\n\n int info = NativeBlas.dgesvd('A', 'A', m, n, A.dup().data, 0, m, S.data, 0, U.data, 0, m, V.data, 0, n);\n\n if (info > 0) {\n throw new LapackConvergenceException(\"GESVD\", info + \" superdiagonals of an intermediate bidiagonal form failed to converge.\");\n }\n\n return new DoubleMatrix[]{U, S, V.transpose()};\n }"
] |
Construct a new uri by replacing query parameters in initialUri with the query parameters provided.
@param initialUri the initial/template URI
@param queryParams the new query parameters. | [
"public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }"
] | [
"public void clearSources()\n {\n synchronized (mAudioSources)\n {\n for (GVRAudioSource source : mAudioSources)\n {\n source.setListener(null);\n }\n mAudioSources.clear();\n }\n }",
"public static final String printTimestamp(Date value)\n {\n return (value == null ? null : TIMESTAMP_FORMAT.get().format(value));\n }",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static float checkFloat(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInFloatRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), FLOAT_MIN, FLOAT_MAX);\n\t\t}\n\n\t\treturn number.floatValue();\n\t}",
"public String findAlias(String entityAlias, List<String> propertyPathWithoutAlias) {\n\t\tRelationshipAliasTree aliasTree = relationshipAliases.get( entityAlias );\n\t\tif ( aliasTree == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tRelationshipAliasTree associationAlias = aliasTree;\n\t\tfor ( int i = 0; i < propertyPathWithoutAlias.size(); i++ ) {\n\t\t\tassociationAlias = associationAlias.findChild( propertyPathWithoutAlias.get( i ) );\n\t\t\tif ( associationAlias == null ) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn associationAlias.getAlias();\n\t}",
"private void handleMultiInstanceEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Encapsulation\");\r\n\t\tint instance = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);\r\n\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Instance = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), instance));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);\r\n\t}",
"public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\n }",
"public HostName toHostName() {\n\t\tHostName host = fromHost;\n\t\tif(host == null) {\n\t\t\tfromHost = host = toCanonicalHostName();\n\t\t}\n\t\treturn host;\n\t}",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) {\n List<String> storeNames = Lists.newArrayList();\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeNames.add(storeDefinition.getName());\n }\n return storeNames;\n }"
] |
Determine the color of the waveform given an index into it.
@param segment the index of the first waveform byte to examine
@param front if {@code true} the front (brighter) segment of a color waveform preview is returned,
otherwise the back (dimmer) segment is returned. Has no effect for blue previews.
@return the color of the waveform at that segment, which may be based on an average
of a number of values starting there, determined by the scale | [
"@SuppressWarnings(\"WeakerAccess\")\n public Color segmentColor(final int segment, final boolean front) {\n final ByteBuffer bytes = getData();\n if (isColor) {\n final int base = segment * 6;\n final int backHeight = segmentHeight(segment, false);\n if (backHeight == 0) {\n return Color.BLACK;\n }\n final int maxLevel = front? 255 : 191;\n final int red = Util.unsign(bytes.get(base + 3)) * maxLevel / backHeight;\n final int green = Util.unsign(bytes.get(base + 4)) * maxLevel / backHeight;\n final int blue = Util.unsign(bytes.get(base + 5)) * maxLevel / backHeight;\n return new Color(red, green, blue);\n } else {\n final int intensity = getData().get(segment * 2 + 1) & 0x07;\n return (intensity >= 5) ? INTENSE_COLOR : NORMAL_COLOR;\n }\n }"
] | [
"public static base_response Import(nitro_service client, responderhtmlpage resource) throws Exception {\n\t\tresponderhtmlpage Importresource = new responderhtmlpage();\n\t\tImportresource.src = resource.src;\n\t\tImportresource.name = resource.name;\n\t\tImportresource.comment = resource.comment;\n\t\tImportresource.overwrite = resource.overwrite;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public long addAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.sadd(getKey(), members);\n }\n });\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 initDurationButtonGroup() {\n\n m_groupDuration = new CmsRadioButtonGroup();\n\n m_endsAfterRadioButton = new CmsRadioButton(\n EndType.TIMES.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_0));\n m_endsAfterRadioButton.setGroup(m_groupDuration);\n m_endsAtRadioButton = new CmsRadioButton(\n EndType.DATE.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_DATE_0));\n m_endsAtRadioButton.setGroup(m_groupDuration);\n m_groupDuration.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (null != value) {\n m_controller.setEndType(value);\n }\n }\n }\n });\n\n }",
"public String[][] getRequiredRuleNames(Param param) {\n\t\tif (isFiltered(param)) {\n\t\t\treturn EMPTY_ARRAY;\n\t\t}\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\tString ruleName = param.ruleName;\n\t\tif (ruleName == null) {\n\t\t\treturn getRequiredRuleNames(param, elementToParse);\n\t\t}\n\t\treturn getAdjustedRequiredRuleNames(param, elementToParse, ruleName);\n\t}",
"@Override\r\n public void close() {\r\n // Use monitor to avoid race between external close and handler thread run()\r\n synchronized (closeMonitor) {\r\n // Close and clear streams, sockets etc.\r\n if (socket != null) {\r\n try {\r\n // Terminates thread blocking on socket read\r\n // and automatically closed depending streams\r\n socket.close();\r\n } catch (IOException e) {\r\n log.warn(\"Can not close socket\", e);\r\n } finally {\r\n socket = null;\r\n }\r\n }\r\n\r\n // Clear user data\r\n session = null;\r\n response = null;\r\n }\r\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public String getProperty(Enum<?> key, boolean lowerCase) {\n final String keyName;\n if (lowerCase) {\n keyName = key.name().toLowerCase(Locale.ENGLISH);\n } else {\n keyName = key.name();\n }\n return getProperty(keyName);\n }",
"@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }",
"final public void addOffset(Integer start, Integer end) {\n if (tokenOffset == null) {\n setOffset(start, end);\n } else if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\"Start offset after end offset\");\n } else {\n tokenOffset.add(start, end);\n }\n }"
] |
Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID,
using cached media instead if it is available, and possibly giving up if we are in passive mode.
@param track uniquely identifies the track whose metadata is desired
@param trackType identifies the type of track being requested, which affects the type of metadata request
message that must be used
@param failIfPassive will prevent the request from taking place if we are in passive mode, so that automatic
metadata updates will use available caches only
@return the metadata found, if any | [
"private TrackMetadata requestMetadataInternal(final DataReference track, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n // First check if we are using cached data for this request.\n MetadataCache cache = getMetadataCache(SlotReference.getSlotReference(track));\n if (cache != null && trackType == CdjStatus.TrackType.REKORDBOX) {\n return cache.getTrackMetadata(null, track);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = getMediaDetailsFor(track.getSlotReference());\n if (sourceDetails != null) {\n final TrackMetadata provided = allMetadataProviders.getTrackMetadata(sourceDetails, track);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (passive.get() && failIfPassive && track.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // Use the dbserver protocol implementation to request the metadata.\n ConnectionManager.ClientTask<TrackMetadata> task = new ConnectionManager.ClientTask<TrackMetadata>() {\n @Override\n public TrackMetadata useClient(Client client) throws Exception {\n return queryMetadata(track, trackType, client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(track.player, task, \"requesting metadata\");\n } catch (Exception e) {\n logger.error(\"Problem requesting metadata, returning null\", e);\n }\n return null;\n }"
] | [
"public static Set<Dependency> getAllDependencies(final Module module, final List<String> producedArtifacts) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n\n for(final Dependency dependency: module.getDependencies()){\n if(!producedArtifacts.contains(dependency.getTarget().getGavc())){\n dependencies.add(dependency);\n }\n }\n\n for(final Module subModule: module.getSubmodules()){\n dependencies.addAll(getAllDependencies(subModule, producedArtifacts));\n }\n\n return dependencies;\n }",
"public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}",
"private void processRedirect(String stringStatusCode,\n HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse) throws Exception {\n // Check if the proxy response is a redirect\n // The following code is adapted from\n // org.tigris.noodle.filters.CheckForRedirect\n // Hooray for open source software\n\n String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();\n if (stringLocation == null) {\n throw new ServletException(\"Received status code: \"\n + stringStatusCode + \" but no \"\n + STRING_LOCATION_HEADER\n + \" header was found in the response\");\n }\n // Modify the redirect to go to this proxy servlet rather than the proxied host\n String stringMyHostName = httpServletRequest.getServerName();\n if (httpServletRequest.getServerPort() != 80) {\n stringMyHostName += \":\" + httpServletRequest.getServerPort();\n }\n stringMyHostName += httpServletRequest.getContextPath();\n httpServletResponse.sendRedirect(stringLocation.replace(\n getProxyHostAndPort() + this.getProxyPath(),\n stringMyHostName));\n }",
"public String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }",
"void writeBestRankTriples() {\n\t\tfor (Resource resource : this.rankBuffer.getBestRankedStatements()) {\n\t\t\ttry {\n\t\t\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\t\t\tRdfWriter.RDF_TYPE, RdfWriter.WB_BEST_RANK.toString());\n\t\t\t} catch (RDFHandlerException e) {\n\t\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tthis.rankBuffer.clear();\n\t}",
"protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {\r\n\r\n try {\r\n\r\n if (file == null) {\r\n throw new IllegalArgumentException(\"File must not be null!\");\r\n }\r\n CmsLock lock = cms.getLock(file);\r\n CmsUser user = cms.getRequestContext().getCurrentUser();\r\n boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()\r\n && (lock.isOwnedBy(user) || lock.isLockableBy(user))\r\n && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);\r\n boolean isReadOnly = !canWrite;\r\n boolean isFolder = file.isFolder();\r\n boolean isRoot = file.getRootPath().length() <= 1;\r\n\r\n Set<Action> aas = new LinkedHashSet<Action>();\r\n addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);\r\n addAction(aas, Action.CAN_GET_PROPERTIES, true);\r\n addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);\r\n addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);\r\n addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);\r\n if (isFolder) {\r\n addAction(aas, Action.CAN_GET_DESCENDANTS, true);\r\n addAction(aas, Action.CAN_GET_CHILDREN, true);\r\n addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);\r\n addAction(aas, Action.CAN_GET_FOLDER_TREE, true);\r\n addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);\r\n addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);\r\n addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);\r\n } else {\r\n addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);\r\n addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);\r\n addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);\r\n }\r\n AllowableActionsImpl result = new AllowableActionsImpl();\r\n result.setAllowableActions(aas);\r\n return result;\r\n } catch (CmsException e) {\r\n handleCmsException(e);\r\n return null;\r\n }\r\n }",
"@Deprecated\n public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) {\n Utils.notNull(nodes);\n this.nodes = new HashSet<Node>(nodes);\n return this;\n }",
"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 ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n IndirectionHandler handler = ProxyHelper.getIndirectionHandler(objectOrProxy);\r\n\r\n if(handler != null)\r\n {\r\n return getKeyValues(cld, handler.getIdentity(), convertToSql); //BRJ: convert Identity\r\n }\r\n else\r\n {\r\n ClassDescriptor realCld = getRealClassDescriptor(cld, objectOrProxy);\r\n return getValuesForObject(realCld.getPkFields(), objectOrProxy, convertToSql);\r\n }\r\n }"
] |
Determines if the key replicates to the given node
@param key
@param nodeId
@return true if the key belongs to the node as some replica | [
"public boolean checkKeyBelongsToNode(byte[] key, int nodeId) {\n List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();\n List<Integer> replicatingPartitions = getReplicatingPartitionList(key);\n // remove all partitions from the list, except those that belong to the\n // node\n replicatingPartitions.retainAll(nodePartitions);\n return replicatingPartitions.size() > 0;\n }"
] | [
"private static MessageInfoType mapMessageInfo(MessageInfo messageInfo) {\n if (messageInfo == null) {\n return null;\n }\n MessageInfoType miType = new MessageInfoType();\n miType.setMessageId(messageInfo.getMessageId());\n miType.setFlowId(messageInfo.getFlowId());\n miType.setPorttype(convertString(messageInfo.getPortType()));\n miType.setOperationName(messageInfo.getOperationName());\n miType.setTransport(messageInfo.getTransportType());\n return miType;\n }",
"public Response deleteTemplate(String id)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.delete(\"/templates/\" + id, new HashMap<String, Object>()));\n }",
"public void loadModel(GVRAndroidResource avatarResource, String attachBone)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n GVRSceneObject boneObject;\n int boneIndex;\n\n if (mSkeleton == null)\n {\n throw new IllegalArgumentException(\"Cannot attach model to avatar - there is no skeleton\");\n }\n boneIndex = mSkeleton.getBoneIndex(attachBone);\n if (boneIndex < 0)\n {\n throw new IllegalArgumentException(attachBone + \" is not a bone in the avatar skeleton\");\n }\n boneObject = mSkeleton.getBone(boneIndex);\n if (boneObject == null)\n {\n throw new IllegalArgumentException(attachBone +\n \" does not have a bone object in the avatar skeleton\");\n }\n boneObject.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }",
"public static aaagroup_aaauser_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_aaauser_binding obj = new aaagroup_aaauser_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_aaauser_binding response[] = (aaagroup_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected Query buildPrefetchQuery(Collection ids)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n query.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n\r\n return query;\r\n }",
"protected void propagateOnNoPick(GVRPicker picker)\n {\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, IPickEvents.class, \"onNoPick\", picker);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, IPickEvents.class, \"onNoPick\", picker);\n }\n }\n }",
"protected void handleExceptions(MessageEvent messageEvent, Exception exception) {\n logger.error(\"Unknown exception. Internal Server Error.\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Internal Server Error\");\n }",
"public void editPhotos(String photosetId, String primaryPhotoId, String[] photoIds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n parameters.put(\"photo_ids\", StringUtilities.join(photoIds, \",\"));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public ItemRequest<Task> findById(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }"
] |
Checks the preconditions for creating a new RequireSubStr processor with a List of Strings.
@param requiredSubStrings
the required substrings
@throws NullPointerException
if requiredSubStrings or one of its elements is null
@throws IllegalArgumentException
if requiredSubStrings is empty | [
"private static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}"
] | [
"private static CmsUUID toUuid(String uuid) {\n\n if (\"null\".equals(uuid) || CmsStringUtil.isEmpty(uuid)) {\n return null;\n }\n return new CmsUUID(uuid);\n\n }",
"private void ensureFields(ClassDescriptorDef classDef, Collection fields) throws ConstraintException\r\n {\r\n boolean forceVirtual = !classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true);\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n // First we check whether this field is already present in the class\r\n FieldDescriptorDef foundFieldDef = classDef.getField(fieldDef.getName());\r\n\r\n if (foundFieldDef != null)\r\n {\r\n if (isEqual(fieldDef, foundFieldDef))\r\n {\r\n if (forceVirtual)\r\n {\r\n foundFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n continue;\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a different field of the same name\");\r\n }\r\n }\r\n\r\n // perhaps a reference or collection ?\r\n if (classDef.getCollection(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a collection of the same name\");\r\n }\r\n if (classDef.getReference(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a reference of the same name\");\r\n }\r\n classDef.addFieldClone(fieldDef);\r\n classDef.getField(fieldDef.getName()).setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n }",
"public static BoxUser.Info createAppUser(BoxAPIConnection api, String name,\n CreateUserParams params) {\n\n params.setIsPlatformAccessOnly(true);\n return createEnterpriseUser(api, null, name, params);\n }",
"public synchronized void stop() {\n if (isRunning()) {\n socket.get().close();\n socket.set(null);\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"public ClientConfig setIdleConnectionTimeout(long idleConnectionTimeout, TimeUnit unit) {\n if (idleConnectionTimeout <= 0) {\n this.idleConnectionTimeoutMs = -1;\n } else {\n if(unit.toMinutes(idleConnectionTimeout) < 10) {\n throw new IllegalArgumentException(\"idleConnectionTimeout should be minimum of 10 minutes\");\n }\n this.idleConnectionTimeoutMs = unit.toMillis(idleConnectionTimeout);\n }\n return this;\n }",
"public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n final ServicesAttachment servicesAttachment = deploymentUnit.getAttachment(Attachments.SERVICES);\n if (servicesAttachment == null || servicesAttachment.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) {\n return; // Skip it if it has not been marked\n }\n final Module module = deploymentUnit.getAttachment(Attachments.MODULE);\n if (module == null) {\n return; // Skip deployments with no module\n }\n\n AttachmentList<DeploymentUnit> duList = deploymentUnit.getAttachment(Attachments.SUB_DEPLOYMENTS);\n List<String> serviceAcitvatorList = new ArrayList<String>();\n if (duList!=null && !duList.isEmpty()) {\n for (DeploymentUnit du : duList) {\n ServicesAttachment duServicesAttachment = du.getAttachment(Attachments.SERVICES);\n for (String serv : duServicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {\n serviceAcitvatorList.add(serv);\n }\n }\n }\n\n ServiceRegistry serviceRegistry = phaseContext.getServiceRegistry();\n if (WildFlySecurityManager.isChecking()) {\n //service registry allows you to modify internal server state across all deployments\n //if a security manager is present we use a version that has permission checks\n serviceRegistry = new SecuredServiceRegistry(serviceRegistry);\n }\n final ServiceActivatorContext serviceActivatorContext = new ServiceActivatorContextImpl(phaseContext.getServiceTarget(), serviceRegistry);\n\n final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();\n\n try {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());\n for (ServiceActivator serviceActivator : module.loadService(ServiceActivator.class)) {\n try {\n for (String serv : servicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {\n if (serv.compareTo(serviceActivator.getClass().getName()) == 0 && !serviceAcitvatorList.contains(serv)) {\n serviceActivator.activate(serviceActivatorContext);\n break;\n }\n }\n } catch (ServiceRegistryException e) {\n throw new DeploymentUnitProcessingException(e);\n }\n }\n } finally {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);\n }\n }",
"public void startServer() throws Exception {\n if (!externalDatabaseHost) {\n try {\n this.port = Utils.getSystemPort(Constants.SYS_DB_PORT);\n server = Server.createTcpServer(\"-tcpPort\", String.valueOf(port), \"-tcpAllowOthers\").start();\n } catch (SQLException e) {\n if (e.toString().contains(\"java.net.UnknownHostException\")) {\n logger.error(\"Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'\");\n logger.error(\"Example: 127.0.0.1 MacBook\");\n throw e;\n }\n }\n }\n }",
"public static base_responses delete(nitro_service client, String hostname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (hostname != null && hostname.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[hostname.length];\n\t\t\tfor (int i=0;i<hostname.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = hostname[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 PersistenceStrategy<?, ?, ?> getInstance(\n\t\t\tCacheMappingType cacheMapping,\n\t\t\tEmbeddedCacheManager externalCacheManager,\n\t\t\tURL configurationUrl,\n\t\t\tJtaPlatform jtaPlatform,\n\t\t\tSet<EntityKeyMetadata> entityTypes,\n\t\t\tSet<AssociationKeyMetadata> associationTypes,\n\t\t\tSet<IdSourceKeyMetadata> idSourceTypes ) {\n\n\t\tif ( cacheMapping == CacheMappingType.CACHE_PER_KIND ) {\n\t\t\treturn getPerKindStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\treturn getPerTableStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform,\n\t\t\t\t\tentityTypes,\n\t\t\t\t\tassociationTypes,\n\t\t\t\t\tidSourceTypes\n\t\t\t);\n\t\t}\n\t}"
] |
Returns the value of the identified field as a Boolean.
@param fieldName the name of the field
@return the value of the field as a Boolean | [
"public Boolean getBoolean(String fieldName) {\n\t\treturn hasValue(fieldName) ? Boolean.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t}"
] | [
"public InternalTile paint(InternalTile tile) throws RenderException {\n\t\tif (tile.getContentType().equals(VectorTileContentType.URL_CONTENT)) {\n\t\t\tif (urlBuilder != null) {\n\t\t\t\tif (paintGeometries) {\n\t\t\t\t\turlBuilder.paintGeometries(paintGeometries);\n\t\t\t\t\turlBuilder.paintLabels(false);\n\t\t\t\t\ttile.setFeatureContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\tif (paintLabels) {\n\t\t\t\t\turlBuilder.paintGeometries(false);\n\t\t\t\t\turlBuilder.paintLabels(paintLabels);\n\t\t\t\t\ttile.setLabelContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\treturn tile;\n\t\t\t}\n\t\t}\n\t\treturn tile;\n\t}",
"public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,\n zoneId);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n boolean first = true;\n Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());\n for(int initPartitionId: sortedInitPartitionIds) {\n if(!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n\n int runLength = idToRunLength.get(initPartitionId);\n if(runLength == 1) {\n sb.append(initPartitionId);\n } else {\n int endPartitionId = (initPartitionId + runLength - 1)\n % cluster.getNumberOfPartitions();\n sb.append(initPartitionId).append(\"-\").append(endPartitionId);\n }\n }\n sb.append(\"]\");\n\n return sb.toString();\n }",
"public void deleteRebalancingState(RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n RebalancerState rebalancerState = getRebalancerState();\n\n if(!rebalancerState.remove(stealInfo))\n throw new IllegalArgumentException(\"Couldn't find \" + stealInfo + \" in \"\n + rebalancerState + \" while deleting\");\n\n if(rebalancerState.isEmpty()) {\n logger.debug(\"Cleaning all rebalancing state\");\n cleanAllRebalancingState();\n } else {\n put(REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n }\n } finally {\n writeLock.unlock();\n }\n }",
"public static 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}",
"public Bundler put(String key, CharSequence[] value) {\n delegate.putCharSequenceArray(key, value);\n return this;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<BritishCutoverDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<BritishCutoverDate>) super.zonedDateTime(temporal);\n }",
"@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public ExecInspection execStartVerbose(String containerId, String... commands) {\n this.readWriteLock.readLock().lock();\n try {\n String id = execCreate(containerId, commands);\n CubeOutput output = execStartOutput(id);\n\n return new ExecInspection(output, inspectExec(id));\n } finally {\n this.readWriteLock.readLock().unlock();\n }\n }",
"private void computeCosts() {\n cost = Long.MAX_VALUE;\n for (QueueItem item : queueSpans) {\n cost = Math.min(cost, item.sequenceSpans.spans.cost());\n }\n }"
] |
Handles a faulted task.
@param faultedEntry the entry holding faulted task
@param throwable the reason for fault
@param context the context object shared across all the task entries in this group during execution
@return an observable represents asynchronous operation in the next stage | [
"private Observable<Indexable> processFaultedTaskAsync(final TaskGroupEntry<TaskItem> faultedEntry,\n final Throwable throwable,\n final InvocationContext context) {\n markGroupAsCancelledIfTerminationStrategyIsIPTC();\n reportError(faultedEntry, throwable);\n if (isRootEntry(faultedEntry)) {\n if (shouldPropagateException(throwable)) {\n return toErrorObservable(throwable);\n }\n return Observable.empty();\n } else if (shouldPropagateException(throwable)) {\n return Observable.concatDelayError(invokeReadyTasksAsync(context), toErrorObservable(throwable));\n } else {\n return invokeReadyTasksAsync(context);\n }\n }"
] | [
"public static Object objectify(ObjectMapper mapper, Object source) {\n return objectify(mapper, source, Object.class);\n }",
"public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}",
"public Token add( Function function ) {\n Token t = new Token(function);\n push( t );\n return t;\n }",
"public String prepareStatementString() throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\treturn buildStatementString(argList);\n\t}",
"private void deliverTempoChangedAnnouncement(final double tempo) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.tempoChanged(tempo);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering tempo changed announcement to listener\", t);\n }\n }\n }",
"public static final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }",
"public String processProcedureArgument(Properties attributes) throws XDocletException\r\n {\r\n String id = attributes.getProperty(ATTRIBUTE_NAME);\r\n ProcedureArgumentDef argDef = _curClassDef.getProcedureArgument(id);\r\n String attrName;\r\n \r\n if (argDef == null)\r\n { \r\n argDef = new ProcedureArgumentDef(id);\r\n _curClassDef.addProcedureArgument(argDef);\r\n }\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 argDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }",
"public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n protected URL getDefinitionsURL() {\n try {\n URL url = CustomEPSGCodes.class.getResource(CUSTOM_EPSG_CODES_FILE);\n // quickly test url\n try (InputStream stream = url.openStream()) {\n //noinspection ResultOfMethodCallIgnored\n stream.read();\n }\n return url;\n } catch (Throwable e) {\n throw new AssertionError(\"Unable to load /epsg.properties file from root of classpath.\");\n }\n }"
] |
Always returns the original proxy object that was serialized.
@return the proxy object
@throws java.io.ObjectStreamException | [
"Object readResolve() throws ObjectStreamException {\n Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);\n if (bean == null) {\n throw BeanLogger.LOG.proxyDeserializationFailure(beanId);\n }\n return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);\n }"
] | [
"public static <X, T> ProducerMethod<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedMethod<T, ? super X> method, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {\n return new ProducerMethod<X, T>(createId(attributes, method, declaringBean), attributes, method, declaringBean, disposalMethod, beanManager, services);\n }",
"public CollectionRequest<Project> findByTeam(String team) {\n \n String path = String.format(\"/teams/%s/projects\", team);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }",
"public void publish() {\n\n CmsDirectPublishDialogAction action = new CmsDirectPublishDialogAction();\n List<CmsResource> resources = getBundleResources();\n I_CmsDialogContext context = new A_CmsDialogContext(\"\", ContextType.appToolbar, resources) {\n\n public void focus(CmsUUID structureId) {\n\n //Nothing to do.\n }\n\n public List<CmsUUID> getAllStructureIdsInView() {\n\n return null;\n }\n\n public void updateUserInfo() {\n\n //Nothing to do.\n }\n };\n action.executeAction(context);\n updateLockInformation();\n\n }",
"private void store(final PrintJobStatus printJobStatus) throws JSONException {\n JSONObject metadata = new JSONObject();\n metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());\n metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());\n metadata.put(JSON_START_DATE, printJobStatus.getStartTime());\n metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());\n if (printJobStatus.getCompletionDate() != null) {\n metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());\n }\n metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));\n if (printJobStatus.getError() != null) {\n metadata.put(JSON_ERROR, printJobStatus.getError());\n }\n if (printJobStatus.getResult() != null) {\n metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());\n metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());\n metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());\n metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());\n }\n this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);\n }",
"public ParallelTaskBuilder prepareTcp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.TCP);\n cb.getTcpMeta().setCommand(command);\n return cb;\n }",
"public static BoxLegalHoldAssignment.Info create(BoxAPIConnection api,\n String policyID, String resourceType, String resourceID) {\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_id\", policyID)\n .add(\"assign_to\", new JsonObject()\n .add(\"type\", resourceType)\n .add(\"id\", resourceID));\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldAssignment createdAssignment = new BoxLegalHoldAssignment(api, responseJSON.get(\"id\").asString());\n return createdAssignment.new Info(responseJSON);\n }",
"public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) {\n\n if (resList == null) {\n return new CmsResourceTypeStatResultList();\n }\n\n resList.deleteOld();\n return resList;\n }",
"private void writeDoubleField(String fieldName, Object value) throws IOException\n {\n double val = ((Number) value).doubleValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"private void setTempoMaster(DeviceUpdate newMaster) {\n DeviceUpdate oldMaster = tempoMaster.getAndSet(newMaster);\n if ((newMaster == null && oldMaster != null) ||\n (newMaster != null && ((oldMaster == null) || !newMaster.getAddress().equals(oldMaster.getAddress())))) {\n // This is a change in master, so report it to any registered listeners\n deliverMasterChangedAnnouncement(newMaster);\n }\n }"
] |
Use this API to add responderpolicy. | [
"public static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {\n if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {\n throw new VoldemortException(\"Node ids are not the same [ lhs cluster node ids (\"\n + lhs.getNodeIds()\n + \") not equal to rhs cluster node ids (\"\n + rhs.getNodeIds() + \") ]\");\n }\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 }",
"private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgTileWriter());\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}",
"public static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context, final Procedure1<? super ContentAssistEntry> init) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, init);\n }",
"public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }",
"public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}",
"public boolean find() {\r\n if (findIterator == null) {\r\n findIterator = root.iterator();\r\n }\r\n if (findCurrent != null && matches()) {\r\n return true;\r\n }\r\n while (findIterator.hasNext()) {\r\n findCurrent = findIterator.next();\r\n resetChildIter(findCurrent);\r\n if (matches()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"private static String stripExtraLineEnd(String text, boolean formalRTF)\n {\n if (formalRTF && text.endsWith(\"\\n\"))\n {\n text = text.substring(0, text.length() - 1);\n }\n return text;\n }"
] |
Gets the metadata on this folder associated with a specified template.
@param templateName the metadata template type name.
@return the metadata returned from the server. | [
"public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\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 }",
"private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }",
"private static JSONObject parseBounds(Bounds bounds) throws JSONException {\n if (bounds != null) {\n JSONObject boundsObject = new JSONObject();\n JSONObject lowerRight = new JSONObject();\n JSONObject upperLeft = new JSONObject();\n\n lowerRight.put(\"x\",\n bounds.getLowerRight().getX().doubleValue());\n lowerRight.put(\"y\",\n bounds.getLowerRight().getY().doubleValue());\n\n upperLeft.put(\"x\",\n bounds.getUpperLeft().getX().doubleValue());\n upperLeft.put(\"y\",\n bounds.getUpperLeft().getY().doubleValue());\n\n boundsObject.put(\"lowerRight\",\n lowerRight);\n boundsObject.put(\"upperLeft\",\n upperLeft);\n\n return boundsObject;\n }\n\n return new JSONObject();\n }",
"public static String padOrTrim(String str, int num) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int leng = str.length();\r\n if (leng < num) {\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < num - leng; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n } else if (leng > num) {\r\n return str.substring(0, num);\r\n } else {\r\n return str;\r\n }\r\n }",
"private void parse(String header)\n {\n ArrayList<String> list = new ArrayList<String>(4);\n StringBuilder sb = new StringBuilder();\n int index = 1;\n while (index < header.length())\n {\n char c = header.charAt(index++);\n if (Character.isDigit(c))\n {\n sb.append(c);\n }\n else\n {\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n sb.setLength(0);\n }\n }\n }\n\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n }\n\n m_id = list.get(0);\n m_sequence = Integer.parseInt(list.get(1));\n m_type = Integer.valueOf(list.get(2));\n if (list.size() > 3)\n {\n m_subtype = Integer.parseInt(list.get(3));\n }\n }",
"public static String chomp(String s) {\r\n if(s.length() == 0)\r\n return s;\r\n int l_1 = s.length() - 1;\r\n if (s.charAt(l_1) == '\\n') {\r\n return s.substring(0, l_1);\r\n }\r\n return s;\r\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 }",
"public static String[] tokenizeUnquoted(String s) {\r\n List tokens = new LinkedList();\r\n int first = 0;\r\n while (first < s.length()) {\r\n first = skipWhitespace(s, first);\r\n int last = scanToken(s, first);\r\n if (first < last) {\r\n tokens.add(s.substring(first, last));\r\n }\r\n first = last;\r\n }\r\n return (String[])tokens.toArray(new String[tokens.size()]);\r\n }",
"public Diff compare(File f1, File f2) throws Exception {\n\t\treturn this.compare(getCtType(f1), getCtType(f2));\n\t}"
] |
Flush output streams. | [
"private void flushOutput() throws IOException {\n outStream.flush();\n outWriter.completeLine();\n errStream.flush();\n errWriter.completeLine();\n }"
] | [
"public void setShowOutput(String mode) {\n try {\n this.outputMode = OutputMode.valueOf(mode.toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n throw new IllegalArgumentException(\"showOutput accepts any of: \"\n + Arrays.toString(OutputMode.values()) + \", value is not valid: \" + mode);\n }\n }",
"public static JmsDestinationType getTypeFromClass(String aClass)\n {\n if (StringUtils.equals(aClass, \"javax.jms.Queue\") || StringUtils.equals(aClass, \"javax.jms.QueueConnectionFactory\"))\n {\n return JmsDestinationType.QUEUE;\n }\n else if (StringUtils.equals(aClass, \"javax.jms.Topic\") || StringUtils.equals(aClass, \"javax.jms.TopicConnectionFactory\"))\n {\n return JmsDestinationType.TOPIC;\n }\n else\n {\n return null;\n }\n }",
"public void get( int row , int col , Complex_F64 output ) {\n ops.get(mat,row,col,output);\n }",
"public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) {\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path(\"_find\").build();\n return this.query(uri, query, classOfT);\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addBooleanFilter(String attribute, Boolean value) {\n booleanFilterMap.put(attribute, value);\n rebuildQueryFacetFilters();\n return this;\n }",
"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 nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }",
"synchronized void removeUserProfile(String id) {\n\n if (id == null) return;\n final String tableName = Table.USER_PROFILES.getName();\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tableName, \"_id = ?\", new String[]{id});\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing user profile from \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n }"
] |
Processes the template for all column definitions of the current table.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void forAllColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curTableDef.getColumns(); it.hasNext(); )\r\n {\r\n _curColumnDef = (ColumnDef)it.next();\r\n generate(template);\r\n }\r\n _curColumnDef = null;\r\n }"
] | [
"private GVRCursorController getUniqueControllerId(int deviceId) {\n GVRCursorController controller = controllerIds.get(deviceId);\n if (controller != null) {\n return controller;\n }\n return null;\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 }",
"private static void listHierarchy(Task task, String indent)\n {\n for (Task child : task.getChildTasks())\n {\n System.out.println(indent + \"Task: \" + child.getName() + \"\\t\" + child.getStart() + \"\\t\" + child.getFinish());\n listHierarchy(child, indent + \" \");\n }\n }",
"public static Chart getTrajectoryChart(String title, Trajectory t){\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[t.size()];\n\t\t double[] yData = new double[t.size()];\n\t\t for(int i = 0; i < t.size(); i++){\n\t\t \txData[i] = t.get(i).x;\n\t\t \tyData[i] = t.get(i).y;\n\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(title, \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\n\t\t return chart;\n\t\t //Show it\n\t\t // SwingWrapper swr = new SwingWrapper(chart);\n\t\t // swr.displayChart();\n\t\t} \n\t\treturn null;\n\t}",
"public Deployment setServerGroups(final Collection<String> serverGroups) {\n this.serverGroups.clear();\n this.serverGroups.addAll(serverGroups);\n return this;\n }",
"public void createInsertionSql(Database model, Platform platform, Writer writer) throws IOException\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n writer.write(platform.getInsertSql(model, (DynaBean)it.next()));\r\n if (it.hasNext())\r\n {\r\n writer.write(\"\\n\");\r\n }\r\n }\r\n }",
"public final void cancelOld(\n final long starttimeThreshold, final long checkTimeThreshold, final String message) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.and(\n builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING),\n builder.or(\n builder.lessThan(root.get(\"entry\").get(\"startTime\"), starttimeThreshold),\n builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold))\n )\n ));\n update.set(root.get(\"status\"), PrintJobStatus.Status.CANCELLED);\n update.set(root.get(\"error\"), message);\n getSession().createQuery(update).executeUpdate();\n }",
"public String haikunate() {\n if (tokenHex) {\n tokenChars = \"0123456789abcdef\";\n }\n\n String adjective = randomString(adjectives);\n String noun = randomString(nouns);\n\n StringBuilder token = new StringBuilder();\n if (tokenChars != null && tokenChars.length() > 0) {\n for (int i = 0; i < tokenLength; i++) {\n token.append(tokenChars.charAt(random.nextInt(tokenChars.length())));\n }\n }\n\n return Stream.of(adjective, noun, token.toString())\n .filter(s -> s != null && !s.isEmpty())\n .collect(joining(delimiter));\n }",
"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 }"
] |
Returns the response error stream, handling the case when it contains gzipped data.
@return gzip decoded (if needed) error stream or null | [
"private InputStream getErrorStream() {\n InputStream errorStream = this.connection.getErrorStream();\n if (errorStream != null) {\n final String contentEncoding = this.connection.getContentEncoding();\n if (contentEncoding != null && contentEncoding.equalsIgnoreCase(\"gzip\")) {\n try {\n errorStream = new GZIPInputStream(errorStream);\n } catch (IOException e) {\n // just return the error stream as is\n }\n }\n }\n\n return errorStream;\n }"
] | [
"public void show() {\n if (!(container instanceof RootPanel)) {\n if (!(container instanceof MaterialDialog)) {\n container.getElement().getStyle().setPosition(Style.Position.RELATIVE);\n }\n div.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);\n }\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.HIDDEN);\n }\n if (type == LoaderType.CIRCULAR) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.LOADER_WRAPPER);\n div.add(preLoader);\n } else if (type == LoaderType.PROGRESS) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.PROGRESS_WRAPPER);\n progress.getElement().getStyle().setProperty(\"margin\", \"auto\");\n div.add(progress);\n }\n container.add(div);\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 }",
"private void processGeneratedProperties(\n\t\t\tSerializable id,\n\t\t\tObject entity,\n\t\t\tObject[] state,\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tGenerationTiming matchTiming) {\n\n\t\tTuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\t\tsaveSharedTuple( entity, tuple, session );\n\n\t\tif ( tuple == null || tuple.getSnapshot().isEmpty() ) {\n\t\t\tthrow log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );\n\t\t}\n\n\t\tint propertyIndex = -1;\n\t\tfor ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {\n\t\t\tpropertyIndex++;\n\t\t\tfinal ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();\n\t\t\tif ( isReadRequired( valueGeneration, matchTiming ) ) {\n\t\t\t\tObject hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( \"\", propertyIndex ), session, entity );\n\t\t\t\tstate[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );\n\t\t\t\tsetPropertyValue( entity, propertyIndex, state[propertyIndex] );\n\t\t\t}\n\t\t}\n\t}",
"private int calculateColor(float angle) {\n\t\tfloat unit = (float) (angle / (2 * Math.PI));\n\t\tif (unit < 0) {\n\t\t\tunit += 1;\n\t\t}\n\n\t\tif (unit <= 0) {\n\t\t\tmColor = COLORS[0];\n\t\t\treturn COLORS[0];\n\t\t}\n\t\tif (unit >= 1) {\n\t\t\tmColor = COLORS[COLORS.length - 1];\n\t\t\treturn COLORS[COLORS.length - 1];\n\t\t}\n\n\t\tfloat p = unit * (COLORS.length - 1);\n\t\tint i = (int) p;\n\t\tp -= i;\n\n\t\tint c0 = COLORS[i];\n\t\tint c1 = COLORS[i + 1];\n\t\tint a = ave(Color.alpha(c0), Color.alpha(c1), p);\n\t\tint r = ave(Color.red(c0), Color.red(c1), p);\n\t\tint g = ave(Color.green(c0), Color.green(c1), p);\n\t\tint b = ave(Color.blue(c0), Color.blue(c1), p);\n\n\t\tmColor = Color.argb(a, r, g, b);\n\t\treturn Color.argb(a, r, g, b);\n\t}",
"private void expireDevices() {\n long now = System.currentTimeMillis();\n // Make a copy so we don't have to worry about concurrent modification.\n Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices);\n for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) {\n if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) {\n devices.remove(entry.getKey());\n deliverLostAnnouncement(entry.getValue());\n }\n }\n if (devices.isEmpty()) {\n firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device.\n }\n }",
"public List<String> uuids(long count) {\n final URI uri = new URIBase(clientUri).path(\"_uuids\").query(\"count\", count).build();\n final JsonObject json = get(uri, JsonObject.class);\n return getGson().fromJson(json.get(\"uuids\").toString(), DeserializationTypes.STRINGS);\n }",
"public String getUniformDescriptor(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate.getUniformDescriptor();\n }",
"public void setSeed(String randomSeed) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) {\n String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED());\n if (!userProperty.equals(randomSeed)) {\n log(\"Ignoring seed attribute because it is overridden by user properties.\", Project.MSG_WARN);\n }\n } else if (!Strings.isNullOrEmpty(randomSeed)) {\n this.random = randomSeed;\n }\n }",
"private final void handleHttpWorkerResponse(\n ResponseOnSingeRequest respOnSingleReq) throws Exception {\n // Successful response from GenericAsyncHttpWorker\n\n // Jeff 20310411: use generic response\n\n String responseContent = respOnSingleReq.getResponseBody();\n response.setResponseContent(respOnSingleReq.getResponseBody());\n\n /**\n * Poller logic if pollable: check if need to poll/ or already complete\n * 1. init poller data and HttpPollerProcessor 2. check if task\n * complete, if not, send the request again.\n */\n if (request.isPollable()) {\n boolean scheduleNextPoll = false;\n boolean errorFindingUuid = false;\n\n // set JobId of the poller\n if (!pollerData.isUuidHasBeenSet()) {\n String jobId = httpPollerProcessor\n .getUuidFromResponse(respOnSingleReq);\n\n if (jobId.equalsIgnoreCase(PcConstants.NA)) {\n errorFindingUuid = true;\n pollingErrorCount++;\n logger.error(\"!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. \"\n\n + \"DEBUG: REGEX_JOBID: \"\n + httpPollerProcessor.getJobIdRegex()\n\n + \"RESPONSE: \"\n + respOnSingleReq.getResponseBody()\n + \" polling Error count\"\n + pollingErrorCount\n + \" at \" + PcDateUtils.getNowDateTimeStrStandard());\n // fail fast\n pollerData.setError(true);\n pollerData.setComplete(true);\n\n } else {\n pollerData.setJobIdAndMarkHasBeenSet(jobId);\n // if myResponse has other errors, mark poll data as error.\n pollerData.setError(httpPollerProcessor\n .ifThereIsErrorInResponse(respOnSingleReq));\n }\n\n }\n if (!pollerData.isError()) {\n\n pollerData\n .setComplete(httpPollerProcessor\n .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));\n pollerData.setCurrentProgress(httpPollerProcessor\n .getProgressFromResponse(respOnSingleReq));\n }\n\n // poll again only if not complete AND no error; 2015: change to\n // over limit\n scheduleNextPoll = !pollerData.isComplete()\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError());\n\n // Schedule next poll and return. (not to answer back to manager yet\n // )\n if (scheduleNextPoll\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError())) {\n\n pollMessageCancellable = getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(httpPollerProcessor\n .getPollIntervalMillis(),\n TimeUnit.MILLISECONDS), getSelf(),\n OperationWorkerMsgType.POLL_PROGRESS,\n getContext().system().dispatcher(), getSelf());\n\n logger.info(\"\\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND\"\n + String.format(\"PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent,\n PcDateUtils.getNowDateTimeStrStandard()));\n\n String responseContentNew = errorFindingUuid ? responseContent\n + \"_PollingErrorCount:\" + pollingErrorCount\n : responseContent;\n logger.info(responseContentNew);\n // log\n pollerData.getPollingHistoryMap().put(\n \"RECV_\" + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\"PROGRESS:%.3f, BODY:%s\",\n pollerData.getCurrentProgress(),\n responseContent));\n return;\n } else {\n pollerData\n .getPollingHistoryMap()\n .put(\"RECV_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\n \"POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent));\n }\n\n }// end if (request.isPollable())\n\n reply(respOnSingleReq.isFailObtainResponse(),\n respOnSingleReq.getErrorMessage(),\n respOnSingleReq.getStackTrace(),\n respOnSingleReq.getStatusCode(),\n respOnSingleReq.getStatusCodeInt(),\n respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());\n\n }"
] |
Deletes a specific, existing project status update.
Returns an empty data record.
@param projectStatus The project status update to delete.
@return Request object | [
"public ItemRequest<ProjectStatus> delete(String projectStatus) {\n\n String path = String.format(\"/project_statuses/%s\", projectStatus);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"DELETE\");\n }"
] | [
"public static String retrieveVendorId() {\n if (MapboxTelemetry.applicationContext == null) {\n return updateVendorId();\n }\n\n SharedPreferences sharedPreferences = obtainSharedPreferences(MapboxTelemetry.applicationContext);\n String mapboxVendorId = sharedPreferences.getString(MAPBOX_SHARED_PREFERENCE_KEY_VENDOR_ID, \"\");\n if (TelemetryUtils.isEmpty(mapboxVendorId)) {\n mapboxVendorId = TelemetryUtils.updateVendorId();\n }\n return mapboxVendorId;\n }",
"public static String getContext(final PObject[] objs) {\n StringBuilder result = new StringBuilder(\"(\");\n boolean first = true;\n for (PObject obj: objs) {\n if (!first) {\n result.append('|');\n }\n first = false;\n result.append(obj.getCurrentPath());\n }\n result.append(')');\n return result.toString();\n }",
"private List<Pair<Integer, Double>> integerPixelCoordinatesAndWeights(double d, int numPixels) {\n if (d <= 0.5) return Collections.singletonList(new Pair<>(0, 1.0));\n else if (d >= numPixels - 0.5) return Collections.singletonList(new Pair<>(numPixels - 1, 1.0));\n else {\n double shifted = d - 0.5;\n double floor = Math.floor(shifted);\n double floorWeight = 1 - (shifted - floor);\n double ceil = Math.ceil(shifted);\n double ceilWeight = 1 - floorWeight;\n assert (floorWeight + ceilWeight == 1);\n return Arrays.asList(new Pair<>((int) floor, floorWeight), new Pair<>((int) ceil, ceilWeight));\n }\n }",
"private void writeTasks() throws JAXBException\n {\n Tasks tasks = m_factory.createTasks();\n m_plannerProject.setTasks(tasks);\n List<net.sf.mpxj.planner.schema.Task> taskList = tasks.getTask();\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task, taskList);\n }\n }",
"public static void mlock(Pointer addr, long len) {\n\n int res = Delegate.mlock(addr, new NativeLong(len));\n if(res != 0) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Mlock failed probably because of insufficient privileges, errno:\"\n + errno.strerror() + \", return value:\" + res);\n }\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"Mlock successfull\");\n\n }\n\n }",
"protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) {\n Object returnObject = invokeJavascript(function);\n if (returnObject instanceof JSObject) {\n try {\n Constructor<T> constructor = returnType.getConstructor(JSObject.class);\n return constructor.newInstance((JSObject) returnObject);\n } catch (Exception ex) {\n throw new IllegalStateException(ex);\n }\n } else {\n return (T) returnObject;\n }\n }",
"@Override\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n final ServletRequest r1 = request;\n chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {\n @SuppressWarnings(\"unchecked\")\n public void setHeader(String name, String value) {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n \n if (r1.getAttribute(\"com.groupon.odo.removeHeaders\") != null)\n headersToRemove = (ArrayList<String>) r1.getAttribute(\"com.groupon.odo.removeHeaders\");\n\n boolean removeHeader = false;\n // need to loop through removeHeaders to make things case insensitive\n for (String headerToRemove : headersToRemove) {\n if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {\n removeHeader = true;\n break;\n }\n }\n\n if (! removeHeader) {\n super.setHeader(name, value);\n }\n }\n });\n }",
"public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException {\n\n // Determine the patch id to rollback\n String patchId;\n final List<String> oneOffs = modification.getPatchIDs();\n if (oneOffs.isEmpty()) {\n patchId = modification.getCumulativePatchID();\n if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) {\n throw PatchLogger.ROOT_LOGGER.noPatchesApplied();\n }\n } else {\n patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1);\n }\n return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification);\n }",
"private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) {\n return buildFilesStream\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath()))\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath()))\n .map(org.jfrog.hudson.pipeline.types.File::new)\n .distinct()\n .collect(Collectors.toList());\n }"
] |
returns a Logger.
@param loggerName the name of the Logger
@return Logger the returned Logger | [
"public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }"
] | [
"public void addColumn(ColumnDef columnDef)\r\n {\r\n columnDef.setOwner(this);\r\n _columns.put(columnDef.getName(), columnDef);\r\n }",
"private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }",
"public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }",
"private void writeResources()\n {\n Resources resources = m_factory.createResources();\n m_plannerProject.setResources(resources);\n List<net.sf.mpxj.planner.schema.Resource> resourceList = resources.getResource();\n for (Resource mpxjResource : m_projectFile.getResources())\n {\n net.sf.mpxj.planner.schema.Resource plannerResource = m_factory.createResource();\n resourceList.add(plannerResource);\n writeResource(mpxjResource, plannerResource);\n }\n }",
"public static base_response update(nitro_service client, nsrpcnode resource) throws Exception {\n\t\tnsrpcnode updateresource = new nsrpcnode();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.srcip = resource.srcip;\n\t\tupdateresource.secure = resource.secure;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public BoundRequestBuilder createRequest()\n throws HttpRequestCreateException {\n BoundRequestBuilder builder = null;\n\n getLogger().debug(\"AHC completeUrl \" + requestUrl);\n\n try {\n\n switch (httpMethod) {\n case GET:\n builder = client.prepareGet(requestUrl);\n break;\n case POST:\n builder = client.preparePost(requestUrl);\n break;\n case PUT:\n builder = client.preparePut(requestUrl);\n break;\n case HEAD:\n builder = client.prepareHead(requestUrl);\n break;\n case OPTIONS:\n builder = client.prepareOptions(requestUrl);\n break;\n case DELETE:\n builder = client.prepareDelete(requestUrl);\n break;\n default:\n break;\n }\n\n PcHttpUtils.addHeaders(builder, this.httpHeaderMap);\n if (!Strings.isNullOrEmpty(postData)) {\n builder.setBody(postData);\n String charset = \"\";\n if (null!=this.httpHeaderMap) {\n charset = this.httpHeaderMap.get(\"charset\");\n }\n if(!Strings.isNullOrEmpty(charset)) {\n builder.setBodyEncoding(charset);\n }\n }\n\n } catch (Exception t) {\n throw new HttpRequestCreateException(\n \"Error in creating request in Httpworker. \"\n + \" If BoundRequestBuilder is null. Then fail to create.\",\n t);\n }\n\n return builder;\n\n }",
"int acquireTransaction(@NotNull final Thread thread) {\n try (CriticalSection ignored = criticalSection.enter()) {\n final int currentThreadPermits = getThreadPermitsToAcquire(thread);\n waitForPermits(thread, currentThreadPermits > 0 ? nestedQueue : regularQueue, 1, currentThreadPermits);\n }\n return 1;\n }",
"protected void reportStorageOpTime(long startNs) {\n if(streamStats != null) {\n streamStats.reportStreamingScan(operation);\n streamStats.reportStorageTime(operation,\n Utils.elapsedTimeNs(startNs, System.nanoTime()));\n }\n }",
"private void handleApplicationUpdateRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Update Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\t\n\t\tlogger.trace(\"Application Update Request from Node \" + nodeId);\n\t\tUpdateState updateState = UpdateState.getUpdateState(incomingMessage.getMessagePayloadByte(0));\n\t\t\n\t\tswitch (updateState) {\n\t\t\tcase NODE_INFO_RECEIVED:\n\t\t\t\tlogger.debug(\"Application update request, node information received.\");\t\t\t\n\t\t\t\tint length = incomingMessage.getMessagePayloadByte(2);\n\t\t\t\tZWaveNode node = getNode(nodeId);\n\t\t\t\t\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\tfor (int i = 6; i < length + 3; i++) {\n\t\t\t\t\tint data = incomingMessage.getMessagePayloadByte(i);\n\t\t\t\t\tif(data == 0xef ) {\n\t\t\t\t\t\t// TODO: Implement control command classes\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.debug(String.format(\"Adding command class 0x%02X to the list of supported command classes.\", data));\n\t\t\t\t\tZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(data, node, this);\n\t\t\t\t\tif (commandClass != null)\n\t\t\t\t\t\tnode.addCommandClass(commandClass);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// advance node stage.\n\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t\n\t\t\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase NODE_INFO_REQ_FAILED:\n\t\t\t\tlogger.debug(\"Application update request, Node Info Request Failed, re-request node info.\");\n\t\t\t\t\n\t\t\t\tSerialMessage requestInfoMessage = this.lastSentMessage;\n\t\t\t\t\n\t\t\t\tif (requestInfoMessage.getMessageClass() != SerialMessage.SerialMessageClass.RequestNodeInfo) {\n\t\t\t\t\tlogger.warn(\"Got application update request without node info request, ignoring.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\tif (--requestInfoMessage.attempts >= 0) {\n\t\t\t\t\tlogger.error(\"Got Node Info Request Failed while sending this serial message. Requeueing\");\n\t\t\t\t\tthis.enqueue(requestInfoMessage);\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tlogger.warn(\"Node Info Request Failed 3x. Discarding message: {}\", lastSentMessage.toString());\n\t\t\t\t}\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(String.format(\"TODO: Implement Application Update Request Handling of %s (0x%02X).\", updateState.getLabel(), updateState.getKey()));\n\t\t}\n\t}"
] |
Wait for the read side to close. Used when the writer needs to know when
the reader finishes consuming a message. | [
"public void await() {\n boolean intr = false;\n final Object lock = this.lock;\n try {\n synchronized (lock) {\n while (! readClosed) {\n try {\n lock.wait();\n } catch (InterruptedException e) {\n intr = true;\n }\n }\n }\n } finally {\n if (intr) {\n Thread.currentThread().interrupt();\n }\n }\n }"
] | [
"public void reformatFile() throws IOException\n {\n List<LineNumberPosition> lineBrokenPositions = new ArrayList<>();\n List<String> brokenLines = breakLines(lineBrokenPositions);\n emitFormatted(brokenLines, lineBrokenPositions);\n }",
"private Map<String, String> getLocaleProperties() {\n\n if (m_localeProperties == null) {\n m_localeProperties = CmsCollectionsGenericWrapper.createLazyMap(\n new CmsProperty.CmsPropertyLocaleTransformer(m_properties, m_locale));\n }\n return m_localeProperties;\n }",
"public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }",
"@Override\n public void setValue(Boolean value, boolean fireEvents) {\n boolean oldValue = getValue();\n if (value) {\n input.getElement().setAttribute(\"checked\", \"true\");\n } else {\n input.getElement().removeAttribute(\"checked\");\n }\n\n if (fireEvents && oldValue != value) {\n ValueChangeEvent.fire(this, getValue());\n }\n }",
"private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }",
"public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }",
"public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\n }",
"@RequestMapping(value = \"/scripts\", method = RequestMethod.GET)\n public String scriptView(Model model) throws Exception {\n return \"script\";\n }",
"public static int[] longestWord(LinkedList<AT_Row> rows, int colNumbers){\r\n\t\tif(rows==null){\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif(rows.size()==0){\r\n\t\t\treturn new int[0];\r\n\t\t}\r\n\r\n\t\tint[] ret = new int[colNumbers];\r\n\r\n\t\tfor(AT_Row row : rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT) {\r\n\t\t\t\tLinkedList<AT_Cell> cells = row.getCells();\r\n\r\n\t\t\t\tfor(int i=0; i<cells.size(); i++) {\r\n\t\t\t\t\tif(cells.get(i).getContent()!=null){\r\n\t\t\t\t\t\tString[] ar = StringUtils.split(Object_To_StrBuilder.convert(cells.get(i).getContent()).toString());\r\n\t\t\t\t\t\tfor(int k=0; k<ar.length; k++){\r\n\t\t\t\t\t\t\tint count = ar[k].length() + cells.get(i).getContext().getPaddingLeft() + cells.get(i).getContext().getPaddingRight();\r\n\t\t\t\t\t\t\tif(count>ret[i]){\r\n\t\t\t\t\t\t\t\tret[i] = count;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn ret;\r\n\t}"
] |
Load a model to attach to the avatar
@param avatarResource resource with avatar model
@param attachBone name of bone to attach model to | [
"public void loadModel(GVRAndroidResource avatarResource, String attachBone)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n GVRSceneObject boneObject;\n int boneIndex;\n\n if (mSkeleton == null)\n {\n throw new IllegalArgumentException(\"Cannot attach model to avatar - there is no skeleton\");\n }\n boneIndex = mSkeleton.getBoneIndex(attachBone);\n if (boneIndex < 0)\n {\n throw new IllegalArgumentException(attachBone + \" is not a bone in the avatar skeleton\");\n }\n boneObject = mSkeleton.getBone(boneIndex);\n if (boneObject == null)\n {\n throw new IllegalArgumentException(attachBone +\n \" does not have a bone object in the avatar skeleton\");\n }\n boneObject.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }"
] | [
"public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }",
"public static void showUserInfo(CmsSessionInfo session) {\n\n final Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide);\n CmsUserInfoDialog dialog = new CmsUserInfoDialog(session, new Runnable() {\n\n public void run() {\n\n window.close();\n }\n\n });\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SHOW_USER_0));\n window.setContent(dialog);\n A_CmsUI.get().addWindow(window);\n }",
"private Observable<Indexable> processFaultedTaskAsync(final TaskGroupEntry<TaskItem> faultedEntry,\n final Throwable throwable,\n final InvocationContext context) {\n markGroupAsCancelledIfTerminationStrategyIsIPTC();\n reportError(faultedEntry, throwable);\n if (isRootEntry(faultedEntry)) {\n if (shouldPropagateException(throwable)) {\n return toErrorObservable(throwable);\n }\n return Observable.empty();\n } else if (shouldPropagateException(throwable)) {\n return Observable.concatDelayError(invokeReadyTasksAsync(context), toErrorObservable(throwable));\n } else {\n return invokeReadyTasksAsync(context);\n }\n }",
"public static base_responses clear(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"protected <T> T getDatamodelObjectFromResponse(JsonNode response, List<String> path, Class<T> targetClass) throws JsonProcessingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"The API response is null\");\n\t\t}\n\t\tJsonNode currentNode = response;\n\t\tfor(String field : path) {\n\t\t\tif (!currentNode.has(field)) {\n\t\t\t\tthrow new JsonMappingException(\"Field '\"+field+\"' not found in API response.\");\n\t\t\t}\n\t\t\tcurrentNode = currentNode.path(field);\n\t\t}\n\t\treturn mapper.treeToValue(currentNode, targetClass);\n\t}",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) {\n this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY));\n }\n\n if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) {\n List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY);\n if(urls.size() > 0) {\n setHttpBootstrapURL(urls.get(0));\n }\n }\n\n if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) {\n setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY,\n maxR2ConnectionPoolSize));\n }\n\n if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY))\n this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs),\n TimeUnit.MILLISECONDS);\n\n // By default, make all the timeouts equal to routing timeout\n timeoutConfig = new TimeoutConfig(timeoutMs, false);\n\n if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE,\n props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE,\n props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) {\n long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY);\n timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs);\n // By default, use the same thing for getVersions() also\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs);\n }\n\n // of course, if someone overrides it, we will respect that\n if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE,\n props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE,\n props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY))\n timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY));\n\n }",
"public static vpnsessionaction[] get(nitro_service service) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tvpnsessionaction[] response = (vpnsessionaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ComplexDouble divi(ComplexDouble c, ComplexDouble result) {\n double d = c.r * c.r + c.i * c.i;\n double newR = (r * c.r + i * c.i) / d;\n double newI = (i * c.r - r * c.i) / d;\n result.r = newR;\n result.i = newI;\n return result;\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 }"
] |
Unmarshals the XML content and adds the file to the bundle files.
@throws CmsException thrown if reading the file or unmarshaling fails. | [
"private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }"
] | [
"private void recurseAndAddFiles(GraphRewrite event, FileService fileService, WindupJavaConfigurationService javaConfigurationService, FileModel file)\n {\n if (javaConfigurationService.checkIfIgnored(event, file))\n return;\n\n String filePath = file.getFilePath();\n File fileReference = new File(filePath);\n Long directorySize = new Long(0);\n\n if (fileReference.isDirectory())\n {\n File[] subFiles = fileReference.listFiles();\n if (subFiles != null)\n {\n for (File reference : subFiles)\n {\n FileModel subFile = fileService.createByFilePath(file, reference.getAbsolutePath());\n recurseAndAddFiles(event, fileService, javaConfigurationService, subFile);\n if (subFile.isDirectory())\n {\n directorySize = directorySize + subFile.getDirectorySize();\n }\n else\n {\n directorySize = directorySize + subFile.getSize();\n }\n }\n }\n file.setDirectorySize(directorySize);\n }\n }",
"public static String toXml(DeploymentDescriptor descriptor) {\n try {\n\n Marshaller marshaller = getContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, \"http://www.jboss.org/jbpm deployment-descriptor.xsd\");\n marshaller.setSchema(schema);\n StringWriter stringWriter = new StringWriter();\n\n // clone the object and cleanup transients\n DeploymentDescriptor clone = ((DeploymentDescriptorImpl) descriptor).clearClone();\n\n marshaller.marshal(clone, stringWriter);\n String output = stringWriter.toString();\n\n return output;\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to generate xml from deployment descriptor\", e);\n }\n }",
"public void scrollOnce() {\n PagerAdapter adapter = getAdapter();\n int currentItem = getCurrentItem();\n int totalCount;\n if (adapter == null || (totalCount = adapter.getCount()) <= 1) {\n return;\n }\n\n int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;\n if (nextItem < 0) {\n if (isCycle) {\n setCurrentItem(totalCount - 1, isBorderAnimation);\n }\n } else if (nextItem == totalCount) {\n if (isCycle) {\n setCurrentItem(0, isBorderAnimation);\n }\n } else {\n setCurrentItem(nextItem, true);\n }\n }",
"private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) {\n\t\tfor (StyleFilter styleFilter : styles) {\n\t\t\tif (styleFilter.getFilter().evaluate(feature)) {\n\t\t\t\treturn styleFilter;\n\t\t\t}\n\t\t}\n\t\treturn new StyleFilterImpl();\n\t}",
"protected TypeReference<?> getBeanPropertyType(Class<?> clazz,\r\n\t\t\tString propertyName, TypeReference<?> originalType) {\r\n\t\tTypeReference<?> propertyDestinationType = null;\r\n\t\tif (beanDestinationPropertyTypeProvider != null) {\r\n\t\t\tpropertyDestinationType = beanDestinationPropertyTypeProvider\r\n\t\t\t\t\t.getPropertyType(clazz, propertyName, originalType);\r\n\t\t}\r\n\t\tif (propertyDestinationType == null) {\r\n\t\t\tpropertyDestinationType = originalType;\r\n\t\t}\r\n\t\treturn propertyDestinationType;\r\n\t}",
"@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}",
"@SuppressWarnings(\"unchecked\")\n public Multimap<String, Processor> getAllRequiredAttributes() {\n Multimap<String, Processor> requiredInputs = HashMultimap.create();\n for (ProcessorGraphNode root: this.roots) {\n final BiMap<String, String> inputMapper = root.getInputMapper();\n for (String attr: inputMapper.keySet()) {\n requiredInputs.put(attr, root.getProcessor());\n }\n final Object inputParameter = root.getProcessor().createInputParameter();\n if (inputParameter instanceof Values) {\n continue;\n } else if (inputParameter != null) {\n final Class<?> inputParameterClass = inputParameter.getClass();\n final Set<String> requiredAttributesDefinedInInputParameter =\n getAttributeNames(inputParameterClass,\n FILTER_ONLY_REQUIRED_ATTRIBUTES);\n for (String attName: requiredAttributesDefinedInInputParameter) {\n try {\n if (inputParameterClass.getField(attName).getType() == Values.class) {\n continue;\n }\n } catch (NoSuchFieldException e) {\n throw new RuntimeException(e);\n }\n String mappedName = ProcessorUtils.getInputValueName(\n root.getProcessor().getInputPrefix(),\n inputMapper, attName);\n requiredInputs.put(mappedName, root.getProcessor());\n }\n }\n }\n\n return requiredInputs;\n }",
"MACAddressSegment[] toEUISegments(boolean extended) {\n\t\tIPv6AddressSegment seg0, seg1, seg2, seg3;\n\t\tint start = addressSegmentIndex;\n\t\tint segmentCount = getSegmentCount();\n\t\tint segmentIndex;\n\t\tif(start < 4) {\n\t\t\tstart = 0;\n\t\t\tsegmentIndex = 4 - start;\n\t\t} else {\n\t\t\tstart -= 4;\n\t\t\tsegmentIndex = 0;\n\t\t}\n\t\tint originalSegmentIndex = segmentIndex;\n\t\tseg0 = (start == 0 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg1 = (start <= 1 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg2 = (start <= 2 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg3 = (start <= 3 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tint macSegCount = (segmentIndex - originalSegmentIndex) << 1;\n\t\tif(!extended) {\n\t\t\tmacSegCount -= 2;\n\t\t}\n\t\tif((seg1 != null && !seg1.matchesWithMask(0xff, 0xff)) || (seg2 != null && !seg2.matchesWithMask(0xfe00, 0xff00)) || macSegCount == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\tMACAddressSegment ZERO_SEGMENT = creator.createSegment(0);\n\t\tMACAddressSegment newSegs[] = creator.createSegmentArray(macSegCount);\n\t\tint macStartIndex = 0;\n\t\tif(seg0 != null) {\n\t\t\tseg0.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t//toggle the u/l bit\n\t\t\tMACAddressSegment macSegment0 = newSegs[0];\n\t\t\tint lower0 = macSegment0.getSegmentValue();\n\t\t\tint upper0 = macSegment0.getUpperSegmentValue();\n\t\t\tint mask2ndBit = 0x2;\n\t\t\tif(!macSegment0.matchesWithMask(mask2ndBit & lower0, mask2ndBit)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t//you can use matches with mask\n\t\t\tlower0 ^= mask2ndBit;//flip the universal/local bit\n\t\t\tupper0 ^= mask2ndBit;\n\t\t\tnewSegs[0] = creator.createSegment(lower0, upper0, null);\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg1 != null) {\n\t\t\tseg1.getSplitSegments(newSegs, macStartIndex, creator); //a ff fe b\n\t\t\tif(!extended) {\n\t\t\t\tnewSegs[macStartIndex + 1] = ZERO_SEGMENT;\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg2 != null) {\n\t\t\tif(!extended) {\n\t\t\t\tif(seg1 != null) {\n\t\t\t\t\tmacStartIndex -= 2;\n\t\t\t\t\tMACAddressSegment first = newSegs[macStartIndex];\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = first;\n\t\t\t\t} else {\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = ZERO_SEGMENT;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg3 != null) {\n\t\t\tseg3.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t}\n\t\treturn newSegs;\n\t}",
"public static appfwprofile_xmlvalidationurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_xmlvalidationurl_binding obj = new appfwprofile_xmlvalidationurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_xmlvalidationurl_binding response[] = (appfwprofile_xmlvalidationurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Add authentication information for the given host
@param host the host
@param credentials the credentials
@param authScheme the scheme for preemptive authentication (should be
<code>null</code> if adding authentication for a proxy server)
@param context the context in which the authentication information
should be saved | [
"private void addAuthentication(HttpHost host, Credentials credentials,\n AuthScheme authScheme, HttpClientContext context) {\n AuthCache authCache = context.getAuthCache();\n if (authCache == null) {\n authCache = new BasicAuthCache();\n context.setAuthCache(authCache);\n }\n \n CredentialsProvider credsProvider = context.getCredentialsProvider();\n if (credsProvider == null) {\n credsProvider = new BasicCredentialsProvider();\n context.setCredentialsProvider(credsProvider);\n }\n \n credsProvider.setCredentials(new AuthScope(host), credentials);\n \n if (authScheme != null) {\n authCache.put(host, authScheme);\n }\n }"
] | [
"public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }",
"public static String getVcsUrl(Map<String, String> env) {\n String url = env.get(\"SVN_URL\");\n if (StringUtils.isBlank(url)) {\n url = publicGitUrl(env.get(\"GIT_URL\"));\n }\n if (StringUtils.isBlank(url)) {\n url = env.get(\"P4PORT\");\n }\n return url;\n }",
"public static Logger getLogger(String className) {\n\t\tif (logType == null) {\n\t\t\tlogType = findLogType();\n\t\t}\n\t\treturn new Logger(logType.createLog(className));\n\t}",
"public CollectionRequest<User> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/users\", workspace);\n return new CollectionRequest<User>(this, User.class, path, \"GET\");\n }",
"private static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) {\n // since indy does not give us the runtime types\n // we produce first a dummy call site, which then changes the target to one,\n // that does the method selection including the the direct call to the \n // real method.\n MutableCallSite mc = new MutableCallSite(type);\n MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall);\n mc.setTarget(mh);\n return mc;\n }",
"private static int getPort(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Port) {\n Port port = (Port) q;\n if (port.value() > 0) {\n return port.value();\n }\n }\n }\n\n ServicePort servicePort = findQualifiedServicePort(service, qualifiers);\n if (servicePort != null) {\n return servicePort.getPort();\n }\n return 0;\n }",
"private static String getHostname() {\n if (Hostname == null) {\n try {\n Hostname = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n Hostname = \"default\";\n LOGGER.warn(\"Can not get current hostname\", e);\n }\n }\n return Hostname;\n }",
"public void setQueryExecuteTimeLimit(long queryExecuteTimeLimit, TimeUnit timeUnit) {\n\t\tthis.queryExecuteTimeLimitInMs = TimeUnit.MILLISECONDS.convert(queryExecuteTimeLimit, timeUnit);\n\t}",
"private static ResourceBundle tryBundle(String baseName, Locale locale, boolean wantBase) {\n\n I_CmsResourceBundle first = null; // The most specialized bundle.\n I_CmsResourceBundle last = null; // The least specialized bundle.\n\n List<String> bundleNames = CmsLocaleManager.getLocaleVariants(baseName, locale, true, true);\n for (String bundleName : bundleNames) {\n // break if we would try the base bundle, but we do not want it directly\n if (bundleName.equals(baseName) && !wantBase && (first == null)) {\n break;\n }\n I_CmsResourceBundle foundBundle = tryBundle(bundleName);\n if (foundBundle != null) {\n if (first == null) {\n first = foundBundle;\n }\n\n if (last != null) {\n last.setParent((ResourceBundle)foundBundle);\n }\n foundBundle.setLocale(locale);\n\n last = foundBundle;\n }\n }\n return (ResourceBundle)first;\n }"
] |
Closes all the producers in the pool | [
"public void close() {\n logger.info(\"Closing all sync producers\");\n if (sync) {\n for (SyncProducer p : syncProducers.values()) {\n p.close();\n }\n } else {\n for (AsyncProducer<V> p : asyncProducers.values()) {\n p.close();\n }\n }\n\n }"
] | [
"public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,\n zoneId);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n boolean first = true;\n Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());\n for(int initPartitionId: sortedInitPartitionIds) {\n if(!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n\n int runLength = idToRunLength.get(initPartitionId);\n if(runLength == 1) {\n sb.append(initPartitionId);\n } else {\n int endPartitionId = (initPartitionId + runLength - 1)\n % cluster.getNumberOfPartitions();\n sb.append(initPartitionId).append(\"-\").append(endPartitionId);\n }\n }\n sb.append(\"]\");\n\n return sb.toString();\n }",
"public void shutdown() {\n debugConnection = null;\n shuttingDown = true;\n try {\n if (serverSocket != null) {\n serverSocket.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }",
"public ParallelTaskBuilder prepareUdp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.UDP);\n cb.getUdpMeta().setCommand(command);\n return cb;\n }",
"public RedwoodConfiguration captureStdout(){\r\n tasks.add(new Runnable() { public void run() { Redwood.captureSystemStreams(true, false); } });\r\n return this;\r\n }",
"private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }",
"public void registerCollectionSizeGauge(\n\t\t\tCollectionSizeGauge collectionSizeGauge) {\n\t\tString name = createMetricName(LocalTaskExecutorService.class,\n\t\t\t\t\"queue-size\");\n\t\tmetrics.register(name, collectionSizeGauge);\n\t}",
"public static base_response add(nitro_service client, vpnclientlessaccesspolicy resource) throws Exception {\n\t\tvpnclientlessaccesspolicy addresource = new vpnclientlessaccesspolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\treturn addresource.add_resource(client);\n\t}",
"public List<DesignDocument> list() throws IOException {\r\n return db.getAllDocsRequestBuilder()\r\n .startKey(\"_design/\")\r\n .endKey(\"_design0\")\r\n .inclusiveEnd(false)\r\n .includeDocs(true)\r\n .build()\r\n .getResponse().getDocsAs(DesignDocument.class);\r\n }",
"public JaCoCoReportReader readJacocoReport(IExecutionDataVisitor executionDataVisitor, ISessionInfoVisitor sessionInfoStore) {\n if (jacocoExecutionData == null) {\n return this;\n }\n\n JaCoCoExtensions.logger().info(\"Analysing {}\", jacocoExecutionData);\n try (InputStream inputStream = new BufferedInputStream(new FileInputStream(jacocoExecutionData))) {\n if (useCurrentBinaryFormat) {\n ExecutionDataReader reader = new ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n } else {\n org.jacoco.previous.core.data.ExecutionDataReader reader = new org.jacoco.previous.core.data.ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n }\n } catch (IOException e) {\n throw new IllegalArgumentException(String.format(\"Unable to read %s\", jacocoExecutionData.getAbsolutePath()), e);\n }\n return this;\n }"
] |
Use this API to fetch auditnslogpolicy_systemglobal_binding resources of given name . | [
"public static auditnslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_systemglobal_binding obj = new auditnslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_systemglobal_binding response[] = (auditnslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private void merge(Map<String, NodeT> source, Map<String, NodeT> target) {\n for (Map.Entry<String, NodeT> entry : source.entrySet()) {\n String key = entry.getKey();\n if (!target.containsKey(key)) {\n target.put(key, entry.getValue());\n }\n }\n }",
"protected static boolean isOperatorLR( Symbol s ) {\n if( s == null )\n return false;\n\n switch( s ) {\n case ELEMENT_DIVIDE:\n case ELEMENT_TIMES:\n case ELEMENT_POWER:\n case RDIVIDE:\n case LDIVIDE:\n case TIMES:\n case POWER:\n case PLUS:\n case MINUS:\n case ASSIGN:\n return true;\n }\n return false;\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}",
"private void transform(File file, Source transformSource)\n throws TransformerConfigurationException, IOException, SAXException, TransformerException,\n ParserConfigurationException {\n\n Transformer transformer = m_transformerFactory.newTransformer(transformSource);\n transformer.setOutputProperty(OutputKeys.ENCODING, \"us-ascii\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\");\n String configDirPath = m_configDir.getAbsolutePath();\n configDirPath = configDirPath.replaceFirst(\"[/\\\\\\\\]$\", \"\");\n transformer.setParameter(\"configDir\", configDirPath);\n XMLReader reader = m_parserFactory.newSAXParser().getXMLReader();\n reader.setEntityResolver(NO_ENTITY_RESOLVER);\n\n Source source;\n\n if (file.exists()) {\n source = new SAXSource(reader, new InputSource(file.getCanonicalPath()));\n } else {\n source = new SAXSource(reader, new InputSource(new ByteArrayInputStream(DEFAULT_XML.getBytes(\"UTF-8\"))));\n }\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n Result target = new StreamResult(baos);\n transformer.transform(source, target);\n byte[] transformedConfig = baos.toByteArray();\n try (FileOutputStream output = new FileOutputStream(file)) {\n output.write(transformedConfig);\n }\n }",
"private ModelNode createCPUNode() throws OperationFailedException {\n ModelNode cpu = new ModelNode().setEmptyObject();\n cpu.get(ARCH).set(getProperty(\"os.arch\"));\n cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());\n return cpu;\n }",
"private void processClassMethods(XMLStreamWriter writer, Class<?> aClass, Set<Method> methodSet) throws XMLStreamException\n {\n Method[] methods = aClass.getDeclaredMethods();\n for (Method method : methods)\n {\n if (!methodSet.contains(method) && Modifier.isPublic(method.getModifiers()) && !Modifier.isInterface(method.getModifiers()))\n {\n if (Modifier.isStatic(method.getModifiers()))\n {\n // TODO Handle static methods here\n }\n else\n {\n String name = method.getName();\n String methodSignature = createMethodSignature(method);\n String fullJavaName = aClass.getCanonicalName() + \".\" + name + methodSignature;\n\n if (!ignoreMethod(fullJavaName))\n {\n //\n // Hide the original method\n //\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n\n writer.writeStartElement(\"attribute\");\n writer.writeAttribute(\"type\", \"System.ComponentModel.EditorBrowsableAttribute\");\n writer.writeAttribute(\"sig\", \"(Lcli.System.ComponentModel.EditorBrowsableState;)V\");\n writer.writeStartElement(\"parameter\");\n writer.writeCharacters(\"Never\");\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n\n //\n // Create a wrapper method\n //\n name = name.toUpperCase().charAt(0) + name.substring(1);\n\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeAttribute(\"modifiers\", \"public\");\n\n writer.writeStartElement(\"body\");\n\n for (int index = 0; index <= method.getParameterTypes().length; index++)\n {\n if (index < 4)\n {\n writer.writeEmptyElement(\"ldarg_\" + index);\n }\n else\n {\n writer.writeStartElement(\"ldarg_s\");\n writer.writeAttribute(\"argNum\", Integer.toString(index));\n writer.writeEndElement();\n }\n }\n\n writer.writeStartElement(\"callvirt\");\n writer.writeAttribute(\"class\", aClass.getName());\n writer.writeAttribute(\"name\", method.getName());\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeEndElement();\n\n if (!method.getReturnType().getName().equals(\"void\"))\n {\n writer.writeEmptyElement(\"ldnull\");\n writer.writeEmptyElement(\"pop\");\n }\n writer.writeEmptyElement(\"ret\");\n writer.writeEndElement();\n writer.writeEndElement();\n\n /*\n * The private method approach doesn't work... so\n * 3. Add EditorBrowsableAttribute (Never) to original methods\n * 4. Generate C Sharp and VB variants of the DLL to avid case-sensitivity issues\n * 5. Implement static method support?\n <attribute type=\"System.ComponentModel.EditorBrowsableAttribute\" sig=\"(Lcli.System.ComponentModel.EditorBrowsableState;)V\">\n 914 <parameter>Never</parameter>\n 915 </attribute>\n */\n\n m_responseList.add(fullJavaName);\n }\n }\n }\n }\n }",
"public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) {\n assertNumericArgument(processTimeout, false);\n this.processTimeout = timeUnit.toMillis(processTimeout);\n return this;\n }",
"public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) {\n final DbArtifact artifact = getArtifact(gavc);\n final List<DbLicense> licenses = new ArrayList<>();\n\n for(final String name: artifact.getLicenses()){\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name);\n\n // Here is a license to identify\n if(matchingLicenses.isEmpty()){\n final DbLicense notIdentifiedLicense = new DbLicense();\n notIdentifiedLicense.setName(name);\n licenses.add(notIdentifiedLicense);\n } else {\n matchingLicenses.stream()\n .filter(filters::shouldBeInReport)\n .forEach(licenses::add);\n }\n }\n\n return licenses;\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 }"
] |
Creates a single property declaration.
@param property Property name.
@param term Property value.
@return The resulting declaration. | [
"protected Declaration createDeclaration(String property, Term<?> term)\n {\n Declaration d = CSSFactory.getRuleFactory().createDeclaration();\n d.unlock();\n d.setProperty(property);\n d.add(term);\n return d;\n }"
] | [
"public static boolean isConstant(Expression expression, Object expected) {\r\n return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue());\r\n }",
"private WeekDay readWeekDay(JSONValue val) throws IllegalArgumentException {\n\n String str = readOptionalString(val);\n if (null != str) {\n return WeekDay.valueOf(str);\n }\n throw new IllegalArgumentException();\n }",
"public static nspbr6[] get(nitro_service service) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\tnspbr6[] response = (nspbr6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_response update(nitro_service client, systemcollectionparam resource) throws Exception {\n\t\tsystemcollectionparam updateresource = new systemcollectionparam();\n\t\tupdateresource.communityname = resource.communityname;\n\t\tupdateresource.loglevel = resource.loglevel;\n\t\tupdateresource.datapath = resource.datapath;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {\n String separator = launcher.isUnix() ? \"/\" : \"\\\\\";\n String java_home = extendedEnv.get(\"JAVA_HOME\");\n if (StringUtils.isNotEmpty(java_home)) {\n if (!StringUtils.endsWith(java_home, separator)) {\n java_home += separator;\n }\n extendedEnv.put(\"PATH+JDK\", java_home + \"bin\");\n }\n }",
"public Iterator<K> tailIterator(@NotNull final K key) {\n return new Iterator<K>() {\n\n private Stack<TreePos<K>> stack;\n private boolean hasNext;\n private boolean hasNextValid;\n\n @Override\n public boolean hasNext() {\n if (hasNextValid) {\n return hasNext;\n }\n hasNextValid = true;\n if (stack == null) {\n Node<K> root = getRoot();\n if (root == null) {\n hasNext = false;\n return hasNext;\n }\n stack = new Stack<>();\n if (!root.getLess(key, stack)) {\n stack.push(new TreePos<>(root));\n }\n }\n TreePos<K> treePos = stack.peek();\n if (treePos.node.isLeaf()) {\n while (treePos.pos >= (treePos.node.isTernary() ? 2 : 1)) {\n stack.pop();\n if (stack.isEmpty()) {\n hasNext = false;\n return hasNext;\n }\n treePos = stack.peek();\n }\n } else {\n if (treePos.pos == 0) {\n treePos = new TreePos<>(treePos.node.getFirstChild());\n } else if (treePos.pos == 1) {\n treePos = new TreePos<>(treePos.node.getSecondChild());\n } else {\n treePos = new TreePos<>(treePos.node.getThirdChild());\n }\n stack.push(treePos);\n while (!treePos.node.isLeaf()) {\n treePos = new TreePos<>(treePos.node.getFirstChild());\n stack.push(treePos);\n }\n }\n treePos.pos++;\n hasNext = true;\n return hasNext;\n }\n\n @Override\n public K next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n hasNextValid = false;\n TreePos<K> treePos = stack.peek();\n // treePos.pos must be 1 or 2 here\n return treePos.pos == 1 ? treePos.node.getFirstKey() : treePos.node.getSecondKey();\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }",
"protected boolean checkPackageLocators(String classPackageName) {\n\t\tif (packageLocators != null && !disablePackageLocatorsScanning && classPackageName.length() > 0\n\t\t\t\t&& (packageLocatorsBasePackage == null || classPackageName.startsWith(packageLocatorsBasePackage))) {\n\t\t\tfor (String packageLocator : packageLocators) {\n\t\t\t\tString[] splitted = classPackageName.split(\"\\\\.\");\n\n\t\t\t\tif (es.cenobit.struts2.json.util.StringUtils.contains(splitted, packageLocator, false))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static void findSomeStringProperties(ApiConnection connection)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tWikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, siteIri);\n\t\twbdf.getFilter().excludeAllProperties();\n\t\twbdf.getFilter().setLanguageFilter(Collections.singleton(\"en\"));\n\n\t\tArrayList<PropertyIdValue> stringProperties = new ArrayList<>();\n\n\t\tSystem.out\n\t\t\t\t.println(\"*** Trying to find string properties for the example ... \");\n\t\tint propertyNumber = 1;\n\t\twhile (stringProperties.size() < 5) {\n\t\t\tArrayList<String> fetchProperties = new ArrayList<>();\n\t\t\tfor (int i = propertyNumber; i < propertyNumber + 10; i++) {\n\t\t\t\tfetchProperties.add(\"P\" + i);\n\t\t\t}\n\t\t\tpropertyNumber += 10;\n\t\t\tMap<String, EntityDocument> results = wbdf\n\t\t\t\t\t.getEntityDocuments(fetchProperties);\n\t\t\tfor (EntityDocument ed : results.values()) {\n\t\t\t\tPropertyDocument pd = (PropertyDocument) ed;\n\t\t\t\tif (DatatypeIdValue.DT_STRING.equals(pd.getDatatype().getIri())\n\t\t\t\t\t\t&& pd.getLabels().containsKey(\"en\")) {\n\t\t\t\t\tstringProperties.add(pd.getEntityId());\n\t\t\t\t\tSystem.out.println(\"* Found string property \"\n\t\t\t\t\t\t\t+ pd.getEntityId().getId() + \" (\"\n\t\t\t\t\t\t\t+ pd.getLabels().get(\"en\") + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstringProperty1 = stringProperties.get(0);\n\t\tstringProperty2 = stringProperties.get(1);\n\t\tstringProperty3 = stringProperties.get(2);\n\t\tstringProperty4 = stringProperties.get(3);\n\t\tstringProperty5 = stringProperties.get(4);\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}",
"public static String objectToColumnString(Object object, String delimiter, String[] fieldNames)\r\n throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0; i < fieldNames.length; i++) {\r\n if (sb.length() > 0) {\r\n sb.append(delimiter);\r\n }\r\n try {\r\n Field field = object.getClass().getDeclaredField(fieldNames[i]);\r\n sb.append(field.get(object)) ;\r\n } catch (IllegalAccessException ex) {\r\n Method method = object.getClass().getDeclaredMethod(\"get\" + StringUtils.capitalize(fieldNames[i]));\r\n sb.append(method.invoke(object));\r\n }\r\n }\r\n return sb.toString();\r\n }"
] |
Addes the current member as a nested object.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException If an error occurs
@doc.tag type="content" | [
"public String processNested(Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n NestedDef nestedDef = _curClassDef.getNested(name);\r\n\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_NESTED,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n ClassDescriptorDef nestedTypeDef = _model.getClass(type.getQualifiedName());\r\n\r\n if (nestedTypeDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (nestedDef == null)\r\n {\r\n nestedDef = new NestedDef(name, nestedTypeDef);\r\n _curClassDef.addNested(nestedDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processNested\", \" Processing nested object \"+nestedDef.getName()+\" of type \"+nestedTypeDef.getName());\r\n\r\n String attrName;\r\n \r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n nestedDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }"
] | [
"public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values, MyReflectionDifferenceHandler differenceHandler)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n\n log.debug(\"Building new instance of Class \" + clazz.getName());\n\n T instance = clazz.newInstance();\n\n for (String key : values.keySet()) {\n Object value = values.get(key);\n\n if (value == null) {\n log.debug(\"Value for field \" + key + \" is null, so ignoring it...\");\n continue;\n }\n \n log.debug(\n \"Invoke setter for \" + key + \" (\" + value.getClass() + \" / \" + value.toString() + \")\");\n Method setter = null;\n try {\n setter = new PropertyDescriptor(key.replace('.', '_'), clazz).getWriteMethod();\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Setter for field \" + key + \" was not found\", e);\n }\n\n Class<?> argumentType = setter.getParameterTypes()[0];\n\n if (argumentType.isAssignableFrom(value.getClass())) {\n setter.invoke(instance, value);\n } else {\n\n Object newValue = differenceHandler.handleDifference(value, setter.getParameterTypes()[0]);\n setter.invoke(instance, newValue);\n\n }\n }\n\n return instance;\n }",
"public static void setTranslucentNavigationFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);\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 }",
"private static boolean hasSelfPermissions(Context context, String... permissions) {\n for (String permission : permissions) {\n if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {\n return true;\n }\n }\n return false;\n }",
"public synchronized void addRoleMapping(final String roleName) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName) == false) {\n newRoles.put(roleName, new RoleMappingImpl(roleName));\n roleMappings = Collections.unmodifiableMap(newRoles);\n }\n }",
"public static String checkRequiredProperties(Properties props,\r\n String ... requiredProps) {\r\n for (String required : requiredProps) {\r\n if (props.getProperty(required) == null) {\r\n return required;\r\n }\r\n }\r\n return null;\r\n }",
"public static ModelNode getFailureDescription(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n throw ControllerClientLogger.ROOT_LOGGER.noFailureDescription();\n }\n if (result.hasDefined(FAILURE_DESCRIPTION)) {\n return result.get(FAILURE_DESCRIPTION);\n }\n return new ModelNode();\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 <T> InternalEjbDescriptor<T> get(String beanName) {\n return cast(ejbByName.get(beanName));\n }"
] |
Sets the path to the script file to load and loads the script.
@param filePath path to script file
@throws IOException if the script cannot be read.
@throws GVRScriptException if a script processing error occurs. | [
"public void setFilePath(String filePath) throws IOException, GVRScriptException\n {\n GVRResourceVolume.VolumeType volumeType = GVRResourceVolume.VolumeType.ANDROID_ASSETS;\n String fname = filePath.toLowerCase();\n \n mLanguage = FileNameUtils.getExtension(fname); \n if (fname.startsWith(\"sd:\"))\n {\n volumeType = GVRResourceVolume.VolumeType.ANDROID_SDCARD;\n }\n else if (fname.startsWith(\"http:\") || fname.startsWith(\"https:\"))\n {\n volumeType = GVRResourceVolume.VolumeType.NETWORK; \n }\n GVRResourceVolume volume = new GVRResourceVolume(getGVRContext(), volumeType,\n FileNameUtils.getParentDirectory(filePath));\n GVRAndroidResource resource = volume.openResource(filePath);\n \n setScriptFile((GVRScriptFile)getGVRContext().getScriptManager().loadScript(resource, mLanguage));\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 void mapText(String oldText, Map<String, String> replacements)\n {\n char c2 = 0;\n if (oldText != null && oldText.length() != 0 && !replacements.containsKey(oldText))\n {\n StringBuilder newText = new StringBuilder(oldText.length());\n for (int loop = 0; loop < oldText.length(); loop++)\n {\n char c = oldText.charAt(loop);\n if (Character.isUpperCase(c))\n {\n newText.append('X');\n }\n else\n {\n if (Character.isLowerCase(c))\n {\n newText.append('x');\n }\n else\n {\n if (Character.isDigit(c))\n {\n newText.append('0');\n }\n else\n {\n if (Character.isLetter(c))\n {\n // Handle other codepages etc. If possible find a way to\n // maintain the same code page as original.\n // E.g. replace with a character from the same alphabet.\n // This 'should' work for most cases\n if (c2 == 0)\n {\n c2 = c;\n }\n newText.append(c2);\n }\n else\n {\n newText.append(c);\n }\n }\n }\n }\n }\n\n replacements.put(oldText, newText.toString());\n }\n }",
"public CollectionRequest<CustomField> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/custom_fields\", workspace);\n return new CollectionRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }",
"public 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}",
"public ProteusApplication addDefaultRoutes(RoutingHandler router)\n {\n\n if (config.hasPath(\"health.statusPath\")) {\n try {\n final String statusPath = config.getString(\"health.statusPath\");\n\n router.add(Methods.GET, statusPath, (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, MediaType.TEXT_PLAIN);\n exchange.getResponseSender().send(\"OK\");\n });\n\n this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(\"*/*\").withProduces(\"text/plain\").withPathTemplate(statusPath).withControllerName(\"Internal\").withMethod(Methods.GET).build());\n\n } catch (Exception e) {\n log.error(\"Error adding health status route.\", e.getMessage());\n }\n }\n\n if (config.hasPath(\"application.favicon\")) {\n try {\n\n final ByteBuffer faviconImageBuffer;\n\n final File faviconFile = new File(config.getString(\"application.favicon\"));\n\n if (!faviconFile.exists()) {\n try (final InputStream stream = this.getClass().getResourceAsStream(config.getString(\"application.favicon\"))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n\n } else {\n try (final InputStream stream = Files.newInputStream(Paths.get(config.getString(\"application.favicon\")))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n }\n\n router.add(Methods.GET, \"favicon.ico\", (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, io.sinistral.proteus.server.MediaType.IMAGE_X_ICON.toString());\n exchange.getResponseSender().send(faviconImageBuffer);\n });\n\n } catch (Exception e) {\n log.error(\"Error adding favicon route.\", e.getMessage());\n }\n }\n\n return this;\n }",
"public Date getNextWorkStart(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToNextWorkStart(cal);\n return cal.getTime();\n }",
"protected float getSizeArcLength(float angle) {\n if (mRadius <= 0) {\n throw new IllegalArgumentException(\"mRadius is not specified!\");\n }\n return angle == Float.MAX_VALUE ? Float.MAX_VALUE :\n LayoutHelpers.lengthOfArc(angle, mRadius);\n }",
"public List<? super OpenShiftResource> processTemplateResources() {\n List<? extends OpenShiftResource> resources;\n final List<? super OpenShiftResource> processedResources = new ArrayList<>();\n templates = OpenShiftResourceFactory.getTemplates(getType());\n boolean sync_instantiation = OpenShiftResourceFactory.syncInstantiation(getType());\n\n /* Instantiate templates */\n for (Template template : templates) {\n resources = processTemplate(template);\n if (resources != null) {\n if (sync_instantiation) {\n /* synchronous template instantiation */\n processedResources.addAll(resources);\n } else {\n /* asynchronous template instantiation */\n try {\n delay(openShiftAdapter, resources);\n } catch (Throwable t) {\n throw new IllegalArgumentException(asynchronousDelayErrorMessage(), t);\n }\n }\n }\n }\n\n return processedResources;\n }",
"public static String defaultHtml(HttpServletRequest request) {\n\n CmsObject cms = CmsFlexController.getController(request).getCmsObject();\n\n // We only want the big red warning in Offline mode\n if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {\n return \"<div><!--Dynamic function not configured--></div>\";\n } else {\n Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);\n String message = Messages.get().getBundle(locale).key(Messages.GUI_FUNCTION_DEFAULT_HTML_0);\n return \"<div style=\\\"border: 2px solid red; padding: 10px;\\\">\" + message + \"</div>\";\n }\n }"
] |
Adds a new gender item and an initial name.
@param entityIdValue
the item representing the gender
@param name
the label to use for representing the gender | [
"private void addNewGenderName(EntityIdValue entityIdValue, String name) {\n\t\tthis.genderNames.put(entityIdValue, name);\n\t\tthis.genderNamesList.add(entityIdValue);\n\t}"
] | [
"@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\n }",
"public Curve getRegressionCurve(){\n\t\t// @TODO Add threadsafe lazy init.\n\t\tif(regressionCurve !=null) {\n\t\t\treturn regressionCurve;\n\t\t}\n\t\tDoubleMatrix a = solveEquationSystem();\n\t\tdouble[] curvePoints=new double[partition.getLength()];\n\t\tcurvePoints[0]=a.get(0);\n\t\tfor(int i=1;i<curvePoints.length;i++) {\n\t\t\tcurvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));\n\t\t}\n\t\treturn new CurveInterpolation(\n\t\t\t\t\"RegressionCurve\",\n\t\t\t\treferenceDate,\n\t\t\t\tCurveInterpolation.InterpolationMethod.LINEAR,\n\t\t\t\tCurveInterpolation.ExtrapolationMethod.CONSTANT,\n\t\t\t\tCurveInterpolation.InterpolationEntity.VALUE,\n\t\t\t\tpartition.getPoints(),\n\t\t\t\tcurvePoints);\n\t}",
"public final void notifyFooterItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= footerItemCount || toPosition >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition\n + \" or toPosition \" + toPosition + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount + contentItemCount, toPosition + headerItemCount + contentItemCount);\n }",
"public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {\n return createEnterpriseUser(api, login, name, null);\n }",
"private static void deleteOldAndEmptyFiles() {\n File dir = LOG_FILE_DIR;\n if (dir.exists()) {\n File[] files = dir.listFiles();\n\n for (File f : files) {\n if (f.length() == 0 ||\n f.lastModified() + MAXFILEAGE < System.currentTimeMillis()) {\n f.delete();\n }\n }\n }\n }",
"public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException {\n Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames);\n Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create();\n if (deploymentNames.isEmpty()) {\n for (String s : runtimeNames) {\n ServerLogger.ROOT_LOGGER.debugf(\"We haven't found any deployment for %s in server-group %s\", s, deploymentsRootAddress.getLastElement().getValue());\n }\n }\n if(removeOperation != null) {\n opBuilder.addStep(removeOperation);\n }\n for (String deploymentName : deploymentNames) {\n opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName)));\n }\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n final ModelNode slave = opBuilder.build().getOperation();\n transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress()));\n }",
"public void addFkToItemClass(String column)\r\n {\r\n if (fksToItemClass == null)\r\n {\r\n fksToItemClass = new Vector();\r\n }\r\n fksToItemClass.add(column);\r\n fksToItemClassAry = null;\r\n }",
"public StandaloneCommandBuilder setDebug(final boolean suspend, final int port) {\n debugArg = String.format(DEBUG_FORMAT, (suspend ? \"y\" : \"n\"), port);\n return this;\n }",
"public boolean matches(String uri) {\n\t\tif (uri == null) {\n\t\t\treturn false;\n\t\t}\n\t\tMatcher matcher = this.matchPattern.matcher(uri);\n\t\treturn matcher.matches();\n\t}"
] |
Return a long value which is the number of rows in the table. | [
"public long queryForCountStar(DatabaseConnection databaseConnection) throws SQLException {\n\t\tif (countStarQuery == null) {\n\t\t\tStringBuilder sb = new StringBuilder(64);\n\t\t\tsb.append(\"SELECT COUNT(*) FROM \");\n\t\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\t\tcountStarQuery = sb.toString();\n\t\t}\n\t\tlong count = databaseConnection.queryForLong(countStarQuery);\n\t\tlogger.debug(\"query of '{}' returned {}\", countStarQuery, count);\n\t\treturn count;\n\t}"
] | [
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }",
"public synchronized void setDeviceName(String name) {\n if (name.getBytes().length > DEVICE_NAME_LENGTH) {\n throw new IllegalArgumentException(\"name cannot be more than \" + DEVICE_NAME_LENGTH + \" bytes long\");\n }\n Arrays.fill(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH, (byte)0);\n System.arraycopy(name.getBytes(), 0, announcementBytes, DEVICE_NAME_OFFSET, name.getBytes().length);\n }",
"public List<BuildpackInstallation> listBuildpackInstallations(String appName) {\n return connection.execute(new BuildpackInstallationList(appName), apiKey);\n }",
"public boolean setCurrentConfiguration(CmsGitConfiguration configuration) {\n\n if ((null != configuration) && configuration.isValid()) {\n m_currentConfiguration = configuration;\n return true;\n }\n return false;\n }",
"private void addSuperClasses(Integer directSuperClass,\n\t\t\tClassRecord subClassRecord) {\n\t\tif (subClassRecord.superClasses.contains(directSuperClass)) {\n\t\t\treturn;\n\t\t}\n\t\tsubClassRecord.superClasses.add(directSuperClass);\n\t\tClassRecord superClassRecord = getClassRecord(directSuperClass);\n\t\tif (superClassRecord == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (Integer superClass : superClassRecord.directSuperClasses) {\n\t\t\taddSuperClasses(superClass, subClassRecord);\n\t\t}\n\t}",
"String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }",
"private ColumnDefinition[] columnDefinitions(ColumnDefinition[] columns, String[] order)\n {\n Map<String, ColumnDefinition> map = makeColumnMap(columns);\n ColumnDefinition[] result = new ColumnDefinition[order.length];\n for (int index = 0; index < order.length; index++)\n {\n result[index] = map.get(order[index]);\n }\n return result;\n }",
"public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }",
"public void putInWakeUpQueue(SerialMessage serialMessage) {\r\n\t\tif (this.wakeUpQueue.contains(serialMessage)) {\r\n\t\t\tlogger.debug(\"Message already on the wake-up queue for node {}. Discarding.\", this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t\r\n\t\tlogger.debug(\"Putting message in wakeup queue for node {}.\", this.getNode().getNodeId());\r\n\t\tthis.wakeUpQueue.add(serialMessage);\r\n\t}"
] |
Answer the SQL-Clause for a FieldCriteria
@param c FieldCriteria
@param cld ClassDescriptor | [
"private String toSQLClause(FieldCriteria c, ClassDescriptor cld)\r\n {\r\n String colName = toSqlClause(c.getAttribute(), cld);\r\n return colName + c.getClause() + c.getValue();\r\n }"
] | [
"public MathTransform calculateLabelTransform(final CoordinateReferenceSystem mapCrs) {\n MathTransform labelTransform;\n if (this.labelProjection != null) {\n try {\n labelTransform = CRS.findMathTransform(mapCrs, this.labelCRS, true);\n } catch (FactoryException e) {\n throw new RuntimeException(e);\n }\n } else {\n labelTransform = IdentityTransform.create(2);\n }\n\n return labelTransform;\n }",
"public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"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 void setFrustum(Matrix4f projMatrix)\n {\n if (projMatrix != null)\n {\n if (mProjMatrix == null)\n {\n mProjMatrix = new float[16];\n }\n mProjMatrix = projMatrix.get(mProjMatrix, 0);\n mScene.setPickVisible(false);\n if (mCuller != null)\n {\n mCuller.set(projMatrix);\n }\n else\n {\n mCuller = new FrustumIntersection(projMatrix);\n }\n }\n mProjection = projMatrix;\n }",
"@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }",
"protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, obj);\r\n }",
"private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,\n final boolean initial) throws OperationFailedException {\n ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);\n if (resolved.recursive) {\n // Some part of expressionString resolved into a different expression.\n // So, start over, ignoring failures. Ignore failures because we don't require\n // that expressions must not resolve to something that *looks like* an expression but isn't\n return resolveExpressionStringRecursively(resolved.result, true, false);\n } else if (resolved.modified) {\n // Typical case\n return new ModelNode(resolved.result);\n } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {\n // We should only get an unmodified expression string back if there was a resolution\n // failure that we ignored.\n assert ignoreDMRResolutionFailure;\n // expressionString came from a node of type expression, so since we did nothing send it back in the same type\n return new ModelNode(new ValueExpression(expressionString));\n } else {\n // The string wasn't really an expression. Two possible cases:\n // 1) if initial == true, someone created a expression node with a non-expression string, which is legal\n // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an\n // expression but can't be resolved. We don't require that expressions must not resolve to something that\n // *looks like* an expression but isn't, so we'll just treat this as a string\n return new ModelNode(expressionString);\n }\n }",
"public void linkOneToMany(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkOneToMany(true, obj, cod,referencedObjects, insert);\n }",
"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 }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.