query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Curries a procedure that takes two arguments.
@param procedure
the original procedure. May not be <code>null</code>.
@param argument
the fixed first argument of {@code procedure}.
@return a procedure that takes one argument. Never <code>null</code>. | [
"@Pure\n\tpublic static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure1<P2>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p) {\n\t\t\t\tprocedure.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}"
] | [
"public static void init() {\n reports.clear();\n Reflections reflections = new Reflections(REPORTS_PACKAGE);\n final Set<Class<? extends Report>> reportClasses = reflections.getSubTypesOf(Report.class);\n\n for(Class<? extends Report> c : reportClasses) {\n LOG.info(\"Report class: \" + c.getName());\n try {\n reports.add(c.newInstance());\n } catch (IllegalAccessException | InstantiationException e) {\n LOG.error(\"Error while loading report implementation classes\", e);\n }\n }\n\n if(LOG.isInfoEnabled()) {\n LOG.info(String.format(\"Detected %s reports\", reports.size()));\n }\n }",
"public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }",
"private void removeAllBroadcasts(Set<String> sessionIds) {\n\n if (sessionIds == null) {\n for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos()) {\n OpenCms.getSessionManager().getBroadcastQueue(info.getSessionId().getStringValue()).clear();\n }\n return;\n }\n for (String sessionId : sessionIds) {\n OpenCms.getSessionManager().getBroadcastQueue(sessionId).clear();\n }\n }",
"public static double blackScholesOptionRho(\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 rho\n\t\t\tdouble dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\n\t\t\tdouble rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn rho;\n\t\t}\n\t}",
"public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\n }",
"public static void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\n }",
"public void addAll(OptionsContainerBuilder container) {\n\t\tfor ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {\n\t\t\taddAll( entry.getKey(), entry.getValue().build() );\n\t\t}\n\t}",
"public static Iterable<BoxRetentionPolicy.Info> getAll(final BoxAPIConnection api, String ... fields) {\r\n return getAll(null, null, null, DEFAULT_LIMIT, api, fields);\r\n }",
"public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }"
] |
Retrieve from the parent pom the path to the modules of the project | [
"private List<String> getMavenModules(MavenModuleSetBuild mavenBuild) throws IOException, InterruptedException {\n FilePath pathToModuleRoot = mavenBuild.getModuleRoot();\n FilePath pathToPom = new FilePath(pathToModuleRoot, mavenBuild.getProject().getRootPOM(null));\n return pathToPom.act(new MavenModulesExtractor());\n }"
] | [
"private String formatAccrueType(AccrueType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.ACCRUE_TYPES)[type.getValue() - 1]);\n }",
"@RequestMapping(value = \"api/edit/server\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getjqRedirects(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(ServerRedirectService.getInstance().tableServers(clientId), \"servers\");\n returnJson.put(\"hostEditor\", Client.isAvailable());\n return returnJson;\n }",
"public Pair<int[][][], int[]> documentToDataAndLabels(List<IN> document) {\r\n\r\n int docSize = document.size();\r\n // first index is position in the document also the index of the\r\n // clique/factor table\r\n // second index is the number of elements in the clique/window these\r\n // features are for (starting with last element)\r\n // third index is position of the feature in the array that holds them\r\n // element in data[j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique\r\n int[][][] data = new int[docSize][windowSize][];\r\n // index is the position in the document\r\n // element in labels[j] is the index of the correct label (if it exists) at\r\n // position j of document\r\n int[] labels = new int[docSize];\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"docSize:\"+docSize);\r\n for (int j = 0; j < docSize; j++) {\r\n CRFDatum<List<String>, CRFLabel> d = makeDatum(document, j, featureFactory);\r\n\r\n List<List<String>> features = d.asFeatures();\r\n for (int k = 0, fSize = features.size(); k < fSize; k++) {\r\n Collection<String> cliqueFeatures = features.get(k);\r\n data[j][k] = new int[cliqueFeatures.size()];\r\n int m = 0;\r\n for (String feature : cliqueFeatures) {\r\n int index = featureIndex.indexOf(feature);\r\n if (index >= 0) {\r\n data[j][k][m] = index;\r\n m++;\r\n } else {\r\n // this is where we end up when we do feature threshold cutoffs\r\n }\r\n }\r\n // Reduce memory use when some features were cut out by threshold\r\n if (m < data[j][k].length) {\r\n int[] f = new int[m];\r\n System.arraycopy(data[j][k], 0, f, 0, m);\r\n data[j][k] = f;\r\n }\r\n }\r\n\r\n IN wi = document.get(j);\r\n labels[j] = classIndex.indexOf(wi.get(AnswerAnnotation.class));\r\n }\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"numClasses: \"+classIndex.size()+\" \"+classIndex);\r\n // System.err.println(\"numDocuments: 1\");\r\n // System.err.println(\"numDatums: \"+data.length);\r\n // System.err.println(\"numFeatures: \"+featureIndex.size());\r\n\r\n return new Pair<int[][][], int[]>(data, labels);\r\n }",
"public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\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 Set<BsonValue> getPausedDocumentIds(final MongoNamespace namespace) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final Set<BsonValue> pausedDocumentIds = new HashSet<>();\n\n for (final CoreDocumentSynchronizationConfig config :\n this.syncConfig.getSynchronizedDocuments(namespace)) {\n if (config.isPaused()) {\n pausedDocumentIds.add(config.getDocumentId());\n }\n }\n\n return pausedDocumentIds;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"@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 ImageSource apply(ImageSource input) {\n ImageSource originalImage = input;\n\n int width = originalImage.getWidth();\n int height = originalImage.getHeight();\n\n boolean[][] matrix = new boolean[width][height]; // black n white boolean matrix; true = blck, false = white\n\n // Copy\n ImageSource filteredImage = new MatrixSource(input);\n\n int[] histogram = OtsuBinarize.imageHistogram(originalImage);\n\n int totalNumberOfpixels = height * width;\n\n int threshold = OtsuBinarize.threshold(histogram, totalNumberOfpixels);\n\n int black = 0;\n int white = 255;\n\n int gray;\n int alpha;\n int newColor;\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n\n if (gray > threshold) {\n matrix[i][j] = false;\n } else {\n matrix[i][j] = true;\n }\n\n }\n }\n\n int blackTreshold = letterThreshold(originalImage, matrix);\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n alpha = originalImage.getA(i, j);\n\n if (gray > blackTreshold) {\n newColor = white;\n } else {\n newColor = black;\n }\n\n newColor = ColorHelper.getARGB(newColor, newColor, newColor, alpha);\n filteredImage.setRGB(i, j, newColor);\n }\n }\n\n return filteredImage;\n }",
"public void fireResourceWrittenEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceWritten(resource);\n }\n }\n }"
] |
Use this API to fetch the statistics of all cmppolicy_stats resources that are configured on netscaler. | [
"public static cmppolicy_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tcmppolicy_stats[] response = (cmppolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}"
] | [
"public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }",
"public AsciiTable setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static Index index(String keyspace, String table, String name) {\n return new Index(table, name).keyspace(keyspace);\n }",
"private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"properties.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Datatype\"\n\t\t\t\t\t+ \",Uses in statements\" + \",Items with such statements\"\n\t\t\t\t\t+ \",Uses in statements with qualifiers\"\n\t\t\t\t\t+ \",Uses in qualifiers\" + \",Uses in references\"\n\t\t\t\t\t+ \",Uses total\" + \",Related properties\");\n\n\t\t\tList<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>(\n\t\t\t\t\tthis.propertyRecords.entrySet());\n\t\t\tCollections.sort(list, new UsageRecordComparator());\n\t\t\tfor (Entry<PropertyIdValue, PropertyRecord> entry : list) {\n\t\t\t\tprintPropertyRecord(out, entry.getValue(), entry.getKey());\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public static appfwprofile_excluderescontenttype_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_excluderescontenttype_binding obj = new appfwprofile_excluderescontenttype_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_excluderescontenttype_binding response[] = (appfwprofile_excluderescontenttype_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void removeXmlBundleFile() throws CmsException {\n\n lockLocalization(null);\n m_cms.deleteResource(m_resource, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_resource = null;\n\n }",
"public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }",
"@Override\n public void onBindViewHolder(GalleryAdapter.ViewHolder holder, int position, List<Object> payloads) {\n if (payloads.isEmpty()) { // If doesn't have any payload then bind the fully item\n super.onBindViewHolder(holder, position, payloads);\n } else {\n for (Object payload : payloads) {\n boolean selected = isSelected(position);\n if (SELECTION_PAYLOAD.equals(payload)) {\n if (VIEW_TYPE_MEDIA == getItemViewType(position)) {\n MediaViewHolder viewHolder = (MediaViewHolder) holder;\n viewHolder.mCheckView.setChecked(selected);\n if (selected) {\n AnimationHelper.scaleView(holder.mImageView, SELECTED_SCALE);\n } else {\n AnimationHelper.scaleView(holder.mImageView, UNSELECTED_SCALE);\n }\n }\n }\n }\n }\n }",
"public WebSocketContext sendToPeers(String message, boolean excludeSelf) {\n return sendToConnections(message, url, manager.urlRegistry(), excludeSelf);\n }"
] |
Computes the null space using QRP decomposition. This is faster than using SVD but slower than QR.
Much more stable than QR though.
@param A (Input) Matrix
@param totalSingular Number of singular values
@return Null space | [
"public static DMatrixRMaj nullspaceQRP( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQRP_DDRM solver = new SolveNullSpaceQRP_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }"
] | [
"public Class<?> getType(String key) {\n Object val = this.data.get(key);\n return val == null ? null : val.getClass();\n }",
"@Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // If the API level is less than 11, we can't rely on the view animation system to\n // do the scrolling animation. Need to tick it here and call postInvalidate() until the scrolling is done.\n if (Build.VERSION.SDK_INT < 11) {\n tickScrollAnimation();\n if (!mScroller.isFinished()) {\n mGraph.postInvalidate();\n }\n }\n }",
"public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }",
"public static int cudnnGetRNNDataDescriptor(\n cudnnRNNDataDescriptor RNNDataDesc, \n int[] dataType, \n int[] layout, \n int[] maxSeqLength, \n int[] batchSize, \n int[] vectorSize, \n int arrayLengthRequested, \n int[] seqLengthArray, \n Pointer paddingFill)\n {\n return checkResult(cudnnGetRNNDataDescriptorNative(RNNDataDesc, dataType, layout, maxSeqLength, batchSize, vectorSize, arrayLengthRequested, seqLengthArray, paddingFill));\n }",
"public ArrayList<Duration> segmentWork(ProjectCalendar projectCalendar, List<TimephasedWork> work, TimescaleUnits rangeUnits, List<DateRange> dateList)\n {\n ArrayList<Duration> result = new ArrayList<Duration>(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, work, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(Duration.getInstance(0, TimeUnit.HOURS));\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(getRangeDuration(projectCalendar, rangeUnits, range, work, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }",
"public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }",
"private void initPixelsArray(BufferedImage image) {\n int width = image.getWidth();\n int height = image.getHeight();\n pixels = new int[width * height];\n image.getRGB(0, 0, width, height, pixels, 0, width);\n\n }",
"private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) {\n final Response response = doLoginRequest(credential, asLinkRequest);\n\n final StitchUserT previousUser = activeUser;\n final StitchUserT user = processLoginResponse(credential, response, asLinkRequest);\n\n if (asLinkRequest) {\n onUserLinked(user);\n } else {\n onUserLoggedIn(user);\n onActiveUserChanged(activeUser, previousUser);\n }\n\n return user;\n }",
"public static String analyzeInvalidMetadataRate(final Cluster currentCluster,\n List<StoreDefinition> currentStoreDefs,\n final Cluster finalCluster,\n List<StoreDefinition> finalStoreDefs) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Dump of invalid metadata rates per zone\").append(Utils.NEWLINE);\n\n HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs);\n\n for(StoreDefinition currentStoreDef: uniqueStores.keySet()) {\n sb.append(\"Store exemplar: \" + currentStoreDef.getName())\n .append(Utils.NEWLINE)\n .append(\"\\tThere are \" + uniqueStores.get(currentStoreDef) + \" other similar stores.\")\n .append(Utils.NEWLINE);\n\n StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef);\n StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs,\n currentStoreDef.getName());\n StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef);\n\n // Only care about existing zones\n for(int zoneId: currentCluster.getZoneIds()) {\n int zonePrimariesCount = 0;\n int invalidMetadata = 0;\n\n // Examine nodes in current cluster in existing zone.\n for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) {\n // For every zone-primary in current cluster\n for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) {\n zonePrimariesCount++;\n // Determine if original zone-primary node is still some\n // form of n-ary in final cluster. If not,\n // InvalidMetadataException will fire.\n if(!finalSRP.getZoneNAryPartitionIds(nodeId)\n .contains(zonePrimaryPartitionId)) {\n invalidMetadata++;\n }\n }\n }\n float rate = invalidMetadata / (float) zonePrimariesCount;\n sb.append(\"\\tZone \" + zoneId)\n .append(\" : total zone primaries \" + zonePrimariesCount)\n .append(\", # that trigger invalid metadata \" + invalidMetadata)\n .append(\" => \" + rate)\n .append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }"
] |
Load and run the OnBrowserCreatedPlugins, this call has been made from the browser pool when a
new browser has been created and ready to be used by the Crawler. The PreCrawling plugins are
executed before these plugins are executed except that the pre-crawling plugins are only
executed on the first created browser.
@param newBrowser the new created browser object | [
"public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {\n\t\tLOGGER.debug(\"Running OnBrowserCreatedPlugins...\");\n\t\tcounters.get(OnBrowserCreatedPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {\n\t\t\tif (plugin instanceof OnBrowserCreatedPlugin) {\n\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\ttry {\n\t\t\t\t\t((OnBrowserCreatedPlugin) plugin)\n\t\t\t\t\t\t\t.onBrowserCreated(newBrowser);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] | [
"public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\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 }",
"private void checkOrMarkPrivateAccess(Expression source, FieldNode fn) {\n if (fn!=null && Modifier.isPrivate(fn.getModifiers()) &&\n (fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) &&\n fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) {\n addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), StaticTypesMarker.PV_FIELDS_ACCESS, fn);\n }\n }",
"public static Date min(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) < 0) ? d1 : d2;\n }\n return result;\n }",
"public static void doPublish(final Jedis jedis, final String namespace, final String channel, final String jobJson) {\n jedis.publish(JesqueUtils.createKey(namespace, CHANNEL, channel), jobJson);\n }",
"private void processRequestHeaderOverrides(HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n for (EndpointOverride selectedPath : requestInfo.selectedRequestPaths) {\n List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();\n for (EnabledEndpoint endpoint : points) {\n if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD) {\n httpMethodProxyRequest.addRequestHeader(endpoint.getArguments()[0].toString(),\n endpoint.getArguments()[1].toString());\n requestInfo.modified = true;\n } else if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE) {\n httpMethodProxyRequest.removeRequestHeader(endpoint.getArguments()[0].toString());\n requestInfo.modified = true;\n }\n }\n }\n }",
"List<CmsResource> getBundleResources() {\n\n List<CmsResource> resources = new ArrayList<>(m_bundleFiles.values());\n if (m_desc != null) {\n resources.add(m_desc);\n }\n return resources;\n\n }",
"private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n\r\n buf.append(join.right.getTableAndAlias());\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n\r\n appendTableWithJoins(join.right, where, buf);\r\n }",
"public User findByEmail(String email) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_FIND_BY_EMAIL);\r\n\r\n parameters.put(\"find_email\", email);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n user.setUsername(XMLUtilities.getChildValue(userElement, \"username\"));\r\n return user;\r\n }"
] |
Set a custom response for this path
@param pathName name of path
@param customResponse value of custom response
@return true if success, false otherwise
@throws Exception exception | [
"public boolean setCustomResponse(String pathName, String customResponse) throws Exception {\n // figure out the new ordinal\n int nextOrdinal = this.getNextOrdinalForMethodId(-1, pathName);\n\n // add override\n this.addMethodToResponseOverride(pathName, \"-1\");\n\n // set argument\n return this.setMethodArguments(pathName, \"-1\", nextOrdinal, customResponse);\n }"
] | [
"public void adjustGlassSize() {\n if (isGlassEnabled()) {\n ResizeHandler handler = getGlassResizer();\n if (handler != null) handler.onResize(null);\n }\n }",
"public EventBus emitSync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\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 }",
"public static Thread newThread(String name, Runnable runnable, boolean daemon) {\n Thread thread = new Thread(runnable, name);\n thread.setDaemon(daemon);\n return thread;\n }",
"private void readAssignments(Project project)\n {\n Project.Assignments assignments = project.getAssignments();\n if (assignments != null)\n {\n SplitTaskFactory splitFactory = new SplitTaskFactory();\n TimephasedWorkNormaliser normaliser = new MSPDITimephasedWorkNormaliser();\n for (Project.Assignments.Assignment assignment : assignments.getAssignment())\n {\n readAssignment(assignment, splitFactory, normaliser);\n }\n }\n }",
"private void readProjectProperties(Settings phoenixSettings, Storepoint storepoint)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(phoenixSettings.getTitle());\n mpxjProperties.setDefaultDurationUnits(phoenixSettings.getBaseunit());\n mpxjProperties.setStatusDate(storepoint.getDataDate());\n }",
"public static Method findGetter(final Object object, final String fieldName) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t}\n\t\t\n\t\tfinal Class<?> clazz = object.getClass();\n\t\t\n\t\t// find a standard getter\n\t\tfinal String standardGetterName = getMethodNameForField(GET_PREFIX, fieldName);\n\t\tMethod getter = findGetterWithCompatibleReturnType(standardGetterName, clazz, false);\n\t\t\n\t\t// if that fails, try for an isX() style boolean getter\n\t\tif( getter == null ) {\n\t\t\tfinal String booleanGetterName = getMethodNameForField(IS_PREFIX, fieldName);\n\t\t\tgetter = findGetterWithCompatibleReturnType(booleanGetterName, clazz, true);\n\t\t}\n\t\t\n\t\tif( getter == null ) {\n\t\t\tthrow new SuperCsvReflectionException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"unable to find getter for field %s in class %s - check that the corresponding nameMapping element matches the field name in the bean\",\n\t\t\t\t\t\tfieldName, clazz.getName()));\n\t\t}\n\t\t\n\t\treturn getter;\n\t}",
"public ConverterServerBuilder baseUri(String baseUri) {\n checkNotNull(baseUri);\n this.baseUri = URI.create(baseUri);\n return this;\n }",
"public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {\n URI uri = request.getURI();\n\n try {\n LOG.fine(\"CONNECT: \" + uri);\n InetAddrPort addrPort;\n // When logging, we'll attempt to send messages to hosts that don't exist\n if (uri.toString().endsWith(\".selenium.doesnotexist:443\")) {\n // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)\n addrPort = new InetAddrPort(443);\n } else {\n addrPort = new InetAddrPort(uri.toString());\n }\n\n if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {\n sendForbid(request, response, uri);\n } else {\n HttpConnection http_connection = request.getHttpConnection();\n http_connection.forceClose();\n\n HttpServer server = http_connection.getHttpServer();\n\n SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server);\n\n int port = listener.getPort();\n\n // Get the timeout\n int timeoutMs = 30000;\n Object maybesocket = http_connection.getConnection();\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n timeoutMs = s.getSoTimeout();\n }\n\n // Create the tunnel\n HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs);\n\n if (tunnel != null) {\n // TODO - need to setup semi-busy loop for IE.\n if (_tunnelTimeoutMs > 0) {\n tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n s.setSoTimeout(_tunnelTimeoutMs);\n }\n }\n tunnel.setTimeoutMs(timeoutMs);\n\n customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());\n request.getHttpConnection().setHttpTunnel(tunnel);\n response.setStatus(HttpResponse.__200_OK);\n response.setContentLength(0);\n }\n request.setHandled(true);\n }\n } catch (Exception e) {\n LOG.fine(\"error during handleConnect\", e);\n response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());\n }\n }"
] |
Close and remove expired streams. Package protected to allow unit tests to invoke it. | [
"void gc() {\n if (stopped) {\n return;\n }\n long expirationTime = System.currentTimeMillis() - timeout;\n for (Iterator<Map.Entry<InputStreamKey, TimedStreamEntry>> iter = streamMap.entrySet().iterator(); iter.hasNext();) {\n if (stopped) {\n return;\n }\n Map.Entry<InputStreamKey, TimedStreamEntry> entry = iter.next();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n if (timedStreamEntry.timestamp.get() <= expirationTime) {\n iter.remove();\n InputStreamKey key = entry.getKey();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }\n }"
] | [
"public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tList<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );\n\t\tfor ( String name : pathWithoutAlias ) {\n\t\t\tsubPath.add( name );\n\t\t\tif ( isAssociation( targetTypeName, subPath ) ) {\n\t\t\t\treturn subPath;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {\n return createEnterpriseUser(api, login, name, null);\n }",
"public static base_responses update(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance updateresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusterinstance();\n\t\t\t\tupdateresources[i].clid = resources[i].clid;\n\t\t\t\tupdateresources[i].deadinterval = resources[i].deadinterval;\n\t\t\t\tupdateresources[i].hellointerval = resources[i].hellointerval;\n\t\t\t\tupdateresources[i].preemption = resources[i].preemption;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"List<Message> getFullTrackList(final CdjStatus.TrackSourceSlot slot, final Client client, final int sortOrder)\n throws IOException, InterruptedException, TimeoutException {\n // Send the metadata menu request\n if (client.tryLockingForMenuOperations(MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n Message response = client.menuRequest(Message.KnownType.TRACK_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slot,\n new NumberField(sortOrder));\n final long count = response.getMenuResultsCount();\n if (count == Message.NO_MENU_RESULTS_AVAILABLE || count == 0) {\n return Collections.emptyList();\n }\n\n // Gather all the metadata menu items\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, response);\n }\n finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock the player for menu operations\");\n }\n }",
"public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\n }",
"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 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}",
"protected void watchConnection(ConnectionHandle connectionHandle) {\r\n\t\tString message = captureStackTrace(UNCLOSED_EXCEPTION_MESSAGE);\r\n\t\tthis.closeConnectionExecutor.submit(new CloseThreadMonitor(Thread.currentThread(), connectionHandle, message, this.closeConnectionWatchTimeoutInMs));\r\n\t}",
"public static base_responses unset(nitro_service client, String certkey[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey unsetresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tunsetresources[i] = new sslcertkey();\n\t\t\t\tunsetresources[i].certkey = certkey[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] |
Executes a batch plan.
@param batchId Used as the ID of the batch plan. This allows related
tasks on client- & server-side to pretty print messages in a
manner that debugging can track specific batch plans across the
cluster.
@param batchPlan The batch plan... | [
"private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) {\n final Cluster batchCurrentCluster = batchPlan.getCurrentCluster();\n final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs();\n final Cluster batchFinalCluster = batchPlan.getFinalCluster();\n final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs();\n\n try {\n final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan();\n\n if(rebalanceTaskInfoList.isEmpty()) {\n RebalanceUtils.printBatchLog(batchId, logger, \"Skipping batch \"\n + batchId + \" since it is empty.\");\n // Even though there is no rebalancing work to do, cluster\n // metadata must be updated so that the server is aware of the\n // new cluster xml.\n adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster,\n batchFinalCluster,\n batchCurrentStoreDefs,\n batchFinalStoreDefs,\n rebalanceTaskInfoList,\n false,\n true,\n false,\n false,\n true);\n return;\n }\n\n RebalanceUtils.printBatchLog(batchId, logger, \"Starting batch \"\n + batchId + \".\");\n\n // Split the store definitions\n List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n true);\n List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n false);\n boolean hasReadOnlyStores = readOnlyStoreDefs != null\n && readOnlyStoreDefs.size() > 0;\n boolean hasReadWriteStores = readWriteStoreDefs != null\n && readWriteStoreDefs.size() > 0;\n\n // STEP 1 - Cluster state change\n boolean finishedReadOnlyPhase = false;\n List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readOnlyStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 2 - Move RO data\n if(hasReadOnlyStores) {\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n // STEP 3 - Cluster change state\n finishedReadOnlyPhase = true;\n filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readWriteStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 4 - Move RW data\n if(hasReadWriteStores) {\n proxyPause();\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Successfully terminated batch \"\n + batchId + \".\");\n\n } catch(Exception e) {\n RebalanceUtils.printErrorLog(batchId, logger, \"Error in batch \"\n + batchId + \" - \" + e.getMessage(), e);\n throw new VoldemortException(\"Rebalance failed on batch \" + batchId,\n e);\n }\n }"
] | [
"public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }",
"public void logError(String message, Object sender) {\n getEventManager().sendEvent(this, IErrorEvents.class, \"onError\", new Object[] { message, sender });\n }",
"private String formatPriority(Priority value)\n {\n String result = null;\n\n if (value != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(m_locale, LocaleData.PRIORITY_TYPES);\n int priority = value.getValue();\n if (priority < Priority.LOWEST)\n {\n priority = Priority.LOWEST;\n }\n else\n {\n if (priority > Priority.DO_NOT_LEVEL)\n {\n priority = Priority.DO_NOT_LEVEL;\n }\n }\n\n priority /= 100;\n\n result = priorityTypes[priority - 1];\n }\n\n return (result);\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 static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }",
"public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }",
"private void processRemarks(Gantt gantt)\n {\n processRemarks(gantt.getRemarks());\n processRemarks(gantt.getRemarks1());\n processRemarks(gantt.getRemarks2());\n processRemarks(gantt.getRemarks3());\n processRemarks(gantt.getRemarks4());\n }",
"public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }",
"@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }"
] |
Checks if the provided duration information is valid.
@return <code>null</code> if the information is valid, the key of the suitable error message otherwise. | [
"private String validateDuration() {\n\n if (!isValidEndTypeForPattern()) {\n return Messages.ERR_SERIALDATE_INVALID_END_TYPE_FOR_PATTERN_0;\n }\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS))\n ? null\n : Messages.ERR_SERIALDATE_SERIES_END_BEFORE_START_0;\n case TIMES:\n return getOccurrences() > 0 ? null : Messages.ERR_SERIALDATE_INVALID_OCCURRENCES_0;\n default:\n return null;\n }\n\n }"
] | [
"public ConfigBuilder withMasterName(final String masterName) {\n if (masterName == null || \"\".equals(masterName)) {\n throw new IllegalArgumentException(\"masterName is null or empty: \" + masterName);\n }\n this.masterName = masterName;\n return this;\n }",
"static Path resolvePath(final Path base, final String... paths) {\n return Paths.get(base.toString(), paths);\n }",
"public BeatGrid requestBeatGridFrom(final DataReference track) {\n for (BeatGrid cached : hotCache.values()) {\n if (cached.dataReference.equals(track)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestBeatGridInternal(track, false);\n }",
"public static double blackScholesDigitalOptionDelta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate delta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);\n\n\t\t\treturn delta;\n\t\t}\n\t}",
"public static base_responses add(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 addresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nspbr6();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].action = resources[i].action;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].nexthop = resources[i].nexthop;\n\t\t\t\taddresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\taddresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void cache(Identity oid, Object obj)\r\n {\r\n if (oid != null && obj != null)\r\n {\r\n ObjectCache cache = getCache(oid, obj, METHOD_CACHE);\r\n if (cache != null)\r\n {\r\n cache.cache(oid, obj);\r\n }\r\n }\r\n }",
"@Override\n\tpublic ClosableIterator<Tuple> callStoredProcedure(String storedProcedureName, ProcedureQueryParameters params, TupleContext tupleContext) {\n\t\tvalidate( params );\n\t\tStringBuilder commandLine = createCallStoreProcedureCommand( storedProcedureName, params );\n\t\tDocument result = callStoredProcedure( commandLine );\n\t\tObject resultValue = result.get( \"retval\" );\n\t\tList<Tuple> resultTuples = extractTuples( storedProcedureName, resultValue );\n\t\treturn CollectionHelper.newClosableIterator( resultTuples );\n\t}",
"public IntervalFrequency getRefreshFrequency() {\n switch (mRefreshInterval) {\n case REALTIME_REFRESH_INTERVAL:\n return IntervalFrequency.REALTIME;\n case HIGH_REFRESH_INTERVAL:\n return IntervalFrequency.HIGH;\n case LOW_REFRESH_INTERVAL:\n return IntervalFrequency.LOW;\n case MEDIUM_REFRESH_INTERVAL:\n return IntervalFrequency.MEDIUM;\n default:\n return IntervalFrequency.NONE;\n }\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 }"
] |
Sets a new value for a given key. an older value is overwritten.
@param key a non null key
@param value the new value | [
"public void put(final K key, V value) {\n ManagedReference<V> ref = new ManagedReference<V>(bundle, value) {\n @Override\n public void finalizeReference() {\n super.finalizeReference();\n internalMap.remove(key, get());\n }\n };\n internalMap.put(key, ref);\n }"
] | [
"public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }",
"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 }",
"private static void transposeBlock(DMatrixRBlock A , DMatrixRBlock A_tran,\n int indexA , int indexC ,\n int width , int height )\n {\n for( int i = 0; i < height; i++ ) {\n int rowIndexC = indexC + i;\n int rowIndexA = indexA + width*i;\n int end = rowIndexA + width;\n for( ; rowIndexA < end; rowIndexC += height, rowIndexA++ ) {\n A_tran.data[ rowIndexC ] = A.data[ rowIndexA ];\n }\n }\n }",
"private String parseAddress(String address) {\r\n try {\r\n StringBuilder buf = new StringBuilder();\r\n InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false);\r\n for (InternetAddress netAddr : netAddrs) {\r\n if (buf.length() > 0) {\r\n buf.append(SP);\r\n }\r\n\r\n buf.append(LB);\r\n\r\n String personal = netAddr.getPersonal();\r\n if (personal != null && (personal.length() != 0)) {\r\n buf.append(Q).append(personal).append(Q);\r\n } else {\r\n buf.append(NIL);\r\n }\r\n buf.append(SP);\r\n buf.append(NIL); // should add route-addr\r\n buf.append(SP);\r\n try {\r\n // Remove quotes to avoid double quoting\r\n MailAddress mailAddr = new MailAddress(netAddr.getAddress().replaceAll(\"\\\"\", \"\\\\\\\\\\\"\"));\r\n buf.append(Q).append(mailAddr.getUser()).append(Q);\r\n buf.append(SP);\r\n buf.append(Q).append(mailAddr.getHost()).append(Q);\r\n } catch (Exception pe) {\r\n buf.append(NIL + SP + NIL);\r\n }\r\n buf.append(RB);\r\n }\r\n\r\n return buf.toString();\r\n } catch (AddressException e) {\r\n throw new RuntimeException(\"Failed to parse address: \" + address, e);\r\n }\r\n }",
"public String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}",
"public static List<String> getValueList(List<String> valuePairs, String delim) {\n List<String> valueList = Lists.newArrayList();\n for(String valuePair: valuePairs) {\n String[] value = valuePair.split(delim, 2);\n if(value.length != 2)\n throw new VoldemortException(\"Invalid argument pair: \" + valuePair);\n valueList.add(value[0]);\n valueList.add(value[1]);\n }\n return valueList;\n }",
"private String FCMGetFreshToken(final String senderID) {\n String token = null;\n try {\n if(senderID != null){\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token with Sender Id - \"+senderID);\n token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);\n }else {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token\");\n token = FirebaseInstanceId.getInstance().getToken();\n }\n getConfigLogger().info(getAccountId(),\"FCM token: \"+token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Error requesting FCM token\", t);\n }\n return token;\n }",
"private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\n }\n }",
"public boolean shouldBeInReport(final DbDependency dependency) {\n if(dependency == null){\n return false;\n }\n if(dependency.getTarget() == null){\n return false;\n }\n if(corporateFilter != null){\n if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){\n return false;\n }\n if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){\n return false;\n }\n }\n\n if(!scopeHandler.filter(dependency)){\n return false;\n }\n\n return true;\n }"
] |
Sets that there are some pending writes that occurred at a time for an associated
locally emitted change event. This variant maintains the last version set.
@param atTime the time at which the write occurred.
@param changeEvent the description of the write/change. | [
"public void setSomePendingWritesAndSave(\n final long atTime,\n final ChangeEvent<BsonDocument> changeEvent\n ) {\n docLock.writeLock().lock();\n try {\n // if we were frozen\n if (isPaused) {\n // unfreeze the document due to the local write\n setPaused(false);\n // and now the unfrozen document is now stale\n setStale(true);\n }\n\n this.lastUncommittedChangeEvent =\n coalesceChangeEvents(this.lastUncommittedChangeEvent, changeEvent);\n this.lastResolution = atTime;\n docsColl.replaceOne(\n getDocFilter(namespace, documentId),\n this);\n } finally {\n docLock.writeLock().unlock();\n }\n }"
] | [
"public static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void readBitmap() {\n // (sub)image position & size.\n header.currentFrame.ix = readShort();\n header.currentFrame.iy = readShort();\n header.currentFrame.iw = readShort();\n header.currentFrame.ih = readShort();\n\n int packed = read();\n // 1 - local color table flag interlace\n boolean lctFlag = (packed & 0x80) != 0;\n int lctSize = (int) Math.pow(2, (packed & 0x07) + 1);\n // 3 - sort flag\n // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color\n // table size\n header.currentFrame.interlace = (packed & 0x40) != 0;\n if (lctFlag) {\n // Read table.\n header.currentFrame.lct = readColorTable(lctSize);\n } else {\n // No local color table.\n header.currentFrame.lct = null;\n }\n\n // Save this as the decoding position pointer.\n header.currentFrame.bufferFrameStart = rawData.position();\n\n // False decode pixel data to advance buffer.\n skipImageData();\n\n if (err()) {\n return;\n }\n\n header.frameCount++;\n // Add image to frame.\n header.frames.add(header.currentFrame);\n }",
"public int findAnimation(GVRAnimation findme)\n {\n int index = 0;\n for (GVRAnimation anim : mAnimations)\n {\n if (anim == findme)\n {\n return index;\n }\n ++index;\n }\n return -1;\n }",
"public void stop() {\n syncLock.lock();\n try {\n if (syncThread == null) {\n return;\n }\n instanceChangeStreamListener.stop();\n syncThread.interrupt();\n try {\n syncThread.join();\n } catch (final InterruptedException e) {\n return;\n }\n syncThread = null;\n isRunning = false;\n } finally {\n syncLock.unlock();\n }\n }",
"public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }",
"public static base_responses add(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 addresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nspbr6();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].action = resources[i].action;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].nexthop = resources[i].nexthop;\n\t\t\t\taddresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\taddresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public <V> V attach(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.put(key, value));\n }",
"public void setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(targetTranslator!=null){\r\n\t\t\tthis.targetTranslator = targetTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t}\r\n\t}",
"public static Value.Builder makeValue(Value value1, Value value2, Value... rest) {\n ArrayValue.Builder arrayValue = ArrayValue.newBuilder();\n arrayValue.addValues(value1);\n arrayValue.addValues(value2);\n arrayValue.addAllValues(Arrays.asList(rest));\n return Value.newBuilder().setArrayValue(arrayValue);\n }"
] |
Populates a resource availability table.
@param table resource availability table
@param data file data | [
"public void process(AvailabilityTable table, byte[] data)\n {\n if (data != null)\n {\n Calendar cal = DateHelper.popCalendar();\n int items = MPPUtility.getShort(data, 0);\n int offset = 12;\n\n for (int loop = 0; loop < items; loop++)\n {\n double unitsValue = MPPUtility.getDouble(data, offset + 4);\n if (unitsValue != 0)\n {\n Date startDate = MPPUtility.getTimestampFromTenths(data, offset);\n Date endDate = MPPUtility.getTimestampFromTenths(data, offset + 20);\n cal.setTime(endDate);\n cal.add(Calendar.MINUTE, -1);\n endDate = cal.getTime();\n Double units = NumberHelper.getDouble(unitsValue / 100);\n Availability item = new Availability(startDate, endDate, units);\n table.add(item);\n }\n offset += 20;\n }\n DateHelper.pushCalendar(cal);\n Collections.sort(table);\n }\n }"
] | [
"private static void freeTempLOB(ClobWrapper clob, BlobWrapper blob)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (clob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the CLOB is open, close it\r\n\t\t\t\tif (clob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tclob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this CLOB\r\n\t\t\t\tclob.freeTemporary();\r\n\t\t\t}\r\n\r\n\t\t\tif (blob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the BLOB is open, close it\r\n\t\t\t\tif (blob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tblob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this BLOB\r\n\t\t\t\tblob.freeTemporary();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n logger.error(\"Error during temporary LOB release\", e);\r\n\t\t}\r\n\t}",
"public static String getBuildString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.build\");\n\t\t}\n\t\treturn versionString;\n\t}",
"static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }",
"protected BufferedImage createErrorImage(final Rectangle area) {\n final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);\n final Graphics2D graphics = bufferedImage.createGraphics();\n try {\n graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));\n graphics.clearRect(0, 0, area.width, area.height);\n return bufferedImage;\n } finally {\n graphics.dispose();\n }\n }",
"private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}",
"public void mergeSubtree(final OperationTransformerRegistry targetRegistry, final Map<PathAddress, ModelVersion> subTree) {\n for(Map.Entry<PathAddress, ModelVersion> entry: subTree.entrySet()) {\n mergeSubtree(targetRegistry, entry.getKey(), entry.getValue());\n }\n }",
"void update(Object feature) throws LayerException {\n\t\tSimpleFeatureSource source = getFeatureSource();\n\t\tif (source instanceof SimpleFeatureStore) {\n\t\t\tSimpleFeatureStore store = (SimpleFeatureStore) source;\n\t\t\tString featureId = getFeatureModel().getId(feature);\n\t\t\tFilter filter = filterService.createFidFilter(new String[] { featureId });\n\t\t\ttransactionSynchronization.synchTransaction(store);\n\t\t\tList<Name> names = new ArrayList<Name>();\n\t\t\tMap<String, Attribute> attrMap = getFeatureModel().getAttributes(feature);\n\t\t\tList<Object> values = new ArrayList<Object>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : attrMap.entrySet()) {\n\t\t\t\tString name = entry.getKey();\n\t\t\t\tnames.add(store.getSchema().getDescriptor(name).getName());\n\t\t\t\tvalues.add(entry.getValue().getValue());\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tstore.modifyFeatures(names.toArray(new Name[names.size()]), values.toArray(), filter);\n\t\t\t\tstore.modifyFeatures(store.getSchema().getGeometryDescriptor().getName(), getFeatureModel()\n\t\t\t\t\t\t.getGeometry(feature), filter);\n\t\t\t\tlog.debug(\"Updated feature {} in {}\", featureId, getFeatureSourceName());\n\t\t\t} catch (IOException ioe) {\n\t\t\t\tfeatureModelUsable = false;\n\t\t\t\tthrow new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);\n\t\t\t}\n\t\t} else {\n\t\t\tlog.error(\"Don't know how to create or update \" + getFeatureSourceName() + \", class \"\n\t\t\t\t\t+ source.getClass().getName() + \" does not implement SimpleFeatureStore\");\n\t\t\tthrow new LayerException(ExceptionCode.CREATE_OR_UPDATE_NOT_IMPLEMENTED, getFeatureSourceName(), source\n\t\t\t\t\t.getClass().getName());\n\t\t}\n\t}",
"public ItemRequest<Workspace> removeUser(String workspace) {\n \n String path = String.format(\"/workspaces/%s/removeUser\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"POST\");\n }",
"private void decreaseIndent() throws IOException\n {\n if (m_pretty)\n {\n m_writer.write('\\n');\n m_indent = m_indent.substring(0, m_indent.length() - INDENT.length());\n m_writer.write(m_indent);\n }\n m_firstNameValuePair.pop();\n }"
] |
Adds a new metadata value of array type.
@param path the path to the field.
@param values the collection of values.
@return the metadata object for chaining. | [
"public Metadata add(String path, List<String> values) {\n JsonArray arr = new JsonArray();\n for (String value : values) {\n arr.add(value);\n }\n this.values.add(this.pathToProperty(path), arr);\n this.addOp(\"add\", path, arr);\n return this;\n }"
] | [
"@UiThread\n public void expandParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n expandParent(i);\n }\n }",
"@SuppressWarnings(\"unchecked\") public static TimeUnit getInstance(String units, Locale locale) throws MPXJException\n {\n Map<String, Integer> map = LocaleData.getMap(locale, LocaleData.TIME_UNITS_MAP);\n Integer result = map.get(units.toLowerCase());\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TIME_UNIT + \" \" + units);\n }\n return (TimeUnit.getInstance(result.intValue()));\n }",
"public static Bic valueOf(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n BicUtil.validate(bic);\n return new Bic(bic);\n }",
"@Override\n public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException {\n long deadline = unit.toMillis(timeout) + System.currentTimeMillis();\n lock.lock(); try {\n assert shutdown;\n while(activeCount != 0) {\n long remaining = deadline - System.currentTimeMillis();\n if (remaining <= 0) {\n break;\n }\n condition.await(remaining, TimeUnit.MILLISECONDS);\n }\n boolean allComplete = activeCount == 0;\n if (!allComplete) {\n ProtocolLogger.ROOT_LOGGER.debugf(\"ActiveOperation(s) %s have not completed within %d %s\", activeRequests.keySet(), timeout, unit);\n }\n return allComplete;\n } finally {\n lock.unlock();\n }\n }",
"public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static void inner_reorder_lower(DMatrix1Row A , DMatrix1Row B )\n {\n final int cols = A.numCols;\n B.reshape(cols,cols);\n\n Arrays.fill(B.data,0);\n for (int i = 0; i <cols; i++) {\n for (int j = 0; j <=i; j++) {\n B.data[i*cols+j] += A.data[i]*A.data[j];\n }\n\n for (int k = 1; k < A.numRows; k++) {\n int indexRow = k*cols;\n double valI = A.data[i+indexRow];\n int indexB = i*cols;\n for (int j = 0; j <= i; j++) {\n B.data[indexB++] += valI*A.data[indexRow++];\n }\n }\n }\n }",
"private void validate(Object object) {\n\t\tSet<ConstraintViolation<Object>> viols = validator.validate(object);\n\t\tfor (ConstraintViolation<Object> constraintViolation : viols) {\n\t\t\tif (Null.class.isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) {\n\t\t\t\tObject o = constraintViolation.getLeafBean();\n\t\t\t\tIterator<Node> iterator = constraintViolation.getPropertyPath().iterator();\n\t\t\t\tString propertyName = null;\n\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\tpropertyName = iterator.next().getName();\n\t\t\t\t}\n\t\t\t\tif (propertyName != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tPropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);\n\t\t\t\t\t\tdescriptor.getWriteMethod().invoke(o, new Object[] { null });\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"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}",
"<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) {\n return handlers.get(artifact);\n }"
] |
Given a particular key, first converts its to the storage format and then
determines which chunk it belongs to
@param key Byte array of keys
@return Chunk id
@throws IllegalStateException if unable to find the chunk id for the given key | [
"public int getChunkForKey(byte[] key) throws IllegalStateException {\n if(numChunks == 0) {\n throw new IllegalStateException(\"The ChunkedFileSet is closed.\");\n }\n\n switch(storageFormat) {\n case READONLY_V0: {\n return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks);\n }\n case READONLY_V1: {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n routingPartitionList.retainAll(nodePartitionIds);\n\n if(routingPartitionList.size() != 1) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n return chunkIdToChunkStart.get(routingPartitionList.get(0))\n + ReadOnlyUtils.chunk(ByteUtils.md5(key),\n chunkIdToNumChunks.get(routingPartitionList.get(0)));\n }\n case READONLY_V2: {\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n\n Pair<Integer, Integer> bucket = null;\n for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) {\n if(bucket == null) {\n bucket = Pair.create(routingPartitionList.get(0), replicaType);\n } else {\n throw new IllegalStateException(\"Found more than one replica for a given partition on the current node!\");\n }\n }\n }\n\n if(bucket == null) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n Integer chunkStart = chunkIdToChunkStart.get(bucket);\n\n if (chunkStart == null) {\n throw new IllegalStateException(\"chunkStart is null.\");\n }\n\n return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket));\n }\n default: {\n throw new IllegalStateException(\"Unsupported storageFormat: \" + storageFormat);\n }\n }\n\n }"
] | [
"public final void loadCollection(\n\t\tfinal SharedSessionContractImplementor session,\n\t\tfinal Serializable id,\n\t\tfinal Type type) throws HibernateException {\n\n\t\tif ( log.isDebugEnabled() ) {\n\t\t\tlog.debug(\n\t\t\t\t\t\"loading collection: \" +\n\t\t\t\t\tMessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() )\n\t\t\t\t);\n\t\t}\n\n\t\tSerializable[] ids = new Serializable[]{id};\n\t\tQueryParameters qp = new QueryParameters( new Type[]{type}, ids, ids );\n\t\tdoQueryAndInitializeNonLazyCollections(\n\t\t\t\tsession,\n\t\t\t\tqp,\n\t\t\t\tOgmLoadingContext.EMPTY_CONTEXT,\n\t\t\t\ttrue\n\t\t\t);\n\n\t\tlog.debug( \"done loading collection\" );\n\n\t}",
"public Set<ConstraintViolation> validate() {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int record = 1; record <= 3; ++record) {\r\n\t\t\terrors.addAll(validate(record));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}",
"private static String firstFoundTableName(PersistenceBroker brokerForClass, ClassDescriptor cld)\r\n {\r\n String name = null;\r\n if (!cld.isInterface() && cld.getFullTableName() != null)\r\n {\r\n return cld.getFullTableName();\r\n }\r\n if (cld.isExtent())\r\n {\r\n Collection extentClasses = cld.getExtentClasses();\r\n for (Iterator iterator = extentClasses.iterator(); iterator.hasNext();)\r\n {\r\n name = firstFoundTableName(brokerForClass, brokerForClass.getClassDescriptor((Class) iterator.next()));\r\n // System.out.println(\"## \" + cld.getClassNameOfObject()+\" - name: \"+name);\r\n if (name != null) break;\r\n }\r\n }\r\n return name;\r\n }",
"private String getHostHeaderForHost(String hostName) {\n List<ServerRedirect> servers = serverRedirectService.tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n String hostHeader = server.getHostHeader();\n if (hostHeader == null || hostHeader.length() == 0) {\n return null;\n }\n return hostHeader;\n }\n }\n return null;\n }",
"public void performImplicitDoubleStep(int x1, int x2 , double real , double img ) {\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n double p_plus_t = 2.0*real;\n double p_times_t = real*real + img*img;\n\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = (a11*a11 - p_plus_t*a11+p_times_t)/a21 + a12;\n b21 = a11+a22-p_plus_t;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = (a11*a11 - p_plus_t*a11+p_times_t) + a12*a21;\n b21 = (a11+a22-p_plus_t)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11, b21, b31);\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 static boolean doAcquireLock(final Jedis jedis, final String namespace, final String lockName, final String lockHolder, final int timeout) {\n final String key = JesqueUtils.createKey(namespace, lockName);\n // If lock already exists, extend it\n String existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n }\n // Check to see if the key exists and is expired for cleanup purposes\n if (jedis.exists(key) && (jedis.ttl(key) < 0)) {\n // It is expired, but it may be in the process of being created, so\n // sleep and check again\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ie) {\n } // Ignore interruptions\n if (jedis.ttl(key) < 0) {\n existingLockHolder = jedis.get(key);\n // If it is our lock mark the time to live\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n } else { // The key is expired, whack it!\n jedis.del(key);\n }\n } else { // Someone else locked it while we were sleeping\n return false;\n }\n }\n // Ignore the cleanup steps above, start with no assumptions test\n // creating the key\n if (jedis.setnx(key, lockHolder) == 1) {\n // Created the lock, now set the expiration\n if (jedis.expire(key, timeout) == 1) { // Set the timeout\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n } else { // Don't know why it failed, but for now just report failed\n // acquisition\n return false;\n }\n }\n // Failed to create the lock\n return false;\n }",
"public static void startTrack(final Object... args){\r\n if(isClosed){ return; }\r\n //--Create Record\r\n final int len = args.length == 0 ? 0 : args.length-1;\r\n final Object content = args.length == 0 ? \"\" : args[len];\r\n final Object[] tags = new Object[len];\r\n final StackTraceElement ste = getStackTrace();\r\n final long timestamp = System.currentTimeMillis();\r\n System.arraycopy(args,0,tags,0,len);\r\n //--Create Task\r\n final long threadID = Thread.currentThread().getId();\r\n final Runnable startTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n Record toPass = new Record(content,tags,depth,ste,timestamp);\r\n depth += 1;\r\n titleStack.push(args.length == 0 ? \"\" : args[len].toString());\r\n handlers.process(toPass, MessageType.START_TRACK, depth, toPass.timesstamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, startTrack );\r\n } else {\r\n //(case: no threading)\r\n startTrack.run();\r\n }\r\n }",
"void onDrawEye(int eye, int swapChainIndex, boolean use_multiview) {\n mCurrentEye = eye;\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n GVRCameraRig mainCameraRig = mMainScene.getMainCameraRig();\n\n if (use_multiview) {\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter(); // this eye is drawn first\n mTracerDrawEyes2.enter();\n }\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.MULTIVIEW, swapChainIndex);\n GVRCamera camera = mMainScene.getMainCameraRig().getCenterCamera();\n GVRCamera left_camera = mMainScene.getMainCameraRig().getLeftCamera();\n renderTarget.cullFromCamera(mMainScene, camera,mRenderBundle.getShaderManager());\n\n captureCenterEye(renderTarget, true);\n capture3DScreenShot(renderTarget, true);\n\n renderTarget.render(mMainScene, left_camera, mRenderBundle.getShaderManager(),mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n\n captureRightEye(renderTarget, true);\n captureLeftEye(renderTarget, true);\n\n captureFinish();\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes2.leave();\n }\n\n\n } else {\n\n if (eye == 1) {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter();\n }\n\n GVRCamera rightCamera = mainCameraRig.getRightCamera();\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.RIGHT, swapChainIndex);\n renderTarget.render(mMainScene, rightCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n captureRightEye(renderTarget, false);\n\n captureFinish();\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n } else {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n\n\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.LEFT, swapChainIndex);\n GVRCamera leftCamera = mainCameraRig.getLeftCamera();\n\n capture3DScreenShot(renderTarget, false);\n\n renderTarget.cullFromCamera(mMainScene, mainCameraRig.getCenterCamera(), mRenderBundle.getShaderManager());\n captureCenterEye(renderTarget, false);\n renderTarget.render(mMainScene, leftCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(), mRenderBundle.getPostEffectRenderTextureB());\n\n captureLeftEye(renderTarget, false);\n\n if (DEBUG_STATS) {\n mTracerDrawEyes2.leave();\n }\n }\n }\n }\n }"
] |
Register the DAO with the cache. This will allow folks to build a DAO externally and then register so it can be
used internally as necessary.
<p>
<b>NOTE:</b> By default this registers the DAO to be associated with the class that it uses. If you need to
register multiple dao's that use different {@link DatabaseTableConfig}s then you should use
{@link #registerDaoWithTableConfig(ConnectionSource, Dao)}.
</p>
<p>
<b>NOTE:</b> You should maybe use the {@link DatabaseTable#daoClass()} and have the DaoManager construct the DAO
if possible.
</p> | [
"public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\taddDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);\n\t}"
] | [
"public static crvserver_policymap_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcrvserver_policymap_binding obj = new crvserver_policymap_binding();\n\t\tobj.set_name(name);\n\t\tcrvserver_policymap_binding response[] = (crvserver_policymap_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean hasValue(String fieldName) {\n\t\treturn resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null;\n\t}",
"public static void main(String[] args) throws IOException, ClassNotFoundException {\r\n CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter();\r\n f.init(new SeqClassifierFlags());\r\n int numDocs = 0;\r\n int numTokens = 0;\r\n int numEntities = 0;\r\n String lastAnsBase = \"\";\r\n for (Iterator<List<CoreLabel>> it = f.getIterator(new FileReader(args[0])); it.hasNext(); ) {\r\n List<CoreLabel> doc = it.next();\r\n numDocs++;\r\n for (CoreLabel fl : doc) {\r\n // System.out.println(\"FL \" + (++i) + \" was \" + fl);\r\n if (fl.word().equals(BOUNDARY)) {\r\n continue;\r\n }\r\n String ans = fl.get(AnswerAnnotation.class);\r\n String ansBase;\r\n String ansPrefix;\r\n String[] bits = ans.split(\"-\");\r\n if (bits.length == 1) {\r\n ansBase = bits[0];\r\n ansPrefix = \"\";\r\n } else {\r\n ansBase = bits[1];\r\n ansPrefix = bits[0];\r\n }\r\n numTokens++;\r\n if (ansBase.equals(\"O\")) {\r\n } else if (ansBase.equals(lastAnsBase)) {\r\n if (ansPrefix.equals(\"B\")) {\r\n numEntities++;\r\n }\r\n } else {\r\n numEntities++;\r\n }\r\n }\r\n }\r\n System.out.println(\"File \" + args[0] + \" has \" + numDocs + \" documents, \" +\r\n numTokens + \" (non-blank line) tokens and \" +\r\n numEntities + \" entities.\");\r\n }",
"public static base_responses delete(nitro_service client, String certkey[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey deleteresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcertkey();\n\t\t\t\tdeleteresources[i].certkey = certkey[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 StatisticsMatrix wrap( DMatrixRMaj m ) {\n StatisticsMatrix ret = new StatisticsMatrix();\n ret.setMatrix( m );\n\n return ret;\n }",
"private void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {\n if (!getTrackMetadataListeners().isEmpty()) {\n final TrackMetadataUpdate update = new TrackMetadataUpdate(player, metadata);\n for (final TrackMetadataListener listener : getTrackMetadataListeners()) {\n try {\n listener.metadataChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering track metadata update to listener\", t);\n }\n }\n }\n }",
"@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"private org.apache.log4j.Logger getLogger()\r\n\t{\r\n /*\r\n Logger interface extends Serializable, thus Log field is\r\n declared 'transient' and we have to null-check\r\n\t\t*/\r\n\t\tif (logger == null)\r\n\t\t{\r\n\t\t\tlogger = org.apache.log4j.Logger.getLogger(name);\r\n\t\t}\r\n\t\treturn logger;\r\n\t}",
"public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter)\n throws Throwable {\n run(configuration, candidateSteps, story, filter, null);\n }"
] |
Creates the automaton map.
@param prefix the prefix
@param valueList the value list
@param filter the filter
@return the map | [
"public static Map<String, Automaton> createAutomatonMap(String prefix,\n List<String> valueList, Boolean filter) {\n HashMap<String, Automaton> automatonMap = new HashMap<>();\n if (valueList != null) {\n for (String item : valueList) {\n if (filter) {\n item = item.replaceAll(\"([\\\\\\\"\\\\)\\\\(\\\\<\\\\>\\\\.\\\\@\\\\#\\\\]\\\\[\\\\{\\\\}])\",\n \"\\\\\\\\$1\");\n }\n automatonMap.put(item,\n new RegExp(prefix + MtasToken.DELIMITER + item + \"\\u0000*\")\n .toAutomaton());\n }\n }\n return automatonMap;\n }"
] | [
"public static void checkMinimumArrayLength(String parameterName,\n int actualLength, int minimumLength) {\n if (actualLength < minimumLength) {\n throw Exceptions\n .IllegalArgument(\n \"Array %s should have at least %d elements, but it only has %d\",\n parameterName, minimumLength, actualLength);\n }\n }",
"private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }",
"public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }",
"public void setWeekDay(String dayString) {\n\n final WeekDay day = WeekDay.valueOf(dayString);\n if (m_model.getWeekDay() != day) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(day);\n onValueChange();\n }\n });\n }\n\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}",
"private void bubbleUpNodeTable(DAGraph<DataT, NodeT> from, LinkedList<String> path) {\n if (path.contains(from.rootNode.key())) {\n path.push(from.rootNode.key()); // For better error message\n throw new IllegalStateException(\"Detected circular dependency: \" + StringUtils.join(path, \" -> \"));\n }\n path.push(from.rootNode.key());\n for (DAGraph<DataT, NodeT> to : from.parentDAGs) {\n this.merge(from.nodeTable, to.nodeTable);\n this.bubbleUpNodeTable(to, path);\n }\n path.pop();\n }",
"private void ensureReferencedFKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException\r\n {\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);\r\n String fkFieldNames = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n ArrayList missingFields = new ArrayList();\r\n SequencedHashMap fkFields = new SequencedHashMap();\r\n\r\n // first we gather all field names\r\n for (CommaListIterator it = new CommaListIterator(fkFieldNames); it.hasNext();)\r\n {\r\n String fieldName = (String)it.next();\r\n FieldDescriptorDef fieldDef = elementClassDef.getField(fieldName);\r\n\r\n if (fieldDef == null)\r\n {\r\n missingFields.add(fieldName);\r\n }\r\n fkFields.put(fieldName, fieldDef);\r\n }\r\n\r\n // next we traverse all sub types and gather fields as we go\r\n for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext() && !missingFields.isEmpty();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n for (int idx = 0; idx < missingFields.size();)\r\n {\r\n FieldDescriptorDef fieldDef = subTypeDef.getField((String)missingFields.get(idx));\r\n\r\n if (fieldDef != null)\r\n {\r\n fkFields.put(fieldDef.getName(), fieldDef);\r\n missingFields.remove(idx);\r\n }\r\n else\r\n {\r\n idx++;\r\n }\r\n }\r\n }\r\n if (!missingFields.isEmpty())\r\n {\r\n throw new ConstraintException(\"Cannot find field \"+missingFields.get(0).toString()+\" in the hierarchy with root type \"+\r\n elementClassDef.getName()+\" which is used as foreignkey in collection \"+\r\n collDef.getName()+\" in \"+collDef.getOwner().getName());\r\n }\r\n\r\n // copy the found fields into the element class\r\n ensureFields(elementClassDef, fkFields.values());\r\n }",
"private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) {\n Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year);\n return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0));\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 }"
] |
Handles the change of a value in the current translation.
@param propertyId the property id of the column where the value has changed. | [
"public void handleChange(Object propertyId) {\n\n try {\n lockOnChange(propertyId);\n } catch (CmsException e) {\n LOG.debug(e);\n }\n if (isDescriptorProperty(propertyId)) {\n m_descriptorHasChanges = true;\n }\n if (isBundleProperty(propertyId)) {\n m_changedTranslations.add(getLocale());\n }\n\n }"
] | [
"public void readFrom(DataInput instream) throws Exception {\n host = S3Util.readString(instream);\n port = instream.readInt();\n protocol = S3Util.readString(instream);\n }",
"@Override\n public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {\n return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);\n }",
"protected int parseZoneId() {\n int result = -1;\n String zoneIdStr = this.request.getHeader(RestMessageHeaders.X_VOLD_ZONE_ID);\n if(zoneIdStr != null) {\n try {\n int zoneId = Integer.parseInt(zoneIdStr);\n if(zoneId < 0) {\n logger.error(\"ZoneId cannot be negative. Assuming the default zone id.\");\n } else {\n result = zoneId;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: \"\n + zoneIdStr,\n nfe);\n }\n }\n return result;\n }",
"@Override\n public void detachScriptFile(IScriptable target) {\n IScriptFile scriptFile = mScriptMap.remove(target);\n if (scriptFile != null) {\n scriptFile.invokeFunction(\"onDetach\", new Object[] { target });\n }\n }",
"protected static void main(String args[]) {\r\n\tint from = Integer.parseInt(args[0]);\t\r\n\tint to = Integer.parseInt(args[1]);\r\n\t\r\n\tstatistics(from,to);\r\n}",
"private void addTables(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Table table : file.getTables())\n {\n final Table t = table;\n MpxjTreeNode childNode = new MpxjTreeNode(table, TABLE_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n\n addColumns(childNode, table);\n }\n }",
"public static long count(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\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_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}",
"protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {\n\t\tswitch (httpMethod) {\n\t\t\tcase GET:\n\t\t\t\treturn new HttpGet(uri);\n\t\t\tcase DELETE:\n\t\t\t\treturn new HttpDelete(uri);\n\t\t\tcase HEAD:\n\t\t\t\treturn new HttpHead(uri);\n\t\t\tcase OPTIONS:\n\t\t\t\treturn new HttpOptions(uri);\n\t\t\tcase POST:\n\t\t\t\treturn new HttpPost(uri);\n\t\t\tcase PUT:\n\t\t\t\treturn new HttpPut(uri);\n\t\t\tcase TRACE:\n\t\t\t\treturn new HttpTrace(uri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid HTTP method: \" + httpMethod);\n\t\t}\n\t}",
"public void run()\r\n { \t\r\n \tSystem.out.println(AsciiSplash.getSplashArt());\r\n System.out.println(\"Welcome to the OJB PB tutorial application\");\r\n System.out.println();\r\n // never stop (there is a special use case to quit the application)\r\n while (true)\r\n {\r\n try\r\n {\r\n // select a use case and perform it\r\n UseCase uc = selectUseCase();\r\n uc.apply();\r\n }\r\n catch (Throwable t)\r\n {\r\n broker.close();\r\n System.out.println(t.getMessage());\r\n }\r\n }\r\n }"
] |
Starts off a new thread to monitor this connection attempt.
@param connectionHandle to monitor | [
"protected void watchConnection(ConnectionHandle connectionHandle) {\r\n\t\tString message = captureStackTrace(UNCLOSED_EXCEPTION_MESSAGE);\r\n\t\tthis.closeConnectionExecutor.submit(new CloseThreadMonitor(Thread.currentThread(), connectionHandle, message, this.closeConnectionWatchTimeoutInMs));\r\n\t}"
] | [
"private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\n }",
"@Override\n\tpublic boolean isSinglePrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn containsSinglePrefixBlock(networkPrefixLength);\n\t}",
"private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public Class<?> getType(String key) {\n Object val = this.data.get(key);\n return val == null ? null : val.getClass();\n }",
"private void initializeSignProperties() {\n if (!signPackage && !signChanges) {\n return;\n }\n\n if (key != null && keyring != null && passphrase != null) {\n return;\n }\n\n Map<String, String> properties =\n readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);\n\n key = lookupIfEmpty(key, properties, KEY);\n keyring = lookupIfEmpty(keyring, properties, KEYRING);\n passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));\n\n if (keyring == null) {\n try {\n keyring = Utils.guessKeyRingFile().getAbsolutePath();\n console.info(\"Located keyring at \" + keyring);\n } catch (FileNotFoundException e) {\n console.warn(e.getMessage());\n }\n }\n }",
"public static HttpConnection connect(String requestMethod,\n URL url,\n String contentType) {\n return new HttpConnection(requestMethod, url, contentType);\n }",
"public void visitParameter(String name, int access) {\n if (mv != null) {\n mv.visitParameter(name, access);\n }\n }",
"private void writePredecessors(Task task)\n {\n List<Relation> relations = task.getPredecessors();\n for (Relation mpxj : relations)\n {\n RelationshipType xml = m_factory.createRelationshipType();\n m_project.getRelationship().add(xml);\n\n xml.setLag(getDuration(mpxj.getLag()));\n xml.setObjectId(Integer.valueOf(++m_relationshipObjectID));\n xml.setPredecessorActivityObjectId(mpxj.getTargetTask().getUniqueID());\n xml.setSuccessorActivityObjectId(mpxj.getSourceTask().getUniqueID());\n xml.setPredecessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSuccessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setType(RELATION_TYPE_MAP.get(mpxj.getType()));\n }\n }",
"public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)\n throws InterruptedException, IOException {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());\n return new LargeFileUpload().\n upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);\n }"
] |
Sets an error message that will be displayed in a popup when the EditText has focus along
with an icon displayed at the right-hand side.
@param error error message to show | [
"@SuppressWarnings(\"unused\")\n public void setError(CharSequence error, Drawable icon) {\n mPhoneEdit.setError(error, icon);\n }"
] | [
"@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }",
"public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }",
"public void implicitDoubleStep( int x1 , int x2 ) {\n if( printHumps )\n System.out.println(\"Performing implicit double step\");\n\n // compute the wilkinson shift\n double z11 = A.get(x2 - 1, x2 - 1);\n double z12 = A.get(x2 - 1, x2);\n double z21 = A.get(x2, x2 - 1);\n double z22 = A.get(x2, x2);\n\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n if( normalize ) {\n temp[0] = a11;temp[1] = a21;temp[2] = a12;temp[3] = a22;temp[4] = a32;\n temp[5] = z11;temp[6] = z22;temp[7] = z12;temp[8] = z21;\n\n double max = Math.abs(temp[0]);\n for( int j = 1; j < temp.length; j++ ) {\n if( Math.abs(temp[j]) > max )\n max = Math.abs(temp[j]);\n }\n a11 /= max;a21 /= max;a12 /= max;a22 /= max;a32 /= max;\n z11 /= max;z22 /= max;z12 /= max;z21 /= max;\n }\n\n // these equations are derived when the eigenvalues are extracted from the lower right\n // 2 by 2 matrix. See page 388 of Fundamentals of Matrix Computations 2nd ed for details.\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = ((a11- z11)*(a11- z22)- z21 * z12)/a21 + a12;\n b21 = a11 + a22 - z11 - z22;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = ((a11- z11)*(a11- z22)- z21 * z12) + a12*a21;\n b21 = (a11 + a22 - z11 - z22)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11 , b21 , b31 );\n }",
"public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public void setMesh(GVRMesh mesh) {\n mMesh = mesh;\n NativeMeshCollider.setMesh(getNative(), mesh.getNative());\n }",
"protected String pauseMsg() throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setPaused(isPaused());\n return ObjectMapperFactory.get().writeValueAsString(status);\n }",
"public static 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}",
"private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }",
"public static String getHeaders(HttpServletRequest request) {\n String headerString = \"\";\n Enumeration<String> headerNames = request.getHeaderNames();\n\n while (headerNames.hasMoreElements()) {\n String name = headerNames.nextElement();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += name + \": \" + request.getHeader(name);\n }\n\n return headerString;\n }"
] |
Internal utility to help JNI add hit objects to the pick list. Specifically for MeshColliders with picking
for UV, Barycentric, and normal coordinates enabled | [
"static GVRPickedObject makeHitMesh(long colliderPointer, float distance, float hitx, float hity, float hitz,\n int faceIndex, float barycentricx, float barycentricy, float barycentricz,\n float texu, float texv, float normalx, float normaly, float normalz)\n {\n GVRCollider collider = GVRCollider.lookup(colliderPointer);\n if (collider == null)\n {\n Log.d(TAG, \"makeHit: cannot find collider for %x\", colliderPointer);\n return null;\n }\n return new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance, faceIndex,\n new float[] {barycentricx, barycentricy, barycentricz},\n new float[]{ texu, texv },\n new float[]{normalx, normaly, normalz});\n }"
] | [
"public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }",
"public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }",
"public void loadWithTimeout(int timeout) {\n\n for (String stylesheet : m_stylesheets) {\n boolean alreadyLoaded = checkStylesheet(stylesheet);\n if (alreadyLoaded) {\n m_loadCounter += 1;\n } else {\n appendStylesheet(stylesheet, m_jsCallback);\n }\n }\n checkAllLoaded();\n if (timeout > 0) {\n Timer timer = new Timer() {\n\n @SuppressWarnings(\"synthetic-access\")\n @Override\n public void run() {\n\n callCallback();\n }\n };\n\n timer.schedule(timeout);\n }\n }",
"public float getMetallic()\n {\n Property p = getProperty(PropertyKey.METALLIC.m_key);\n\n if (null == p || null == p.getData())\n {\n throw new IllegalArgumentException(\"Metallic property not found\");\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.FloatBuffer fbuf = ((java.nio.ByteBuffer) rawValue).asFloatBuffer();\n return fbuf.get();\n }\n else\n {\n return (Float) rawValue;\n }\n }",
"private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }",
"protected Channel awaitChannel() throws IOException {\n Channel channel = this.channel;\n if(channel != null) {\n return channel;\n }\n synchronized (lock) {\n for(;;) {\n if(state == State.CLOSED) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n channel = this.channel;\n if(channel != null) {\n return channel;\n }\n if(state == State.CLOSING) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n try {\n lock.wait();\n } catch (InterruptedException e) {\n throw new IOException(e);\n }\n }\n }\n }",
"public static Object setProperty( String key, String value ) {\n return prp.setProperty( key, value );\n }",
"protected void runStatements(Reader reader, PrintStream out)\n throws IOException {\n log.debug(\"runStatements()\");\n StringBuilder txt = new StringBuilder();\n String line = \"\";\n BufferedReader in = new BufferedReader(reader);\n\n while ((line = in.readLine()) != null) {\n line = getProject().replaceProperties(line);\n if (line.indexOf(\"--\") >= 0) {\n txt.append(\"\\n\");\n }\n }\n // Catch any statements not followed by ;\n if (!txt.toString().equals(\"\")) {\n execGroovy(txt.toString(), out);\n }\n }",
"public static Cluster createUpdatedCluster(Cluster currentCluster,\n int stealerNodeId,\n List<Integer> donatedPartitions) {\n Cluster updatedCluster = Cluster.cloneCluster(currentCluster);\n // Go over every donated partition one by one\n for(int donatedPartition: donatedPartitions) {\n\n // Gets the donor Node that owns this donated partition\n Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition);\n Node stealerNode = updatedCluster.getNodeById(stealerNodeId);\n\n if(donorNode == stealerNode) {\n // Moving to the same location = No-op\n continue;\n }\n\n // Update the list of partitions for this node\n donorNode = removePartitionFromNode(donorNode, donatedPartition);\n stealerNode = addPartitionToNode(stealerNode, donatedPartition);\n\n // Sort the nodes\n updatedCluster = updateCluster(updatedCluster,\n Lists.newArrayList(donorNode, stealerNode));\n\n }\n\n return updatedCluster;\n }"
] |
Set a proxy with authentication for REST-requests.
@param proxyHost
@param proxyPort
@param username
@param password | [
"public void setProxy(String proxyHost, int proxyPort, String username, String password) {\n setProxy(proxyHost, proxyPort);\n proxyAuth = true;\n proxyUser = username;\n proxyPassword = password;\n }"
] | [
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getTotalVisits() {\n EventDetail ed = getLocalDataStore().getEventDetail(Constants.APP_LAUNCHED_EVENT);\n if (ed != null) return ed.getCount();\n\n return 0;\n }",
"public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }",
"public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }",
"@SuppressWarnings(\"InsecureCryptoUsage\") // Only used in known-weak crypto \"legacy\" mode.\n static byte[] aes128Encrypt(StringBuilder message, String key) {\n try {\n key = normalizeString(key, 16);\n rightPadString(message, '{', 16);\n Cipher cipher = Cipher.getInstance(\"AES/ECB/NoPadding\");\n cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), \"AES\"));\n return cipher.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public static void main(String[] args) {\r\n\r\n String[] s = {\"there once was a man\", \"this one is a manic\", \"hey there\", \"there once was a mane\", \"once in a manger.\", \"where is one match?\", \"Jo3seph Smarr!\", \"Joseph R Smarr\"};\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.println(\"s1: \" + s[i]);\r\n System.out.println(\"s2: \" + s[j]);\r\n System.out.println(\"edit distance: \" + editDistance(s[i], s[j]));\r\n System.out.println(\"LCS: \" + longestCommonSubstring(s[i], s[j]));\r\n System.out.println(\"LCCS: \" + longestCommonContiguousSubstring(s[i], s[j]));\r\n System.out.println();\r\n }\r\n }\r\n }",
"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}",
"protected void markStatementsForInsertion(\n\t\t\tStatementDocument currentDocument, List<Statement> addStatements) {\n\t\tfor (Statement statement : addStatements) {\n\t\t\taddStatement(statement, true);\n\t\t}\n\n\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\tif (this.toKeep.containsKey(sg.getProperty())) {\n\t\t\t\tfor (Statement statement : sg) {\n\t\t\t\t\tif (!this.toDelete.contains(statement.getStatementId())) {\n\t\t\t\t\t\taddStatement(statement, false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public BoxFileUploadSessionPartList listParts(int offset, int limit) {\n URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint();\n URLTemplate template = new URLTemplate(listPartsURL.toString());\n\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(OFFSET_QUERY_STRING, offset);\n String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString();\n\n //Template is initalized with the full URL. So empty string for the path.\n URL url = template.buildWithQuery(\"\", queryString);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n return new BoxFileUploadSessionPartList(jsonObject);\n }",
"public final void error(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.ERROR, pObject, null);\r\n\t}"
] |
Helper method to load a property file from class path.
@param filesToLoad
an array of paths (class path paths) designating where the files may be. All files are loaded, in the order
given. Missing files are silently ignored.
@return a Properties object, which may be empty but not null. | [
"public static Properties loadProperties(String[] filesToLoad)\n {\n Properties p = new Properties();\n InputStream fis = null;\n for (String path : filesToLoad)\n {\n try\n {\n fis = Db.class.getClassLoader().getResourceAsStream(path);\n if (fis != null)\n {\n p.load(fis);\n jqmlogger.info(\"A jqm.properties file was found at {}\", path);\n }\n }\n catch (IOException e)\n {\n // We allow no configuration files, but not an unreadable configuration file.\n throw new DatabaseException(\"META-INF/jqm.properties file is invalid\", e);\n }\n finally\n {\n closeQuietly(fis);\n }\n }\n\n // Overload the datasource name from environment variable if any (tests only).\n String dbName = System.getenv(\"DB\");\n if (dbName != null)\n {\n p.put(\"com.enioka.jqm.jdbc.datasource\", \"jdbc/\" + dbName);\n }\n\n // Done\n return p;\n }"
] | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal);\n }",
"public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, Class<T> clazz) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tClassConnectionSource key = new ClassConnectionSource(connectionSource, clazz);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) dao;\n\t\treturn castDao;\n\t}",
"public String propertyValue(Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n return value;\r\n }",
"private <FT, FID> FT createForeignShell(ConnectionSource connectionSource, Object val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tFT foreignObject = castDao.createObjectInstance();\n\t\tforeignIdField.assignField(connectionSource, foreignObject, val, false, objectCache);\n\t\treturn foreignObject;\n\t}",
"public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n GVRCamera shadowCam = GVRShadowMap.makeOrthoShadowCamera(\n getGVRContext().getMainScene().getMainCameraRig().getCenterCamera());\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }",
"public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }",
"public static RouteInfo of(ActionContext context) {\n H.Method m = context.req().method();\n String path = context.req().url();\n RequestHandler handler = context.handler();\n if (null == handler) {\n handler = UNKNOWN_HANDLER;\n }\n return new RouteInfo(m, path, handler);\n }",
"public static base_responses unset(nitro_service client, String acl6name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 unsetresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tunsetresources[i] = new nsacl6();\n\t\t\t\tunsetresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }"
] |
Use this API to fetch a vpnglobal_authenticationsamlpolicy_binding resources. | [
"public static vpnglobal_authenticationsamlpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_authenticationsamlpolicy_binding obj = new vpnglobal_authenticationsamlpolicy_binding();\n\t\tvpnglobal_authenticationsamlpolicy_binding response[] = (vpnglobal_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public List<GetLocationResult> search(String q, int maxRows, Locale locale)\n\t\t\tthrows Exception {\n\t\tList<GetLocationResult> searchResult = new ArrayList<GetLocationResult>();\n\n\t\tString url = URLEncoder.encode(q, \"UTF8\");\n\t\turl = \"q=select%20*%20from%20geo.placefinder%20where%20text%3D%22\"\n\t\t\t\t+ url + \"%22\";\n\t\tif (maxRows > 0) {\n\t\t\turl = url + \"&count=\" + maxRows;\n\t\t}\n\t\turl = url + \"&flags=GX\";\n\t\tif (null != locale) {\n\t\t\turl = url + \"&locale=\" + locale;\n\t\t}\n\t\tif (appId != null) {\n\t\t\turl = url + \"&appid=\" + appId;\n\t\t}\n\n\t\tInputStream inputStream = connect(url);\n\t\tif (null != inputStream) {\n\t\t\tSAXBuilder parser = new SAXBuilder();\n\t\t\tDocument doc = parser.build(inputStream);\n\n\t\t\tElement root = doc.getRootElement();\n\n\t\t\t// check code for exception\n\t\t\tString message = root.getChildText(\"Error\");\n\t\t\t// Integer errorCode = Integer.parseInt(message);\n\t\t\tif (message != null && Integer.parseInt(message) != 0) {\n\t\t\t\tthrow new Exception(root.getChildText(\"ErrorMessage\"));\n\t\t\t}\n\t\t\tElement results = root.getChild(\"results\");\n\t\t\tfor (Object obj : results.getChildren(\"Result\")) {\n\t\t\t\tElement toponymElement = (Element) obj;\n\t\t\t\tGetLocationResult location = getLocationFromElement(toponymElement);\n\t\t\t\tsearchResult.add(location);\n\t\t\t}\n\t\t}\n\t\treturn searchResult;\n\t}",
"@SuppressWarnings(\"unused\")\n public boolean isValid() {\n Phonenumber.PhoneNumber phoneNumber = getPhoneNumber();\n return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber);\n }",
"public boolean isValid() {\n\t\tif(parsedHost != null) {\n\t\t\treturn true;\n\t\t}\n\t\tif(validationException != null) {\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tvalidate();\n\t\t\treturn true;\n\t\t} catch(HostNameException e) {\n\t\t\treturn false;\n\t\t}\n\t}",
"public ItemRequest<Project> delete(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"DELETE\");\n }",
"private void srand(int ijkl) {\n u = new double[97];\n\n int ij = ijkl / 30082;\n int kl = ijkl % 30082;\n\n // Handle the seed range errors\n // First random number seed must be between 0 and 31328\n // Second seed must have a value between 0 and 30081\n if (ij < 0 || ij > 31328 || kl < 0 || kl > 30081) {\n ij = ij % 31329;\n kl = kl % 30082;\n }\n\n int i = ((ij / 177) % 177) + 2;\n int j = (ij % 177) + 2;\n int k = ((kl / 169) % 178) + 1;\n int l = kl % 169;\n\n int m;\n double s, t;\n for (int ii = 0; ii < 97; ii++) {\n s = 0.0;\n t = 0.5;\n for (int jj = 0; jj < 24; jj++) {\n m = (((i * j) % 179) * k) % 179;\n i = j;\n j = k;\n k = m;\n l = (53 * l + 1) % 169;\n if (((l * m) % 64) >= 32) {\n s += t;\n }\n t *= 0.5;\n }\n u[ii] = s;\n }\n\n c = 362436.0 / 16777216.0;\n cd = 7654321.0 / 16777216.0;\n cm = 16777213.0 / 16777216.0;\n i97 = 96;\n j97 = 32;\n }",
"public static gslbvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tgslbvserver_spilloverpolicy_binding obj = new gslbvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tgslbvserver_spilloverpolicy_binding response[] = (gslbvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static List<File> listFiles(File[] directories, IOFileFilter fileFilter, IOFileFilter dirFilter) {\n List<File> files = new ArrayList<>();\n for (File directory : directories) {\n if (!directory.isDirectory()) {\n continue;\n }\n Collection<File> filesInDirectory = FileUtils.listFiles(directory,\n fileFilter,\n dirFilter);\n files.addAll(filesInDirectory);\n }\n return files;\n }",
"public String prepareStatementString() throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\treturn buildStatementString(argList);\n\t}",
"public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {\n\t\ttry {\n\t\t\ttemplate.saveState();\n\t\t\t// opacity\n\t\t\tPdfGState state = new PdfGState();\n\t\t\tstate.setFillOpacity(opacity);\n\t\t\tstate.setBlendMode(PdfGState.BM_NORMAL);\n\t\t\ttemplate.setGState(state);\n\t\t\t// clipping code\n\t\t\tif (clipRect != null) {\n\t\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),\n\t\t\t\t\t\tclipRect.getHeight());\n\t\t\t\ttemplate.clip();\n\t\t\t\ttemplate.newPath();\n\t\t\t}\n\t\t\ttemplate.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(), origY\n\t\t\t\t\t+ rect.getBottom());\n\t\t} catch (DocumentException e) {\n\t\t\tlog.warn(\"could not draw image\", e);\n\t\t} finally {\n\t\t\ttemplate.restoreState();\n\t\t}\n\t}"
] |
Is portlet env supported.
@return true if portlet env is supported, false otherwise | [
"public static boolean isPortletEnvSupported() {\n if (enabled == null) {\n synchronized (PortletSupport.class) {\n if (enabled == null) {\n try {\n PortletSupport.class.getClassLoader().loadClass(\"javax.portlet.PortletContext\");\n enabled = true;\n } catch (Throwable ignored) {\n enabled = false;\n }\n }\n }\n }\n return enabled;\n }"
] | [
"public void contextInitialized(ServletContextEvent event) {\n this.context = event.getServletContext();\n\n // Output a simple message to the server's console\n System.out.println(\"The Simple Web App. Is Ready\");\n\n ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(\n \"/client.xml\");\n LocatorService client = (LocatorService) context\n .getBean(\"locatorService\");\n\n String serviceHost = this.context.getInitParameter(\"serviceHost\");\n\n try {\n client.registerEndpoint(new QName(\n \"http://talend.org/esb/examples/\", \"GreeterService\"),\n serviceHost, BindingType.SOAP_11, TransportType.HTTP, null);\n } catch (InterruptedExceptionFault e) {\n e.printStackTrace();\n } catch (ServiceLocatorFault e) {\n e.printStackTrace();\n }\n }",
"static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }",
"public Bundler put(String key, CharSequence[] value) {\n delegate.putCharSequenceArray(key, value);\n return this;\n }",
"private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }",
"public static Long getSize(final File file){\n if ( file!=null && file.exists() ){\n return file.length();\n }\n return null;\n }",
"public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}",
"private String getParentWBS(String wbs)\n {\n String result;\n int index = wbs.lastIndexOf('.');\n if (index == -1)\n {\n result = null;\n }\n else\n {\n result = wbs.substring(0, index);\n }\n return result;\n }",
"public Set<ConstraintViolation> validate() {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int record = 1; record <= 3; ++record) {\r\n\t\t\terrors.addAll(validate(record));\r\n\t\t}\r\n\t\treturn errors;\r\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 }"
] |
Add a row to the table if it does not already exist
@param cells String... | [
"public void addRow(final String... cells){\n final Row row = new Row((Object[]) cells);\n\n if(!rows.contains(row)){\n rows.add(row);\n }\n }"
] | [
"public static boolean queryHasResult(Statement stmt, String sql) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n return rs.next();\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }",
"public 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 insertValue(int index, float[] newValue) {\n if ( newValue.length == 2) {\n try {\n value.add( index, new SFVec2f(newValue[0], newValue[1]) );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) exception \" + e);\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec2f insertValue set with array length not equal to 2\");\n }\n }",
"public static double JensenShannonDivergence(double[] p, double[] q) {\n double[] m = new double[p.length];\n for (int i = 0; i < m.length; i++) {\n m[i] = (p[i] + q[i]) / 2;\n }\n\n return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;\n }",
"public static base_response add(nitro_service client, route6 resource) throws Exception {\n\t\troute6 addresource = new route6();\n\t\taddresource.network = resource.network;\n\t\taddresource.gateway = resource.gateway;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.weight = resource.weight;\n\t\taddresource.distance = resource.distance;\n\t\taddresource.cost = resource.cost;\n\t\taddresource.advertise = resource.advertise;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"public Jar addClass(Class<?> clazz) throws IOException {\n final String resource = clazz.getName().replace('.', '/') + \".class\";\n return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource));\n }",
"public static netbridge_vlan_binding[] get(nitro_service service, String name) throws Exception{\n\t\tnetbridge_vlan_binding obj = new netbridge_vlan_binding();\n\t\tobj.set_name(name);\n\t\tnetbridge_vlan_binding response[] = (netbridge_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_response delete(nitro_service client, application resource) throws Exception {\n\t\tapplication deleteresource = new application();\n\t\tdeleteresource.appname = resource.appname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"protected PreparedStatement prepareStatement(Connection con,\r\n String sql,\r\n boolean scrollable,\r\n boolean createPreparedStatement,\r\n int explicitFetchSizeHint)\r\n throws SQLException\r\n {\r\n PreparedStatement result;\r\n\r\n // if a JDBC1.0 driver is used the signature\r\n // prepareStatement(String, int, int) is not defined.\r\n // we then call the JDBC1.0 variant prepareStatement(String)\r\n try\r\n {\r\n // if necessary use JDB1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result =\r\n con.prepareStatement(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result =\r\n con.prepareCall(\r\n sql,\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n }\r\n }\r\n else\r\n {\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // this exception is raised if Driver is not JDBC 2.0 compliant\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql\r\n .getClass()\r\n .getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n if (createPreparedStatement)\r\n {\r\n result = con.prepareStatement(sql);\r\n }\r\n else\r\n {\r\n result = con.prepareCall(sql);\r\n }\r\n FORCEJDBC1_0 = true;\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n if (!ProxyHelper.isNormalOjbProxy(result)) // tomdz: What about VirtualProxy\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }"
] |
Read holidays from the database and create calendar exceptions. | [
"private void readHolidays()\n {\n for (MapRow row : m_tables.get(\"HOL\"))\n {\n ProjectCalendar calendar = m_calendarMap.get(row.getInteger(\"CALENDAR_ID\"));\n if (calendar != null)\n {\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"ANNUAL\"))\n {\n RecurringData recurring = new RecurringData();\n recurring.setRecurrenceType(RecurrenceType.YEARLY);\n recurring.setYearlyAbsoluteFromDate(date);\n recurring.setStartDate(date);\n exception.setRecurring(recurring);\n // TODO set end date based on project end date\n }\n }\n }\n }"
] | [
"public static Method getSetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"set\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\treturn sourceMethod;\r\n\t}",
"private void processCalendars() throws SQLException\n {\n List<Row> rows = getTable(\"EXCEPTIONN\");\n Map<Integer, DayType> exceptionMap = m_reader.createExceptionTypeMap(rows);\n\n rows = getTable(\"WORK_PATTERN\");\n Map<Integer, Row> workPatternMap = m_reader.createWorkPatternMap(rows);\n\n rows = new LinkedList<Row>();// getTable(\"WORK_PATTERN_ASSIGNMENT\"); // Need to generate an example\n Map<Integer, List<Row>> workPatternAssignmentMap = m_reader.createWorkPatternAssignmentMap(rows);\n\n rows = getTable(\"EXCEPTION_ASSIGNMENT\");\n Map<Integer, List<Row>> exceptionAssignmentMap = m_reader.createExceptionAssignmentMap(rows);\n\n rows = getTable(\"TIME_ENTRY\");\n Map<Integer, List<Row>> timeEntryMap = m_reader.createTimeEntryMap(rows);\n\n rows = getTable(\"CALENDAR\");\n Collections.sort(rows, CALENDAR_COMPARATOR);\n for (Row row : rows)\n {\n m_reader.processCalendar(row, workPatternMap, workPatternAssignmentMap, exceptionAssignmentMap, timeEntryMap, exceptionMap);\n }\n\n //\n // Update unique counters at this point as we will be generating\n // resource calendars, and will need to auto generate IDs\n //\n m_reader.getProject().getProjectConfig().updateUniqueCounters();\n }",
"public void setScriptText(String scriptText, String language)\n {\n GVRScriptFile newScript = new GVRJavascriptScriptFile(getGVRContext(), scriptText);\n mLanguage = GVRScriptManager.LANG_JAVASCRIPT;\n setScriptFile(newScript);\n }",
"public static final String printTime(Date value)\n {\n return (value == null ? null : TIME_FORMAT.get().format(value));\n }",
"public static aaauser_intranetip_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_intranetip_binding obj = new aaauser_intranetip_binding();\n\t\tobj.set_username(username);\n\t\taaauser_intranetip_binding response[] = (aaauser_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }",
"public static String getTitleGalleryKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(GUI_TITLE_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }",
"MongoCollection<BsonDocument> getUndoCollection(final MongoNamespace namespace) {\n return localClient\n .getDatabase(String.format(\"sync_undo_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), BsonDocument.class)\n .withCodecRegistry(MongoClientSettings.getDefaultCodecRegistry());\n }",
"public void logout() {\n String userIdentifier = session.get(config().sessionKeyUsername());\n SessionManager sessionManager = app().sessionManager();\n sessionManager.logout(session);\n if (S.notBlank(userIdentifier)) {\n app().eventBus().trigger(new LogoutEvent(userIdentifier));\n }\n }"
] |
Set the serial pattern type.
@param patternType the pattern type to set. | [
"public void setPattern(String patternType) {\r\n\r\n final PatternType type = PatternType.valueOf(patternType);\r\n if (type != m_model.getPatternType()) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n EndType oldEndType = m_model.getEndType();\r\n m_model.setPatternType(type);\r\n m_model.setIndividualDates(null);\r\n m_model.setInterval(getPatternDefaultValues().getInterval());\r\n m_model.setEveryWorkingDay(Boolean.FALSE);\r\n m_model.clearWeekDays();\r\n m_model.clearIndividualDates();\r\n m_model.clearWeeksOfMonth();\r\n m_model.clearExceptions();\r\n if (type.equals(PatternType.NONE) || type.equals(PatternType.INDIVIDUAL)) {\r\n m_model.setEndType(EndType.SINGLE);\r\n } else if (oldEndType.equals(EndType.SINGLE)) {\r\n m_model.setEndType(EndType.TIMES);\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n }\r\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\r\n m_model.setMonth(getPatternDefaultValues().getMonth());\r\n if (type.equals(PatternType.WEEKLY)) {\r\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\r\n }\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }"
] | [
"public String getUuidFromResponse(ResponseOnSingeRequest myResponse) {\n\n String uuid = PcConstants.NA;\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(getJobIdRegex());\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n uuid = matcher.group(1);\n }\n\n return uuid;\n }",
"@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n blockB.reshape(B.numRows,B.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n // since overwrite B is true X does not need to be passed in\n alg.solve(blockB,null);\n\n MatrixOps_DDRB.convert(blockB,X);\n }",
"public final void end() {\n final Thread thread = threadRef;\n if (thread != null) {\n thread.interrupt();\n try {\n thread.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n this.threadRef = null;\n }",
"public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"@SuppressWarnings(\"WeakerAccess\")\n public String formatCueCountdown() {\n int count = getCueCountdown();\n\n if (count == 511) {\n return \"--.-\";\n }\n\n if ((count >= 1) && (count <= 256)) {\n int bars = (count - 1) / 4;\n int beats = ((count - 1) % 4) + 1;\n return String.format(\"%02d.%d\", bars, beats);\n }\n\n if (count == 0) {\n return \"00.0\";\n }\n\n return \"??.?\";\n }",
"private String validateDuration() {\n\n if (!isValidEndTypeForPattern()) {\n return Messages.ERR_SERIALDATE_INVALID_END_TYPE_FOR_PATTERN_0;\n }\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS))\n ? null\n : Messages.ERR_SERIALDATE_SERIES_END_BEFORE_START_0;\n case TIMES:\n return getOccurrences() > 0 ? null : Messages.ERR_SERIALDATE_INVALID_OCCURRENCES_0;\n default:\n return null;\n }\n\n }",
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }",
"public byte[] getMessageBuffer() {\n\t\tByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();\n\t\tbyte[] result;\n\t\tresultByteBuffer.write((byte)0x01);\n\t\tint messageLength = messagePayload.length + \n\t\t\t\t(this.messageClass == SerialMessageClass.SendData && \n\t\t\t\tthis.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length\n\t\t\n\t\tresultByteBuffer.write((byte) messageLength);\n\t\tresultByteBuffer.write((byte) messageType.ordinal());\n\t\tresultByteBuffer.write((byte) messageClass.getKey());\n\t\t\n\t\ttry {\n\t\t\tresultByteBuffer.write(messagePayload);\n\t\t} catch (IOException e) {\n\t\t\t\n\t\t}\n\n\t\t// callback ID and transmit options for a Send Data message.\n\t\tif (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {\n\t\t\tresultByteBuffer.write(transmitOptions);\n\t\t\tresultByteBuffer.write(callbackId);\n\t\t}\n\t\t\n\t\tresultByteBuffer.write((byte) 0x00);\n\t\tresult = resultByteBuffer.toByteArray();\n\t\tresult[result.length - 1] = 0x01;\n\t\tresult[result.length - 1] = calculateChecksum(result);\n\t\tlogger.debug(\"Assembled message buffer = \" + SerialMessage.bb2hex(result));\n\t\treturn result;\n\t}",
"PathAddress toPathAddress(final ObjectName name) {\n return ObjectNameAddressUtil.toPathAddress(rootObjectInstance.getObjectName(), getRootResourceAndRegistration().getRegistration(), name);\n }"
] |
Retrieve the value from the REST request body.
TODO: REST-Server value cannot be null ( null/empty string ?) | [
"private void parseValue() {\n ChannelBuffer content = this.request.getContent();\n this.parsedValue = new byte[content.capacity()];\n content.readBytes(parsedValue);\n }"
] | [
"@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }",
"public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\n }",
"@SuppressWarnings(\"unchecked\")\n public B setTargetType(Class<?> type) {\n Objects.requireNonNull(type);\n set(AbstractQuery.KEY_QUERY_TARGET_TYPE, type);\n return (B) this;\n }",
"public static String generateQuery(final String key, final Object value) {\n\t\tfinal Map<String, Object> params = new HashMap<>();\n\t\tparams.put(key, value);\n\t\treturn generateQuery(params);\n\t}",
"protected static void checkChannels(final Iterable<String> channels) {\n if (channels == null) {\n throw new IllegalArgumentException(\"channels must not be null\");\n }\n for (final String channel : channels) {\n if (channel == null || \"\".equals(channel)) {\n throw new IllegalArgumentException(\"channels' members must not be null: \" + channels);\n }\n }\n }",
"public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }",
"private static synchronized StreamHandler getStreamHandler() {\n if (methodHandler == null) {\n methodHandler = new ConsoleHandler();\n methodHandler.setFormatter(new Formatter() {\n @Override\n public String format(LogRecord record) {\n return record.getMessage() + \"\\n\";\n }\n });\n methodHandler.setLevel(Level.FINE);\n }\n return methodHandler;\n }",
"public Jar setListAttribute(String name, Collection<?> values) {\n return setAttribute(name, join(values));\n }",
"public void deleteOrganization(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n repositoryHandler.deleteOrganization(dbOrganization.getName());\n repositoryHandler.removeModulesOrganization(dbOrganization);\n }"
] |
Open a database and build a set of table names.
@param url database URL
@return set containing table names | [
"private Set<String> populateTableNames(String url) throws SQLException\n {\n Set<String> tableNames = new HashSet<String>();\n Connection connection = null;\n ResultSet rs = null;\n\n try\n {\n connection = DriverManager.getConnection(url);\n DatabaseMetaData dmd = connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tableNames.add(rs.getString(\"TABLE_NAME\").toUpperCase());\n }\n }\n\n finally\n {\n if (rs != null)\n {\n rs.close();\n }\n\n if (connection != null)\n {\n connection.close();\n }\n }\n\n return tableNames;\n }"
] | [
"public void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }",
"public LayoutScroller.ScrollableList getPageScrollable() {\n return new LayoutScroller.ScrollableList() {\n\n @Override\n public int getScrollingItemsCount() {\n return MultiPageWidget.super.getScrollingItemsCount();\n }\n\n @Override\n public float getViewPortWidth() {\n return MultiPageWidget.super.getViewPortWidth();\n }\n\n @Override\n public float getViewPortHeight() {\n return MultiPageWidget.super.getViewPortHeight();\n }\n\n @Override\n public float getViewPortDepth() {\n return MultiPageWidget.super.getViewPortDepth();\n }\n\n @Override\n public boolean scrollToPosition(int pos, final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollToPosition(pos, listener);\n }\n\n @Override\n public boolean scrollByOffset(float xOffset, float yOffset, float zOffset,\n final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollByOffset(xOffset, yOffset, zOffset, listener);\n }\n\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.registerDataSetObserver(observer);\n }\n\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.unregisterDataSetObserver(observer);\n }\n\n @Override\n public int getCurrentPosition() {\n return MultiPageWidget.super.getCurrentPosition();\n }\n\n };\n }",
"public static Dimension dimensionsToFit(Dimension target, Dimension source) {\n\n // if target width/height is zero then we have no preference for that, so set it to the original value,\n // since it cannot be any larger\n int maxWidth;\n if (target.getX() == 0) {\n maxWidth = source.getX();\n } else {\n maxWidth = target.getX();\n }\n\n int maxHeight;\n if (target.getY() == 0) {\n maxHeight = source.getY();\n } else {\n maxHeight = target.getY();\n }\n\n double wscale = maxWidth / (double) source.getX();\n double hscale = maxHeight / (double) source.getY();\n\n if (wscale < hscale)\n return new Dimension((int) (source.getX() * wscale), (int) (source.getY() * wscale));\n else\n return new Dimension((int) (source.getX() * hscale), (int) (source.getY() * hscale));\n }",
"private long getTime(Date start, Date end)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n { \n endTime = DateHelper.addDays(endTime, 1);\n }\n\n total = (endTime.getTime() - startTime.getTime());\n }\n return (total);\n }",
"public void retrieveCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, false);\r\n }",
"public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n String expected = attributes.getProperty(ATTRIBUTE_VALUE);\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n if (expected.equals(value))\r\n {\r\n generate(template);\r\n }\r\n }",
"public void processActivityCodes(List<Row> types, List<Row> typeValues, List<Row> assignments)\n {\n ActivityCodeContainer container = m_project.getActivityCodes();\n Map<Integer, ActivityCode> map = new HashMap<Integer, ActivityCode>();\n\n for (Row row : types)\n {\n ActivityCode code = new ActivityCode(row.getInteger(\"actv_code_type_id\"), row.getString(\"actv_code_type\"));\n container.add(code);\n map.put(code.getUniqueID(), code);\n }\n\n for (Row row : typeValues)\n {\n ActivityCode code = map.get(row.getInteger(\"actv_code_type_id\"));\n if (code != null)\n {\n ActivityCodeValue value = code.addValue(row.getInteger(\"actv_code_id\"), row.getString(\"short_name\"), row.getString(\"actv_code_name\"));\n m_activityCodeMap.put(value.getUniqueID(), value);\n }\n }\n\n for (Row row : assignments)\n {\n Integer taskID = row.getInteger(\"task_id\");\n List<Integer> list = m_activityCodeAssignments.get(taskID);\n if (list == null)\n {\n list = new ArrayList<Integer>();\n m_activityCodeAssignments.put(taskID, list);\n }\n list.add(row.getInteger(\"actv_code_id\"));\n }\n }",
"private static String getUnexpectedTypeMessage(final Class<?> expectedType, final Object actualValue) {\n\t\tif( expectedType == null ) {\n\t\t\tthrow new NullPointerException(\"expectedType should not be null\");\n\t\t}\n\t\tString expectedClassName = expectedType.getName();\n\t\tString actualClassName = (actualValue != null) ? actualValue.getClass().getName() : \"null\";\n\t\treturn String.format(\"the input value should be of type %s but is %s\", expectedClassName, actualClassName);\n\t}",
"public static byte[] addContentToExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItem = getContentItem(deploymentResource);\n byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItem).asBytes();\n List<ModelNode> contents = CONTENT_PARAM_ALL_EXPLODED.resolveModelAttribute(context, operation).asList();\n final List<ExplodedContent> addedFiles = new ArrayList<>(contents.size());\n\n final ModelNode slave = operation.clone();\n ModelNode slaveAddedfiles = slave.get(UPDATED_PATHS.getName()).setEmptyList();\n for(ModelNode content : contents) {\n InputStream in;\n if(hasValidContentAdditionParameterDefined(content)) {\n in = getInputStream(context, content);\n } else {\n in = null;\n }\n String path = TARGET_PATH.resolveModelAttribute(context, content).asString();\n addedFiles.add(new ExplodedContent(path, in));\n slaveAddedfiles.add(path);\n }\n final boolean overwrite = OVERWRITE.resolveModelAttribute(context, operation).asBoolean(true);\n final byte[] hash = contentRepository.addContentToExploded(oldHash, addedFiles, overwrite);\n\n // Clear the contents and update with the hash\n ModelNode addedContent = new ModelNode().setEmptyObject();\n addedContent.get(HASH).set(hash);\n addedContent.get(TARGET_PATH.getName()).set(\".\");\n slave.get(CONTENT).setEmptyList().add(addedContent);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }"
] |
Registers the deployment resources needed.
@param deploymentResourceSupport the deployment resource support
@param service the service, which may be {@code null}, used to find the resource names that need to be registered | [
"public static void registerDeploymentResource(final DeploymentResourceSupport deploymentResourceSupport, final LoggingConfigurationService service) {\n final PathElement base = PathElement.pathElement(\"configuration\", service.getConfiguration());\n deploymentResourceSupport.getDeploymentSubModel(LoggingExtension.SUBSYSTEM_NAME, base);\n final LogContextConfiguration configuration = service.getValue();\n // Register the child resources if the configuration is not null in cases where a log4j configuration was used\n if (configuration != null) {\n registerDeploymentResource(deploymentResourceSupport, base, HANDLER, configuration.getHandlerNames());\n registerDeploymentResource(deploymentResourceSupport, base, LOGGER, configuration.getLoggerNames());\n registerDeploymentResource(deploymentResourceSupport, base, FORMATTER, configuration.getFormatterNames());\n registerDeploymentResource(deploymentResourceSupport, base, FILTER, configuration.getFilterNames());\n registerDeploymentResource(deploymentResourceSupport, base, POJO, configuration.getPojoNames());\n registerDeploymentResource(deploymentResourceSupport, base, ERROR_MANAGER, configuration.getErrorManagerNames());\n }\n }"
] | [
"private void initialize(Handler callbackHandler, int threadPoolSize) {\n\t\tmDownloadDispatchers = new DownloadDispatcher[threadPoolSize];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}",
"public static boolean updateImageParentOnAgents(final JenkinsBuildInfoLog log, final String imageTag, final String host, final int buildInfoId) throws IOException, InterruptedException {\n boolean parentUpdated = updateImageParent(log, imageTag, host, buildInfoId);\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n boolean parentNodeUpdated = node.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n return updateImageParent(log, imageTag, host, buildInfoId);\n }\n });\n parentUpdated = parentUpdated ? parentUpdated : parentNodeUpdated;\n }\n return parentUpdated;\n }",
"public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }",
"static <T> boolean syncInstantiation(T objectType) {\n List<Template> templates = new ArrayList<>();\n Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);\n if (tr == null) {\n /* Default to synchronous instantiation */\n return true;\n } else {\n return tr.syncInstantiation();\n }\n }",
"public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }",
"public void init(final MultivaluedMap<String, String> queryParameters) {\n final String scopeCompileParam = queryParameters.getFirst(ServerAPI.SCOPE_COMPILE_PARAM);\n if(scopeCompileParam != null){\n this.scopeComp = Boolean.valueOf(scopeCompileParam);\n }\n final String scopeProvidedParam = queryParameters.getFirst(ServerAPI.SCOPE_PROVIDED_PARAM);\n if(scopeProvidedParam != null){\n this.scopePro = Boolean.valueOf(scopeProvidedParam);\n }\n final String scopeRuntimeParam = queryParameters.getFirst(ServerAPI.SCOPE_RUNTIME_PARAM);\n if(scopeRuntimeParam != null){\n this.scopeRun = Boolean.valueOf(scopeRuntimeParam);\n }\n final String scopeTestParam = queryParameters.getFirst(ServerAPI.SCOPE_TEST_PARAM);\n if(scopeTestParam != null){\n this.scopeTest = Boolean.valueOf(scopeTestParam);\n }\n }",
"public static final int getInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n is.read(data);\n return getInt(data, 0);\n }",
"public void update(int number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];\n ByteUtils.writeInt(numberInBytes, number, 0);\n update(numberInBytes);\n }",
"private int getClosingParenthesisPosition(String text, int opening)\n {\n if (text.charAt(opening) != '(')\n {\n return -1;\n }\n\n int count = 0;\n for (int i = opening; i < text.length(); i++)\n {\n char c = text.charAt(i);\n switch (c)\n {\n case '(':\n {\n ++count;\n break;\n }\n\n case ')':\n {\n --count;\n if (count == 0)\n {\n return i;\n }\n break;\n }\n }\n }\n\n return -1;\n }"
] |
Checks that arguments and parameter types match.
@param params method parameters
@param args type arguments
@return -1 if arguments do not match, 0 if arguments are of the exact type and >0 when one or more argument is
not of the exact type but still match | [
"public static int allParametersAndArgumentsMatch(Parameter[] params, ClassNode[] args) {\n if (params==null) {\n params = Parameter.EMPTY_ARRAY;\n }\n int dist = 0;\n if (args.length<params.length) return -1;\n // we already know the lengths are equal\n for (int i = 0; i < params.length; i++) {\n ClassNode paramType = params[i].getType();\n ClassNode argType = args[i];\n if (!isAssignableTo(argType, paramType)) return -1;\n else {\n if (!paramType.equals(argType)) dist+=getDistance(argType, paramType);\n }\n }\n return dist;\n }"
] | [
"public void reset(int profileId, String clientUUID) throws Exception {\n PreparedStatement statement = null;\n\n // TODO: need a better way to do this than brute force.. but the iterative approach is too slow\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n // first remove all enabled overrides with this client uuid\n String queryString = \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n statement.close();\n\n // clean up request response table for this uuid\n queryString = \"UPDATE \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" SET \" + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \"=?, \"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \"=?, \"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \"=-1, \"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \"=0, \"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \"=0 \"\n + \"WHERE \" + Constants.GENERIC_CLIENT_UUID + \"=? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, \"\");\n statement.setString(2, \"\");\n statement.setString(3, clientUUID);\n statement.setInt(4, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n this.updateActive(profileId, clientUUID, false);\n }",
"public static tmsessionpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\ttmsessionpolicy_binding obj = new tmsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\ttmsessionpolicy_binding response = (tmsessionpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static base_response delete(nitro_service client, String sitename) throws Exception {\n\t\tgslbsite deleteresource = new gslbsite();\n\t\tdeleteresource.sitename = sitename;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static String fromClassPath() {\n Set<String> versions = new HashSet<>();\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> manifests = classLoader.getResources(\"META-INF/MANIFEST.MF\");\n\n while (manifests.hasMoreElements()) {\n URL manifestURL = manifests.nextElement();\n try (InputStream is = manifestURL.openStream()) {\n Manifest manifest = new Manifest();\n manifest.read(is);\n\n Attributes buildInfo = manifest.getAttributes(\"Build-Info\");\n if (buildInfo != null) {\n if (buildInfo.getValue(\"Selenium-Version\") != null) {\n versions.add(buildInfo.getValue(\"Selenium-Version\"));\n } else {\n // might be in build-info part\n if (manifest.getEntries() != null) {\n if (manifest.getEntries().containsKey(\"Build-Info\")) {\n final Attributes attributes = manifest.getEntries().get(\"Build-Info\");\n\n if (attributes.getValue(\"Selenium-Version\") != null) {\n versions.add(attributes.getValue(\"Selenium-Version\"));\n }\n }\n }\n }\n }\n }\n }\n } catch (Exception e) {\n logger.log(Level.WARNING,\n \"Exception {0} occurred while resolving selenium version and latest image is going to be used.\",\n e.getMessage());\n return SELENIUM_VERSION;\n }\n\n if (versions.isEmpty()) {\n logger.log(Level.INFO, \"No version of Selenium found in classpath. Using latest image.\");\n return SELENIUM_VERSION;\n }\n\n String foundVersion = versions.iterator().next();\n if (versions.size() > 1) {\n logger.log(Level.WARNING, \"Multiple versions of Selenium found in classpath. Using the first one found {0}.\",\n foundVersion);\n }\n\n return foundVersion;\n }",
"public static double Y(int n, double x) {\r\n double by, bym, byp, tox;\r\n\r\n if (n == 0) return Y0(x);\r\n if (n == 1) return Y(x);\r\n\r\n tox = 2.0 / x;\r\n by = Y(x);\r\n bym = Y0(x);\r\n for (int j = 1; j < n; j++) {\r\n byp = j * tox * by - bym;\r\n bym = by;\r\n by = byp;\r\n }\r\n return by;\r\n }",
"private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }",
"private static void parseStencil(JSONObject modelJSON,\n Shape current) throws JSONException {\n // get stencil type\n if (modelJSON.has(\"stencil\")) {\n JSONObject stencil = modelJSON.getJSONObject(\"stencil\");\n // TODO other attributes of stencil\n String stencilString = \"\";\n if (stencil.has(\"id\")) {\n stencilString = stencil.getString(\"id\");\n }\n current.setStencil(new StencilType(stencilString));\n }\n }",
"@SuppressWarnings(\"SameParameterValue\")\n private void assembleAndSendPacket(Util.PacketType kind, byte[] payload, InetAddress destination, int port) throws IOException {\n DatagramPacket packet = Util.buildPacket(kind,\n ByteBuffer.wrap(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH).asReadOnlyBuffer(),\n ByteBuffer.wrap(payload));\n packet.setAddress(destination);\n packet.setPort(port);\n socket.get().send(packet);\n }",
"private static void parseTarget(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"target\")) {\n JSONObject targetObject = modelJSON.getJSONObject(\"target\");\n if (targetObject.has(\"resourceId\")) {\n current.setTarget(getShapeWithId(targetObject.getString(\"resourceId\"),\n shapes));\n }\n }\n }"
] |
Dumps a single material property to stdout.
@param property the property | [
"public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }"
] | [
"public static <OutT, InT> PagedList<OutT> toPagedList(List<InT> list, final Func1<InT, OutT> mapper) {\n PageImpl<InT> page = new PageImpl<>();\n page.setItems(list);\n page.setNextPageLink(null);\n PagedList<InT> pagedList = new PagedList<InT>(page) {\n @Override\n public Page<InT> nextPage(String nextPageLink) {\n return null;\n }\n };\n PagedListConverter<InT, OutT> converter = new PagedListConverter<InT, OutT>() {\n @Override\n public Observable<OutT> typeConvertAsync(InT inner) {\n return Observable.just(mapper.call(inner));\n }\n };\n return converter.convert(pagedList);\n }",
"private List<TimephasedCost> getTimephasedCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n ProjectCalendar cal = getCalendar();\n\n double remainingCost = getRemainingCost().doubleValue();\n\n if (remainingCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(cal, remainingCost, getStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(cal, remainingCost, getFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently depending on whether or not\n //any actual has been entered, since we want to mimic the other timephased data\n //where planned and actual values do not overlap\n double numWorkingDays = cal.getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n if (getActualCost().intValue() > 0)\n {\n //need to get three possible blocks of data: one for the possible partial amount\n //overlap with timephased actual cost; one with all the standard amount days\n //that happen after the actual cost stops; and one with any remaining\n //partial day cost amount\n\n int numActualDaysUsed = (int) Math.ceil(getActualCost().doubleValue() / standardAmountPerDay);\n Date actualWorkFinish = cal.getDate(getStart(), Duration.getInstance(numActualDaysUsed, TimeUnit.DAYS), false);\n\n double partialDayActualAmount = getActualCost().doubleValue() % standardAmountPerDay;\n\n if (partialDayActualAmount > 0)\n {\n double dayAmount = standardAmountPerDay < remainingCost ? standardAmountPerDay - partialDayActualAmount : remainingCost;\n\n result.add(splitCostEnd(cal, dayAmount, actualWorkFinish));\n\n remainingCost -= dayAmount;\n }\n\n //see if there's anything left to work with\n if (remainingCost > 0)\n {\n //have to split up the amount into standard prorated amount days and whatever is left\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, cal.getNextWorkStart(actualWorkFinish)));\n }\n\n }\n else\n {\n //no actual cost to worry about, so just a standard split from the beginning of the assignment\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, getStart()));\n }\n }\n }\n\n return result;\n }",
"protected List<CmsResource> getTopFolders(List<CmsResource> folders) {\n\n List<String> folderPaths = new ArrayList<String>();\n List<CmsResource> topFolders = new ArrayList<CmsResource>();\n Map<String, CmsResource> foldersByPath = new HashMap<String, CmsResource>();\n for (CmsResource folder : folders) {\n folderPaths.add(folder.getRootPath());\n foldersByPath.put(folder.getRootPath(), folder);\n }\n Collections.sort(folderPaths);\n Set<String> topFolderPaths = new HashSet<String>(folderPaths);\n for (int i = 0; i < folderPaths.size(); i++) {\n for (int j = i + 1; j < folderPaths.size(); j++) {\n if (folderPaths.get(j).startsWith((folderPaths.get(i)))) {\n topFolderPaths.remove(folderPaths.get(j));\n } else {\n break;\n }\n }\n }\n for (String path : topFolderPaths) {\n topFolders.add(foldersByPath.get(path));\n }\n return topFolders;\n }",
"public static base_response unlink(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey unlinkresource = new sslcertkey();\n\t\tunlinkresource.certkey = resource.certkey;\n\t\treturn unlinkresource.perform_operation(client,\"unlink\");\n\t}",
"public static final Duration parseDuration(String value)\n {\n return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);\n }",
"public synchronized void tick() {\n long currentTime = GVRTime.getMilliTime();\n long cutoffTime = currentTime - BUFFER_SECONDS * 1000;\n ListIterator<Long> it = mTimestamps.listIterator();\n while (it.hasNext()) {\n Long timestamp = it.next();\n if (timestamp < cutoffTime) {\n it.remove();\n } else {\n break;\n }\n }\n\n mTimestamps.add(currentTime);\n mStatColumn.addValue(((float)mTimestamps.size()) / BUFFER_SECONDS);\n }",
"protected String createName() {\n final StringBuilder buf = new StringBuilder(128);\n try {\n buf.append(InetAddress.getLocalHost().getHostName()).append(COLON)\n .append(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]) // PID\n .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);\n for (final String queueName : this.queueNames) {\n buf.append(',').append(queueName);\n }\n } catch (UnknownHostException uhe) {\n throw new RuntimeException(uhe);\n }\n return buf.toString();\n }",
"public void init( DMatrixRMaj A ) {\n if( A.numRows != A.numCols)\n throw new IllegalArgumentException(\"Must be square\");\n\n if( A.numCols != N ) {\n N = A.numCols;\n QT.reshape(N,N, false);\n\n if( w.length < N ) {\n w = new double[ N ];\n gammas = new double[N];\n b = new double[N];\n }\n }\n\n // just copy the top right triangle\n QT.set(A);\n }",
"public static base_response Reboot(nitro_service client, reboot resource) throws Exception {\n\t\treboot Rebootresource = new reboot();\n\t\tRebootresource.warm = resource.warm;\n\t\treturn Rebootresource.perform_operation(client);\n\t}"
] |
The default field facets.
@param categoryConjunction flag, indicating if category selections in the facet should be "AND" combined.
@return the default field facets. | [
"private Map<String, I_CmsSearchConfigurationFacetField> getDefaultFieldFacets(boolean categoryConjunction) {\n\n Map<String, I_CmsSearchConfigurationFacetField> fieldFacets = new HashMap<String, I_CmsSearchConfigurationFacetField>();\n fieldFacets.put(\n CmsListManager.FIELD_CATEGORIES,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_CATEGORIES,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Category\",\n SortOrder.index,\n null,\n Boolean.valueOf(categoryConjunction),\n null,\n Boolean.TRUE));\n fieldFacets.put(\n CmsListManager.FIELD_PARENT_FOLDERS,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_PARENT_FOLDERS,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Folders\",\n SortOrder.index,\n null,\n Boolean.FALSE,\n null,\n Boolean.TRUE));\n return Collections.unmodifiableMap(fieldFacets);\n\n }"
] | [
"private void deliverMasterYieldCommand(int toPlayer) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldMasterTo(toPlayer);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield command to listener\", t);\n }\n }\n }",
"public void setBoneName(int boneindex, String bonename)\n {\n mBoneNames[boneindex] = bonename;\n NativeSkeleton.setBoneName(getNative(), boneindex, bonename);\n }",
"public static gslbservice[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tgslbservice[] response = (gslbservice[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"@Override\n public ModelNode resolveValue(ExpressionResolver resolver, ModelNode value) throws OperationFailedException {\n\n // Pass non-LIST values through the superclass so it can reject weird values and, in the odd chance\n // that's how this object is set up, turn undefined into a default list value.\n ModelNode superResult = value.getType() == ModelType.LIST ? value : super.resolveValue(resolver, value);\n\n // If it's not a LIST (almost certainly UNDEFINED), then nothing more we can do\n if (superResult.getType() != ModelType.LIST) {\n return superResult;\n }\n // Resolve each element.\n // Don't mess with the original value\n ModelNode clone = superResult == value ? value.clone() : superResult;\n ModelNode result = new ModelNode();\n result.setEmptyList();\n for (ModelNode element : clone.asList()) {\n result.add(valueType.resolveValue(resolver, element));\n }\n // Validate the entire list\n getValidator().validateParameter(getName(), result);\n return result;\n }",
"public void removeAccessory(HomekitAccessory accessory) {\n this.registry.remove(accessory);\n logger.info(\"Removed accessory \" + accessory.getLabel());\n if (started) {\n registry.reset();\n webHandler.resetConnections();\n }\n }",
"public static Date max(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) > 0) ? d1 : d2;\n }\n return result;\n }",
"public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {\n\t\tinit(t1, t2);\n\t\tSTR = new int[size1][size2];\n\t\tcomputeOptimalStrategy();\n\t\treturn computeDistUsingStrArray(it1, it2);\n\t}",
"@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }",
"public ItemRequest<CustomField> insertEnumOption(String customField) {\n \n String path = String.format(\"/custom_fields/%s/enum_options/insert\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"POST\");\n }"
] |
Adds this handler to the widget.
@param <H> the type of handler to add
@param type the event type
@param handler the handler
@return {@link HandlerRegistration} used to remove the handler | [
"protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {\r\n\r\n return ensureHandlers().addHandlerToSource(type, this, handler);\r\n }"
] | [
"private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\n }\n }",
"public static int positionOf(char value, char[] array) {\n for (int i = 0; i < array.length; i++) {\n if (value == array[i]) {\n return i;\n }\n }\n throw new OkapiException(\"Unable to find character '\" + value + \"' in character array.\");\n }",
"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}",
"public static void executorShutDown(ExecutorService executorService, long timeOutSec) {\n try {\n executorService.shutdown();\n executorService.awaitTermination(timeOutSec, TimeUnit.SECONDS);\n } catch(Exception e) {\n logger.warn(\"Error while stoping executor service.\", e);\n }\n }",
"public int getIndexByDate(Date date)\n {\n int result = -1;\n int index = 0;\n\n for (CostRateTableEntry entry : this)\n {\n if (DateHelper.compare(date, entry.getEndDate()) < 0)\n {\n result = index;\n break;\n }\n ++index;\n }\n\n return result;\n }",
"public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }",
"public static String roundCorner(int radiusInner, int radiusOuter, int color) {\n if (radiusInner < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radiusOuter < 0) {\n throw new IllegalArgumentException(\"Outer radius must be greater than or equal to zero.\");\n }\n StringBuilder builder = new StringBuilder(FILTER_ROUND_CORNER).append(\"(\").append(radiusInner);\n if (radiusOuter > 0) {\n builder.append(\"|\").append(radiusOuter);\n }\n final int r = (color & 0xFF0000) >>> 16;\n final int g = (color & 0xFF00) >>> 8;\n final int b = color & 0xFF;\n return builder.append(\",\") //\n .append(r).append(\",\") //\n .append(g).append(\",\") //\n .append(b).append(\")\") //\n .toString();\n }",
"private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }",
"private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)\n {\n Map<String, AnnotationValue> annotationValueMap = new HashMap<>();\n if (node instanceof SingleMemberAnnotation)\n {\n SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());\n annotationValueMap.put(\"value\", value);\n }\n else if (node instanceof NormalAnnotation)\n {\n @SuppressWarnings(\"unchecked\")\n List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();\n for (MemberValuePair annotationValue : annotationValues)\n {\n String key = annotationValue.getName().toString();\n Expression expression = annotationValue.getValue();\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);\n annotationValueMap.put(key, value);\n }\n }\n typeRef.setAnnotationValues(annotationValueMap);\n }"
] |
Returns the Set of entities recognized by this Classifier.
@return The Set of entities recognized by this Classifier. | [
"public Set<String> getTags() {\r\n Set<String> tags = new HashSet<String>(classIndex.objectsList());\r\n tags.remove(flags.backgroundSymbol);\r\n return tags;\r\n }"
] | [
"static void handleNotificationClicked(Context context,Bundle notification) {\n if (notification == null) return;\n\n String _accountId = null;\n try {\n _accountId = notification.getString(Constants.WZRK_ACCT_ID_KEY);\n } catch (Throwable t) {\n // no-op\n }\n\n if (instances == null) {\n CleverTapAPI instance = createInstanceIfAvailable(context, _accountId);\n if (instance != null) {\n instance.pushNotificationClickedEvent(notification);\n }\n return;\n }\n\n for (String accountId: instances.keySet()) {\n CleverTapAPI instance = CleverTapAPI.instances.get(accountId);\n boolean shouldProcess = false;\n if (instance != null) {\n shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);\n }\n if (shouldProcess) {\n instance.pushNotificationClickedEvent(notification);\n break;\n }\n }\n }",
"public static float smoothStep(float a, float b, float x) {\n\t\tif (x < a)\n\t\t\treturn 0;\n\t\tif (x >= b)\n\t\t\treturn 1;\n\t\tx = (x - a) / (b - a);\n\t\treturn x*x * (3 - 2*x);\n\t}",
"@Override\n public void invert( ZMatrixRMaj inv ) {\n if( inv.numRows != n || inv.numCols != n ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n if( inv.data == t ) {\n throw new IllegalArgumentException(\"Passing in the same matrix that was decomposed.\");\n }\n\n if(decomposer.isLower()) {\n setToInverseL(inv.data);\n } else {\n throw new RuntimeException(\"Implement\");\n }\n }",
"protected final boolean isDurationValid() {\n\n if (isValidEndTypeForPattern()) {\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS));\n case TIMES:\n return getOccurrences() > 0;\n case SINGLE:\n return true;\n default:\n return false;\n }\n } else {\n return false;\n }\n }",
"private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException {\n PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());\n\n Iterator rIt = keyrings.getKeyRings();\n\n while (rIt.hasNext()) {\n PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next();\n Iterator kIt = kRing.getSecretKeys();\n\n while (kIt.hasNext()) {\n PGPSecretKey key = (PGPSecretKey) kIt.next();\n\n if (key.isSigningKey() && String.format(\"%08x\", key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) {\n return key;\n }\n }\n }\n\n return null;\n }",
"public static base_response enable(nitro_service client, String id) throws Exception {\n\t\tInterface enableresource = new Interface();\n\t\tenableresource.id = id;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}",
"public static void main(String[] args) {\n CmdLine cmd = new CmdLine();\n Configuration conf = new Configuration();\n int res = 0;\n try {\n res = ToolRunner.run(conf, cmd, args);\n } catch (Exception e) {\n System.err.println(\"Error while running MR job\");\n e.printStackTrace();\n }\n System.exit(res);\n }",
"private static Set<String> excludedMethods(String... methodNames)\n {\n Set<String> set = new HashSet<String>(MpxjTreeNode.DEFAULT_EXCLUDED_METHODS);\n set.addAll(Arrays.asList(methodNames));\n return set;\n }",
"public static systemmemory_stats get(nitro_service service) throws Exception{\n\t\tsystemmemory_stats obj = new systemmemory_stats();\n\t\tsystemmemory_stats[] response = (systemmemory_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}"
] |
Read all task relationships from a ConceptDraw PROJECT file.
@param cdp ConceptDraw PROJECT file | [
"private void readRelationships(Document cdp)\n {\n for (Link link : cdp.getLinks().getLink())\n {\n readRelationship(link);\n }\n }"
] | [
"public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException {\n\t\t// Calculate new derivatives. Note that this method is called only with\n\t\t// parameters = parameterCurrent, so we may use valueCurrent.\n\n\t\tVector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length);\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\tfinal double[] parametersNew\t= parameters.clone();\n\t\t\tfinal double[] derivative\t\t= derivatives[parameterIndex];\n\n\t\t\tfinal int workerParameterIndex = parameterIndex;\n\t\t\tCallable<double[]> worker = new Callable<double[]>() {\n\t\t\t\tpublic double[] call() {\n\t\t\t\t\tdouble parameterFiniteDifference;\n\t\t\t\t\tif(parameterSteps != null) {\n\t\t\t\t\t\tparameterFiniteDifference = parameterSteps[workerParameterIndex];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try to adaptively set a parameter shift. Note that in some\n\t\t\t\t\t\t * applications it may be important to set parameterSteps.\n\t\t\t\t\t\t * appropriately.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tparameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Shift parameter value\n\t\t\t\t\tparametersNew[workerParameterIndex] += parameterFiniteDifference;\n\n\t\t\t\t\t// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsetValues(parametersNew, derivative);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// We signal an exception to calculate the derivative as NaN\n\t\t\t\t\t\tArrays.fill(derivative, Double.NaN);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) {\n\t\t\t\t\t\tderivative[valueIndex] -= valueCurrent[valueIndex];\n\t\t\t\t\t\tderivative[valueIndex] /= parameterFiniteDifference;\n\t\t\t\t\t\tif(Double.isNaN(derivative[valueIndex])) {\n\t\t\t\t\t\t\tderivative[valueIndex] = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn derivative;\n\t\t\t\t}\n\t\t\t};\n\t\t\tif(executor != null) {\n\t\t\t\tFuture<double[]> valueFuture = executor.submit(worker);\n\t\t\t\tvalueFutures.add(parameterIndex, valueFuture);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tFutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker);\n\t\t\t\tvalueFutureTask.run();\n\t\t\t\tvalueFutures.add(parameterIndex, valueFutureTask);\n\t\t\t}\n\t\t}\n\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\ttry {\n\t\t\t\tderivatives[parameterIndex] = valueFutures.get(parameterIndex).get();\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t}\n\t\t}\n\t}",
"private void initHasMasterMode() throws CmsException {\n\n if (hasDescriptor()\n && m_cms.hasPermissions(m_desc, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {\n m_hasMasterMode = true;\n } else {\n m_hasMasterMode = false;\n }\n }",
"public GroovyClassDoc[] innerClasses() {\n Collections.sort(nested);\n return nested.toArray(new GroovyClassDoc[nested.size()]);\n }",
"void publish() {\n assert publishedFullRegistry != null : \"Cannot write directly to main registry\";\n\n writeLock.lock();\n try {\n if (!modified) {\n return;\n }\n publishedFullRegistry.writeLock.lock();\n try {\n publishedFullRegistry.clear(true);\n copy(this, publishedFullRegistry);\n pendingRemoveCapabilities.clear();\n pendingRemoveRequirements.clear();\n modified = false;\n } finally {\n publishedFullRegistry.writeLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }",
"public void append(Object object, String indentation) {\n\t\tappend(object, indentation, segments.size());\n\t}",
"public static int getNavigationBarHeight(Context context) {\n Resources resources = context.getResources();\n int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? \"navigation_bar_height\" : \"navigation_bar_height_landscape\", \"dimen\", \"android\");\n if (id > 0) {\n return resources.getDimensionPixelSize(id);\n }\n return 0;\n }",
"private static void loadFile(String filePath) {\n final Path path = FileSystems.getDefault().getPath(filePath);\n\n try {\n data.clear();\n data.load(Files.newBufferedReader(path));\n } catch(IOException e) {\n LOG.warn(\"Exception while loading \" + path.toString(), e);\n }\n }",
"private static Parameter buildParameter(final Map<String, GenericsType> genericFromReceiver, final Map<String, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) {\n if (genericFromReceiver.isEmpty() && (placeholdersFromContext==null||placeholdersFromContext.isEmpty())) {\n return methodParameter;\n }\n if (paramType.isArray()) {\n ClassNode componentType = paramType.getComponentType();\n Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName());\n Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType);\n return new Parameter(component.getType().makeArray(), component.getName());\n }\n ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType);\n\n return new Parameter(resolved, methodParameter.getName());\n }",
"public int[] next()\n {\n boolean hasNewPerm = false;\n\n escape:while( level >= 0) {\n// boolean foundZero = false;\n for( int i = iter[level]; i < data.length; i = iter[level] ) {\n iter[level]++;\n\n if( data[i] == -1 ) {\n level++;\n data[i] = level-1;\n\n if( level >= data.length ) {\n // a new permutation has been created return the results.\n hasNewPerm = true;\n System.arraycopy(data,0,ret,0,ret.length);\n level = level-1;\n data[i] = -1;\n break escape;\n } else {\n valk[level] = i;\n }\n }\n }\n\n data[valk[level]] = -1;\n iter[level] = 0;\n level = level-1;\n\n }\n\n if( hasNewPerm )\n return ret;\n return null;\n }"
] |
Closes the outbound socket binding connection.
@throws IOException | [
"public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }"
] | [
"public static appfwpolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_policybinding_binding obj = new appfwpolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_policybinding_binding response[] = (appfwpolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public JsonObject getJSONwithOperations(TreeContext context, ITree tree, List<Operation> operations) {\n\n\t\tOperationNodePainter opNodePainter = new OperationNodePainter(operations);\n\t\tCollection<NodePainter> painters = new ArrayList<NodePainter>();\n\t\tpainters.add(opNodePainter);\n\t\treturn getJSONwithCustorLabels(context, tree, painters);\n\t}",
"public static int cudnnConvolutionBackwardBias(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dbDesc, \n Pointer db)\n {\n return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db));\n }",
"protected void adoptElement(DomXmlElement elementToAdopt) {\n Document document = this.domElement.getOwnerDocument();\n Element element = elementToAdopt.domElement;\n\n if (!document.equals(element.getOwnerDocument())) {\n Node node = document.adoptNode(element);\n if (node == null) {\n throw LOG.unableToAdoptElement(elementToAdopt);\n }\n }\n }",
"public static Date getTime(int hour, int minutes)\n {\n Calendar cal = popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hour);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, 0);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result;\n }",
"public static base_response update(nitro_service client, route6 resource) throws Exception {\n\t\troute6 updateresource = new route6();\n\t\tupdateresource.network = resource.network;\n\t\tupdateresource.gateway = resource.gateway;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.distance = resource.distance;\n\t\tupdateresource.cost = resource.cost;\n\t\tupdateresource.advertise = resource.advertise;\n\t\tupdateresource.msr = resource.msr;\n\t\tupdateresource.monitor = resource.monitor;\n\t\tupdateresource.td = resource.td;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }",
"public static aaauser_binding get(nitro_service service, String username) throws Exception{\n\t\taaauser_binding obj = new aaauser_binding();\n\t\tobj.set_username(username);\n\t\taaauser_binding response = (aaauser_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void addJoin(TableAlias left, Object[] leftKeys, TableAlias right, Object[] rightKeys, boolean outer,\r\n String name)\r\n {\r\n TableAlias extAlias, rightCopy;\r\n\r\n left.addJoin(new Join(left, leftKeys, right, rightKeys, outer, name));\r\n\r\n // build join between left and extents of right\r\n if (right.hasExtents())\r\n {\r\n for (int i = 0; i < right.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) right.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) rightKeys);\r\n\r\n left.addJoin(new Join(left, leftKeys, extAlias, extKeys, true, name));\r\n }\r\n }\r\n\r\n // we need to copy the alias on the right for each extent on the left\r\n if (left.hasExtents())\r\n {\r\n for (int i = 0; i < left.extents.size(); i++)\r\n {\r\n extAlias = (TableAlias) left.extents.get(i);\r\n FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) leftKeys);\r\n rightCopy = right.copy(\"C\" + i);\r\n\r\n // copies are treated like normal extents\r\n right.extents.add(rightCopy);\r\n right.extents.addAll(rightCopy.extents);\r\n\r\n addJoin(extAlias, extKeys, rightCopy, rightKeys, true, name);\r\n }\r\n }\r\n }"
] |
Set the repeat type.
In the default {@linkplain GVRRepeatMode#ONCE run-once} mode, animations
run once, ignoring the {@linkplain #getRepeatCount() repeat count.} In
{@linkplain GVRRepeatMode#PINGPONG ping pong} and
{@linkplain GVRRepeatMode#REPEATED repeated} modes, animations do honor
the repeat count, which {@linkplain #DEFAULT_REPEAT_COUNT defaults} to 2.
@param repeatMode
One of the {@link GVRRepeatMode} constants
@return {@code this}, so you can chain setProperty() calls.
@throws IllegalArgumentException
If {@code repetitionType} is not one of the
{@link GVRRepeatMode} constants | [
"public GVRAnimation setRepeatMode(int repeatMode) {\n if (GVRRepeatMode.invalidRepeatMode(repeatMode)) {\n throw new IllegalArgumentException(repeatMode\n + \" is not a valid repetition type\");\n }\n mRepeatMode = repeatMode;\n return this;\n }"
] | [
"public RedwoodConfiguration clear(){\r\n tasks = new LinkedList<Runnable>();\r\n tasks.add(new Runnable(){ public void run(){\r\n Redwood.clearHandlers();\r\n Redwood.restoreSystemStreams();\r\n Redwood.clearLoggingClasses();\r\n } });\r\n return this;\r\n }",
"synchronized void transitionFailed(final InternalState state) {\n final InternalState current = this.internalState;\n if(state == current) {\n // Revert transition and mark as failed\n switch (current) {\n case PROCESS_ADDING:\n this.internalState = InternalState.PROCESS_STOPPED;\n break;\n case PROCESS_STARTED:\n internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), InternalState.PROCESS_STARTED, InternalState.PROCESS_ADDED);\n break;\n case PROCESS_STARTING:\n this.internalState = InternalState.PROCESS_ADDED;\n break;\n case SEND_STDIN:\n case SERVER_STARTING:\n this.internalState = InternalState.PROCESS_STARTED;\n break;\n }\n this.requiredState = InternalState.FAILED;\n notifyAll();\n }\n }",
"@RequestMapping(value = \"api/edit/disable\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);\n //TODO also need to disable custom override if there is one of those\n editService.removeCustomOverride(path_id, clientUUID);\n\n return null;\n }",
"public static int findFirstNonAnnotationLine(ASTNode node, SourceCode sourceCode) {\r\n if (node instanceof AnnotatedNode && !((AnnotatedNode) node).getAnnotations().isEmpty()) {\r\n\r\n // HACK: Groovy line numbers are broken when annotations have a parameter :(\r\n // so we must look at the lineNumber, not the lastLineNumber\r\n AnnotationNode lastAnnotation = null;\r\n for (AnnotationNode annotation : ((AnnotatedNode) node).getAnnotations()) {\r\n if (lastAnnotation == null) lastAnnotation = annotation;\r\n else if (lastAnnotation.getLineNumber() < annotation.getLineNumber()) lastAnnotation = annotation;\r\n }\r\n\r\n String rawLine = getRawLine(sourceCode, lastAnnotation.getLastLineNumber()-1);\r\n\r\n if(rawLine == null) {\r\n return node.getLineNumber();\r\n }\r\n\r\n // is the annotation the last thing on the line?\r\n if (rawLine.length() > lastAnnotation.getLastColumnNumber()) {\r\n // no it is not\r\n return lastAnnotation.getLastLineNumber();\r\n }\r\n // yes it is the last thing, return the next thing\r\n return lastAnnotation.getLastLineNumber() + 1;\r\n }\r\n return node.getLineNumber();\r\n }",
"public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\t\t// Check if the LMM uses a discount curve which is created from a forward curve\n\t\tif(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains(\"DiscountCurveFromForwardCurve\".toLowerCase())){\n\t\t\treturn new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime));\n\t\t}\n\t\telse {\n\t\t\t// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.\n\t\t\t// Only at startTime 0!\n\t\t\treturn (DiscountCurveInterface) model.getModel().getDiscountCurve();\n\t\t}\n\n\t}",
"public static void Forward(double[] data) {\n double[] result = new double[data.length];\n\n for (int k = 0; k < result.length; k++) {\n double sum = 0;\n for (int n = 0; n < data.length; n++) {\n double theta = ((2.0 * Math.PI) / data.length) * k * n;\n sum += data[n] * cas(theta);\n }\n result[k] = (1.0 / Math.sqrt(data.length)) * sum;\n }\n\n for (int i = 0; i < result.length; i++) {\n data[i] = result[i];\n }\n\n }",
"@Pure\n\tpublic static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure1<P2>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p) {\n\t\t\t\tprocedure.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}",
"public static List<StoreDefinition> validateRebalanceStore(List<StoreDefinition> storeDefList) {\n List<StoreDefinition> returnList = new ArrayList<StoreDefinition>(storeDefList.size());\n\n for(StoreDefinition def: storeDefList) {\n if(!def.isView() && !canRebalanceList.contains(def.getType())) {\n throw new VoldemortException(\"Rebalance does not support rebalancing of stores of type \"\n + def.getType() + \" - \" + def.getName());\n } else if(!def.isView()) {\n returnList.add(def);\n } else {\n logger.debug(\"Ignoring view \" + def.getName() + \" for rebalancing\");\n }\n }\n return returnList;\n }",
"public List<PathAddressTransformer> getPathTransformations(final PathAddress address, PlaceholderResolver placeholderResolver) {\n final List<PathAddressTransformer> list = new ArrayList<PathAddressTransformer>();\n final Iterator<PathElement> iterator = address.iterator();\n resolvePathTransformers(iterator, list, placeholderResolver);\n if(iterator.hasNext()) {\n while(iterator.hasNext()) {\n iterator.next();\n list.add(PathAddressTransformer.DEFAULT);\n }\n }\n return list;\n }"
] |
Formats a vertex using it's properties. Debugging purposes. | [
"public static final String vertexAsString(Vertex vertex, int depth, String withEdgesOfLabel)\n {\n StringBuilder sb = new StringBuilder();\n vertexAsString(vertex, depth, withEdgesOfLabel, sb, 0, new HashSet<>());\n return sb.toString();\n }"
] | [
"@UiHandler(\"m_addButton\")\r\n void addButtonClick(ClickEvent e) {\r\n\r\n if (null != m_newDate.getValue()) {\r\n m_dateList.addDate(m_newDate.getValue());\r\n m_newDate.setValue(null);\r\n if (handleChange()) {\r\n m_controller.setDates(m_dateList.getDates());\r\n }\r\n }\r\n }",
"public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n if (rangeEnd > 0) {\n request.addHeader(\"Range\", String.format(\"bytes=%s-%s\", Long.toString(rangeStart),\n Long.toString(rangeEnd)));\n } else {\n request.addHeader(\"Range\", String.format(\"bytes=%s-\", Long.toString(rangeStart)));\n }\n\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n } finally {\n response.disconnect();\n }\n }",
"private ClassDescriptor discoverDescriptor(Class clazz)\r\n {\r\n ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName());\r\n\r\n if (result == null)\r\n {\r\n Class superClass = clazz.getSuperclass();\r\n // only recurse if the superClass is not java.lang.Object\r\n if (superClass != null)\r\n {\r\n result = discoverDescriptor(superClass);\r\n }\r\n if (result == null)\r\n {\r\n // we're also checking the interfaces as there could be normal\r\n // mappings for them in the repository (using factory-class,\r\n // factory-method, and the property field accessor)\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n if ((interfaces != null) && (interfaces.length > 0))\r\n {\r\n for (int idx = 0; (idx < interfaces.length) && (result == null); idx++)\r\n {\r\n result = discoverDescriptor(interfaces[idx]);\r\n }\r\n }\r\n }\r\n\r\n if (result != null)\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tsynchronized (descriptorTable) {\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n \t\tdescriptorTable.put(clazz.getName(), result);\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \t}\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n }\r\n return result;\r\n }",
"private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException {\n\t\tList<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>();\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read next field from config file\", e);\n\t\t\t}\n\t\t\tif (line == null || line.equals(CONFIG_FILE_FIELDS_END)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader);\n\t\t\tif (fieldConfig == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfields.add(fieldConfig);\n\t\t}\n\t\tconfig.setFieldConfigs(fields);\n\t}",
"@Override\n\tpublic Integer getPrefixLengthForSingleBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tInteger divPrefix = div.getPrefixLengthForSingleBlock();\n\t\t\tif(divPrefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\ttotalPrefix += divPrefix;\n\t\t\tif(divPrefix < div.getBitCount()) {\n\t\t\t\t//remaining segments must be full range or we return null\n\t\t\t\tfor(i++; i < count; i++) {\n\t\t\t\t\tAddressDivisionBase laterDiv = getDivision(i);\n\t\t\t\t\tif(!laterDiv.isFullRange()) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cacheBits(totalPrefix);\n\t}",
"@Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // If the API level is less than 11, we can't rely on the view animation system to\n // do the scrolling animation. Need to tick it here and call postInvalidate() until the scrolling is done.\n if (Build.VERSION.SDK_INT < 11) {\n tickScrollAnimation();\n if (!mScroller.isFinished()) {\n mGraph.postInvalidate();\n }\n }\n }",
"public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }",
"public void validate(final List<Throwable> validationErrors) {\n if (this.matchers == null) {\n validationErrors.add(new IllegalArgumentException(\n \"Matchers cannot be null. There should be at least a !acceptAll matcher\"));\n }\n if (this.matchers != null && this.matchers.isEmpty()) {\n validationErrors.add(new IllegalArgumentException(\n \"There are no url matchers defined. There should be at least a \" +\n \"!acceptAll matcher\"));\n }\n }",
"private void getSingleValue(Method method, Object object, Map<String, String> map)\n {\n Object value;\n try\n {\n value = filterValue(method.invoke(object));\n }\n catch (Exception ex)\n {\n value = ex.toString();\n }\n\n if (value != null)\n {\n map.put(getPropertyName(method), String.valueOf(value));\n }\n }"
] |
Compares the two comma-separated lists.
@param list1 The first list
@param list2 The second list
@return <code>true</code> if the lists are equal | [
"public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\n }"
] | [
"public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }",
"public static SPIProvider getInstance()\n {\n if (me == null)\n {\n final ClassLoader cl = ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader();\n me = SPIProviderResolver.getInstance(cl).getProvider();\n }\n return me;\n }",
"public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\n }",
"protected boolean inViewPort(final int dataIndex) {\n boolean inViewPort = true;\n\n for (Layout layout: mLayouts) {\n inViewPort = inViewPort && (layout.inViewPort(dataIndex) || !layout.isClippingEnabled());\n }\n return inViewPort;\n }",
"public synchronized void setMonitoredPlayer(final int player) {\n if (player < 0) {\n throw new IllegalArgumentException(\"player cannot be negative\");\n }\n clearPlaybackState();\n monitoredPlayer.set(player);\n if (player > 0) { // Start monitoring the specified player\n setPlaybackState(player, 0, false); // Start with default values for required simple state.\n VirtualCdj.getInstance().addUpdateListener(updateListener);\n MetadataFinder.getInstance().addTrackMetadataListener(metadataListener);\n cueList.set(null); // Assume the worst, but see if we have one available next.\n if (MetadataFinder.getInstance().isRunning()) {\n TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n if (metadata != null) {\n cueList.set(metadata.getCueList());\n }\n }\n WaveformFinder.getInstance().addWaveformListener(waveformListener);\n if (WaveformFinder.getInstance().isRunning() && WaveformFinder.getInstance().isFindingDetails()) {\n waveform.set(WaveformFinder.getInstance().getLatestDetailFor(player));\n } else {\n waveform.set(null);\n }\n BeatGridFinder.getInstance().addBeatGridListener(beatGridListener);\n if (BeatGridFinder.getInstance().isRunning()) {\n beatGrid.set(BeatGridFinder.getInstance().getLatestBeatGridFor(player));\n } else {\n beatGrid.set(null);\n }\n try {\n TimeFinder.getInstance().start();\n if (!animating.getAndSet(true)) {\n // Create the thread to update our position smoothly as the track plays\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (animating.get()) {\n try {\n Thread.sleep(33); // Animate at 30 fps\n } catch (InterruptedException e) {\n logger.warn(\"Waveform animation thread interrupted; ending\");\n animating.set(false);\n }\n setPlaybackPosition(TimeFinder.getInstance().getTimeFor(getMonitoredPlayer()));\n }\n }\n }).start();\n }\n } catch (Exception e) {\n logger.error(\"Unable to start the TimeFinder to animate the waveform detail view\");\n animating.set(false);\n }\n } else { // Stop monitoring any player\n animating.set(false);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n cueList.set(null);\n waveform.set(null);\n beatGrid.set(null);\n }\n if (!autoScroll.get()) {\n invalidate();\n }\n repaint();\n }",
"public static void fillHermitian(ZMatrixRMaj 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 A.set(i,i,rand.nextDouble()*range + min,0);\n\n for( int j = i+1; j < length; j++ ) {\n double real = rand.nextDouble()*range + min;\n double imaginary = rand.nextDouble()*range + min;\n A.set(i,j,real,imaginary);\n A.set(j,i,real,-imaginary);\n }\n }\n }",
"public static void setPropertySafely(Marshaller marshaller, String name, Object value) {\n try {\n marshaller.setProperty(name, value);\n } catch (PropertyException e) {\n LOGGER.warn(String.format(\"Can't set \\\"%s\\\" property to given marshaller\", name), e);\n }\n }",
"public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}",
"private Class getDynamicProxyClass(Class baseClass) {\r\n Class[] m_dynamicProxyClassInterfaces;\r\n if (foundInterfaces.containsKey(baseClass)) {\r\n m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);\r\n } else {\r\n m_dynamicProxyClassInterfaces = getInterfaces(baseClass);\r\n foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);\r\n }\r\n\r\n // return dynymic Proxy Class implementing all interfaces\r\n Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);\r\n return proxyClazz;\r\n }"
] |
Finds the first Field with given field name in the Class and in its super classes.
@param type The Class type
@param fieldName The field name to get
@return an {@code Optional}. Use isPresent() to find out if the field name was found. | [
"public static Optional<Field> getField(Class<?> type, final String fieldName) {\n Optional<Field> field = Iterables.tryFind(newArrayList(type.getDeclaredFields()), havingFieldName(fieldName));\n\n if (!field.isPresent() && type.getSuperclass() != null){\n field = getField(type.getSuperclass(), fieldName);\n }\n\n return field;\n }"
] | [
"public static dnsnsecrec[] get(nitro_service service, dnsnsecrec_args args) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsnsecrec[] response = (dnsnsecrec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public GVRRenderData setCullFace(GVRCullFaceEnum cullFace, int passIndex) {\n if (passIndex < mRenderPassList.size()) {\n mRenderPassList.get(passIndex).setCullFace(cullFace);\n } else {\n Log.e(TAG, \"Trying to set cull face to a invalid pass. Pass \" + passIndex + \" was not created.\");\n }\n return this;\n }",
"public final void notifyHeaderItemChanged(int position) {\n if (position < 0 || position >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position);\n }",
"@Override\n protected void initBuilderSpecific() throws Exception {\n reset();\n FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);\n FilePath gradlePropertiesPath = new FilePath(workspace, \"gradle.properties\");\n if (releaseProps == null) {\n releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());\n }\n if (nextIntegProps == null) {\n nextIntegProps =\n PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());\n }\n }",
"public static STSClient createSTSX509Client(Bus bus, Map<String, String> stsProps) {\r\n final STSClient stsClient = createClient(bus, stsProps);\r\n\r\n stsClient.setWsdlLocation(stsProps.get(STS_X509_WSDL_LOCATION));\r\n stsClient.setEndpointQName(new QName(stsProps.get(STS_NAMESPACE), stsProps.get(STS_X509_ENDPOINT_NAME)));\r\n\r\n return stsClient;\r\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 }",
"public synchronized int getPartitionStoreMoves() {\n int count = 0;\n for (List<Integer> entry : storeToPartitionIds.values())\n count += entry.size();\n return count;\n }",
"public static String createClassName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return name;\n }",
"public <T> InternalEjbDescriptor<T> get(String beanName) {\n return cast(ejbByName.get(beanName));\n }"
] |
Check that an array only contains elements that are not null.
@param values, can't be null
@return | [
"public static boolean containsOnlyNotNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o== null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}"
] | [
"public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}",
"public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {\r\n\t\treturn new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),\r\n\t\t\t\tgetBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}",
"public void process(String inputFile, String outputFile) throws Exception\n {\n System.out.println(\"Reading input file started.\");\n long start = System.currentTimeMillis();\n ProjectFile projectFile = readFile(inputFile);\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading input file 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 }",
"@Override\n public final int getInt(final int i) {\n int val = this.array.optInt(i, Integer.MIN_VALUE);\n if (val == Integer.MIN_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }",
"public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private String getActivityStatus(Task mpxj)\n {\n String result;\n if (mpxj.getActualStart() == null)\n {\n result = \"Not Started\";\n }\n else\n {\n if (mpxj.getActualFinish() == null)\n {\n result = \"In Progress\";\n }\n else\n {\n result = \"Completed\";\n }\n }\n return result;\n }",
"public void fillFromToWith(int from, int to, Object val) {\r\n\tcheckRangeFromTo(from,to,this.size);\r\n\tfor (int i=from; i<=to;) setQuick(i++,val); \r\n}",
"public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n eachMatch(self.toString(), regex.toString(), closure);\n return self;\n }",
"@Override\n public final Boolean optBool(final String key, final Boolean defaultValue) {\n Boolean result = optBool(key);\n return result == null ? defaultValue : result;\n }"
] |
Open the log file for writing. | [
"public static void openLogFile() throws IOException\n {\n if (LOG_FILE != null)\n {\n System.out.println(\"SynchroLogger Configured\");\n LOG = new PrintWriter(new FileWriter(LOG_FILE));\n }\n }"
] | [
"public Model interpolateModel(Model model, File projectDir, ModelBuildingRequest config,\n\t\t\tModelProblemCollector problems) {\n\t\tinterpolateObject(model, model, projectDir, config, problems);\n\n\t\treturn model;\n\t}",
"private void fillToolBar(final I_CmsAppUIContext context) {\n\n context.setAppTitle(m_messages.key(Messages.GUI_APP_TITLE_0));\n\n // create components\n Component publishBtn = createPublishButton();\n m_saveBtn = createSaveButton();\n m_saveExitBtn = createSaveExitButton();\n Component closeBtn = createCloseButton();\n\n context.enableDefaultToolbarButtons(false);\n context.addToolbarButtonRight(closeBtn);\n context.addToolbarButton(publishBtn);\n context.addToolbarButton(m_saveExitBtn);\n context.addToolbarButton(m_saveBtn);\n\n Component addDescriptorBtn = createAddDescriptorButton();\n if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n addDescriptorBtn.setEnabled(false);\n }\n context.addToolbarButton(addDescriptorBtn);\n if (m_model.getBundleType().equals(BundleType.XML)) {\n Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton();\n context.addToolbarButton(convertToPropertyBundleBtn);\n }\n }",
"protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }",
"public static gslbservice[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tgslbservice[] response = (gslbservice[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public static double findMax( double[] u, int startU , int length ) {\n double max = -1;\n\n int index = startU*2;\n int stopIndex = (startU + length)*2;\n for( ; index < stopIndex;) {\n double real = u[index++];\n double img = u[index++];\n\n double val = real*real + img*img;\n\n if( val > max ) {\n max = val;\n }\n }\n\n return Math.sqrt(max);\n }",
"public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }",
"private static Map<String, Integer> findClasses(Path path)\n {\n List<String> paths = findPaths(path, true);\n Map<String, Integer> results = new HashMap<>();\n for (String subPath : paths)\n {\n if (subPath.endsWith(\".java\") || subPath.endsWith(\".class\"))\n {\n String qualifiedName = PathUtil.classFilePathToClassname(subPath);\n addClassToMap(results, qualifiedName);\n }\n }\n return results;\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}",
"private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot.\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));\n if (cache != null) {\n final AlbumArt result = cache.getAlbumArt(null, artReference);\n if (result != null) {\n artCache.put(artReference, result);\n }\n return result;\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());\n if (sourceDetails != null) {\n final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);\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 && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the art using the dbserver protocol.\n ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {\n @Override\n public AlbumArt useClient(Client client) throws Exception {\n return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);\n }\n };\n\n try {\n AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, \"requesting artwork\");\n if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.\n artCache.put(artReference, artwork);\n }\n return artwork;\n } catch (Exception e) {\n logger.error(\"Problem requesting album art, returning null\", e);\n }\n return null;\n }"
] |
Compares current cluster with final cluster. Uses pertinent store defs
for each cluster to determine if a node that hosts a zone-primary in the
current cluster will no longer host any zone-nary in the final cluster.
This check is the precondition for a server returning an invalid metadata
exception to a client on a normal-case put or get. Normal-case being that
the zone-primary receives the pseudo-master put or the get operation.
@param currentCluster
@param currentStoreDefs
@param finalCluster
@param finalStoreDefs
@return pretty-printed string documenting invalid metadata rates for each
zone. | [
"public static String analyzeInvalidMetadataRate(final Cluster currentCluster,\n List<StoreDefinition> currentStoreDefs,\n final Cluster finalCluster,\n List<StoreDefinition> finalStoreDefs) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Dump of invalid metadata rates per zone\").append(Utils.NEWLINE);\n\n HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs);\n\n for(StoreDefinition currentStoreDef: uniqueStores.keySet()) {\n sb.append(\"Store exemplar: \" + currentStoreDef.getName())\n .append(Utils.NEWLINE)\n .append(\"\\tThere are \" + uniqueStores.get(currentStoreDef) + \" other similar stores.\")\n .append(Utils.NEWLINE);\n\n StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef);\n StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs,\n currentStoreDef.getName());\n StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef);\n\n // Only care about existing zones\n for(int zoneId: currentCluster.getZoneIds()) {\n int zonePrimariesCount = 0;\n int invalidMetadata = 0;\n\n // Examine nodes in current cluster in existing zone.\n for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) {\n // For every zone-primary in current cluster\n for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) {\n zonePrimariesCount++;\n // Determine if original zone-primary node is still some\n // form of n-ary in final cluster. If not,\n // InvalidMetadataException will fire.\n if(!finalSRP.getZoneNAryPartitionIds(nodeId)\n .contains(zonePrimaryPartitionId)) {\n invalidMetadata++;\n }\n }\n }\n float rate = invalidMetadata / (float) zonePrimariesCount;\n sb.append(\"\\tZone \" + zoneId)\n .append(\" : total zone primaries \" + zonePrimariesCount)\n .append(\", # that trigger invalid metadata \" + invalidMetadata)\n .append(\" => \" + rate)\n .append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }"
] | [
"public void applyTo(Context ctx, GradientDrawable drawable) {\n if (mColorInt != 0) {\n drawable.setColor(mColorInt);\n } else if (mColorRes != -1) {\n drawable.setColor(ContextCompat.getColor(ctx, mColorRes));\n }\n }",
"public static void main(String[] args) {\n DirectoryIterator iter = new DirectoryIterator(args);\n while(iter.hasNext())\n System.out.println(iter.next().getAbsolutePath());\n }",
"protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public static String formatDateRange(Context context, ReadablePartial start, ReadablePartial end, int flags) {\n return formatDateRange(context, toMillis(start), toMillis(end), flags);\n }",
"public static void addHeaders(BoundRequestBuilder builder,\n Map<String, String> headerMap) {\n for (Entry<String, String> entry : headerMap.entrySet()) {\n String name = entry.getKey();\n String value = entry.getValue();\n builder.addHeader(name, value);\n }\n\n }",
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.fullString) == null) {\n\t\t\tstringCache.fullString = result = toNormalizedString(IPv4StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}",
"public float getPositionZ(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"private Object getAttributeRecursively(Object feature, String name) throws LayerException {\n\t\tif (feature == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Split up properties: the first and the rest.\n\t\tString[] properties = name.split(SEPARATOR_REGEXP, 2);\n\t\tObject tempFeature;\n\n\t\t// If the first property is the identifier:\n\t\tif (properties[0].equals(getFeatureInfo().getIdentifier().getName())) {\n\t\t\ttempFeature = getId(feature);\n\t\t} else {\n\t\t\tEntity entity = entityMapper.asEntity(feature);\n\t\t\tHibernateEntity child = (HibernateEntity) entity.getChild(properties[0]);\n\t\t\ttempFeature = child == null ? null : child.getObject();\n\t\t}\n\n\t\t// Detect if the first property is a collection (one-to-many):\n\t\tif (tempFeature instanceof Collection<?>) {\n\t\t\tCollection<?> features = (Collection<?>) tempFeature;\n\t\t\tObject[] values = new Object[features.size()];\n\t\t\tint count = 0;\n\t\t\tfor (Object value : features) {\n\t\t\t\tif (properties.length == 1) {\n\t\t\t\t\tvalues[count++] = value;\n\t\t\t\t} else {\n\t\t\t\t\tvalues[count++] = getAttributeRecursively(value, properties[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn values;\n\t\t} else { // Else first property is not a collection (one-to-many):\n\t\t\tif (properties.length == 1 || tempFeature == null) {\n\t\t\t\treturn tempFeature;\n\t\t\t} else {\n\t\t\t\treturn getAttributeRecursively(tempFeature, properties[1]);\n\t\t\t}\n\t\t}\n\t}",
"public static cmpglobal_cmppolicy_binding[] get(nitro_service service) throws Exception{\n\t\tcmpglobal_cmppolicy_binding obj = new cmpglobal_cmppolicy_binding();\n\t\tcmpglobal_cmppolicy_binding response[] = (cmpglobal_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Adds a file with the provided description. | [
"public void addFile(String description, FileModel fileModel)\n {\n Map<FileModel, ProblemFileSummary> files = addDescription(description);\n\n if (files.containsKey(fileModel))\n {\n files.get(fileModel).addOccurrence();\n } else {\n files.put(fileModel, new ProblemFileSummary(fileModel, 1));\n }\n }"
] | [
"public void addDependencyTaskGroup(TaskGroup dependencyTaskGroup) {\n if (dependencyTaskGroup.proxyTaskGroupWrapper.isActive()) {\n dependencyTaskGroup.proxyTaskGroupWrapper.addDependentTaskGroup(this);\n } else {\n DAGraph<TaskItem, TaskGroupEntry<TaskItem>> dependencyGraph = dependencyTaskGroup;\n super.addDependencyGraph(dependencyGraph);\n }\n }",
"protected byte[] getBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache() || (cached = valueCache.lowerBytes) == null) {\n\t\t\tvalueCache.lowerBytes = cached = getBytesImpl(true);\n\t\t}\n\t\treturn cached;\n\t}",
"private String fixApiDocRoot(String str) {\n\tif (str == null)\n\t return null;\n\tString fixed = str.trim();\n\tif (fixed.isEmpty())\n\t return \"\";\n\tif (File.separatorChar != '/')\n\t fixed = fixed.replace(File.separatorChar, '/');\n\tif (!fixed.endsWith(\"/\"))\n\t fixed = fixed + \"/\";\n\treturn fixed;\n }",
"public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }",
"private Date readOptionalDate(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return new Date(Long.parseLong(str.stringValue()));\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // do nothing - return the default value\n }\n }\n return null;\n }",
"String deriveGroupIdFromPackages(ProjectModel projectModel)\n {\n Map<Object, Long> pkgsMap = new HashMap<>();\n Set<String> pkgs = new HashSet<>(1000);\n GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(graphContext.getGraph()).V(projectModel);\n\n\n pkgsMap = pipeline.out(ProjectModel.PROJECT_MODEL_TO_FILE)\n .has(WindupVertexFrame.TYPE_PROP, new P(new BiPredicate<String, String>() {\n @Override\n public boolean test(String o, String o2) {\n return o.contains(o2);\n }\n },\n GraphTypeManager.getTypeValue(JavaClassFileModel.class)))\n .hasKey(JavaClassFileModel.PROPERTY_PACKAGE_NAME)\n .groupCount()\n .by(v -> upToThirdDot(graphContext, (Vertex)v)).toList().get(0);\n\n Map.Entry<Object, Long> biggest = null;\n for (Map.Entry<Object, Long> entry : pkgsMap.entrySet())\n {\n if (biggest == null || biggest.getValue() < entry.getValue())\n biggest = entry;\n }\n // More than a half is of this package.\n if (biggest != null && biggest.getValue() > pkgsMap.size() / 2)\n return biggest.getKey().toString();\n\n return null;\n }",
"private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {\n\t\tdouble interpolationEntitiyTime;\n\t\tRandomVariable interpolationEntityForwardValue;\n\t\tswitch(interpolationEntityForward) {\n\t\tcase FORWARD:\n\t\tdefault:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward;\n\t\t\tbreak;\n\t\tcase FORWARD_TIMES_DISCOUNTFACTOR:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));\n\t\t\tbreak;\n\t\tcase ZERO:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime = fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);\n\t\t\tbreak;\n\t\t}\n\t\tcase DISCOUNTFACTOR:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime\t\t= fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t\tsuper.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);\n\t}",
"public void implicitDoubleStep( int x1 , int x2 ) {\n if( printHumps )\n System.out.println(\"Performing implicit double step\");\n\n // compute the wilkinson shift\n double z11 = A.get(x2 - 1, x2 - 1);\n double z12 = A.get(x2 - 1, x2);\n double z21 = A.get(x2, x2 - 1);\n double z22 = A.get(x2, x2);\n\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n if( normalize ) {\n temp[0] = a11;temp[1] = a21;temp[2] = a12;temp[3] = a22;temp[4] = a32;\n temp[5] = z11;temp[6] = z22;temp[7] = z12;temp[8] = z21;\n\n double max = Math.abs(temp[0]);\n for( int j = 1; j < temp.length; j++ ) {\n if( Math.abs(temp[j]) > max )\n max = Math.abs(temp[j]);\n }\n a11 /= max;a21 /= max;a12 /= max;a22 /= max;a32 /= max;\n z11 /= max;z22 /= max;z12 /= max;z21 /= max;\n }\n\n // these equations are derived when the eigenvalues are extracted from the lower right\n // 2 by 2 matrix. See page 388 of Fundamentals of Matrix Computations 2nd ed for details.\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = ((a11- z11)*(a11- z22)- z21 * z12)/a21 + a12;\n b21 = a11 + a22 - z11 - z22;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = ((a11- z11)*(a11- z22)- z21 * z12) + a12*a21;\n b21 = (a11 + a22 - z11 - z22)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11 , b21 , b31 );\n }"
] |
Create a list of operations required to a boot a managed server.
@param serverName the server name
@param domainModel the complete domain model
@param hostModel the local host model
@param domainController the domain controller
@return the list of boot operations | [
"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 static String copyToString(InputStream in, Charset charset) throws IOException {\n\t\tAssert.notNull(in, \"No InputStream specified\");\n\t\tStringBuilder out = new StringBuilder();\n\t\tInputStreamReader reader = new InputStreamReader(in, charset);\n\t\tchar[] buffer = new char[BUFFER_SIZE];\n\t\tint bytesRead = -1;\n\t\twhile ((bytesRead = reader.read(buffer)) != -1) {\n\t\t\tout.append(buffer, 0, bytesRead);\n\t\t}\n\t\treturn out.toString();\n\t}",
"public static List<DockerImage> getImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId && image.hasManifest()) {\n list.add(image);\n }\n }\n return list;\n }",
"public void setTextureBufferSize(final int size) {\n mRootViewGroup.post(new Runnable() {\n @Override\n public void run() {\n mRootViewGroup.setTextureBufferSize(size);\n }\n });\n }",
"private static void bodyWithBuilderAndSeparator(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n Variable result = new Variable(\"result\");\n Variable separator = new Variable(\"separator\");\n\n code.addLine(\" %1$s %2$s = new %1$s(\\\"%3$s{\\\");\", StringBuilder.class, result, typename);\n if (generatorsByProperty.size() > 1) {\n // If there's a single property, we don't actually use the separator variable\n code.addLine(\" %s %s = \\\"\\\";\", String.class, separator);\n }\n\n Property first = generatorsByProperty.keySet().iterator().next();\n Property last = getLast(generatorsByProperty.keySet());\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n switch (generator.initialState()) {\n case HAS_DEFAULT:\n throw new RuntimeException(\"Internal error: unexpected default field\");\n\n case OPTIONAL:\n code.addLine(\" if (%s) {\", (Excerpt) generator::addToStringCondition);\n break;\n\n case REQUIRED:\n code.addLine(\" if (!%s.contains(%s.%s)) {\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n break;\n }\n code.add(\" \").add(result);\n if (property != first) {\n code.add(\".append(%s)\", separator);\n }\n code.add(\".append(\\\"%s=\\\").append(%s)\",\n property.getName(), (Excerpt) generator::addToStringValue);\n if (property != last) {\n code.add(\";%n %s = \\\", \\\"\", separator);\n }\n code.add(\";%n }%n\");\n }\n code.addLine(\" return %s.append(\\\"}\\\").toString();\", result);\n }",
"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 }",
"public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable unsetresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new bridgetable();\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }",
"public Iterable<BoxLegalHoldAssignment.Info> getAssignments(String type, String id, int limit, String ... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (type != null) {\n builder.appendParam(\"assign_to_type\", type);\n }\n if (id != null) {\n builder.appendParam(\"assign_to_id\", id);\n }\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new BoxResourceIterable<BoxLegalHoldAssignment.Info>(\n this.getAPI(), LEGAL_HOLD_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(\n this.getAPI().getBaseURL(), builder.toString(), this.getID()), limit) {\n\n @Override\n protected BoxLegalHoldAssignment.Info factory(JsonObject jsonObject) {\n BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(\n BoxLegalHoldPolicy.this.getAPI(), jsonObject.get(\"id\").asString());\n return assignment.new Info(jsonObject);\n }\n };\n }",
"private Boolean readOptionalBoolean(JSONObject json, String key) {\n\n try {\n return Boolean.valueOf(json.getBoolean(key));\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON boolean failed. Default to provided default value.\", e);\n }\n return null;\n }"
] |
Initializes data structures | [
"void init( DMatrixSparseCSC A ) {\n this.A = A;\n this.m = A.numRows;\n this.n = A.numCols;\n\n this.next = 0;\n this.head = m;\n this.tail = m + n;\n this.nque = m + 2*n;\n\n if( parent.length < n || leftmost.length < m) {\n parent = new int[n];\n post = new int[n];\n pinv = new int[m+n];\n countsR = new int[n];\n leftmost = new int[m];\n }\n gwork.reshape(m+3*n);\n }"
] | [
"public LayoutScroller.ScrollableList getPageScrollable() {\n return new LayoutScroller.ScrollableList() {\n\n @Override\n public int getScrollingItemsCount() {\n return MultiPageWidget.super.getScrollingItemsCount();\n }\n\n @Override\n public float getViewPortWidth() {\n return MultiPageWidget.super.getViewPortWidth();\n }\n\n @Override\n public float getViewPortHeight() {\n return MultiPageWidget.super.getViewPortHeight();\n }\n\n @Override\n public float getViewPortDepth() {\n return MultiPageWidget.super.getViewPortDepth();\n }\n\n @Override\n public boolean scrollToPosition(int pos, final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollToPosition(pos, listener);\n }\n\n @Override\n public boolean scrollByOffset(float xOffset, float yOffset, float zOffset,\n final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollByOffset(xOffset, yOffset, zOffset, listener);\n }\n\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.registerDataSetObserver(observer);\n }\n\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.unregisterDataSetObserver(observer);\n }\n\n @Override\n public int getCurrentPosition() {\n return MultiPageWidget.super.getCurrentPosition();\n }\n\n };\n }",
"public PhotoContext getContext(String photoId, String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else {\r\n if (logger.isInfoEnabled()) {\r\n logger.info(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n }\r\n return photoContext;\r\n }",
"static String md5(String input) {\n if (input == null || input.length() == 0) {\n throw new IllegalArgumentException(\"Input string must not be blank.\");\n }\n try {\n MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n algorithm.reset();\n algorithm.update(input.getBytes());\n byte[] messageDigest = algorithm.digest();\n\n StringBuilder hexString = new StringBuilder();\n for (byte messageByte : messageDigest) {\n hexString.append(Integer.toHexString((messageByte & 0xFF) | 0x100).substring(1, 3));\n }\n return hexString.toString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"private void emitSuiteStart(Description description, long startTimestamp) throws IOException {\n String suiteName = description.getDisplayName();\n if (useSimpleNames) {\n if (suiteName.lastIndexOf('.') >= 0) {\n suiteName = suiteName.substring(suiteName.lastIndexOf('.') + 1);\n }\n }\n logShort(shortTimestamp(startTimestamp) +\n \"Suite: \" +\n FormattingUtils.padTo(maxClassNameColumns, suiteName, \"[...]\"));\n }",
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }",
"public static <K, V> Map<K, V> immutableMapView(Map<K, V> map) {\n if (map instanceof ImmutableMap<?, ?>) {\n return map;\n }\n return Collections.unmodifiableMap(map);\n }",
"public List<URL> scan(Predicate<String> filter)\n {\n List<URL> discoveredURLs = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> filteredResourcePaths = filterAddonResources(addon, filter);\n for (String filePath : filteredResourcePaths)\n {\n URL ruleFile = addon.getClassLoader().getResource(filePath);\n if (ruleFile != null)\n discoveredURLs.add(ruleFile);\n }\n }\n return discoveredURLs;\n }",
"public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }",
"static Parameter createParameter(final String name, final String value) {\n if (value != null && isQuoted(value)) {\n return new QuotedParameter(name, value);\n }\n return new Parameter(name, value);\n }"
] |
Returns the total number of weights associated with this classifier.
@return number of weights | [
"public int getNumWeights() {\r\n if (weights == null) return 0;\r\n int numWeights = 0;\r\n for (double[] wts : weights) {\r\n numWeights += wts.length;\r\n }\r\n return numWeights;\r\n }"
] | [
"public static List<String> getBuildNumbersNotToBeDeleted(Run build) {\n List<String> notToDelete = Lists.newArrayList();\n List<? extends Run<?, ?>> builds = build.getParent().getBuilds();\n for (Run<?, ?> run : builds) {\n if (run.isKeepLog()) {\n notToDelete.add(String.valueOf(run.getNumber()));\n }\n }\n return notToDelete;\n }",
"public static double JensenShannonDivergence(double[] p, double[] q) {\n double[] m = new double[p.length];\n for (int i = 0; i < m.length; i++) {\n m[i] = (p[i] + q[i]) / 2;\n }\n\n return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2;\n }",
"public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }",
"private void updateDates(Task parentTask)\n {\n if (parentTask.hasChildTasks())\n {\n Date plannedStartDate = null;\n Date plannedFinishDate = null;\n\n for (Task task : parentTask.getChildTasks())\n {\n updateDates(task);\n plannedStartDate = DateHelper.min(plannedStartDate, task.getStart());\n plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish());\n }\n\n parentTask.setStart(plannedStartDate);\n parentTask.setFinish(plannedFinishDate);\n }\n }",
"public static spilloverpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_stats response = (spilloverpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"static InstalledIdentity load(final InstalledImage image, final ProductConfig productConfig, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n\n // build the identity information\n final String productVersion = productConfig.resolveVersion();\n final String productName = productConfig.resolveName();\n final Identity identity = new AbstractLazyIdentity() {\n @Override\n public String getName() {\n return productName;\n }\n\n @Override\n public String getVersion() {\n return productVersion;\n }\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n };\n\n final Properties properties = PatchUtils.loadProperties(identity.getDirectoryStructure().getInstallationInfo());\n final List<String> allPatches = PatchUtils.readRefs(properties, Constants.ALL_PATCHES);\n\n // Step 1 - gather the installed layers data\n final InstalledConfiguration conf = createInstalledConfig(image);\n // Step 2 - process the actual module and bundle roots\n final ProcessedLayers processedLayers = process(conf, moduleRoots, bundleRoots);\n final InstalledConfiguration config = processedLayers.getConf();\n\n // Step 3 - create the actual config objects\n // Process layers\n final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl(identity, allPatches, image);\n for (final LayerPathConfig layer : processedLayers.getLayers().values()) {\n final String name = layer.name;\n installedIdentity.putLayer(name, createPatchableTarget(name, layer, config.getLayerMetadataDir(name), image));\n }\n // Process add-ons\n for (final LayerPathConfig addOn : processedLayers.getAddOns().values()) {\n final String name = addOn.name;\n installedIdentity.putAddOn(name, createPatchableTarget(name, addOn, config.getAddOnMetadataDir(name), image));\n }\n return installedIdentity;\n }",
"private Object tryConvert(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final Object rowValue) throws URISyntaxException, IOException {\n if (this.converters.isEmpty()) {\n return rowValue;\n }\n\n String value = String.valueOf(rowValue);\n for (TableColumnConverter<?> converter: this.converters) {\n if (converter.canConvert(value)) {\n return converter.resolve(clientHttpRequestFactory, value);\n }\n }\n\n return rowValue;\n }",
"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 static base_response disable(nitro_service client, String id) throws Exception {\n\t\tInterface disableresource = new Interface();\n\t\tdisableresource.id = id;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}"
] |
Adds search fields from elements on a container page to a container page's document.
@param document The document for the container page
@param cms The current CmsObject
@param resource The resource of the container page
@param systemFields The list of field names for fields where mappings to should be discarded, since these fields are used system internally.
@return the manipulated document | [
"protected I_CmsSearchDocument appendFieldMappingsFromElementsOnThePage(\n I_CmsSearchDocument document,\n CmsObject cms,\n CmsResource resource,\n List<String> systemFields) {\n\n try {\n CmsFile file = cms.readFile(resource);\n CmsXmlContainerPage containerPage = CmsXmlContainerPageFactory.unmarshal(cms, file);\n CmsContainerPageBean containerBean = containerPage.getContainerPage(cms);\n if (containerBean != null) {\n for (CmsContainerElementBean element : containerBean.getElements()) {\n element.initResource(cms);\n CmsResource elemResource = element.getResource();\n Set<CmsSearchField> mappedFields = getXSDMappingsForPage(cms, elemResource);\n if (mappedFields != null) {\n\n for (CmsSearchField field : mappedFields) {\n if (!systemFields.contains(field.getName())) {\n document = appendFieldMapping(\n document,\n field,\n cms,\n elemResource,\n CmsSolrDocumentXmlContent.extractXmlContent(cms, elemResource, getIndex()),\n cms.readPropertyObjects(resource, false),\n cms.readPropertyObjects(resource, true));\n } else {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.LOG_SOLR_ERR_MAPPING_TO_INTERNALLY_USED_FIELD_3,\n elemResource.getRootPath(),\n field.getName(),\n resource.getRootPath()));\n }\n }\n }\n }\n }\n } catch (CmsException e) {\n // Should be thrown if element on the page does not exist anymore - this is possible, but not necessarily an error.\n // Hence, just notice it in the debug log.\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n }\n return document;\n }"
] | [
"private void registerChildInternal(IgnoreDomainResourceTypeResource child) {\n child.setParent(this);\n children.put(child.getName(), child);\n }",
"private void populateCalendar(Record record, ProjectCalendar calendar, boolean isBaseCalendar)\n {\n if (isBaseCalendar == true)\n {\n calendar.setName(record.getString(0));\n }\n else\n {\n calendar.setParent(m_projectFile.getCalendarByName(record.getString(0)));\n }\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.getInstance(record.getInteger(1)));\n calendar.setWorkingDay(Day.MONDAY, DayType.getInstance(record.getInteger(2)));\n calendar.setWorkingDay(Day.TUESDAY, DayType.getInstance(record.getInteger(3)));\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.getInstance(record.getInteger(4)));\n calendar.setWorkingDay(Day.THURSDAY, DayType.getInstance(record.getInteger(5)));\n calendar.setWorkingDay(Day.FRIDAY, DayType.getInstance(record.getInteger(6)));\n calendar.setWorkingDay(Day.SATURDAY, DayType.getInstance(record.getInteger(7)));\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }",
"private static void attachToContent(Activity activity, MenuDrawer menuDrawer) {\n /**\n * Do not call mActivity#setContentView.\n * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to\n * MenuDrawer#setContentView, which then again would call Activity#setContentView.\n */\n ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);\n content.removeAllViews();\n content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }",
"public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }",
"public static dnsglobal_binding get(nitro_service service) throws Exception{\n\t\tdnsglobal_binding obj = new dnsglobal_binding();\n\t\tdnsglobal_binding response = (dnsglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static <T> int createTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn doCreateTable(dao, false);\n\t}",
"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 }",
"private void readContents(int maxFrames) {\n // Read GIF file content blocks.\n boolean done = false;\n while (!(done || err() || header.frameCount > maxFrames)) {\n int code = read();\n switch (code) {\n // Image separator.\n case 0x2C:\n // The graphics control extension is optional, but will always come first if it exists.\n // If one did\n // exist, there will be a non-null current frame which we should use. However if one\n // did not exist,\n // the current frame will be null and we must create it here. See issue #134.\n if (header.currentFrame == null) {\n header.currentFrame = new GifFrame();\n }\n readBitmap();\n break;\n // Extension.\n case 0x21:\n code = read();\n switch (code) {\n // Graphics control extension.\n case 0xf9:\n // Start a new frame.\n header.currentFrame = new GifFrame();\n readGraphicControlExt();\n break;\n // Application extension.\n case 0xff:\n readBlock();\n String app = \"\";\n for (int i = 0; i < 11; i++) {\n app += (char) block[i];\n }\n if (app.equals(\"NETSCAPE2.0\")) {\n readNetscapeExt();\n } else {\n // Don't care.\n skip();\n }\n break;\n // Comment extension.\n case 0xfe:\n skip();\n break;\n // Plain text extension.\n case 0x01:\n skip();\n break;\n // Uninteresting extension.\n default:\n skip();\n }\n break;\n // Terminator.\n case 0x3b:\n done = true;\n break;\n // Bad byte, but keep going and see what happens break;\n case 0x00:\n default:\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n }\n }",
"@Override\n public final Double optDouble(final String key, final Double defaultValue) {\n Double result = optDouble(key);\n return result == null ? defaultValue : result;\n }"
] |
The main method. See the class documentation. | [
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CRFClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFClassifier<CoreLabel> crf = new CRFClassifier<CoreLabel>(props);\r\n String testFile = crf.flags.testFile;\r\n String textFile = crf.flags.textFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n String loadTextPath = crf.flags.loadTextClassifier;\r\n String serializeTo = crf.flags.serializeTo;\r\n String serializeToText = crf.flags.serializeToText;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (loadTextPath != null) {\r\n System.err.println(\"Warning: this is now only tested for Chinese Segmenter\");\r\n System.err.println(\"(Sun Dec 23 00:59:39 2007) (pichuan)\");\r\n try {\r\n crf.loadTextClassifier(loadTextPath, props);\r\n // System.err.println(\"DEBUG: out from crf.loadTextClassifier\");\r\n } catch (Exception e) {\r\n throw new RuntimeException(\"error loading \" + loadTextPath, e);\r\n }\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else if (crf.flags.trainFile != null || crf.flags.trainFileList != null) {\r\n crf.train();\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n\r\n // System.err.println(\"Using \" + crf.flags.featureFactory);\r\n // System.err.println(\"Using \" +\r\n // StringUtils.getShortClassName(crf.readerAndWriter));\r\n\r\n if (serializeTo != null) {\r\n crf.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (serializeToText != null) {\r\n crf.serializeTextClassifier(serializeToText);\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter<CoreLabel> readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.searchGraphPrefix != null) {\r\n crf.classifyAndWriteViterbiSearchGraph(testFile, crf.flags.searchGraphPrefix, crf.makeReaderAndWriter());\r\n } else if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else if (crf.flags.printLabelValue) {\r\n crf.printLabelInformation(testFile, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n\r\n if (textFile != null) {\r\n crf.classifyAndWriteAnswers(textFile);\r\n }\r\n\r\n if (crf.flags.readStdin) {\r\n crf.classifyStdin();\r\n }\r\n }"
] | [
"private InputStream prepareInputStream(InputStream stream) throws IOException\n {\n InputStream result;\n BufferedInputStream bis = new BufferedInputStream(stream);\n readHeaderProperties(bis);\n if (isCompressed())\n {\n result = new InflaterInputStream(bis);\n }\n else\n {\n result = bis;\n }\n return result;\n }",
"public static <T> List<T> toList(Iterable<T> items) {\r\n List<T> list = new ArrayList<T>();\r\n addAll(list, items);\r\n return list;\r\n }",
"public float get(int row, int col) {\n if (row < 0 || row > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + row + \", Size: 4\");\n }\n if (col < 0 || col > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + col + \", Size: 4\");\n }\n\n return m_data[row * 4 + col];\n }",
"public static int findLastIndexOf(Object self, int startIndex, Closure closure) {\n int result = -1;\n int i = 0;\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {\n Object value = iter.next();\n if (i < startIndex) {\n continue;\n }\n if (bcw.call(value)) {\n result = i;\n }\n }\n return result;\n }",
"private Query getReportQueryByCriteriaCount(ReportQueryByCriteria aQuery)\r\n {\r\n ReportQueryByCriteria countQuery = (ReportQueryByCriteria) getQueryByCriteriaCount(aQuery);\r\n\r\n // BRJ: keep the original columns to build the Join\r\n countQuery.setJoinAttributes(aQuery.getAttributes());\r\n\r\n // BRJ: we have to preserve groupby information\r\n Iterator iter = aQuery.getGroupBy().iterator();\r\n while(iter.hasNext())\r\n {\r\n countQuery.addGroupBy((FieldHelper) iter.next());\r\n }\r\n\r\n return countQuery;\r\n }",
"public static void resize(GVRMesh mesh, float xsize, float ysize, float zsize) {\n float dim[] = getBoundingSize(mesh);\n\n scale(mesh, xsize / dim[0], ysize / dim[1], zsize / dim[2]);\n }",
"public List<Integer> getPathOrder(int profileId) {\n ArrayList<Integer> pathOrder = new ArrayList<Integer>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \"\n + Constants.DB_TABLE_PATH + \" WHERE \"\n + Constants.GENERIC_PROFILE_ID + \" = ? \"\n + \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\"\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n pathOrder.add(results.getInt(Constants.GENERIC_ID));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n logger.info(\"pathOrder = {}\", pathOrder);\n return pathOrder;\n }",
"private String FCMGetFreshToken(final String senderID) {\n String token = null;\n try {\n if(senderID != null){\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token with Sender Id - \"+senderID);\n token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);\n }else {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token\");\n token = FirebaseInstanceId.getInstance().getToken();\n }\n getConfigLogger().info(getAccountId(),\"FCM token: \"+token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Error requesting FCM token\", t);\n }\n return token;\n }",
"public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }"
] |
Enforces the correct srid on incoming features.
@param feature
object to enforce srid on
@throws LayerException
problem getting or setting srid | [
"private void enforceSrid(Object feature) throws LayerException {\n\t\tGeometry geom = getFeatureModel().getGeometry(feature);\n\t\tif (null != geom) {\n\t\t\tgeom.setSRID(srid);\n\t\t\tgetFeatureModel().setGeometry(feature, geom);\n\t\t}\n\t}"
] | [
"@Override\r\n\tpublic String toHexString(boolean with0xPrefix) { \r\n\t\tString result;\r\n\t\tif(hasNoStringCache() || (result = (with0xPrefix ? stringCache.hexStringPrefixed : stringCache.hexString)) == null) {\r\n\t\t\tresult = toHexString(with0xPrefix, null);\r\n\t\t\tif(with0xPrefix) {\r\n\t\t\t\tstringCache.hexStringPrefixed = result;\r\n\t\t\t} else {\r\n\t\t\t\tstringCache.hexString = result;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\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}",
"private void setPlaybackPosition(long milliseconds) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.position != milliseconds) {\n setPlaybackState(oldState.player, milliseconds, oldState.playing);\n }\n }",
"@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"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}",
"public static String asTime(long time) {\n if (time > HOUR) {\n return String.format(\"%.1f h\", (time / HOUR));\n } else if (time > MINUTE) {\n return String.format(\"%.1f m\", (time / MINUTE));\n } else if (time > SECOND) {\n return String.format(\"%.1f s\", (time / SECOND));\n } else {\n return String.format(\"%d ms\", time);\n }\n }",
"public static Set<Annotation> filterInterceptorBindings(BeanManagerImpl beanManager, Collection<Annotation> annotations) {\n Set<Annotation> interceptorBindings = new InterceptorBindingSet(beanManager);\n for (Annotation annotation : annotations) {\n if (beanManager.isInterceptorBinding(annotation.annotationType())) {\n interceptorBindings.add(annotation);\n }\n }\n return interceptorBindings;\n }",
"public List<Object> stepsInstances(List<CandidateSteps> candidateSteps) {\n List<Object> instances = new ArrayList<>();\n for (CandidateSteps steps : candidateSteps) {\n if (steps instanceof Steps) {\n instances.add(((Steps) steps).instance());\n }\n }\n return instances;\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 }"
] |
Notifies that multiple content items are removed.
@param positionStart the position.
@param itemCount the item count. | [
"public final void notifyContentItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount, itemCount);\n }"
] | [
"protected void checkObserverMethods() {\n Collection<EnhancedAnnotatedMethod<?, ? super T>> observerMethods = BeanMethods.getObserverMethods(this.getEnhancedAnnotated());\n Collection<EnhancedAnnotatedMethod<?, ? super T>> asyncObserverMethods = BeanMethods.getAsyncObserverMethods(this.getEnhancedAnnotated());\n checkObserverMethods(observerMethods);\n checkObserverMethods(asyncObserverMethods);\n }",
"public void add(int ds, Object value) throws SerializationException, InvalidDataSetException {\r\n\t\tif (value == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDataSetInfo dsi = dsiFactory.create(ds);\r\n\t\tbyte[] data = dsi.getSerializer().serialize(value, activeSerializationContext);\r\n\t\tDataSet dataSet = new DefaultDataSet(dsi, data);\r\n\t\tdataSets.add(dataSet);\r\n\t}",
"public 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 load(LoadConfiguration config, String prefix) {\n\t\tif (config.getMode() == Mode.INSERT) {\n\t\t\treturn loadInsert(config, prefix);\n\t\t}\n\t\telse if (config.getMode() == Mode.UPDATE) {\n\t\t\treturn loadUpdate(config, prefix);\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unsupported mode \" + config.getMode());\n\t}",
"synchronized void setServerProcessStopping() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(null, InternalState.STOPPED, InternalState.PROCESS_STOPPING);\n }",
"public static double KullbackLeiblerDivergence(double[] p, double[] q) {\n boolean intersection = false;\n double k = 0;\n\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n intersection = true;\n k += p[i] * Math.log(p[i] / q[i]);\n }\n }\n\n if (intersection)\n return k;\n else\n return Double.POSITIVE_INFINITY;\n }",
"public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }",
"private CmsFavoriteEntry getEntry(Component row) {\n\n if (row instanceof CmsFavInfo) {\n\n return ((CmsFavInfo)row).getEntry();\n\n }\n return null;\n\n }",
"private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }"
] |
Use this API to disable Interface of given name. | [
"public static base_response disable(nitro_service client, String id) throws Exception {\n\t\tInterface disableresource = new Interface();\n\t\tdisableresource.id = id;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}"
] | [
"@Override\n public final synchronized void stopService(long millis) {\n running = false;\n try {\n if (keepRunning) {\n keepRunning = false;\n interrupt();\n quit();\n if (0L == millis) {\n join();\n } else {\n join(millis);\n }\n }\n } catch (InterruptedException e) {\n //its possible that the thread exits between the lines keepRunning=false and interrupt above\n log.warn(\"Got interrupted while stopping {}\", this, e);\n\n Thread.currentThread().interrupt();\n }\n }",
"public String checkIn(byte[] data) {\n String id = UUID.randomUUID().toString();\n dataMap.put(id, data);\n return id;\n }",
"public static boolean isRevisionDumpFile(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.REVISION_DUMP.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.REVISION_DUMP.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}",
"private InputValue getInputValue(FormInput input) {\n\n\t\t/* Get the DOM element from Selenium. */\n\t\tWebElement inputElement = browser.getWebElement(input.getIdentification());\n\n\t\tswitch (input.getType()) {\n\t\t\tcase TEXT:\n\t\t\tcase PASSWORD:\n\t\t\tcase HIDDEN:\n\t\t\tcase SELECT:\n\t\t\tcase TEXTAREA:\n\t\t\t\treturn new InputValue(inputElement.getAttribute(\"value\"));\n\t\t\tcase RADIO:\n\t\t\tcase CHECKBOX:\n\t\t\tdefault:\n\t\t\t\tString value = inputElement.getAttribute(\"value\");\n\t\t\t\tBoolean checked = inputElement.isSelected();\n\t\t\t\treturn new InputValue(value, checked);\n\t\t}\n\n\t}",
"public static base_response change(nitro_service client, appfwsignatures resource) throws Exception {\n\t\tappfwsignatures updateresource = new appfwsignatures();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.mergedefault = resource.mergedefault;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}",
"private void readRelationships()\n {\n for (MapRow row : m_tables.get(\"REL\"))\n {\n Task predecessor = m_activityMap.get(row.getString(\"PREDECESSOR_ACTIVITY_ID\"));\n Task successor = m_activityMap.get(row.getString(\"SUCCESSOR_ACTIVITY_ID\"));\n if (predecessor != null && successor != null)\n {\n Duration lag = row.getDuration(\"LAG_VALUE\");\n RelationType type = row.getRelationType(\"LAG_TYPE\");\n\n successor.addPredecessor(predecessor, type, lag);\n }\n }\n }",
"public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,\n final int greedyAttempts,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<Integer> greedySwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(greedySwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(greedySwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n for(int i = 0; i < greedyAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,\n nodeIds,\n greedySwapMaxPartitionsPerNode,\n greedySwapMaxPartitionsPerZone,\n storeDefs);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (swap attempt \" + i + \" in zone \"\n + zoneIds.get(zoneIdOffset) + \")\");\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n return returnCluster;\n }",
"public void initialize() throws SQLException {\n\t\tif (initialized) {\n\t\t\t// just skip it if already initialized\n\t\t\treturn;\n\t\t}\n\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalStateException(\"connectionSource was never set on \" + getClass().getSimpleName());\n\t\t}\n\n\t\tdatabaseType = connectionSource.getDatabaseType();\n\t\tif (databaseType == null) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"connectionSource is getting a null DatabaseType in \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableConfig == null) {\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, dataClass);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t}\n\t\tstatementExecutor = new StatementExecutor<T, ID>(databaseType, tableInfo, this);\n\n\t\t/*\n\t\t * This is a bit complex. Initially, when we were configuring the field types, external DAO information would be\n\t\t * configured for auto-refresh, foreign BaseDaoEnabled classes, and foreign-collections. This would cause the\n\t\t * system to go recursive and for class loops, a stack overflow.\n\t\t * \n\t\t * Then we fixed this by putting a level counter in the FieldType constructor that would stop the configurations\n\t\t * when we reach some recursion level. But this created some bad problems because we were using the DaoManager\n\t\t * to cache the created DAOs that had been constructed already limited by the level.\n\t\t * \n\t\t * What we do now is have a 2 phase initialization. The constructor initializes most of the fields but then we\n\t\t * go back and call FieldType.configDaoInformation() after we are done. So for every DAO that is initialized\n\t\t * here, we have to see if it is the top DAO. If not we save it for dao configuration later.\n\t\t */\n\t\tList<BaseDaoImpl<?, ?>> daoConfigList = daoConfigLevelLocal.get();\n\t\tdaoConfigList.add(this);\n\t\tif (daoConfigList.size() > 1) {\n\t\t\t// if we have recursed then just save the dao for later configuration\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t/*\n\t\t\t * WARNING: We do _not_ use an iterator here because we may be adding to the list as we process it and we'll\n\t\t\t * get exceptions otherwise. This is an ArrayList so the get(i) should be efficient.\n\t\t\t * \n\t\t\t * Also, do _not_ get a copy of daoConfigLevel.doArray because that array may be replaced by another, larger\n\t\t\t * one during the recursion.\n\t\t\t */\n\t\t\tfor (int i = 0; i < daoConfigList.size(); i++) {\n\t\t\t\tBaseDaoImpl<?, ?> dao = daoConfigList.get(i);\n\n\t\t\t\t/*\n\t\t\t\t * Here's another complex bit. The first DAO that is being constructed as part of a DAO chain is not yet\n\t\t\t\t * in the DaoManager cache. If we continue onward we might come back around and try to configure this\n\t\t\t\t * DAO again. Forcing it into the cache here makes sure it won't be configured twice. This will cause it\n\t\t\t\t * to be stuck in twice when it returns out to the DaoManager but that's a small price to pay. This also\n\t\t\t\t * applies to self-referencing classes.\n\t\t\t\t */\n\t\t\t\tDaoManager.registerDao(connectionSource, dao);\n\n\t\t\t\ttry {\n\t\t\t\t\t// config our fields which may go recursive\n\t\t\t\t\tfor (FieldType fieldType : dao.getTableInfo().getFieldTypes()) {\n\t\t\t\t\t\tfieldType.configDaoInformation(connectionSource, dao.getDataClass());\n\t\t\t\t\t}\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t// unregister the DAO we just pre-registered\n\t\t\t\t\tDaoManager.unregisterDao(connectionSource, dao);\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\n\t\t\t\t// it's now been fully initialized\n\t\t\t\tdao.initialized = true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// if we throw we want to clear our class hierarchy here\n\t\t\tdaoConfigList.clear();\n\t\t\tdaoConfigLevelLocal.remove();\n\t\t}\n\t}",
"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 }"
] |
Recursively read a task, and any sub tasks.
@param mpxjParent Parent for the MPXJ tasks
@param gpTask GanttProject task | [
"private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n Task mpxjTask = mpxjParent.addTask();\n mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n mpxjTask.setName(gpTask.getName());\n mpxjTask.setPercentageComplete(gpTask.getComplete());\n mpxjTask.setPriority(getPriority(gpTask.getPriority()));\n mpxjTask.setHyperlink(gpTask.getWebLink());\n\n Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS);\n mpxjTask.setDuration(duration);\n\n if (duration.getDuration() == 0)\n {\n mpxjTask.setMilestone(true);\n }\n else\n {\n mpxjTask.setStart(gpTask.getStart());\n mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false));\n }\n\n mpxjTask.setConstraintDate(gpTask.getThirdDate());\n if (mpxjTask.getConstraintDate() != null)\n {\n // TODO: you don't appear to be able to change this setting in GanttProject\n // task.getThirdDateConstraint()\n mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN);\n }\n\n readTaskCustomFields(gpTask, mpxjTask);\n\n m_eventManager.fireTaskReadEvent(mpxjTask);\n\n // TODO: read custom values\n\n //\n // Process child tasks\n //\n for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask())\n {\n readTask(mpxjTask, childTask);\n }\n }"
] | [
"public static ComplexNumber Sin(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.sin(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n result.real = Math.sin(z1.real) * Math.cosh(z1.imaginary);\r\n result.imaginary = Math.cos(z1.real) * Math.sinh(z1.imaginary);\r\n }\r\n\r\n return result;\r\n }",
"public static cacheselector get(nitro_service service, String selectorname) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tcacheselector response = (cacheselector) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public T removeBundle(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createBundleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }",
"public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }",
"public String get(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return args.iterator().hasNext() ? args.iterator().next().getValue() : null;\n }\n return null;\n }",
"public static String plus(Number value, String right) {\n return DefaultGroovyMethods.toString(value) + right;\n }",
"private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) {\n\t\tif (logger.isTraceEnabled()) {\n\t\t\tlogger.trace(String.format(\"%s received %s\", ctx.channel(), frame.text()));\n\t\t}\n\n\t\taddTraceForFrame(frame, \"text\");\n\t\tctx.channel().write(new TextWebSocketFrame(\"Echo: \" + frame.text()));\n\t}",
"public static String make512Safe(StringBuffer input, String newline) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString content = input.toString();\n\t\tString rest = content;\n\t\twhile (!rest.isEmpty()) {\n\t\t\tif (rest.contains(\"\\n\")) {\n\t\t\t\tString line = rest.substring(0, rest.indexOf(\"\\n\"));\n\t\t\t\trest = rest.substring(rest.indexOf(\"\\n\") + 1);\n\t\t\t\tif (line.length() > 1 && line.charAt(line.length() - 1) == '\\r')\n\t\t\t\t\tline = line.substring(0, line.length() - 1);\n\t\t\t\tappend512Safe(line, result, newline);\n\t\t\t} else {\n\t\t\t\tappend512Safe(rest, result, newline);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result.toString();\n\t}",
"public static filterhtmlinjectionparameter get(nitro_service service, options option) throws Exception{\n\t\tfilterhtmlinjectionparameter obj = new filterhtmlinjectionparameter();\n\t\tfilterhtmlinjectionparameter[] response = (filterhtmlinjectionparameter[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}"
] |
Wait and retry. | [
"public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }"
] | [
"public 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 final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }",
"public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {\n URI uri = request.getURI();\n\n try {\n LOG.fine(\"CONNECT: \" + uri);\n InetAddrPort addrPort;\n // When logging, we'll attempt to send messages to hosts that don't exist\n if (uri.toString().endsWith(\".selenium.doesnotexist:443\")) {\n // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)\n addrPort = new InetAddrPort(443);\n } else {\n addrPort = new InetAddrPort(uri.toString());\n }\n\n if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {\n sendForbid(request, response, uri);\n } else {\n HttpConnection http_connection = request.getHttpConnection();\n http_connection.forceClose();\n\n HttpServer server = http_connection.getHttpServer();\n\n SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server);\n\n int port = listener.getPort();\n\n // Get the timeout\n int timeoutMs = 30000;\n Object maybesocket = http_connection.getConnection();\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n timeoutMs = s.getSoTimeout();\n }\n\n // Create the tunnel\n HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs);\n\n if (tunnel != null) {\n // TODO - need to setup semi-busy loop for IE.\n if (_tunnelTimeoutMs > 0) {\n tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n s.setSoTimeout(_tunnelTimeoutMs);\n }\n }\n tunnel.setTimeoutMs(timeoutMs);\n\n customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());\n request.getHttpConnection().setHttpTunnel(tunnel);\n response.setStatus(HttpResponse.__200_OK);\n response.setContentLength(0);\n }\n request.setHandled(true);\n }\n } catch (Exception e) {\n LOG.fine(\"error during handleConnect\", e);\n response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());\n }\n }",
"private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}",
"public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {\r\n\r\n return ensureHandlers().addHandlerToSource(type, this, handler);\r\n }",
"public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }"
] |
Add a range to an exception, ensure that we don't try to add null ranges.
@param exception target exception
@param start exception start
@param finish exception finish | [
"private void addExceptionRange(ProjectCalendarException exception, Date start, Date finish)\n {\n if (start != null && finish != null)\n {\n exception.addRange(new DateRange(start, finish));\n }\n }"
] | [
"private void writeFinalResults() {\n\t\t// Print a final report:\n\t\tprintStatus();\n\n\t\t// Store property counts in files:\n\t\twritePropertyStatisticsToFile(this.itemStatistics,\n\t\t\t\t\"item-property-counts.csv\");\n\t\twritePropertyStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-property-counts.csv\");\n\n\t\t// Store site link statistics in file:\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"site-link-counts.csv\"))) {\n\n\t\t\tout.println(\"Site key,Site links\");\n\t\t\tfor (Entry<String, Integer> entry : this.siteLinkStatistics\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t// Store term statistics in file:\n\t\twriteTermStatisticsToFile(this.itemStatistics, \"item-term-counts.csv\");\n\t\twriteTermStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-term-counts.csv\");\n\t}",
"public int addCollidable(GVRSceneObject sceneObj)\n {\n synchronized (mCollidables)\n {\n int index = mCollidables.indexOf(sceneObj);\n if (index >= 0)\n {\n return index;\n }\n mCollidables.add(sceneObj);\n return mCollidables.size() - 1;\n }\n }",
"public String read(int numBytes) throws IOException {\n Preconditions.checkArgument(numBytes >= 0);\n Preconditions.checkArgument(numBytes <= MAX_ALLOWABLE_BUFFER_SIZE);\n int numBytesRemaining = numBytes;\n // first read whatever we need from our buffer\n if (!isReadBufferEmpty()) {\n int length = Math.min(end - offset, numBytesRemaining);\n copyToStrBuffer(buffer, offset, length);\n offset += length;\n numBytesRemaining -= length;\n }\n\n // next read the remaining chars directly into our strBuffer\n if (numBytesRemaining > 0) {\n readAmountToStrBuffer(numBytesRemaining);\n }\n\n if (strBufferIndex > 0 && strBuffer[strBufferIndex - 1] != LF) {\n // the last byte doesn't correspond to lf\n return readLine(false);\n }\n\n int strBufferLength = strBufferIndex;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strBufferLength, charset);\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 static MetadataTemplate getMetadataTemplateByID(BoxAPIConnection api, String templateID) {\n\n URL url = METADATA_TEMPLATE_BY_ID_URL_TEMPLATE.build(api.getBaseURL(), templateID);\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new MetadataTemplate(response.getJSON());\n }",
"public void postDoNotUseArtifact(final String gavc, final Boolean doNotUse, 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.getDoNotUseArtifact(gavc));\n final ClientResponse response = resource.queryParam(ServerAPI.DO_NOT_USE, doNotUse.toString())\n .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to post do not use artifact\";\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 }",
"void backupConfiguration() throws IOException {\n\n final String configuration = Constants.CONFIGURATION;\n\n final File a = new File(installedImage.getAppClientDir(), configuration);\n final File d = new File(installedImage.getDomainDir(), configuration);\n final File s = new File(installedImage.getStandaloneDir(), configuration);\n\n if (a.exists()) {\n final File ab = new File(configBackup, Constants.APP_CLIENT);\n backupDirectory(a, ab);\n }\n if (d.exists()) {\n final File db = new File(configBackup, Constants.DOMAIN);\n backupDirectory(d, db);\n }\n if (s.exists()) {\n final File sb = new File(configBackup, Constants.STANDALONE);\n backupDirectory(s, sb);\n }\n\n }",
"public Info getInfo() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }",
"public void removeAt(int index) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.remove(index);\n } else {\n mObjects.remove(index);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }"
] |
An efficient method for exchanging data between two bit strings. Both bit strings must
be long enough that they contain the full length of the specified substring.
@param other The bitstring with which this bitstring should swap bits.
@param start The start position for the substrings to be exchanged. All bit
indices are big-endian, which means position 0 is the rightmost bit.
@param length The number of contiguous bits to swap. | [
"public void swapSubstring(BitString other, int start, int length)\n {\n assertValidIndex(start);\n other.assertValidIndex(start);\n \n int word = start / WORD_LENGTH;\n\n int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;\n if (partialWordSize > 0)\n {\n swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize));\n ++word;\n }\n\n int remainingBits = length - partialWordSize;\n int stop = remainingBits / WORD_LENGTH;\n for (int i = word; i < stop; i++)\n {\n int temp = data[i];\n data[i] = other.data[i];\n other.data[i] = temp;\n }\n\n remainingBits %= WORD_LENGTH;\n if (remainingBits > 0)\n {\n swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits));\n }\n }"
] | [
"public static <V> V doWorkInPoolNicely(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) {\n final V result;\n try {\n result = doWorkInPool(pool, work);\n } catch (RuntimeException re) {\n throw re;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return result;\n }",
"void backupConfiguration() throws IOException {\n\n final String configuration = Constants.CONFIGURATION;\n\n final File a = new File(installedImage.getAppClientDir(), configuration);\n final File d = new File(installedImage.getDomainDir(), configuration);\n final File s = new File(installedImage.getStandaloneDir(), configuration);\n\n if (a.exists()) {\n final File ab = new File(configBackup, Constants.APP_CLIENT);\n backupDirectory(a, ab);\n }\n if (d.exists()) {\n final File db = new File(configBackup, Constants.DOMAIN);\n backupDirectory(d, db);\n }\n if (s.exists()) {\n final File sb = new File(configBackup, Constants.STANDALONE);\n backupDirectory(s, sb);\n }\n\n }",
"static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }",
"public static Span prefix(Bytes rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n Bytes fp = followingPrefix(rowPrefix);\n return new Span(rowPrefix, true, fp == null ? Bytes.EMPTY : fp, false);\n }",
"public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }",
"private ProjectFile handleXerFile(InputStream stream) throws Exception\n {\n PrimaveraXERFileReader reader = new PrimaveraXERFileReader();\n reader.setCharset(m_charset);\n List<ProjectFile> projects = reader.readAll(stream);\n ProjectFile project = null;\n for (ProjectFile file : projects)\n {\n if (file.getProjectProperties().getExportFlag())\n {\n project = file;\n break;\n }\n }\n if (project == null && !projects.isEmpty())\n {\n project = projects.get(0);\n }\n return project;\n }",
"@POST\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response addCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an add 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 add!\");\n throw new WebApplicationException(Response.serverError().status(HttpStatus.BAD_REQUEST_400)\n .entity(\"CorporateGroupId to add should be in the query content.\").build());\n }\n\n getOrganizationHandler().addCorporateGroupId(organizationId, corporateGroupId);\n return Response.ok().status(HttpStatus.CREATED_201).build();\n }",
"Map<String, EntityDocument> getEntityDocumentMap(int numOfEntities,\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tif (numOfEntities == 0) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\t\tconfigureProperties(properties);\n\t\treturn this.wbGetEntitiesAction.wbGetEntities(properties);\n\t}",
"private void setHex() {\r\n\r\n String hRed = Integer.toHexString(getRed());\r\n String hGreen = Integer.toHexString(getGreen());\r\n String hBlue = Integer.toHexString(getBlue());\r\n\r\n if (hRed.length() == 0) {\r\n hRed = \"00\";\r\n }\r\n if (hRed.length() == 1) {\r\n hRed = \"0\" + hRed;\r\n }\r\n if (hGreen.length() == 0) {\r\n hGreen = \"00\";\r\n }\r\n if (hGreen.length() == 1) {\r\n hGreen = \"0\" + hGreen;\r\n }\r\n if (hBlue.length() == 0) {\r\n hBlue = \"00\";\r\n }\r\n if (hBlue.length() == 1) {\r\n hBlue = \"0\" + hBlue;\r\n }\r\n\r\n m_hex = hRed + hGreen + hBlue;\r\n }"
] |
Return the item view type used by the adapter to implement recycle mechanism.
@param content to be rendered.
@return an integer that represents the renderer inside the adapter. | [
"int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }"
] | [
"public EventsRequest<Event> get(String resource, String sync) {\n return new EventsRequest<Event>(this, Event.class, \"/events\", \"GET\")\n .query(\"resource\", resource)\n .query(\"sync\", sync);\n }",
"public void addExtraInfo(String key, Object value) {\n // Turn extraInfo into map\n Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo);\n // Add value\n infoMap.put(key, value);\n\n // Turn back into string\n extraInfo = getJSONFromMap(infoMap);\n }",
"private void deleteUnusedCaseSteps( ReportModel model ) {\n\n for( ScenarioModel scenarioModel : model.getScenarios() ) {\n if( scenarioModel.isCasesAsTable() && !hasAttachment( scenarioModel ) ) {\n List<ScenarioCaseModel> cases = scenarioModel.getScenarioCases();\n for( int i = 1; i < cases.size(); i++ ) {\n ScenarioCaseModel caseModel = cases.get( i );\n caseModel.setSteps( Collections.<StepModel>emptyList() );\n }\n }\n }\n }",
"protected Object getFieldData(Integer id, FieldType type, byte[][] fixedData, Var2Data varData)\n {\n Object result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.read(id, fixedData, varData);\n }\n\n return result;\n }",
"public ServerSocket createServerSocket() throws IOException {\n final ServerSocket socket = getServerSocketFactory().createServerSocket(name);\n socket.bind(getSocketAddress());\n return socket;\n }",
"public ChannelInfo getChannel(String name) {\n final URI uri = uriWithPath(\"./channels/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ChannelInfo.class);\n }",
"public static java.sql.Date toDate(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Date) {\n return (java.sql.Date) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Date(IN_DATE_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Date(IN_DATE_FORMAT.parse(value.toString()).getTime());\n }",
"public static boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }",
"@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }"
] |
Invokes the exit logger if and only if no ExitLogger was previously invoked.
@param logger the logger. Cannot be {@code null} | [
"public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }"
] | [
"public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);\n return new Processor(p);\n }",
"protected boolean setChannel(final Channel newChannel) {\n if(newChannel == null) {\n return false;\n }\n synchronized (lock) {\n if(state != State.OPEN || channel != null) {\n return false;\n }\n this.channel = newChannel;\n this.channel.addCloseHandler(new CloseHandler<Channel>() {\n @Override\n public void handleClose(final Channel closed, final IOException exception) {\n synchronized (lock) {\n if(FutureManagementChannel.this.channel == closed) {\n FutureManagementChannel.this.channel = null;\n }\n lock.notifyAll();\n }\n }\n });\n lock.notifyAll();\n return true;\n }\n }",
"public static WidgetLib init(GVRContext gvrContext, String customPropertiesAsset)\n throws InterruptedException, JSONException, NoSuchMethodException {\n if (mInstance == null) {\n // Constructor sets mInstance to ensure the initialization order\n new WidgetLib(gvrContext, customPropertiesAsset);\n }\n return mInstance.get();\n }",
"public static tmsessionparameter get(nitro_service service) throws Exception{\n\t\ttmsessionparameter obj = new tmsessionparameter();\n\t\ttmsessionparameter[] response = (tmsessionparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static ModelNode createLocalHostHostInfo(final LocalHostControllerInfo hostInfo, final ProductConfig productConfig,\n final IgnoredDomainResourceRegistry ignoredResourceRegistry, final Resource hostModelResource) {\n final ModelNode info = new ModelNode();\n info.get(NAME).set(hostInfo.getLocalHostName());\n info.get(RELEASE_VERSION).set(Version.AS_VERSION);\n info.get(RELEASE_CODENAME).set(Version.AS_RELEASE_CODENAME);\n info.get(MANAGEMENT_MAJOR_VERSION).set(Version.MANAGEMENT_MAJOR_VERSION);\n info.get(MANAGEMENT_MINOR_VERSION).set(Version.MANAGEMENT_MINOR_VERSION);\n info.get(MANAGEMENT_MICRO_VERSION).set(Version.MANAGEMENT_MICRO_VERSION);\n final String productName = productConfig.getProductName();\n final String productVersion = productConfig.getProductVersion();\n if(productName != null) {\n info.get(PRODUCT_NAME).set(productName);\n }\n if(productVersion != null) {\n info.get(PRODUCT_VERSION).set(productVersion);\n }\n ModelNode ignoredModel = ignoredResourceRegistry.getIgnoredResourcesAsModel();\n if (ignoredModel.hasDefined(IGNORED_RESOURCE_TYPE)) {\n info.get(IGNORED_RESOURCES).set(ignoredModel.require(IGNORED_RESOURCE_TYPE));\n }\n boolean ignoreUnaffectedServerGroups = hostInfo.isRemoteDomainControllerIgnoreUnaffectedConfiguration();\n IgnoredNonAffectedServerGroupsUtil.addCurrentServerGroupsToHostInfoModel(ignoreUnaffectedServerGroups, hostModelResource, info);\n return info;\n }",
"public static String[] randomResourceNames(String prefix, int maxLen, int count) {\n String[] names = new String[count];\n ResourceNamer resourceNamer = SdkContext.getResourceNamerFactory().createResourceNamer(\"\");\n for (int i = 0; i < count; i++) {\n names[i] = resourceNamer.randomName(prefix, maxLen);\n }\n return names;\n }",
"@Override public void write(ProjectFile projectFile, OutputStream out) throws IOException\n {\n m_projectFile = projectFile;\n m_eventManager = projectFile.getEventManager();\n\n m_writer = new PrintStream(out); // the print stream class is the easiest way to create a text file\n m_buffer = new StringBuilder();\n\n try\n {\n write(); // method call a method, this is how MPXJ is structured, so I followed the lead?\n }\n\n // catch (Exception e)\n // { // used during console debugging\n // System.out.println(\"Caught Exception in SDEFWriter.java\");\n // System.out.println(\" \" + e.toString());\n // }\n\n finally\n { // keeps things cool after we're done\n m_writer = null;\n m_projectFile = null;\n m_buffer = null;\n }\n }",
"public static String getOperationName(final ModelNode op) {\n if (op.hasDefined(OP)) {\n return op.get(OP).asString();\n }\n throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound();\n }",
"@Override\n public final int getInt(final String key) {\n Integer result = optInt(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }"
] |
Obtain the class of a given className
@param className
@return
@throws Exception | [
"private synchronized Class<?> getClass(String className) throws Exception {\n // see if we need to invalidate the class\n ClassInformation classInfo = classInformation.get(className);\n File classFile = new File(classInfo.pluginPath);\n if (classFile.lastModified() > classInfo.lastModified) {\n logger.info(\"Class {} has been modified, reloading\", className);\n logger.info(\"Thread ID: {}\", Thread.currentThread().getId());\n classInfo.loaded = false;\n classInformation.put(className, classInfo);\n\n // also cleanup anything in methodInformation with this className so it gets reloaded\n Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next();\n if (entry.getKey().startsWith(className)) {\n iter.remove();\n }\n }\n }\n\n if (!classInfo.loaded) {\n loadClass(className);\n }\n\n return classInfo.loadedClass;\n }"
] | [
"protected void threadWatch(final ConnectionHandle c) {\r\n\t\tthis.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) {\r\n\t\t\tpublic void finalizeReferent() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (!CachedConnectionStrategy.this.pool.poolShuttingDown){\r\n\t\t\t\t\t\t\tlogger.debug(\"Monitored thread is dead, closing off allocated connection.\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tc.internalClose();\r\n\t\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tCachedConnectionStrategy.this.threadFinalizableRefs.remove(c);\r\n\t\t\t}\r\n\t\t});\r\n\t}",
"public void recordResourceRequestTimeUs(SocketDestination dest, long resourceRequestTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n } else {\n this.resourceRequestTimeRequestCounter.addRequest(resourceRequestTimeUs\n * Time.NS_PER_US);\n }\n }",
"private TableAlias getTableAliasForPath(String aPath, String aUserAlias, List hintClasses)\r\n {\r\n if (aUserAlias == null)\r\n {\r\n return getTableAliasForPath(aPath, hintClasses);\r\n }\r\n else\r\n {\r\n\t\t\treturn getTableAliasForPath(aUserAlias + ALIAS_SEPARATOR + aPath, hintClasses);\r\n }\r\n }",
"public void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }",
"private Map<String, Object> getMapFromJSON(String json) {\n Map<String, Object> propMap = new HashMap<String, Object>();\n ObjectMapper mapper = new ObjectMapper();\n\n // Initialize string if empty\n if (json == null || json.length() == 0) {\n json = \"{}\";\n }\n\n try {\n // Convert string\n propMap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>(){});\n } catch (Exception e) {\n ;\n }\n return propMap;\n }",
"public static base_responses unset(nitro_service client, gslbservice resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice unsetresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new gslbservice();\n\t\t\t\tunsetresources[i].servicename = resources[i].servicename;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"@Nonnull\n\tpublic static InterfaceAnalysis analyze(@Nonnull final String code) {\n\t\tCheck.notNull(code, \"code\");\n\n\t\tfinal CompilationUnit unit = Check.notNull(SourceCodeReader.parse(code), \"compilationUnit\");\n\t\tfinal List<TypeDeclaration> types = Check.notEmpty(unit.getTypes(), \"typeDeclarations\");\n\t\tCheck.stateIsTrue(types.size() == 1, \"only one interface declaration per analysis is supported\");\n\n\t\tfinal ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) types.get(0);\n\n\t\tfinal Imports imports = SourceCodeReader.findImports(unit.getImports());\n\t\tfinal Package pkg = unit.getPackage() != null ? new Package(unit.getPackage().getName().toString()) : Package.UNDEFINED;\n\t\tfinal List<Annotation> annotations = SourceCodeReader.findAnnotations(type.getAnnotations(), imports);\n\t\tfinal List<Method> methods = SourceCodeReader.findMethods(type.getMembers(), imports);\n\t\tCheck.stateIsTrue(!hasPossibleMutatingMethods(methods), \"The passed interface '%s' seems to have mutating methods\", type.getName());\n\t\tfinal List<Interface> extendsInterfaces = SourceCodeReader.findExtends(type);\n\t\tfinal String interfaceName = type.getName();\n\t\treturn new ImmutableInterfaceAnalysis(annotations, extendsInterfaces, imports.asList(), interfaceName, methods, pkg);\n\t}",
"private InputStream tryPath(String path) {\r\n Logger.getLogger().debug(\"Trying path \\\"\" + path + \"\\\".\");\r\n return getClass().getResourceAsStream(path);\r\n }",
"public CollectionRequest<Team> users(String team) {\n \n String path = String.format(\"/teams/%s/users\", team);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }"
] |
Send Request Node info message to the controller.
@param nodeId the nodeId of the node to identify
@throws SerialInterfaceException when timing out or getting an invalid response. | [
"public void requestNodeInfo(int nodeId) {\n\t\tSerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.RequestNodeInfo, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationUpdate, SerialMessage.SerialMessagePriority.High);\n \tbyte[] newPayload = { (byte) nodeId };\n \tnewMessage.setMessagePayload(newPayload);\n \tthis.enqueue(newMessage);\n\t}"
] | [
"public static<Z> Function0<Z> lift(Callable<Z> f) {\n\treturn bridge.lift(f);\n }",
"public void addIn(Object attribute, Query subQuery)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }",
"public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action,\r\n RetentionPolicyParams optionalParams) {\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_name\", name)\r\n .add(\"policy_type\", type)\r\n .add(\"disposition_action\", action);\r\n if (!type.equals(TYPE_INDEFINITE)) {\r\n requestJSON.add(\"retention_length\", length);\r\n }\r\n if (optionalParams != null) {\r\n requestJSON.add(\"can_owner_extend_retention\", optionalParams.getCanOwnerExtendRetention());\r\n requestJSON.add(\"are_owners_notified\", optionalParams.getAreOwnersNotified());\r\n\r\n List<BoxUser.Info> customNotificationRecipients = optionalParams.getCustomNotificationRecipients();\r\n if (customNotificationRecipients.size() > 0) {\r\n JsonArray users = new JsonArray();\r\n for (BoxUser.Info user : customNotificationRecipients) {\r\n JsonObject userJSON = new JsonObject()\r\n .add(\"type\", \"user\")\r\n .add(\"id\", user.getID());\r\n users.add(userJSON);\r\n }\r\n requestJSON.add(\"custom_notification_recipients\", users);\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 BoxRetentionPolicy createdPolicy = new BoxRetentionPolicy(api, responseJSON.get(\"id\").asString());\r\n return createdPolicy.new Info(responseJSON);\r\n }",
"public AT_Row setPaddingBottom(int paddingBottom) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public boolean getEnterpriseFlag(int index)\n {\n return (BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(TaskFieldLists.ENTERPRISE_FLAG, index))));\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }",
"private Server setUpServer() {\n Server server = new Server(port);\n ResourceHandler handler = new ResourceHandler();\n handler.setDirectoriesListed(true);\n handler.setWelcomeFiles(new String[]{\"index.html\"});\n handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString());\n HandlerList handlers = new HandlerList();\n handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});\n server.setStopAtShutdown(true);\n server.setHandler(handlers);\n return server;\n }",
"public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }"
] |
Return the number of entries in the cue list that represent hot cues.
@return the number of cue list entries that are hot cues | [
"public int getHotCueCount() {\n if (rawMessage != null) {\n return (int) ((NumberField) rawMessage.arguments.get(5)).getValue();\n }\n int total = 0;\n for (Entry entry : entries) {\n if (entry.hotCueNumber > 0) {\n ++total;\n }\n }\n return total;\n }"
] | [
"@IntRange(from = 0, to = OPAQUE)\n private static int resolveLineAlpha(\n @IntRange(from = 0, to = OPAQUE) final int sceneAlpha,\n final float maxDistance,\n final float distance) {\n final float alphaPercent = 1f - distance / maxDistance;\n final int alpha = (int) ((float) OPAQUE * alphaPercent);\n return alpha * sceneAlpha / OPAQUE;\n }",
"public static boolean isValidFqcn(String str) {\n if (isNullOrEmpty(str)) {\n return false;\n }\n final String[] parts = str.split(\"\\\\.\");\n if (parts.length < 2) {\n return false;\n }\n for (String part : parts) {\n if (!isValidJavaIdentifier(part)) {\n return false;\n }\n }\n return true;\n }",
"public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\n }",
"public static server_service_binding[] get(nitro_service service, String name) throws Exception{\n\t\tserver_service_binding obj = new server_service_binding();\n\t\tobj.set_name(name);\n\t\tserver_service_binding response[] = (server_service_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@SuppressWarnings(\"unchecked\")\n\tpublic <S extends IPAddressPartConfiguredString<T, P>> SQLStringMatcher<T, P, S> getNetworkStringMatcher(boolean isEntireAddress, IPAddressSQLTranslator translator) {\n\t\treturn new SQLStringMatcher<T, P, S>((S) this, isEntireAddress, translator);\n\t}",
"public List<List<IN>> classify(String str) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, plainTextReaderAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }",
"private MBeanServer getServerForName(String name) {\n try {\n MBeanServer mbeanServer = null;\n final ObjectName objectNameQuery = new ObjectName(name + \":type=Service,*\");\n\n for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {\n if (server.queryNames(objectNameQuery, null).size() > 0) {\n mbeanServer = server;\n // we found it, bail out\n break;\n }\n }\n\n return mbeanServer;\n } catch (Exception e) {\n }\n\n return null;\n }",
"void writeNoValueRestriction(RdfWriter rdfWriter, String propertyUri,\n\t\t\tString rangeUri, String subject) throws RDFHandlerException {\n\n\t\tResource bnodeSome = rdfWriter.getFreshBNode();\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_CLASS);\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.OWL_COMPLEMENT_OF,\n\t\t\t\tbnodeSome);\n\t\trdfWriter.writeTripleValueObject(bnodeSome, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\trdfWriter.writeTripleUriObject(bnodeSome, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\trdfWriter.writeTripleUriObject(bnodeSome,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}",
"private static OkHttpClient getUnsafeOkHttpClient() {\n try {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] {\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }\n };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new java.security.SecureRandom());\n // Create an ssl socket factory with our all-trusting manager\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n\n OkHttpClient okHttpClient = new OkHttpClient();\n okHttpClient.setSslSocketFactory(sslSocketFactory);\n okHttpClient.setHostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n return okHttpClient;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] |
Translate a path that has previously been unescaped and unquoted.
That is called at command execution when the calue is retrieved prior to be
used as ModelNode value.
@param path The unquoted, unescaped path.
@return A path with ~ and default dir expanded. | [
"public String translatePath(String path) {\n String translated;\n // special character: ~ maps to the user's home directory\n if (path.startsWith(\"~\" + File.separator)) {\n translated = System.getProperty(\"user.home\") + path.substring(1);\n } else if (path.startsWith(\"~\")) {\n String userName = path.substring(1);\n translated = new File(new File(System.getProperty(\"user.home\")).getParent(),\n userName).getAbsolutePath();\n // Keep the path separator in translated or add one if no user home specified\n translated = userName.isEmpty() || path.endsWith(File.separator) ? translated + File.separator : translated;\n } else if (!new File(path).isAbsolute()) {\n translated = ctx.getCurrentDir().getAbsolutePath() + File.separator + path;\n } else {\n translated = path;\n }\n return translated;\n }"
] | [
"static PlexusConfiguration convert(ModelNode configuration, ModelNode jsonSchema, String extensionId, String id) {\n ConversionContext ctx = new ConversionContext();\n ctx.currentSchema = jsonSchema;\n ctx.rootSchema = jsonSchema;\n ctx.pushTag(extensionId);\n ctx.id = id;\n return convert(configuration, ctx);\n }",
"public int size(final K1 firstKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap.size();\n\t}",
"private static CharSequence convertReverseDNSIPv4(String str, int suffixStartIndex) throws AddressStringException {\n\t\tStringBuilder builder = new StringBuilder(suffixStartIndex);\n\t\tint segCount = 0;\n\t\tint j = suffixStartIndex;\n\t\tfor(int i = suffixStartIndex - 1; i > 0; i--) {\n\t\t\tchar c1 = str.charAt(i);\n\t\t\tif(c1 == IPv4Address.SEGMENT_SEPARATOR) {\n\t\t\t\tif(j - i <= 1) {\n\t\t\t\t\tthrow new AddressStringException(str, i);\n\t\t\t\t}\n\t\t\t\tfor(int k = i + 1; k < j; k++) {\n\t\t\t\t\tbuilder.append(str.charAt(k));\n\t\t\t\t}\n\t\t\t\tbuilder.append(c1);\n\t\t\t\tj = i;\n\t\t\t\tsegCount++;\n\t\t\t}\n\t\t}\n\t\tfor(int k = 0; k < j; k++) {\n\t\t\tbuilder.append(str.charAt(k));\n\t\t}\n\t\tif(segCount + 1 != IPv4Address.SEGMENT_COUNT) {\n\t\t\tthrow new AddressStringException(str, 0);\n\t\t}\n\t\treturn builder;\n\t}",
"public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }",
"@Override\n\tpublic Object executeJavaScript(String code) throws CrawljaxException {\n\t\ttry {\n\t\t\tJavascriptExecutor js = (JavascriptExecutor) browser;\n\t\t\treturn js.executeScript(code);\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t}",
"public ParallelTaskBuilder prepareSsh() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.SSH);\n return cb;\n }",
"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 PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }"
] |
private int numCalls = 0; | [
"protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }"
] | [
"private void prepareInitialState(boolean isNewObject)\r\n {\r\n // determine appropriate modification state\r\n ModificationState initialState;\r\n if(isNewObject)\r\n {\r\n // if object is not already persistent it must be marked as new\r\n // it must be marked as dirty because it must be stored even if it will not modified during tx\r\n initialState = StateNewDirty.getInstance();\r\n }\r\n else if(isDeleted(oid))\r\n {\r\n // if object is already persistent it will be marked as old.\r\n // it is marked as dirty as it has been deleted during tx and now it is inserted again,\r\n // possibly with new field values.\r\n initialState = StateOldDirty.getInstance();\r\n }\r\n else\r\n {\r\n // if object is already persistent it will be marked as old.\r\n // it is marked as clean as it has not been modified during tx already\r\n initialState = StateOldClean.getInstance();\r\n }\r\n // remember it:\r\n modificationState = initialState;\r\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 Pixel[] pixels() {\n Pixel[] pixels = new Pixel[count()];\n Point[] points = points();\n for (int k = 0; k < points.length; k++) {\n pixels[k] = pixel(points[k]);\n }\n return pixels;\n }",
"public static Iterable<Metadata> getAllMetadata(BoxItem item, String ... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new BoxResourceIterable<Metadata>(\n item.getAPI(),\n GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery(item.getItemURL().toString(), builder.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected Metadata factory(JsonObject jsonObject) {\n return new Metadata(jsonObject);\n }\n\n };\n }",
"public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }",
"public void updateConfig(String appName, Map<String, String> config) {\n connection.execute(new ConfigUpdate(appName, config), apiKey);\n }",
"private void setSiteFilters(String filters) {\n\t\tthis.filterSites = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterSites, filters.split(\",\"));\n\t\t}\n\t}",
"private void setRecordNumber(LinkedList<String> list)\n {\n try\n {\n String number = list.remove(0);\n m_recordNumber = Integer.valueOf(number);\n }\n catch (NumberFormatException ex)\n {\n // Malformed MPX file: the record number isn't a valid integer\n // Catch the exception here, leaving m_recordNumber as null\n // so we will skip this record entirely.\n }\n }",
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (variableName == null)\n {\n setVariableName(Iteration.getPayloadVariableName(event, context));\n }\n }"
] |
Populate a task from a Row instance.
@param row Row instance
@param task Task instance | [
"private void populateTask(Row row, Task task)\n {\n //\"PROJID\"\n task.setUniqueID(row.getInteger(\"TASKID\"));\n //GIVEN_DURATIONTYPF\n //GIVEN_DURATIONELA_MONTHS\n task.setDuration(row.getDuration(\"GIVEN_DURATIONHOURS\"));\n task.setResume(row.getDate(\"RESUME\"));\n //task.setStart(row.getDate(\"GIVEN_START\"));\n //LATEST_PROGRESS_PERIOD\n //TASK_WORK_RATE_TIME_UNIT\n //TASK_WORK_RATE\n //PLACEMENT\n //BEEN_SPLIT\n //INTERRUPTIBLE\n //HOLDING_PIN\n ///ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n task.setActualDuration(row.getDuration(\"ACTUAL_DURATIONHOURS\"));\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //task.setBaselineWork(row.getDuration(\"EFFORT_BUDGET\"));\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n task.setPercentageComplete(row.getDouble(\"OVERALL_PERCENV_COMPLETE\"));\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n task.setNotes(getNotes(row));\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //BAR\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n task.setStart(row.getDate(\"STARZ\"));\n task.setFinish(row.getDate(\"ENJ\"));\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n\n processConstraints(row, task);\n\n if (NumberHelper.getInt(task.getPercentageComplete()) != 0)\n {\n task.setActualStart(task.getStart());\n if (task.getPercentageComplete().intValue() == 100)\n {\n task.setActualFinish(task.getFinish());\n task.setDuration(task.getActualDuration());\n }\n }\n }"
] | [
"protected void copyClasspathResource(File outputDirectory,\n String resourceName,\n String targetFileName) throws IOException\n {\n String resourcePath = classpathPrefix + resourceName;\n InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);\n copyStream(outputDirectory, resourceStream, targetFileName);\n }",
"public static <V> Map<V, V> convertListToMap(List<V> list) {\n Map<V, V> map = new HashMap<V, V>();\n if(list.size() % 2 != 0)\n throw new VoldemortException(\"Failed to convert list to map.\");\n for(int i = 0; i < list.size(); i += 2) {\n map.put(list.get(i), list.get(i + 1));\n }\n return map;\n }",
"public SingleAssetEuropeanOptionProductDescriptor getDescriptor(LocalDate referenceDate, int index) throws ArrayIndexOutOfBoundsException{\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tif(index >= strikes.length) {\n\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Strike index out of bounds\");\n\t\t}else {\n\t\t\treturn new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[index]);\n\t\t}\n\t}",
"@Override\n public void perform(Rewrite event, EvaluationContext context)\n {\n perform((GraphRewrite) event, context);\n }",
"public Association getAssociation(String collectionRole) {\n\t\tif ( associations == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn associations.get( collectionRole );\n\t}",
"public Map<String, T> parseMap(JsonParser jsonParser) throws IOException {\n HashMap<String, T> map = new HashMap<String, T>();\n while (jsonParser.nextToken() != JsonToken.END_OBJECT) {\n String key = jsonParser.getText();\n jsonParser.nextToken();\n if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) {\n map.put(key, null);\n } else{\n map.put(key, parse(jsonParser));\n }\n }\n return map;\n }",
"private static long scanForLocSig(FileChannel channel) throws IOException {\n\n channel.position(0);\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long end = channel.size();\n while (channel.position() <= end) {\n\n read(bb, channel);\n\n int bufferPos = 0;\n while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the size of the pattern is static\n // b) the pattern is static and has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Outer switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid local file record\n long startLocRecord = channel.position() - bb.limit() + bufferPos;\n long currentPos = channel.position();\n if (validateLocalFileRecord(channel, startLocRecord, -1)) {\n return startLocRecord;\n }\n // Restore position in case it shifted\n channel.position(currentPos);\n\n // wasn't a valid local file 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 += LOC_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos += 4;\n }\n }\n }\n\n return -1;\n }",
"private void fillConnections(int connectionsToCreate) throws InterruptedException {\r\n\t\ttry {\r\n\t\t\tfor (int i=0; i < connectionsToCreate; i++){\r\n\t\t\t//\tboolean dbDown = this.pool.getDbIsDown().get();\r\n\t\t\t\tif (this.pool.poolShuttingDown){\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tthis.partition.addFreeConnection(new ConnectionHandle(null, this.partition, this.pool, false));\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlogger.error(\"Error in trying to obtain a connection. Retrying in \"+this.acquireRetryDelayInMs+\"ms\", e);\r\n\t\t\tThread.sleep(this.acquireRetryDelayInMs);\r\n\t\t}\r\n\r\n\t}",
"@Override\n public void process(TestCaseResult context) {\n context.getParameters().add(new Parameter()\n .withName(getName())\n .withValue(getValue())\n .withKind(ParameterKind.valueOf(getKind()))\n );\n }"
] |
Read a single field alias from an extended attribute.
@param attribute extended attribute | [
"private void readFieldAlias(Project.ExtendedAttributes.ExtendedAttribute attribute)\n {\n String alias = attribute.getAlias();\n if (alias != null && alias.length() != 0)\n {\n FieldType field = FieldTypeHelper.getInstance(Integer.parseInt(attribute.getFieldID()));\n m_projectFile.getCustomFields().getCustomField(field).setAlias(attribute.getAlias());\n }\n }"
] | [
"protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}",
"public static CmsGalleryTabConfiguration resolve(String configStr) {\r\n\r\n CmsGalleryTabConfiguration tabConfig;\r\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(configStr)) {\r\n configStr = \"*sitemap,types,galleries,categories,vfstree,search,results\";\r\n }\r\n if (DEFAULT_CONFIGURATIONS != null) {\r\n tabConfig = DEFAULT_CONFIGURATIONS.get(configStr);\r\n if (tabConfig != null) {\r\n return tabConfig;\r\n }\r\n\r\n }\r\n return parse(configStr);\r\n }",
"private void processCalendarHours(byte[] data, ProjectCalendar defaultCalendar, ProjectCalendar cal, boolean isBaseCalendar)\n {\n // Dump out the calendar related data and fields.\n //MPPUtility.dataDump(data, true, false, false, false, true, false, true);\n\n int offset;\n ProjectCalendarHours hours;\n int periodIndex;\n int index;\n int defaultFlag;\n int periodCount;\n Date start;\n long duration;\n Day day;\n List<DateRange> dateRanges = new ArrayList<DateRange>(5);\n\n for (index = 0; index < 7; index++)\n {\n offset = getCalendarHoursOffset() + (60 * index);\n defaultFlag = data == null ? 1 : MPPUtility.getShort(data, offset);\n day = Day.getInstance(index + 1);\n\n if (defaultFlag == 1)\n {\n if (isBaseCalendar)\n {\n if (defaultCalendar == null)\n {\n cal.setWorkingDay(day, DEFAULT_WORKING_WEEK[index]);\n if (cal.isWorkingDay(day))\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n else\n {\n boolean workingDay = defaultCalendar.isWorkingDay(day);\n cal.setWorkingDay(day, workingDay);\n if (workingDay)\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n for (DateRange range : defaultCalendar.getHours(day))\n {\n hours.addRange(range);\n }\n }\n }\n }\n else\n {\n cal.setWorkingDay(day, DayType.DEFAULT);\n }\n }\n else\n {\n dateRanges.clear();\n\n periodIndex = 0;\n periodCount = MPPUtility.getShort(data, offset + 2);\n while (periodIndex < periodCount)\n {\n int startOffset = offset + 8 + (periodIndex * 2);\n start = MPPUtility.getTime(data, startOffset);\n int durationOffset = offset + 20 + (periodIndex * 4);\n duration = MPPUtility.getDuration(data, durationOffset);\n Date end = new Date(start.getTime() + duration);\n dateRanges.add(new DateRange(start, end));\n ++periodIndex;\n }\n\n if (dateRanges.isEmpty())\n {\n cal.setWorkingDay(day, false);\n }\n else\n {\n cal.setWorkingDay(day, true);\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n\n for (DateRange range : dateRanges)\n {\n hours.addRange(range);\n }\n }\n }\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 Double getAvgEventValue() {\n resetIfNeeded();\n synchronized(this) {\n long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval;\n if(eventsLastInterval > 0)\n return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0)\n / eventsLastInterval;\n else\n return 0.0;\n }\n }",
"public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}",
"public static ProducerRequest readFrom(ByteBuffer buffer) {\n String topic = Utils.readShortString(buffer);\n int partition = buffer.getInt();\n int messageSetSize = buffer.getInt();\n ByteBuffer messageSetBuffer = buffer.slice();\n messageSetBuffer.limit(messageSetSize);\n buffer.position(buffer.position() + messageSetSize);\n return new ProducerRequest(topic, partition, new ByteBufferMessageSet(messageSetBuffer));\n }",
"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 }",
"public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) {\n d.negate();\n Quaternionf q = new Quaternionf();\n // check for exception condition\n if ((d.x == 0) && (d.z == 0)) {\n // exception condition if direction is (0,y,0):\n // straight up, straight down or all zero's.\n if (d.y > 0) { // direction straight up\n AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0,\n 0);\n q.set(angleAxis);\n } else if (d.y < 0) { // direction straight down\n AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0);\n q.set(angleAxis);\n } else { // All zero's. Just set to identity quaternion\n q.identity();\n }\n } else {\n d.normalize();\n Vector3f up = new Vector3f(0, 1, 0);\n Vector3f s = new Vector3f();\n d.cross(up, s);\n s.normalize();\n Vector3f u = new Vector3f();\n d.cross(s, u);\n u.normalize();\n Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x,\n d.y, d.z, 0, 0, 0, 0, 1);\n q.setFromNormalized(matrix);\n }\n return q;\n }"
] |
Check local saved copy first ??. If Auth by username is available, then we will not need to make the API call.
@throws FlickrException | [
"private void setNsid() throws FlickrException {\n\n if (username != null && !username.equals(\"\")) {\n Auth auth = null;\n if (authStore != null) {\n auth = authStore.retrieve(username); // assuming FileAuthStore is enhanced else need to\n // keep in user-level files.\n\n if (auth != null) {\n nsid = auth.getUser().getId();\n }\n }\n if (auth != null)\n return;\n\n Auth[] allAuths = authStore.retrieveAll();\n for (int i = 0; i < allAuths.length; i++) {\n if (username.equals(allAuths[i].getUser().getUsername())) {\n nsid = allAuths[i].getUser().getId();\n return;\n }\n }\n\n // For this to work: REST.java or PeopleInterface needs to change to pass apiKey\n // as the parameter to the call which is not authenticated.\n\n // Get nsid using flickr.people.findByUsername\n PeopleInterface peopleInterf = flickr.getPeopleInterface();\n User u = peopleInterf.findByUsername(username);\n if (u != null) {\n nsid = u.getId();\n }\n }\n }"
] | [
"public ProjectCalendarWeek getWorkWeek(Date date)\n {\n ProjectCalendarWeek week = null;\n if (!m_workWeeks.isEmpty())\n {\n sortWorkWeeks();\n\n int low = 0;\n int high = m_workWeeks.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarWeek midVal = m_workWeeks.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getDateRange().getStart(), midVal.getDateRange().getEnd(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n week = midVal;\n break;\n }\n }\n }\n }\n\n if (week == null && getParent() != null)\n {\n // Check base calendar as well for a work week.\n week = getParent().getWorkWeek(date);\n }\n return (week);\n }",
"public boolean equalId(Element otherElement) {\r\n\t\tif (getElementId() == null || otherElement.getElementId() == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn getElementId().equalsIgnoreCase(otherElement.getElementId());\r\n\t}",
"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 Set<RateType> getRateTypes() {\n @SuppressWarnings(\"unchecked\")\n Set<RateType> rateSet = get(KEY_RATE_TYPES, Set.class);\n if (rateSet == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(rateSet);\n }",
"public ByteBuffer[] toDirectByteBuffers(long offset, long size) {\n long pos = offset;\n long blockSize = Integer.MAX_VALUE;\n long limit = offset + size;\n int numBuffers = (int) ((size + (blockSize - 1)) / blockSize);\n ByteBuffer[] result = new ByteBuffer[numBuffers];\n int index = 0;\n while (pos < limit) {\n long blockLength = Math.min(limit - pos, blockSize);\n result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this)\n .order(ByteOrder.nativeOrder());\n pos += blockLength;\n }\n return result;\n\n }",
"public static void dumpRow(Map<String, Object> row)\n {\n for (Entry<String, Object> entry : row.entrySet())\n {\n Object value = entry.getValue();\n System.out.println(entry.getKey() + \" = \" + value + \" ( \" + (value == null ? \"\" : value.getClass().getName()) + \")\");\n }\n }",
"public String toIPTC(SubjectReferenceSystem srs) {\r\n\t\tStringBuffer b = new StringBuffer();\r\n\t\tb.append(\"IPTC:\");\r\n\t\tb.append(getNumber());\r\n\t\tb.append(\":\");\r\n\t\tif (getNumber().endsWith(\"000000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\"::\");\r\n\t\t} else if (getNumber().endsWith(\"000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\":\");\r\n\t\t} else {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 5) + \"000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t}\r\n\t\treturn b.toString();\r\n\t}",
"public static void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }",
"private ResourceField selectField(ResourceField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }"
] |
This method writes assignment data to a Planner file. | [
"private void writeAssignments()\n {\n Allocations allocations = m_factory.createAllocations();\n m_plannerProject.setAllocations(allocations);\n\n List<Allocation> allocationList = allocations.getAllocation();\n for (ResourceAssignment mpxjAssignment : m_projectFile.getResourceAssignments())\n {\n Allocation plannerAllocation = m_factory.createAllocation();\n allocationList.add(plannerAllocation);\n\n plannerAllocation.setTaskId(getIntegerString(mpxjAssignment.getTask().getUniqueID()));\n plannerAllocation.setResourceId(getIntegerString(mpxjAssignment.getResourceUniqueID()));\n plannerAllocation.setUnits(getIntegerString(mpxjAssignment.getUnits()));\n\n m_eventManager.fireAssignmentWrittenEvent(mpxjAssignment);\n }\n }"
] | [
"public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }",
"public static int NextPowerOf2(int x) {\r\n --x;\r\n x |= x >> 1;\r\n x |= x >> 2;\r\n x |= x >> 4;\r\n x |= x >> 8;\r\n x |= x >> 16;\r\n return ++x;\r\n }",
"public static base_response update(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy updateresource = new transformpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.logaction = resource.logaction;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static int[] Unique(int[] values) {\r\n HashSet<Integer> lst = new HashSet<Integer>();\r\n for (int i = 0; i < values.length; i++) {\r\n lst.add(values[i]);\r\n }\r\n\r\n int[] v = new int[lst.size()];\r\n Iterator<Integer> it = lst.iterator();\r\n for (int i = 0; i < v.length; i++) {\r\n v[i] = it.next();\r\n }\r\n\r\n return v;\r\n }",
"public <OD> Where<T, ID> idEq(Dao<OD, ?> dataDao, OD data) throws SQLException {\n\t\tif (idColumnName == null) {\n\t\t\tthrow new SQLException(\"Object has no id column specified\");\n\t\t}\n\t\taddClause(new SimpleComparison(idColumnName, idFieldType, dataDao.extractId(data),\n\t\t\t\tSimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"public final ZoomToFeatures copy() {\n ZoomToFeatures obj = new ZoomToFeatures();\n obj.zoomType = this.zoomType;\n obj.minScale = this.minScale;\n obj.minMargin = this.minMargin;\n return obj;\n }",
"private void init_jdbcTypes() throws SQLException\r\n {\r\n ReportQuery q = (ReportQuery) getQueryObject().getQuery();\r\n m_jdbcTypes = new int[m_attributeCount];\r\n \r\n // try to get jdbcTypes from Query\r\n if (q.getJdbcTypes() != null)\r\n {\r\n m_jdbcTypes = q.getJdbcTypes();\r\n }\r\n else\r\n {\r\n ResultSetMetaData rsMetaData = getRsAndStmt().m_rs.getMetaData();\r\n for (int i = 0; i < m_attributeCount; i++)\r\n {\r\n m_jdbcTypes[i] = rsMetaData.getColumnType(i + 1);\r\n }\r\n \r\n }\r\n }",
"public synchronized ControlPoint getControlPoint(final String deploymentName, final String entryPointName) {\n ControlPointIdentifier id = new ControlPointIdentifier(deploymentName, entryPointName);\n ControlPoint ep = entryPoints.get(id);\n if (ep == null) {\n ep = new ControlPoint(this, deploymentName, entryPointName, trackIndividualControlPoints);\n entryPoints.put(id, ep);\n }\n ep.increaseReferenceCount();\n return ep;\n }",
"public PhotoContext getContext(String photoId, String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else {\r\n if (logger.isInfoEnabled()) {\r\n logger.info(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n }\r\n return photoContext;\r\n }"
] |
Returns a JRDesignExpression that points to the main report connection
@return | [
"public static JRDesignExpression getReportConnectionExpression() {\n JRDesignExpression connectionExpression = new JRDesignExpression();\n connectionExpression.setText(\"$P{\" + JRDesignParameter.REPORT_CONNECTION + \"}\");\n connectionExpression.setValueClass(Connection.class);\n return connectionExpression;\n }"
] | [
"public String calculateCacheKey(String sql, int autoGeneratedKeys) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\ttmp.append(autoGeneratedKeys);\r\n\t\treturn tmp.toString();\r\n\t}",
"public void get( int row , int col , Complex_F64 output ) {\n ops.get(mat,row,col,output);\n }",
"private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }",
"final public void addPosition(int position) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(position);\n } else {\n tokenPosition.add(position);\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public static <T> void defaultHandleContextMenuForMultiselect(\n Table table,\n CmsContextMenu menu,\n ItemClickEvent event,\n List<I_CmsSimpleContextMenuEntry<Collection<T>>> entries) {\n\n if (!event.isCtrlKey() && !event.isShiftKey()) {\n if (event.getButton().equals(MouseButton.RIGHT)) {\n Collection<T> oldValue = ((Collection<T>)table.getValue());\n if (oldValue.isEmpty() || !oldValue.contains(event.getItemId())) {\n table.setValue(new HashSet<Object>(Arrays.asList(event.getItemId())));\n }\n Collection<T> selection = (Collection<T>)table.getValue();\n menu.setEntries(entries, selection);\n menu.openForTable(event, table);\n }\n }\n\n }",
"public StatementGroup findStatementGroup(String propertyIdValue) {\n\t\tif (this.claims.containsKey(propertyIdValue)) {\n\t\t\treturn new StatementGroupImpl(this.claims.get(propertyIdValue));\n\t\t}\n\t\treturn null;\n\t}",
"public void setVelocityRange( final Vector3f minV, final Vector3f maxV )\n {\n if (null != mGVRContext) {\n mGVRContext.runOnGlThread(new Runnable() {\n\n @Override\n public void run() {\n minVelocity = minV;\n maxVelocity = maxV;\n }\n });\n }\n }",
"public TwoDHashMap<K2, K3, V> getAs2d(final K1 firstKey) {\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 != null ) {\n\t\t\treturn new TwoDHashMap<K2, K3, V>(innerMap1);\n\t\t} else {\n\t\t\treturn new TwoDHashMap<K2, K3, V>();\n\t\t}\n\t\t\n\t}",
"public List<ServerRedirect> getServerMappings() {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONObject response = new JSONObject(doGet(BASE_SERVER, null));\n JSONArray serverArray = response.getJSONArray(\"servers\");\n\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServer = serverArray.getJSONObject(i);\n ServerRedirect server = getServerRedirectFromJSON(jsonServer);\n if (server != null) {\n servers.add(server);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return servers;\n }"
] |
Returns all keys in no particular order. | [
"public long[] keys() {\n long[] values = new long[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n values[idx++] = entry.key;\n entry = entry.next;\n }\n }\n return values;\n }"
] | [
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerGroup createServerGroup(Model model,\n @RequestParam(value = \"name\") String name,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId);\n return ServerRedirectService.getInstance().getServerGroup(groupId, profileId);\n }",
"public ServerRedirect getRedirect(int id) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n\n return curServer;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }",
"public static JRDesignExpression getDataSourceExpression(DJDataSource ds) {\n JRDesignExpression exp = new JRDesignExpression();\n exp.setValueClass(JRDataSource.class);\n\n String dsType = getDataSourceTypeStr(ds.getDataSourceType());\n String expText = null;\n if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_FIELD) {\n expText = dsType + \"$F{\" + ds.getDataSourceExpression() + \"})\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_PARAMETER) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_TYPE_SQL_CONNECTION) {\n expText = dsType + REPORT_PARAMETERS_MAP + \".get( \\\"\" + ds.getDataSourceExpression() + \"\\\" ) )\";\n } else if (ds.getDataSourceOrigin() == DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE) {\n expText = \"((\" + JRDataSource.class.getName() + \") $P{REPORT_DATA_SOURCE})\";\n }\n\n exp.setText(expText);\n\n return exp;\n }",
"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 GregorianCalendar millisToCalendar(long millis) {\r\n\r\n GregorianCalendar result = new GregorianCalendar();\r\n result.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\r\n result.setTimeInMillis((long)(Math.ceil(millis / 1000) * 1000));\r\n return result;\r\n }",
"public void sendData(SerialMessage serialMessage)\n\t{\n \tif (serialMessage.getMessageClass() != SerialMessage.SerialMessageClass.SendData) {\n \t\tlogger.error(String.format(\"Invalid message class %s (0x%02X) for sendData\", serialMessage.getMessageClass().getLabel(), serialMessage.getMessageClass().getKey()));\n \t\treturn;\n \t}\n \tif (serialMessage.getMessageType() != SerialMessage.SerialMessageType.Request) {\n \t\tlogger.error(\"Only request messages can be sent\");\n \t\treturn;\n \t}\n \t\n \tZWaveNode node = this.getNode(serialMessage.getMessageNode());\n \t\t\t\n \tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD) {\n \t\tlogger.debug(\"Node {} is dead, not sending message.\", node.getNodeId());\n\t\t\treturn;\n \t}\n\t\t\n \tif (!node.isListening() && serialMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null && !wakeUpCommandClass.isAwake()) {\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(serialMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n \t\n \tserialMessage.setTransmitOptions(TRANSMIT_OPTION_ACK | TRANSMIT_OPTION_AUTO_ROUTE | TRANSMIT_OPTION_EXPLORE);\n \tif (++sentDataPointer > 0xFF)\n \t\tsentDataPointer = 1;\n \tserialMessage.setCallbackId(sentDataPointer);\n \tlogger.debug(\"Callback ID = {}\", sentDataPointer);\n \tthis.enqueue(serialMessage);\n\t}",
"protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }",
"public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {\n return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);\n }",
"public Object getRealObjectIfMaterialized(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(objectOrProxy);\r\n\r\n return handler.alreadyMaterialized() ? handler.getRealSubject() : null;\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 catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n VirtualProxy proxy = (VirtualProxy) objectOrProxy;\r\n\r\n return proxy.alreadyMaterialized() ? proxy.getRealSubject() : null;\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }"
] |
Use this API to update rnatparam. | [
"public static base_response update(nitro_service client, rnatparam resource) throws Exception {\n\t\trnatparam updateresource = new rnatparam();\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"@JsonProperty\n public String timestamp() {\n if (timestampAsText == null) {\n timestampAsText = DateTimeFormatter.ISO_INSTANT.format(timestamp);\n }\n return timestampAsText;\n }",
"public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }",
"public static base_responses unset(nitro_service client, String name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (name != null && name.length > 0) {\n\t\t\tclusternodegroup unsetresources[] = new clusternodegroup[name.length];\n\t\t\tfor (int i=0;i<name.length;i++){\n\t\t\t\tunsetresources[i] = new clusternodegroup();\n\t\t\t\tunsetresources[i].name = name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public static <T> T mode(Collection<T> values) {\r\n Set<T> modes = modes(values);\r\n return modes.iterator().next();\r\n }",
"public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\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 }",
"private <T> T readIntoBean(final T bean, final String[] nameMapping, final CellProcessor[] processors)\n\t\tthrows IOException {\n\t\t\n\t\tif( readRow() ) {\n\t\t\tif( nameMapping.length != length() ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\t\"the nameMapping array and the number of columns read \"\n\t\t\t\t\t\t+ \"should be the same size (nameMapping length = %d, columns = %d)\", nameMapping.length,\n\t\t\t\t\tlength()));\n\t\t\t}\n\t\t\t\n\t\t\tif( processors == null ) {\n\t\t\t\tprocessedColumns.clear();\n\t\t\t\tprocessedColumns.addAll(getColumns());\n\t\t\t} else {\n\t\t\t\texecuteProcessors(processedColumns, processors);\n\t\t\t}\n\t\t\t\n\t\t\treturn populateBean(bean, nameMapping);\n\t\t}\n\t\t\n\t\treturn null; // EOF\n\t}",
"public static callhome get(nitro_service service) throws Exception{\n\t\tcallhome obj = new callhome();\n\t\tcallhome[] response = (callhome[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }"
] |
Records the list of backedup files into a text file
@param filesInEnv
@param backupDir | [
"private void recordBackupSet(File backupDir) throws IOException {\n String[] filesInEnv = env.getHome().list();\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy_MM_dd_kk_mm_ss\");\n String recordFileName = \"backupset-\" + format.format(new Date());\n File recordFile = new File(backupDir, recordFileName);\n if(recordFile.exists()) {\n recordFile.renameTo(new File(backupDir, recordFileName + \".old\"));\n }\n\n PrintStream backupRecord = new PrintStream(new FileOutputStream(recordFile));\n backupRecord.println(\"Lastfile:\" + Long.toHexString(backupHelper.getLastFileInBackupSet()));\n if(filesInEnv != null) {\n for(String file: filesInEnv) {\n if(file.endsWith(BDB_EXT))\n backupRecord.println(file);\n }\n }\n backupRecord.close();\n }"
] | [
"public void update(int width, int height, float[] data)\n throws IllegalArgumentException\n {\n if ((width <= 0) || (height <= 0) ||\n (data == null) || (data.length < height * width * mFloatsPerPixel))\n {\n throw new IllegalArgumentException();\n }\n NativeFloatImage.update(getNative(), width, height, 0, data);\n }",
"private void addSubMatrixVariables(List<TokenList.Token> inputs, List<Variable> variables) {\n for (int i = 0; i < inputs.size(); i++) {\n TokenList.Token t = inputs.get(i);\n if( t.getType() != Type.VARIABLE )\n throw new ParseError(\"Expected variables only in sub-matrix input, not \"+t.getType());\n Variable v = t.getVariable();\n if( v.getType() == VariableType.INTEGER_SEQUENCE || isVariableInteger(t) ) {\n variables.add(v);\n } else {\n throw new ParseError(\"Expected an integer, integer sequence, or array range to define a submatrix\");\n }\n }\n }",
"public byte[] getByteArray(int offset)\n {\n byte[] result = null;\n\n if (offset > 0 && offset < m_data.length)\n {\n int nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n int itemSize = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n if (itemSize > 0 && itemSize < m_data.length)\n {\n int blockRemainingSize = 28;\n\n if (nextBlockOffset != -1 || itemSize <= blockRemainingSize)\n {\n int itemRemainingSize = itemSize;\n result = new byte[itemSize];\n int resultOffset = 0;\n\n while (nextBlockOffset != -1)\n {\n MPPUtility.getByteArray(m_data, offset, blockRemainingSize, result, resultOffset);\n resultOffset += blockRemainingSize;\n offset += blockRemainingSize;\n itemRemainingSize -= blockRemainingSize;\n\n if (offset != nextBlockOffset)\n {\n offset = nextBlockOffset;\n }\n\n nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n blockRemainingSize = 32;\n }\n\n MPPUtility.getByteArray(m_data, offset, itemRemainingSize, result, resultOffset);\n }\n }\n }\n\n return (result);\n }",
"private void pushDeviceToken(final String token, final boolean register, final PushType type) {\n pushDeviceToken(this.context, token, register, type);\n }",
"@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }",
"public ItemRequest<Webhook> getById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"GET\");\n }",
"public static String readTextFile(InputStream inputStream) {\n InputStreamReader streamReader = new InputStreamReader(inputStream);\n return readTextFile(streamReader);\n }",
"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 void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case REQUEST_PERMISSIONS_CODE:\n if (listener != null) {\n boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;\n listener.onPermissionResult(granted);\n }\n break;\n default:\n // Ignored\n }\n }"
] |
Register the given mbean with the platform mbean server
@param mbean The mbean to register
@param name The name to register under | [
"public static void registerMbean(Object mbean, ObjectName name) {\n registerMbean(ManagementFactory.getPlatformMBeanServer(),\n JmxUtils.createModelMBean(mbean),\n name);\n }"
] | [
"public int executeUpdate(String query) throws Exception {\n int returnVal = 0;\n Statement queryStatement = null;\n\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n returnVal = queryStatement.executeUpdate(query);\n } catch (Exception e) {\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnVal;\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 boolean validate(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n if (conn == null)\n return false;\n\n if (!conn.isClosed() && conn.isValid(10))\n return true;\n\n stmt.close();\n conn.close();\n } catch (SQLException e) {\n // this may well fail. that doesn't matter. we're just making an\n // attempt to clean up, and if we can't, that's just too bad.\n }\n return false;\n }",
"public void addProcedure(ProcedureDef procDef)\r\n {\r\n procDef.setOwner(this);\r\n _procedures.put(procDef.getName(), procDef);\r\n }",
"public static snmpmanager[] get(nitro_service service) throws Exception{\n\t\tsnmpmanager obj = new snmpmanager();\n\t\tsnmpmanager[] response = (snmpmanager[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}\", this.getNode().getNodeId(), endpoint.getEndpointId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) MULTI_CHANNEL_CAPABILITY_GET,\r\n\t\t\t\t\t\t\t\t(byte) endpoint.getEndpointId() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\r\n\t}",
"public double multi8p(int x, int y, double masc) {\n int aR = getIntComponent0(x - 1, y - 1);\n int bR = getIntComponent0(x - 1, y);\n int cR = getIntComponent0(x - 1, y + 1);\n int aG = getIntComponent1(x - 1, y - 1);\n int bG = getIntComponent1(x - 1, y);\n int cG = getIntComponent1(x - 1, y + 1);\n int aB = getIntComponent1(x - 1, y - 1);\n int bB = getIntComponent1(x - 1, y);\n int cB = getIntComponent1(x - 1, y + 1);\n\n\n int dR = getIntComponent0(x, y - 1);\n int eR = getIntComponent0(x, y);\n int fR = getIntComponent0(x, y + 1);\n int dG = getIntComponent1(x, y - 1);\n int eG = getIntComponent1(x, y);\n int fG = getIntComponent1(x, y + 1);\n int dB = getIntComponent1(x, y - 1);\n int eB = getIntComponent1(x, y);\n int fB = getIntComponent1(x, y + 1);\n\n\n int gR = getIntComponent0(x + 1, y - 1);\n int hR = getIntComponent0(x + 1, y);\n int iR = getIntComponent0(x + 1, y + 1);\n int gG = getIntComponent1(x + 1, y - 1);\n int hG = getIntComponent1(x + 1, y);\n int iG = getIntComponent1(x + 1, y + 1);\n int gB = getIntComponent1(x + 1, y - 1);\n int hB = getIntComponent1(x + 1, y);\n int iB = getIntComponent1(x + 1, y + 1);\n\n double rgb = 0;\n\n rgb = ((aR * masc) + (bR * masc) + (cR * masc) +\n (dR * masc) + (eR * masc) + (fR * masc) +\n (gR * masc) + (hR * masc) + (iR * masc));\n\n return (rgb);\n\n }",
"private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }",
"public static CharSequence getAt(CharSequence text, int index) {\n index = normaliseIndex(index, text.length());\n return text.subSequence(index, index + 1);\n }"
] |
It's enough to just set the disabled attribute on the
element, but we want to also add a "disabled" class so that we can
style it.
At some point we'll just be able to use .button:disabled,
but that doesn't work in IE8- | [
"public static void setEnabled(Element element, boolean enabled) {\n element.setPropertyBoolean(\"disabled\", !enabled);\n\tsetStyleName(element, \"disabled\", !enabled);\n }"
] | [
"private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}",
"public BoxCollaborationWhitelistExemptTarget.Info getInfo() {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(),\n this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n return new Info(JsonObject.readFrom(response.getJSON()));\n }",
"protected I_CmsFacetQueryItem parseFacetQueryItem(JSONObject item) {\n\n String query;\n try {\n query = item.getString(JSON_KEY_QUERY_FACET_QUERY_QUERY);\n } catch (JSONException e) {\n // TODO: Log\n return null;\n }\n String label = parseOptionalStringValue(item, JSON_KEY_QUERY_FACET_QUERY_LABEL);\n return new CmsFacetQueryItem(query, label);\n }",
"public Where<T, ID> eq(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"public static boolean isDiagonalPositive( DMatrixRMaj a ) {\n for( int i = 0; i < a.numRows; i++ ) {\n if( !(a.get(i,i) >= 0) )\n return false;\n }\n return true;\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 }",
"@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }",
"public 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 }",
"void buildControl(BinaryPackageControlFile packageControlFile, File[] controlFiles, List<String> conffiles, StringBuilder checksums, File output) throws IOException, ParseException {\n final File dir = output.getParentFile();\n if (dir != null && (!dir.exists() || !dir.isDirectory())) {\n throw new IOException(\"Cannot write control file at '\" + output.getAbsolutePath() + \"'\");\n }\n\n final TarArchiveOutputStream outputStream = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(output)));\n outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);\n\n boolean foundConffiles = false;\n\n // create the final package control file out of the \"control\" file, copy all other files, ignore the directories\n for (File file : controlFiles) {\n if (file.isDirectory()) {\n // warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)\n if (!isDefaultExcludes(file)) {\n console.warn(\"Found directory '\" + file + \"' in the control directory. Maybe you are pointing to wrong dir?\");\n }\n continue;\n }\n\n if (\"conffiles\".equals(file.getName())) {\n foundConffiles = true;\n }\n\n if (CONFIGURATION_FILENAMES.contains(file.getName()) || MAINTAINER_SCRIPTS.contains(file.getName())) {\n FilteredFile configurationFile = new FilteredFile(new FileInputStream(file), resolver);\n configurationFile.setOpenToken(openReplaceToken);\n configurationFile.setCloseToken(closeReplaceToken);\n addControlEntry(file.getName(), configurationFile.toString(), outputStream);\n\n } else if (!\"control\".equals(file.getName())) {\n // initialize the information stream to guess the type of the file\n InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));\n Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);\n infoStream.close();\n\n // fix line endings for shell scripts\n InputStream in = new FileInputStream(file);\n if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {\n byte[] buf = Utils.toUnixLineEndings(in);\n in = new ByteArrayInputStream(buf);\n }\n\n addControlEntry(file.getName(), IOUtils.toString(in), outputStream);\n\n in.close();\n }\n }\n\n if (foundConffiles) {\n console.info(\"Found file 'conffiles' in the control directory. Skipping conffiles generation.\");\n } else if ((conffiles != null) && (conffiles.size() > 0)) {\n addControlEntry(\"conffiles\", createPackageConffilesFile(conffiles), outputStream);\n } else {\n console.info(\"Skipping 'conffiles' generation. No entries defined in maven/pom or ant/build.xml.\");\n }\n\n if (packageControlFile == null) {\n throw new FileNotFoundException(\"No 'control' file found in \" + controlFiles.toString());\n }\n\n addControlEntry(\"control\", packageControlFile.toString(), outputStream);\n addControlEntry(\"md5sums\", checksums.toString(), outputStream);\n\n outputStream.close();\n }"
] |
Builds the DynamicReport object. Cannot be used twice since this produced
undesired results on the generated DynamicReport object
@return | [
"public DynamicReport build() {\n\n if (built) {\n throw new DJBuilderException(\"DynamicReport already built. Cannot use more than once.\");\n } else {\n built = true;\n }\n\n report.setOptions(options);\n if (!globalVariablesGroup.getFooterVariables().isEmpty() || !globalVariablesGroup.getHeaderVariables().isEmpty() || !globalVariablesGroup.getVariables().isEmpty() || hasPercentageColumn()) {\n report.getColumnsGroups().add(0, globalVariablesGroup);\n }\n\n createChartGroups();\n\n addGlobalCrosstabs();\n\n addSubreportsToGroups();\n\n concatenateReports();\n\n report.setAutoTexts(autoTexts);\n return report;\n }"
] | [
"public void rotateToFaceCamera(final GVRTransform transform) {\n //see http://stackoverflow.com/questions/5782658/extracting-yaw-from-a-quaternion\n final GVRTransform t = getMainCameraRig().getHeadTransform();\n final Quaternionf q = new Quaternionf(0, t.getRotationY(), 0, t.getRotationW()).normalize();\n\n transform.rotateWithPivot(q.w, q.x, q.y, q.z, 0, 0, 0);\n }",
"public static String confSetName() {\n String profile = SysProps.get(AppConfigKey.PROFILE.key());\n if (S.blank(profile)) {\n profile = Act.mode().name().toLowerCase();\n }\n return profile;\n }",
"@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}",
"private void calcCurrentItem() {\n int pointerAngle;\n\n // calculate the correct pointer angle, depending on clockwise drawing or not\n if(mOpenClockwise) {\n pointerAngle = (mIndicatorAngle + 360 - mPieRotation) % 360;\n }\n else {\n pointerAngle = (mIndicatorAngle + 180 + mPieRotation) % 360;\n }\n\n for (int i = 0; i < mPieData.size(); ++i) {\n PieModel model = mPieData.get(i);\n if (model.getStartAngle() <= pointerAngle && pointerAngle <= model.getEndAngle()) {\n if (i != mCurrentItem) {\n setCurrentItem(i, false);\n }\n break;\n }\n }\n }",
"protected void doSplitTokenImpl(Token token, ITokenAcceptor result) {\n\t\tString text = token.getText();\n\t\tint indentation = computeIndentation(text);\n\t\tif (indentation == -1 || indentation == currentIndentation) {\n\t\t\t// no change of indentation level detected simply process the token\n\t\t\tresult.accept(token);\n\t\t} else if (indentation > currentIndentation) {\n\t\t\t// indentation level increased\n\t\t\tsplitIntoBeginToken(token, indentation, result);\n\t\t} else if (indentation < currentIndentation) {\n\t\t\t// indentation level decreased\n\t\t\tint charCount = computeIndentationRelevantCharCount(text);\n\t\t\tif (charCount > 0) {\n\t\t\t\t// emit whitespace including newline\n\t\t\t\tsplitWithText(token, text.substring(0, charCount), result);\t\n\t\t\t}\n\t\t\t// emit end tokens at the beginning of the line\n\t\t\tdecreaseIndentation(indentation, result);\n\t\t\tif (charCount != text.length()) {\n\t\t\t\thandleRemainingText(token, text.substring(charCount), indentation, result);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new IllegalStateException(String.valueOf(indentation));\n\t\t}\n\t}",
"public String convertFromJavaString(String string, boolean useUnicode) {\n\t\tint firstEscapeSequence = string.indexOf('\\\\');\n\t\tif (firstEscapeSequence == -1) {\n\t\t\treturn string;\n\t\t}\n\t\tint length = string.length();\n\t\tStringBuilder result = new StringBuilder(length);\n\t\tappendRegion(string, 0, firstEscapeSequence, result);\n\t\treturn convertFromJavaString(string, useUnicode, firstEscapeSequence, result);\n\t}",
"public List<TerminalString> getOptionLongNamesWithDash() {\n List<ProcessedOption> opts = getOptions();\n List<TerminalString> names = new ArrayList<>(opts.size());\n for (ProcessedOption o : opts) {\n if(o.getValues().size() == 0 &&\n o.activator().isActivated(new ParsedCommand(this)))\n names.add(o.getRenderedNameWithDashes());\n }\n\n return names;\n }",
"private void checkExistingTracks() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n checkIfSignatureReady(entry.getKey().player);\n }\n }\n }\n });\n }",
"public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}"
] |
Return the score of the specified element of the sorted set at key.
@param member
@return The score value or <code>null</code> if the element does not exist in the set. | [
"public Double score(final String member) {\n return doWithJedis(new JedisCallable<Double>() {\n @Override\n public Double call(Jedis jedis) {\n return jedis.zscore(getKey(), member);\n }\n });\n }"
] | [
"private void proxyPause() {\n logger.info(\"Pausing after cluster state has changed to allow proxy bridges to be established. \"\n + \"Will start rebalancing work on servers in \"\n + proxyPauseSec\n + \" seconds.\");\n try {\n Thread.sleep(TimeUnit.SECONDS.toMillis(proxyPauseSec));\n } catch(InterruptedException e) {\n logger.warn(\"Sleep interrupted in proxy pause.\");\n }\n }",
"private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }",
"private void setConstraints(Task task, MapRow row)\n {\n ConstraintType constraintType = null;\n Date constraintDate = null;\n Date lateDate = row.getDate(\"CONSTRAINT_LATE_DATE\");\n Date earlyDate = row.getDate(\"CONSTRAINT_EARLY_DATE\");\n\n switch (row.getInteger(\"CONSTRAINT_TYPE\").intValue())\n {\n case 2: // Cannot Reschedule\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = task.getStart();\n break;\n }\n\n case 12: //Finish Between\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = lateDate;\n break;\n }\n\n case 10: // Finish On or After\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 11: // Finish On or Before\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = lateDate;\n break;\n }\n\n case 13: // Mandatory Start\n case 5: // Start On\n case 9: // Finish On\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 14: // Mandatory Finish\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 4: // Start As Late As Possible\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n break;\n }\n\n case 3: // Start As Soon As Possible\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n break;\n }\n\n case 8: // Start Between\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n constraintDate = earlyDate;\n break;\n }\n\n case 6: // Start On or Before\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 15: // Work Between\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n }\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"private String filterAttributes(String html) {\n\t\tString filteredHtml = html;\n\t\tfor (String attribute : this.filterAttributes) {\n\t\t\tString regex = \"\\\\s\" + attribute + \"=\\\"[^\\\"]*\\\"\";\n\t\t\tPattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n\t\t\tMatcher m = p.matcher(html);\n\t\t\tfilteredHtml = m.replaceAll(\"\");\n\t\t}\n\t\treturn filteredHtml;\n\t}",
"public void revisitThrowEvents(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<Signal> toAddSignals = new ArrayList<Signal>();\n Set<Error> toAddErrors = new HashSet<Error>();\n Set<Escalation> toAddEscalations = new HashSet<Escalation>();\n Set<Message> toAddMessages = new HashSet<Message>();\n Set<ItemDefinition> toAddItemDefinitions = new HashSet<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setThrowEventsInfo((Process) root,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n }\n for (Lane lane : _lanes) {\n setThrowEventsInfoForLanes(lane,\n def,\n rootElements,\n toAddSignals,\n toAddErrors,\n toAddEscalations,\n toAddMessages,\n toAddItemDefinitions);\n }\n for (Signal s : toAddSignals) {\n def.getRootElements().add(s);\n }\n for (Error er : toAddErrors) {\n def.getRootElements().add(er);\n }\n for (Escalation es : toAddEscalations) {\n def.getRootElements().add(es);\n }\n for (ItemDefinition idef : toAddItemDefinitions) {\n def.getRootElements().add(idef);\n }\n for (Message msg : toAddMessages) {\n def.getRootElements().add(msg);\n }\n }",
"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 }",
"@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }",
"public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void flush() throws IOException {\n checkMutable();\n long startTime = System.currentTimeMillis();\n channel.force(true);\n long elapsedTime = System.currentTimeMillis() - startTime;\n LogFlushStats.recordFlushRequest(elapsedTime);\n logger.debug(\"flush time \" + elapsedTime);\n setHighWaterMark.set(getSizeInBytes());\n logger.debug(\"flush high water mark:\" + highWaterMark());\n }"
] |
Retrieve an enterprise field value.
@param index field index
@return field value | [
"public boolean getEnterpriseFlag(int index)\n {\n return (BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(TaskFieldLists.ENTERPRISE_FLAG, index))));\n }"
] | [
"public static base_response disable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance disableresource = new clusterinstance();\n\t\tdisableresource.clid = clid;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public Headers getAllHeaders() {\n Headers requestHeaders = getHeaders();\n requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders;\n //We don't want to add headers more than once.\n return requestHeaders;\n }",
"public static String readCorrelationId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String correlationId = null;\n Header hdCorrelationId = ((SoapMessage) message).getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n if (hdCorrelationId.getObject() instanceof String) {\n correlationId = (String) hdCorrelationId.getObject();\n } else if (hdCorrelationId.getObject() instanceof Node) {\n Node headerNode = (Node) hdCorrelationId.getObject();\n correlationId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found CorrelationId soap header but value is not a String or a Node! Value: \"\n + hdCorrelationId.getObject().toString());\n }\n }\n return correlationId;\n }",
"public void writeNameValuePair(String name, long value) throws IOException\n {\n internalWriteNameValuePair(name, Long.toString(value));\n }",
"protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }",
"private void addGroups(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Group group : file.getGroups())\n {\n final Group g = group;\n MpxjTreeNode childNode = new MpxjTreeNode(group)\n {\n @Override public String toString()\n {\n return g.getName();\n }\n };\n parentNode.add(childNode);\n }\n }",
"final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }",
"private void prepareInitialState(boolean isNewObject)\r\n {\r\n // determine appropriate modification state\r\n ModificationState initialState;\r\n if(isNewObject)\r\n {\r\n // if object is not already persistent it must be marked as new\r\n // it must be marked as dirty because it must be stored even if it will not modified during tx\r\n initialState = StateNewDirty.getInstance();\r\n }\r\n else if(isDeleted(oid))\r\n {\r\n // if object is already persistent it will be marked as old.\r\n // it is marked as dirty as it has been deleted during tx and now it is inserted again,\r\n // possibly with new field values.\r\n initialState = StateOldDirty.getInstance();\r\n }\r\n else\r\n {\r\n // if object is already persistent it will be marked as old.\r\n // it is marked as clean as it has not been modified during tx already\r\n initialState = StateOldClean.getInstance();\r\n }\r\n // remember it:\r\n modificationState = initialState;\r\n }",
"public void waitForBuffer(long timeoutMilli) {\n //assert(callerProcessing.booleanValue() == false);\n\n synchronized(buffer) {\n if( dirtyBuffer )\n return;\n if( !foundEOF() ) {\n logger.trace(\"Waiting for things to come in, or until timeout\");\n try {\n if( timeoutMilli > 0 )\n buffer.wait(timeoutMilli);\n else\n buffer.wait();\n } catch(InterruptedException ie) {\n logger.trace(\"Woken up, while waiting for buffer\");\n }\n // this might went early, but running the processing again isn't a big deal\n logger.trace(\"Waited\");\n }\n }\n }"
] |
get children nodes name
@param zkClient zkClient
@param path full path
@return children nodes name or null while path not exist | [
"public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }"
] | [
"public ChannelInfo getChannel(String name) {\n final URI uri = uriWithPath(\"./channels/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ChannelInfo.class);\n }",
"public HostName toHostName() {\n\t\tHostName host = fromHost;\n\t\tif(host == null) {\n\t\t\tfromHost = host = toCanonicalHostName();\n\t\t}\n\t\treturn host;\n\t}",
"public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }",
"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 Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\n }",
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }",
"public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n GVRCamera shadowCam = GVRShadowMap.makeOrthoShadowCamera(\n getGVRContext().getMainScene().getMainCameraRig().getCenterCamera());\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }",
"public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedInsert == null) {\n\t\t\tmappedInsert = MappedCreate.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}",
"private static boolean isEqual(Method m, Method a) {\n if (m.getName().equals(a.getName()) && m.getParameterTypes().length == a.getParameterTypes().length && m.getReturnType().isAssignableFrom(a.getReturnType())) {\n for (int i = 0; i < m.getParameterTypes().length; i++) {\n if (!(m.getParameterTypes()[i].isAssignableFrom(a.getParameterTypes()[i]))) {\n return false;\n }\n }\n return true;\n }\n return false;\n }"
] |
Wrap CallableStatement with a proxy.
@param target statement handle
@param connectionHandle originating bonecp connection
@return Proxy to a Callablestatement. | [
"protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}"
] | [
"public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {\r\n\t\treturn new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),\r\n\t\t\t\tgetBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}",
"private List<Key> getScatterKeys(\n int numSplits, Query query, PartitionId partition, Datastore datastore)\n throws DatastoreException {\n Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);\n\n List<Key> keySplits = new ArrayList<Key>();\n\n QueryResultBatch batch;\n do {\n RunQueryRequest scatterRequest =\n RunQueryRequest.newBuilder()\n .setPartitionId(partition)\n .setQuery(scatterPointQuery)\n .build();\n batch = datastore.runQuery(scatterRequest).getBatch();\n for (EntityResult result : batch.getEntityResultsList()) {\n keySplits.add(result.getEntity().getKey());\n }\n scatterPointQuery.setStartCursor(batch.getEndCursor());\n scatterPointQuery.getLimitBuilder().setValue(\n scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());\n } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);\n Collections.sort(keySplits, DatastoreHelper.getKeyComparator());\n return keySplits;\n }",
"public StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }",
"private FieldType addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n FieldType field = null;\n \n try\n {\n switch (fieldType)\n {\n case TASK:\n {\n do\n {\n field = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (RESERVED_TASK_FIELDS.contains(field));\n\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n\n break;\n }\n \n case RESOURCE:\n {\n field = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n case ASSIGNMENT:\n {\n field = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n default:\n {\n break;\n }\n } \n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n \n return field;\n }",
"public static boolean removeDefaultCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject profile = getDefaultProfile();\n String profileName = profile.getString(\"name\");\n PathValueClient client = new PathValueClient(profileName, false);\n return client.removeCustomResponse(pathValue, requestType);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"private Set<String> findResourceNamesFromFileSystem(String classPathRootOnDisk, String scanRootLocation, File folder) {\n LOGGER.debug(\"Scanning for resources in path: {} ({})\", folder.getPath(), scanRootLocation);\n\n File[] files = folder.listFiles();\n if (files == null) {\n return emptySet();\n }\n\n Set<String> resourceNames = new TreeSet<>();\n\n for (File file : files) {\n if (file.canRead()) {\n if (file.isDirectory()) {\n resourceNames.addAll(findResourceNamesFromFileSystem(classPathRootOnDisk, scanRootLocation, file));\n } else {\n resourceNames.add(toResourceNameOnClasspath(classPathRootOnDisk, file));\n }\n }\n }\n\n return resourceNames;\n }",
"protected void layoutGroupSubreports(DJGroup columnsGroup, JRDesignGroup jgroup) {\n\t\tlog.debug(\"Starting subreport layout...\");\n\t\tJRDesignBand footerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupFooterSection()).getBandsList().get(0);\n\t\tJRDesignBand headerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupHeaderSection()).getBandsList().get(0);\n\n\t\tlayOutSubReportInBand(columnsGroup, headerBand, DJConstants.HEADER);\n\t\tlayOutSubReportInBand(columnsGroup, footerBand, DJConstants.FOOTER);\n\n\t}",
"private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)\n throws CmsException {\n\n CmsObject cmsClone;\n if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {\n cmsClone = cms;\n } else {\n cmsClone = OpenCms.initCmsObject(cms);\n cmsClone.getRequestContext().setSiteRoot(module.getSite());\n }\n\n return cmsClone;\n }",
"public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}"
] |
Map originator type.
@param originatorType the originator type
@return the originator | [
"private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }"
] | [
"public ItemRequest<Task> removeDependents(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public NRShape makeShape(Date from, Date to) {\n UnitNRShape fromShape = tree.toUnitShape(from);\n UnitNRShape toShape = tree.toUnitShape(to);\n return tree.toRangeShape(fromShape, toShape);\n }",
"private void refreshMetadataCache(final Queue<WindupMetadataSystem> metadataSystemCache, final DecompilerSettings settings)\n {\n metadataSystemCache.clear();\n for (int i = 0; i < this.getNumberOfThreads(); i++)\n {\n metadataSystemCache.add(new NoRetryMetadataSystem(settings.getTypeLoader()));\n }\n }",
"public double[] sampleToEigenSpace( double[] sampleData ) {\n if( sampleData.length != A.getNumCols() )\n throw new IllegalArgumentException(\"Unexpected sample length\");\n DMatrixRMaj mean = DMatrixRMaj.wrap(A.getNumCols(),1,this.mean);\n\n DMatrixRMaj s = new DMatrixRMaj(A.getNumCols(),1,true,sampleData);\n DMatrixRMaj r = new DMatrixRMaj(numComponents,1);\n\n CommonOps_DDRM.subtract(s, mean, s);\n\n CommonOps_DDRM.mult(V_t,s,r);\n\n return r.data;\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 }",
"private void registerChildInternal(IgnoreDomainResourceTypeResource child) {\n child.setParent(this);\n children.put(child.getName(), child);\n }",
"private <T> void add(EjbDescriptor<T> ejbDescriptor) {\n InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor);\n ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor);\n ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName());\n }",
"public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"public PlacesList<Place> find(String query) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PlacesList<Place> placesList = new PlacesList<Place>();\r\n parameters.put(\"method\", METHOD_FIND);\r\n\r\n parameters.put(\"query\", query);\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 placesElement = response.getPayload();\r\n NodeList placesNodes = placesElement.getElementsByTagName(\"place\");\r\n placesList.setPage(\"1\");\r\n placesList.setPages(\"1\");\r\n placesList.setPerPage(\"\" + placesNodes.getLength());\r\n placesList.setTotal(\"\" + placesNodes.getLength());\r\n for (int i = 0; i < placesNodes.getLength(); i++) {\r\n Element placeElement = (Element) placesNodes.item(i);\r\n placesList.add(parsePlace(placeElement));\r\n }\r\n return placesList;\r\n }"
] |
The main entry point for processing graphical indicator definitions.
@param indicators graphical indicators container
@param properties project properties
@param props properties data | [
"public void process(CustomFieldContainer indicators, ProjectProperties properties, Props props)\n {\n m_container = indicators;\n m_properties = properties;\n m_data = props.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n\n if (m_data != null)\n {\n int columnsCount = MPPUtility.getInt(m_data, 4);\n m_headerOffset = 8;\n for (int loop = 0; loop < columnsCount; loop++)\n {\n processColumns();\n }\n }\n }"
] | [
"public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // check constraints now after all classes have been processed\r\n for (Iterator it = getClasses(); it.hasNext();)\r\n {\r\n ((ClassDescriptorDef)it.next()).checkConstraints(checkLevel);\r\n }\r\n // additional model constraints that either deal with bigger parts of the model or\r\n // can only be checked after the individual classes have been checked (e.g. specific\r\n // attributes have been ensured)\r\n new ModelConstraints().check(this, checkLevel);\r\n }",
"public synchronized void doneTask(int stealerId, int donorId) {\n removeNodesFromWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting--;\n doneSignal.countDown();\n // Try and schedule more tasks now that resources may be available to do\n // so.\n scheduleMoreTasks();\n }",
"public static protocolip_stats get(nitro_service service) throws Exception{\n\t\tprotocolip_stats obj = new protocolip_stats();\n\t\tprotocolip_stats[] response = (protocolip_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}",
"public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal);\n }",
"public static base_responses export(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata exportresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new appfwlearningdata();\n\t\t\t\texportresources[i].profilename = resources[i].profilename;\n\t\t\t\texportresources[i].securitycheck = resources[i].securitycheck;\n\t\t\t\texportresources[i].target = resources[i].target;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}",
"public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }",
"private int countHours(Integer hours)\n {\n int value = hours.intValue();\n int hoursPerDay = 0;\n int hour = 0;\n while (value > 0)\n {\n // Move forward until we find a working hour\n while (hour < 24)\n {\n if ((value & 0x1) != 0)\n {\n ++hoursPerDay;\n }\n value = value >> 1;\n ++hour;\n }\n }\n return hoursPerDay;\n }"
] |
Cleanup function to remove all allocated listeners | [
"public void cleanup() {\n synchronized (_sslMap) {\n for (SslRelayOdo relay : _sslMap.values()) {\n if (relay.getHttpServer() != null && relay.isStarted()) {\n relay.getHttpServer().removeListener(relay);\n }\n }\n\n sslRelays.clear();\n }\n }"
] | [
"public void addAll(OptionsContainerBuilder container) {\n\t\tfor ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {\n\t\t\taddAll( entry.getKey(), entry.getValue().build() );\n\t\t}\n\t}",
"protected void fireEvent(HotKey hotKey) {\n HotKeyEvent event = new HotKeyEvent(hotKey);\n if (useSwingEventQueue) {\n SwingUtilities.invokeLater(event);\n } else {\n if (eventQueue == null) {\n eventQueue = Executors.newSingleThreadExecutor();\n }\n eventQueue.execute(event);\n }\n }",
"public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}",
"public static String minus(CharSequence self, Object target) {\n String s = self.toString();\n String text = DefaultGroovyMethods.toString(target);\n int index = s.indexOf(text);\n if (index == -1) return s;\n int end = index + text.length();\n if (s.length() > end) {\n return s.substring(0, index) + s.substring(end);\n }\n return s.substring(0, index);\n }",
"public static CompressionType getDumpFileCompressionType(String fileName) {\n\t\tif (fileName.endsWith(\".gz\")) {\n\t\t\treturn CompressionType.GZIP;\n\t\t} else if (fileName.endsWith(\".bz2\")) {\n\t\t\treturn CompressionType.BZ2;\n\t\t} else {\n\t\t\treturn CompressionType.NONE;\n\t\t}\n\t}",
"public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }",
"@SuppressForbidden(\"legitimate sysstreams.\")\n public static void warn(String message, Throwable t) {\n PrintStream w = (warnings == null ? System.err : warnings);\n try {\n w.print(\"WARN: \");\n w.print(message);\n if (t != null) {\n w.print(\" -> \");\n try {\n t.printStackTrace(w);\n } catch (OutOfMemoryError e) {\n // Ignore, OOM.\n w.print(t.getClass().getName());\n w.print(\": \");\n w.print(t.getMessage());\n w.println(\" (stack unavailable; OOM)\");\n }\n } else {\n w.println();\n }\n w.flush();\n } catch (OutOfMemoryError t2) {\n w.println(\"ERROR: Couldn't even serialize a warning (out of memory).\");\n } catch (Throwable t2) {\n // Can't do anything, really. Probably an OOM?\n w.println(\"ERROR: Couldn't even serialize a warning.\");\n }\n }",
"private void removeMount(SlotReference slot) {\n mediaDetails.remove(slot);\n if (mediaMounts.remove(slot)) {\n deliverMountUpdate(slot, false);\n }\n }",
"public static final Priority parsePriority(BigInteger priority)\n {\n return (priority == null ? null : Priority.getInstance(priority.intValue()));\n }"
] |
Set the String of request body data to be sent to the server.
@param input String of request body data to be sent to the server
@return an {@link HttpConnection} for method chaining | [
"public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }"
] | [
"private void setRequestProps(WbGetEntitiesActionData properties) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"info|datatype\");\n\t\tif (!this.filter.excludeAllLanguages()) {\n\t\t\tbuilder.append(\"|labels|aliases|descriptions\");\n\t\t}\n\t\tif (!this.filter.excludeAllProperties()) {\n\t\t\tbuilder.append(\"|claims\");\n\t\t}\n\t\tif (!this.filter.excludeAllSiteLinks()) {\n\t\t\tbuilder.append(\"|sitelinks\");\n\t\t}\n\n\t\tproperties.props = builder.toString();\n\t}",
"private static Class<?> getRawClass(Type type) {\n if (type instanceof Class) {\n return (Class<?>) type;\n }\n if (type instanceof ParameterizedType) {\n return getRawClass(((ParameterizedType) type).getRawType());\n }\n // For TypeVariable and WildcardType, returns the first upper bound.\n if (type instanceof TypeVariable) {\n return getRawClass(((TypeVariable) type).getBounds()[0]);\n }\n if (type instanceof WildcardType) {\n return getRawClass(((WildcardType) type).getUpperBounds()[0]);\n }\n if (type instanceof GenericArrayType) {\n Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());\n return Array.newInstance(componentClass, 0).getClass();\n }\n // This shouldn't happen as we captured all implementations of Type above (as or Java 8)\n throw new IllegalArgumentException(\"Unsupported type \" + type + \" of type class \" + type.getClass());\n }",
"public RedwoodConfiguration collapseExact(){\r\n tasks.add(new Runnable() { public void run() { Redwood.spliceHandler(VisibilityHandler.class, new RepeatedRecordHandler(RepeatedRecordHandler.EXACT), OutputHandler.class); } });\r\n return this;\r\n }",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {\n setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {\n setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {\n setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));\n }\n\n if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {\n setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));\n }\n\n if(props.containsKey(NETTY_SERVER_PORT)) {\n setServerPort(props.getInt(NETTY_SERVER_PORT));\n }\n\n if(props.containsKey(NETTY_SERVER_BACKLOG)) {\n setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));\n }\n\n if(props.containsKey(COORDINATOR_CORE_THREADS)) {\n setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_MAX_THREADS)) {\n setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {\n setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {\n setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {\n setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {\n setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));\n }\n\n if(props.containsKey(ADMIN_ENABLE)) {\n setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));\n }\n\n if(props.containsKey(ADMIN_PORT)) {\n setAdminPort(props.getInt(ADMIN_PORT));\n }\n\n }",
"private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }",
"public void putAll(Map<KEY, VALUE> mapDataToPut) {\n int targetSize = maxSize - mapDataToPut.size();\n if (maxSize > 0 && values.size() > targetSize) {\n evictToTargetSize(targetSize);\n }\n Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();\n for (Entry<KEY, VALUE> entry : entries) {\n put(entry.getKey(), entry.getValue());\n }\n }",
"private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }",
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {\n MultipartContent.Part part = new MultipartContent.Part()\n .setContent(new InputStreamContent(fileType, fileContent))\n .setHeaders(new HttpHeaders().set(\n \"Content-Disposition\",\n String.format(\"form-data; name=\\\"file\\\"; filename=\\\"%s\\\"\", fileName) // TODO: escape fileName?\n ));\n MultipartContent content = new MultipartContent()\n .setMediaType(new HttpMediaType(\"multipart/form-data\").setParameter(\"boundary\", UUID.randomUUID().toString()))\n .addPart(part);\n\n String path = String.format(\"/tasks/%s/attachments\", task);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"POST\")\n .data(content);\n }"
] |
This method writes task data to an MSPDI file.
@param project Root node of the MSPDI file | [
"private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }"
] | [
"public static dnspolicy_dnspolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnspolicylabel_binding obj = new dnspolicy_dnspolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnspolicylabel_binding response[] = (dnspolicy_dnspolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public AppMsg setLayoutGravity(int gravity) {\n mLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, gravity);\n return this;\n }",
"@Override\n public final int getInt(final int i) {\n int val = this.array.optInt(i, Integer.MIN_VALUE);\n if (val == Integer.MIN_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }",
"public 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 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}",
"public static final FieldType getInstance(int fieldID)\n {\n FieldType result;\n int prefix = fieldID & 0xFFFF0000;\n int index = fieldID & 0x0000FFFF;\n\n switch (prefix)\n {\n case MPPTaskField.TASK_FIELD_BASE:\n {\n result = MPPTaskField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(TaskField.class, index);\n }\n break;\n }\n\n case MPPResourceField.RESOURCE_FIELD_BASE:\n {\n result = MPPResourceField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(ResourceField.class, index);\n }\n break;\n }\n\n case MPPAssignmentField.ASSIGNMENT_FIELD_BASE:\n {\n result = MPPAssignmentField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(AssignmentField.class, index);\n }\n break;\n }\n\n case MPPConstraintField.CONSTRAINT_FIELD_BASE:\n {\n result = MPPConstraintField.getInstance(index);\n if (result == null)\n {\n result = getPlaceholder(ConstraintField.class, index);\n }\n break;\n }\n\n default:\n {\n result = getPlaceholder(null, index);\n break;\n }\n }\n\n return result;\n }",
"public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) {\n try {\n return cast(resourceLoader.classForName(className));\n } catch (ResourceLoadingException e) {\n return null;\n } catch (SecurityException e) {\n return null;\n }\n }",
"private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }",
"public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] |
Performs an inline lower Cholesky decomposition on an inner row-major matrix. Only
the lower triangular portion of the matrix is read or written to.
@param T Array containing an inner row-major matrix. Modified.
@param indexT First index of the inner row-major matrix.
@param n Number of rows and columns of the matrix.
@return If the decomposition succeeded. | [
"public static boolean lower( double[]T , int indexT , int n ) {\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = T[ indexT + j*n+i];\n\n // todo optimize\n for( int k = 0; k < i; k++ ) {\n sum -= T[ indexT + i*n+k] * T[ indexT + j*n+k];\n }\n\n if( i == j ) {\n // is it positive-definite?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n T[ indexT + i*n+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n T[ indexT + j*n+i] = sum*div_el_ii;\n }\n }\n }\n\n return true;\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 String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }",
"public synchronized void addMapStats(\n final MapfishMapContext mapContext, final MapAttribute.MapAttributeValues mapValues) {\n this.mapStats.add(new MapStats(mapContext, mapValues));\n }",
"public static Document readDocumentFromString(String s) throws Exception {\r\n InputSource in = new InputSource(new StringReader(s));\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(false);\r\n return factory.newDocumentBuilder().parse(in);\r\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 }",
"public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }",
"public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }",
"private double sumSquaredDiffs()\n { \n double mean = getArithmeticMean();\n double squaredDiffs = 0;\n for (int i = 0; i < getSize(); i++)\n {\n double diff = mean - dataSet[i];\n squaredDiffs += (diff * diff);\n }\n return squaredDiffs;\n }",
"public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }"
] |
Handles Multi Channel Encapsulation message. Decapsulates
an Application Command message and handles it using the right
endpoint.
@param serialMessage the serial message to process.
@param offset the offset at which to start procesing. | [
"private void handleMultiChannelEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-channel Encapsulation\");\r\n\t\tCommandClass commandClass;\r\n\t\tZWaveCommandClass zwaveCommandClass;\r\n\t\tint endpointId = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 2);\r\n\t\tcommandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\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\tZWaveEndpoint endpoint = this.endpoints.get(endpointId);\r\n\t\t\r\n\t\tif (endpoint == null){\r\n\t\t\tlogger.error(\"Endpoint {} not found on node {}. Cannot set command classes.\", endpoint, this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tzwaveCommandClass = endpoint.getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.warn(String.format(\"CommandClass %s (0x%02x) not implemented by endpoint %d, fallback to main node.\", commandClass.getLabel(), commandClassCode, endpointId));\r\n\t\t\tzwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t}\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"CommandClass %s (0x%02x) not implemented by node %d.\", commandClass.getLabel(), commandClassCode, this.getNode().getNodeId()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Endpoint = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), endpointId));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset + 3, endpointId);\r\n\t}"
] | [
"public int size() {\n\t\tint size = cleared ? 0 : snapshot.size();\n\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\tcase PUT:\n\t\t\t\t\tif ( cleared || !snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize++;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tif ( !cleared && snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn size;\n\t}",
"private void deliverAlbumArtUpdate(int player, AlbumArt art) {\n if (!getAlbumArtListeners().isEmpty()) {\n final AlbumArtUpdate update = new AlbumArtUpdate(player, art);\n for (final AlbumArtListener listener : getAlbumArtListeners()) {\n try {\n listener.albumArtChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering album art update to listener\", t);\n }\n }\n }\n }",
"public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }",
"public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\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 void enableCustomResponse(String custom, int path_id, String client_uuid) throws Exception {\n\n updateRequestResponseTables(\"custom_response\", custom, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }",
"public byte[] getByteArray(int offset)\n {\n byte[] result = null;\n\n if (offset > 0 && offset < m_data.length)\n {\n int nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n int itemSize = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n if (itemSize > 0 && itemSize < m_data.length)\n {\n int blockRemainingSize = 28;\n\n if (nextBlockOffset != -1 || itemSize <= blockRemainingSize)\n {\n int itemRemainingSize = itemSize;\n result = new byte[itemSize];\n int resultOffset = 0;\n\n while (nextBlockOffset != -1)\n {\n MPPUtility.getByteArray(m_data, offset, blockRemainingSize, result, resultOffset);\n resultOffset += blockRemainingSize;\n offset += blockRemainingSize;\n itemRemainingSize -= blockRemainingSize;\n\n if (offset != nextBlockOffset)\n {\n offset = nextBlockOffset;\n }\n\n nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n blockRemainingSize = 32;\n }\n\n MPPUtility.getByteArray(m_data, offset, itemRemainingSize, result, resultOffset);\n }\n }\n }\n\n return (result);\n }",
"private String getDatatypeLabel(DatatypeIdValue datatype) {\n\t\tif (datatype.getIri() == null) { // TODO should be redundant once the\n\t\t\t\t\t\t\t\t\t\t\t// JSON parsing works\n\t\t\treturn \"Unknown\";\n\t\t}\n\n\t\tswitch (datatype.getIri()) {\n\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\t\treturn \"Commons media\";\n\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\t\treturn \"Globe coordinates\";\n\t\tcase DatatypeIdValue.DT_ITEM:\n\t\t\treturn \"Item\";\n\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\treturn \"Quantity\";\n\t\tcase DatatypeIdValue.DT_STRING:\n\t\t\treturn \"String\";\n\t\tcase DatatypeIdValue.DT_TIME:\n\t\t\treturn \"Time\";\n\t\tcase DatatypeIdValue.DT_URL:\n\t\t\treturn \"URL\";\n\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\t\treturn \"Property\";\n\t\tcase DatatypeIdValue.DT_EXTERNAL_ID:\n\t\t\treturn \"External identifier\";\n\t\tcase DatatypeIdValue.DT_MATH:\n\t\t\treturn \"Math\";\n\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\treturn \"Monolingual Text\";\n\t\tdefault:\n\t\t\tthrow new RuntimeException(\"Unknown datatype \" + datatype.getIri());\n\t\t}\n\t}",
"public boolean rename(final File from, final File to) {\n boolean renamed = false;\n if (this.isWriteable(from)) {\n renamed = from.renameTo(to);\n } else {\n LogLog.debug(from + \" is not writeable for rename (retrying)\");\n }\n if (!renamed) {\n from.renameTo(to);\n renamed = (!from.exists());\n }\n return renamed;\n }"
] |
Returns the compact records for all sections in the specified project.
@param project The project to get sections from.
@return Request object | [
"public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }"
] | [
"public static GVRCameraRig makeInstance(GVRContext gvrContext) {\n final GVRCameraRig result = gvrContext.getApplication().getDelegate().makeCameraRig(gvrContext);\n result.init(gvrContext);\n return result;\n }",
"public static gslbservice get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice response = (gslbservice) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void addFieldDescriptor(FieldDescriptor fld)\r\n {\r\n fld.setClassDescriptor(this); // BRJ\r\n if (m_FieldDescriptions == null)\r\n {\r\n m_FieldDescriptions = new FieldDescriptor[1];\r\n m_FieldDescriptions[0] = fld;\r\n }\r\n else\r\n {\r\n int size = m_FieldDescriptions.length;\r\n FieldDescriptor[] tmpArray = new FieldDescriptor[size + 1];\r\n System.arraycopy(m_FieldDescriptions, 0, tmpArray, 0, size);\r\n tmpArray[size] = fld;\r\n m_FieldDescriptions = tmpArray;\r\n // 2. Sort fields according to their getOrder() Property\r\n Arrays.sort(m_FieldDescriptions, FieldDescriptor.getComparator());\r\n }\r\n\r\n m_fieldDescriptorNameMap = null;\r\n m_PkFieldDescriptors = null;\r\n m_nonPkFieldDescriptors = null;\r\n m_lockingFieldDescriptors = null;\r\n m_RwFieldDescriptors = null;\r\n m_RwNonPkFieldDescriptors = null;\r\n }",
"public static void 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 ComplexNumber Multiply(ComplexNumber z1, ComplexNumber z2) {\r\n double z1R = z1.real, z1I = z1.imaginary;\r\n double z2R = z2.real, z2I = z2.imaginary;\r\n\r\n return new ComplexNumber(z1R * z2R - z1I * z2I, z1R * z2I + z1I * z2R);\r\n }",
"private void modifyBeliefCount(int count){\n introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null);\n }",
"public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }",
"public boolean hasRequiredMiniFluoProps() {\n boolean valid = true;\n if (getMiniStartAccumulo()) {\n // ensure that client properties are not set since we are using MiniAccumulo\n valid &= verifyStringPropNotSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_ZOOKEEPERS_PROP, CLIENT_ACCUMULO_ZOOKEEPERS_PROP);\n valid &= verifyStringPropNotSet(CONNECTION_ZOOKEEPERS_PROP, CLIENT_ZOOKEEPER_CONNECT_PROP);\n if (valid == false) {\n log.error(\"Client properties should not be set in your configuration if MiniFluo is \"\n + \"configured to start its own accumulo (indicated by fluo.mini.start.accumulo being \"\n + \"set to true)\");\n }\n } else {\n valid &= hasRequiredClientProps();\n valid &= hasRequiredAdminProps();\n valid &= hasRequiredOracleProps();\n valid &= hasRequiredWorkerProps();\n }\n return valid;\n }",
"private String toSQLPattern(String attribute) {\n String pattern = attribute.replace(\"*\", \"%\");\n if (!pattern.startsWith(\"%\")) {\n pattern = \"%\" + pattern;\n }\n if (!pattern.endsWith(\"%\")) {\n pattern = pattern.concat(\"%\");\n }\n return pattern;\n }"
] |
Read an optional boolean value form a JSON value.
@param val the JSON value that should represent the boolean.
@return the boolean from the JSON or null if reading the boolean fails. | [
"private Boolean readOptionalBoolean(JSONValue val) {\n\n JSONBoolean b = null == val ? null : val.isBoolean();\n if (b != null) {\n return Boolean.valueOf(b.booleanValue());\n }\n return null;\n }"
] | [
"private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }",
"private void appendClazzColumnForSelect(StringBuffer buf)\r\n {\r\n ClassDescriptor cld = getSearchClassDescriptor();\r\n ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);\r\n\r\n if (clds.length == 0)\r\n {\r\n return;\r\n }\r\n \r\n buf.append(\",CASE\");\r\n\r\n for (int i = clds.length; i > 0; i--)\r\n {\r\n buf.append(\" WHEN \");\r\n\r\n ClassDescriptor subCld = clds[i - 1];\r\n FieldDescriptor[] fieldDescriptors = subCld.getPkFields();\r\n\r\n TableAlias alias = getTableAliasForClassDescriptor(subCld);\r\n for (int j = 0; j < fieldDescriptors.length; j++)\r\n {\r\n FieldDescriptor field = fieldDescriptors[j];\r\n if (j > 0)\r\n {\r\n buf.append(\" AND \");\r\n }\r\n appendColumn(alias, field, buf);\r\n buf.append(\" IS NOT NULL\");\r\n }\r\n buf.append(\" THEN '\").append(subCld.getClassNameOfObject()).append(\"'\");\r\n }\r\n buf.append(\" ELSE '\").append(cld.getClassNameOfObject()).append(\"'\");\r\n buf.append(\" END AS \" + SqlHelper.OJB_CLASS_COLUMN);\r\n }",
"public void deleteDescriptorIfNecessary() throws CmsException {\n\n if (m_removeDescriptorOnCancel && (m_desc != null)) {\n m_cms.deleteResource(m_desc, CmsResourceDeleteMode.valueOf(2));\n }\n\n }",
"public static base_response update(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable updateresource = new bridgetable();\n\t\tupdateresource.bridgeage = resource.bridgeage;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public ItemRequest<Story> findById(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"GET\");\n }",
"public GeoMultiPoint addPoint(GeoPoint point) {\n\t\tContracts.assertNotNull( point, \"point\" );\n\t\tthis.points.add( point );\n\t\treturn this;\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 }",
"@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException\n {\n try\n {\n populateMemberData(reader, file, root);\n processProjectProperties();\n\n if (!reader.getReadPropertiesOnly())\n {\n processSubProjectData();\n processGraphicalIndicators();\n processCustomValueLists();\n processCalendarData();\n processResourceData();\n processTaskData();\n processConstraintData();\n processAssignmentData();\n postProcessTasks();\n\n if (reader.getReadPresentationData())\n {\n processViewPropertyData();\n processTableData();\n processViewData();\n processFilterData();\n processGroupData();\n processSavedViewState();\n }\n }\n }\n\n finally\n {\n clearMemberData();\n }\n }",
"private void setRawDirection(SwipyRefreshLayoutDirection direction) {\n if (mDirection == direction) {\n return;\n }\n\n mDirection = direction;\n switch (mDirection) {\n case BOTTOM:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();\n break;\n case TOP:\n default:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();\n break;\n }\n }"
] |
Select calendar data from the database.
@throws SQLException | [
"private void processCalendars() throws SQLException\n {\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_CALENDARS WHERE PROJ_ID=?\", m_projectID))\n {\n processCalendar(row);\n }\n\n updateBaseCalendarNames();\n\n processCalendarData(m_project.getCalendars());\n }"
] | [
"private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }",
"public static ConstraintField getInstance(int value)\n {\n ConstraintField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n\n return (result);\n }",
"public void setValue(Quaternionf rot) {\n mX = rot.x;\n mY = rot.y;\n mZ = rot.z;\n mW = rot.w;\n }",
"public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException\r\n {\r\n return newInstance(target, types, args, false);\r\n }",
"private static String resolveJavaCommand(final Path javaHome) {\n final String exe;\n if (javaHome == null) {\n exe = \"java\";\n } else {\n exe = javaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n return exe;\n }",
"private int getPrototypeIndex(Renderer renderer) {\n int index = 0;\n for (Renderer prototype : prototypes) {\n if (prototype.getClass().equals(renderer.getClass())) {\n break;\n }\n index++;\n }\n return index;\n }",
"protected void buildSuperJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)\r\n {\r\n ClassDescriptor superCld = cld.getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n SuperReferenceDescriptor superRef = cld.getSuperReference();\r\n FieldDescriptor[] leftFields = superRef.getForeignKeyFieldDescriptors(cld);\r\n TableAlias base_alias = getTableAliasForPath(name, null, null);\r\n String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;\r\n TableAlias right = new TableAlias(superCld, aliasName, useOuterJoin, null);\r\n\r\n Join join1to1 = new Join(left, leftFields, right, superCld.getPkFields(), useOuterJoin, \"superClass\");\r\n base_alias.addJoin(join1to1);\r\n\r\n buildSuperJoinTree(right, superCld, name, useOuterJoin);\r\n }\r\n }",
"private void readExceptionDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay day)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod timePeriod = day.getTimePeriod();\n Date fromDate = timePeriod.getFromDate();\n Date toDate = timePeriod.getToDate();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = day.getWorkingTimes();\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n\n if (times != null)\n {\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n exception.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"public <Result, Param extends Resource> Result execWithoutCacheClear(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\ttry {\n\t\t\tcacheAdapter.ignoreNotifications();\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tcacheAdapter.listenToNotifications();\n\t\t}\n\t}"
] |
Use this API to unset the properties of aaaparameter resource.
Properties that need to be unset are specified in args array. | [
"public static base_response unset(nitro_service client, aaaparameter resource, String[] args) throws Exception{\n\t\taaaparameter unsetresource = new aaaparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] | [
"public String pop() {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.spop(getKey());\n }\n });\n }",
"public GeoMultiPoint addPoint(GeoPoint point) {\n\t\tContracts.assertNotNull( point, \"point\" );\n\t\tthis.points.add( point );\n\t\treturn this;\n\t}",
"private org.apache.tools.ant.types.Path resolveFiles(org.apache.tools.ant.types.Path path) {\n org.apache.tools.ant.types.Path cloned = new org.apache.tools.ant.types.Path(getProject());\n for (String location : path.list()) {\n cloned.createPathElement().setLocation(new File(location));\n }\n return cloned;\n }",
"public BlurBuilder brightness(float brightness) {\n data.preProcessors.add(new RenderscriptBrightnessProcessor(data.contextWrapper.getRenderScript(), brightness, data.contextWrapper.getResources()));\n return this;\n }",
"void addSomeValuesRestriction(Resource subject, String propertyUri,\n\t\t\tString rangeUri) {\n\t\tthis.someValuesQueue.add(new PropertyRestriction(subject, propertyUri,\n\t\t\t\trangeUri));\n\t}",
"public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }",
"@Override\n\tpublic IPAddress toAddress() throws UnknownHostException, HostNameException {\n\t\tIPAddress addr = resolvedAddress;\n\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t//note that validation handles empty address resolution\n\t\t\tvalidate();\n\t\t\tsynchronized(this) {\n\t\t\t\taddr = resolvedAddress;\n\t\t\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t\t\tif(parsedHost.isAddressString()) {\n\t\t\t\t\t\taddr = parsedHost.asAddress();\n\t\t\t\t\t\tresolvedIsNull = (addr == null);\n\t\t\t\t\t\t//note there is no need to apply prefix or mask here, it would have been applied to the address already\n\t\t\t\t\t} else {\n\t\t\t\t\t\tString strHost = parsedHost.getHost();\n\t\t\t\t\t\tif(strHost.length() == 0 && !validationOptions.emptyIsLoopback) {\n\t\t\t\t\t\t\taddr = null;\n\t\t\t\t\t\t\tresolvedIsNull = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//Note we do not set resolvedIsNull, so we will attempt to resolve again if the previous attempt threw an exception\n\t\t\t\t\t\t\tInetAddress inetAddress = InetAddress.getByName(strHost);\n\t\t\t\t\t\t\tbyte bytes[] = inetAddress.getAddress();\n\t\t\t\t\t\t\tInteger networkPrefixLength = parsedHost.getNetworkPrefixLength();\n\t\t\t\t\t\t\tif(networkPrefixLength == null) {\n\t\t\t\t\t\t\t\tIPAddress mask = parsedHost.getMask();\n\t\t\t\t\t\t\t\tif(mask != null) {\n\t\t\t\t\t\t\t\t\tbyte maskBytes[] = mask.getBytes();\n\t\t\t\t\t\t\t\t\tif(maskBytes.length != bytes.length) {\n\t\t\t\t\t\t\t\t\t\tthrow new HostNameException(host, \"ipaddress.error.ipMismatch\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfor(int i = 0; i < bytes.length; i++) {\n\t\t\t\t\t\t\t\t\t\tbytes[i] &= maskBytes[i];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tnetworkPrefixLength = mask.getBlockMaskPrefixLength(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tIPAddressStringParameters addressParams = validationOptions.addressOptions;\n\t\t\t\t\t\t\tif(bytes.length == IPv6Address.BYTE_COUNT) {\n\t\t\t\t\t\t\t\tIPv6AddressCreator creator = addressParams.getIPv6Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, null, this); /* address creation */\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tIPv4AddressCreator creator = addressParams.getIPv4Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, this); /* address creation */\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tresolvedAddress = addr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn addr;\n\t}",
"public static RouteInfo of(ActionContext context) {\n H.Method m = context.req().method();\n String path = context.req().url();\n RequestHandler handler = context.handler();\n if (null == handler) {\n handler = UNKNOWN_HANDLER;\n }\n return new RouteInfo(m, path, handler);\n }",
"public int getChunkForKey(byte[] key) throws IllegalStateException {\n if(numChunks == 0) {\n throw new IllegalStateException(\"The ChunkedFileSet is closed.\");\n }\n\n switch(storageFormat) {\n case READONLY_V0: {\n return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks);\n }\n case READONLY_V1: {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n routingPartitionList.retainAll(nodePartitionIds);\n\n if(routingPartitionList.size() != 1) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n return chunkIdToChunkStart.get(routingPartitionList.get(0))\n + ReadOnlyUtils.chunk(ByteUtils.md5(key),\n chunkIdToNumChunks.get(routingPartitionList.get(0)));\n }\n case READONLY_V2: {\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n\n Pair<Integer, Integer> bucket = null;\n for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) {\n if(bucket == null) {\n bucket = Pair.create(routingPartitionList.get(0), replicaType);\n } else {\n throw new IllegalStateException(\"Found more than one replica for a given partition on the current node!\");\n }\n }\n }\n\n if(bucket == null) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n Integer chunkStart = chunkIdToChunkStart.get(bucket);\n\n if (chunkStart == null) {\n throw new IllegalStateException(\"chunkStart is null.\");\n }\n\n return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket));\n }\n default: {\n throw new IllegalStateException(\"Unsupported storageFormat: \" + storageFormat);\n }\n }\n\n }"
] |
Prepare a parallel HTTP DELETE Task.
@param url
the UrlPostfix: e.g. in http://localhost:8080/index.html.,the url is "/index.html"
@return the parallel task builder | [
"public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }"
] | [
"public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }",
"private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, boolean logDetails) {\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\tdatabaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter);\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"dropping table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"DROP TABLE \");\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(' ');\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t}",
"public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}",
"@Deprecated\n @SuppressWarnings(\"deprecation\")\n public void push(String eventName, HashMap<String, Object> chargeDetails,\n ArrayList<HashMap<String, Object>> items)\n throws InvalidEventNameException {\n // This method is for only charged events\n if (!eventName.equals(Constants.CHARGED_EVENT)) {\n throw new InvalidEventNameException(\"Not a charged event\");\n }\n CleverTapAPI cleverTapAPI = weakReference.get();\n if(cleverTapAPI == null){\n Logger.d(\"CleverTap Instance is null.\");\n } else {\n cleverTapAPI.pushChargedEvent(chargeDetails, items);\n }\n }",
"public static PipelineConfiguration.Builder parse(ModelNode json) {\n ModelNode analyzerIncludeNode = json.get(\"analyzers\").get(\"include\");\n ModelNode analyzerExcludeNode = json.get(\"analyzers\").get(\"exclude\");\n ModelNode filterIncludeNode = json.get(\"filters\").get(\"include\");\n ModelNode filterExcludeNode = json.get(\"filters\").get(\"exclude\");\n ModelNode transformIncludeNode = json.get(\"transforms\").get(\"include\");\n ModelNode transformExcludeNode = json.get(\"transforms\").get(\"exclude\");\n ModelNode reporterIncludeNode = json.get(\"reporters\").get(\"include\");\n ModelNode reporterExcludeNode = json.get(\"reporters\").get(\"exclude\");\n\n return builder()\n .withTransformationBlocks(json.get(\"transformBlocks\"))\n .withAnalyzerExtensionIdsInclude(asStringList(analyzerIncludeNode))\n .withAnalyzerExtensionIdsExclude(asStringList(analyzerExcludeNode))\n .withFilterExtensionIdsInclude(asStringList(filterIncludeNode))\n .withFilterExtensionIdsExclude(asStringList(filterExcludeNode))\n .withTransformExtensionIdsInclude(asStringList(transformIncludeNode))\n .withTransformExtensionIdsExclude(asStringList(transformExcludeNode))\n .withReporterExtensionIdsInclude(asStringList(reporterIncludeNode))\n .withReporterExtensionIdsExclude(asStringList(reporterExcludeNode));\n }",
"public ArrayList getFields(String fieldNames) throws NoSuchFieldException\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new NoSuchFieldException(name);\r\n }\r\n result.add(fieldDef);\r\n }\r\n return result;\r\n }",
"@Override\r\n public V get(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V deltaResult = deltaMap.get(key);\r\n if (deltaResult == null) {\r\n return originalMap.get(key);\r\n }\r\n if (deltaResult == nullValue) {\r\n return null;\r\n }\r\n if (deltaResult == removedValue) {\r\n return null;\r\n }\r\n return deltaResult;\r\n }",
"private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }",
"public static base_response delete(nitro_service client, String viewname) throws Exception {\n\t\tdnsview deleteresource = new dnsview();\n\t\tdeleteresource.viewname = viewname;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] |
Executes the given transaction within the context of a write lock.
@param t The transaction to execute. | [
"protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }"
] | [
"private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}",
"public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }",
"public JsonNode apply(final JsonNode node) {\n requireNonNull(node, \"node\");\n JsonNode ret = node.deepCopy();\n for (final JsonPatchOperation operation : operations) {\n ret = operation.apply(ret);\n }\n\n return ret;\n }",
"public static <T, R extends Resource<T>> T getEntity(R resource) {\n return resource.getEntity();\n }",
"public void flush() throws IOException {\n if (unflushed.get() == 0) return;\n\n synchronized (lock) {\n if (logger.isTraceEnabled()) {\n logger.debug(\"Flushing log '\" + name + \"' last flushed: \" + getLastFlushedTime() + \" current time: \" + System\n .currentTimeMillis());\n }\n segments.getLastView().getMessageSet().flush();\n unflushed.set(0);\n lastflushedTime.set(System.currentTimeMillis());\n }\n }",
"public void process(CustomFieldContainer indicators, ProjectProperties properties, Props props)\n {\n m_container = indicators;\n m_properties = properties;\n m_data = props.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n\n if (m_data != null)\n {\n int columnsCount = MPPUtility.getInt(m_data, 4);\n m_headerOffset = 8;\n for (int loop = 0; loop < columnsCount; loop++)\n {\n processColumns();\n }\n }\n }",
"private static float angleDeg(final float ax, final float ay,\n final float bx, final float by) {\n final double angleRad = Math.atan2(ay - by, ax - bx);\n double angle = Math.toDegrees(angleRad);\n if (angleRad < 0) {\n angle += 360;\n }\n return (float) angle;\n }",
"private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }",
"private Month readOptionalMonth(JSONValue val) {\n\n String str = readOptionalString(val);\n if (null != str) {\n try {\n return Month.valueOf(str);\n } catch (@SuppressWarnings(\"unused\") IllegalArgumentException e) {\n // Do nothing -return the default value\n }\n }\n return null;\n }"
] |
This method processes a single deferred relationship list.
@param dr deferred relationship list data
@throws MPXJException | [
"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 }"
] | [
"public static List<Integer> asList(int[] a) {\r\n List<Integer> result = new ArrayList<Integer>(a.length);\r\n for (int i = 0; i < a.length; i++) {\r\n result.add(Integer.valueOf(a[i]));\r\n }\r\n return result;\r\n }",
"private boolean skipBar(Row row)\n {\n List<Row> childRows = row.getChildRows();\n return childRows.size() == 1 && childRows.get(0).getChildRows().isEmpty();\n }",
"@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }",
"public static NbtAddress[] getAllByAddress( NbtAddress addr )\n throws UnknownHostException {\n try {\n NbtAddress[] addrs = CLIENT.getNodeStatus( addr );\n cacheAddressArray( addrs );\n return addrs;\n } catch( UnknownHostException uhe ) {\n throw new UnknownHostException( \"no name with type 0x\" +\n Hexdump.toHexString( addr.hostName.hexCode, 2 ) +\n ((( addr.hostName.scope == null ) ||\n ( addr.hostName.scope.length() == 0 )) ?\n \" with no scope\" : \" with scope \" + addr.hostName.scope ) +\n \" for host \" + addr.getHostAddress() );\n }\n }",
"protected void onRemoveParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onRemoveOwnersParent(parent);\n }\n }",
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }",
"List<List<Word>> getDifferentArguments( List<List<Word>> argumentWords ) {\n List<List<Word>> result = Lists.newArrayList();\n for( int i = 0; i < argumentWords.size(); i++ ) {\n result.add( Lists.<Word>newArrayList() );\n }\n\n int nWords = argumentWords.get( 0 ).size();\n\n for( int iWord = 0; iWord < nWords; iWord++ ) {\n Word wordOfFirstCase = argumentWords.get( 0 ).get( iWord );\n\n // data tables have equal here, otherwise\n // the cases would be structurally different\n if( wordOfFirstCase.isDataTable() ) {\n continue;\n }\n\n boolean different = false;\n for( int iCase = 1; iCase < argumentWords.size(); iCase++ ) {\n Word wordOfCase = argumentWords.get( iCase ).get( iWord );\n if( !wordOfCase.getFormattedValue().equals( wordOfFirstCase.getFormattedValue() ) ) {\n different = true;\n break;\n }\n\n }\n if( different ) {\n for( int iCase = 0; iCase < argumentWords.size(); iCase++ ) {\n result.get( iCase ).add( argumentWords.get( iCase ).get( iWord ) );\n }\n }\n }\n\n return result;\n }",
"public static aaapreauthenticationpolicy_aaaglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_aaaglobal_binding obj = new aaapreauthenticationpolicy_aaaglobal_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_aaaglobal_binding response[] = (aaapreauthenticationpolicy_aaaglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\taddDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);\n\t}"
] |
Use this API to fetch all the gslbrunningconfig resources that are configured on netscaler. | [
"public static gslbrunningconfig get(nitro_service service) throws Exception{\n\t\tgslbrunningconfig obj = new gslbrunningconfig();\n\t\tgslbrunningconfig[] response = (gslbrunningconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException {\n build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(),\n getSvnAuthenticationProvider(build), buildListener));\n }",
"public void setProductModules(final String name, final List<String> moduleNames) {\n final DbProduct dbProduct = getProduct(name);\n dbProduct.setModules(moduleNames);\n repositoryHandler.store(dbProduct);\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 }",
"private static void flushCurrentWord( StringBuilder currentWords, List<Word> formattedWords, boolean cutWhitespace ) {\n if( currentWords.length() > 0 ) {\n if( cutWhitespace && currentWords.charAt( currentWords.length() - 1 ) == ' ' ) {\n currentWords.setLength( currentWords.length() - 1 );\n }\n formattedWords.add( new Word( currentWords.toString() ) );\n currentWords.setLength( 0 );\n }\n }",
"protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) {\n if (value == null) {\n return \"\";\n }\n else {\n // midnight GMT\n Date date = new Date(0);\n // offset by timezone and value\n date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue());\n // format it\n return fmt.format(date);\n }\n }",
"public void sendEventsFromQueue() {\n if (null == queue || stopSending) {\n return;\n }\n LOG.fine(\"Scheduler called for sending events\");\n\n int packageSize = getEventsPerMessageCall();\n\n while (!queue.isEmpty()) {\n final List<Event> list = new ArrayList<Event>();\n int i = 0;\n while (i < packageSize && !queue.isEmpty()) {\n Event event = queue.remove();\n if (event != null && !filter(event)) {\n list.add(event);\n i++;\n }\n }\n if (list.size() > 0) {\n executor.execute(new Runnable() {\n public void run() {\n try {\n sendEvents(list);\n } catch (MonitoringException e) {\n e.logException(Level.SEVERE);\n }\n }\n });\n\n }\n }\n\n }",
"public int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }",
"private void readTaskCustomPropertyDefinitions(Tasks gpTasks)\n {\n for (Taskproperty definition : gpTasks.getTaskproperties().getTaskproperty())\n {\n //\n // Ignore everything but custom values\n //\n if (!\"custom\".equals(definition.getType()))\n {\n continue;\n }\n\n //\n // Find the next available field of the correct type.\n //\n String type = definition.getValuetype();\n FieldType fieldType = TASK_PROPERTY_TYPES.get(type).getField();\n\n //\n // If we have run out of fields of the right type, try using a text field.\n //\n if (fieldType == null)\n {\n fieldType = TASK_PROPERTY_TYPES.get(\"text\").getField();\n }\n\n //\n // If we actually have a field available, set the alias to match\n // the name used in GanttProject.\n //\n if (fieldType != null)\n {\n CustomField field = m_projectFile.getCustomFields().getCustomField(fieldType);\n field.setAlias(definition.getName());\n String defaultValue = definition.getDefaultvalue();\n if (defaultValue != null && defaultValue.isEmpty())\n {\n defaultValue = null;\n }\n m_taskPropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue));\n }\n }\n }",
"void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException {\n persist(key, value, enableDisableMode, disable, file, null);\n }"
] |
Get a property as a json array or default.
@param key the property name
@param defaultValue default | [
"public final PJsonArray optJSONArray(final String key, final PJsonArray defaultValue) {\n PJsonArray result = optJSONArray(key);\n return result != null ? result : defaultValue;\n }"
] | [
"@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }",
"public ItemRequest<Tag> createInWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/tags\", workspace);\n return new ItemRequest<Tag>(this, Tag.class, path, \"POST\");\n }",
"public static String simpleTypeName(Object obj) {\n if (obj == null) {\n return \"null\";\n }\n\n return simpleTypeName(obj.getClass(), false);\n }",
"public float getBitangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_bitangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"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 RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}",
"void unbind(String key)\r\n {\r\n NamedEntry entry = new NamedEntry(key, null, false);\r\n localUnbind(key);\r\n addForDeletion(entry);\r\n }",
"public void serializeTimingData(Path outputPath)\n {\n //merge subThreads instances into the main instance\n merge();\n\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n fw.write(\"Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\\n\");\n for (Map.Entry<String, TimingData> timing : executionInfo.entrySet())\n {\n TimingData data = timing.getValue();\n long totalMillis = (data.totalNanos / 1000000);\n double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions;\n fw.write(String.format(\"%6d, %6d, %8.2f, %s\\n\",\n data.numberOfExecutions, totalMillis, millisPerExecution,\n StringEscapeUtils.escapeCsv(timing.getKey())\n ));\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }",
"private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }"
] |
Creates the code mappings.
@param mtasTokenIdFactory
the mtas token id factory
@param level
the level
@param stringValue
the string value
@param offsetStart
the offset start
@param offsetEnd
the offset end
@param realOffsetStart
the real offset start
@param realOffsetEnd
the real offset end
@param codePositions
the code positions
@throws IOException
Signals that an I/O exception has occurred. | [
"private void createCodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int realOffsetStart, int realOffsetEnd, List<Integer> codePositions)\n throws IOException {\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, filterString(stringValues[0].trim()));\n token.setOffset(offsetStart, offsetEnd);\n token.setRealOffset(realOffsetStart, realOffsetEnd);\n token.addPositions(codePositions.stream().mapToInt(i -> i).toArray());\n tokenCollection.add(token);\n level.tokens.add(token);\n }"
] | [
"private void insert(int position, int c) {\r\n for (int i = 143; i > position; i--) {\r\n set[i] = set[i - 1];\r\n character[i] = character[i - 1];\r\n }\r\n character[position] = c;\r\n }",
"private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }",
"private void clearDeck(TrackMetadataUpdate update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverBeatGridUpdate(update.player, null);\n }\n }",
"public static void doPriorityEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) {\n jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n jedis.lpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }",
"private void emitSuiteEnd(AggregatedSuiteResultEvent e, int suitesCompleted) throws IOException {\n assert showSuiteSummary;\n\n final StringBuilder b = new StringBuilder();\n final int totalErrors = this.totalErrors.addAndGet(e.isSuccessful() ? 0 : 1);\n b.append(String.format(Locale.ROOT, \"%sCompleted [%d/%d%s]%s in %.2fs, \",\n shortTimestamp(e.getStartTimestamp() + e.getExecutionTime()),\n suitesCompleted,\n totalSuites,\n totalErrors == 0 ? \"\" : \" (\" + totalErrors + \"!)\",\n e.getSlave().slaves > 1 ? \" on J\" + e.getSlave().id : \"\",\n e.getExecutionTime() / 1000.0d));\n b.append(e.getTests().size()).append(Pluralize.pluralize(e.getTests().size(), \" test\"));\n\n int failures = e.getFailureCount();\n if (failures > 0) {\n b.append(\", \").append(failures).append(Pluralize.pluralize(failures, \" failure\"));\n }\n\n int errors = e.getErrorCount();\n if (errors > 0) {\n b.append(\", \").append(errors).append(Pluralize.pluralize(errors, \" error\"));\n }\n\n int ignored = e.getIgnoredCount();\n if (ignored > 0) {\n b.append(\", \").append(ignored).append(\" skipped\");\n }\n\n if (!e.isSuccessful()) {\n b.append(FAILURE_STRING);\n }\n\n b.append(\"\\n\");\n logShort(b, false);\n }",
"public String getKeySchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String keySchema = schema.getField(keyFieldName).schema().toString();\n return keySchema;\n }",
"private void decreaseIndent() throws IOException\n {\n if (m_pretty)\n {\n m_writer.write('\\n');\n m_indent = m_indent.substring(0, m_indent.length() - INDENT.length());\n m_writer.write(m_indent);\n }\n m_firstNameValuePair.pop();\n }",
"public Resource addReference(Reference reference) {\n\t\tResource resource = this.rdfWriter.getUri(Vocabulary.getReferenceUri(reference));\n\n\t\tthis.referenceQueue.add(reference);\n\t\tthis.referenceSubjectQueue.add(resource);\n\n\t\treturn resource;\n\t}",
"public RedwoodConfiguration collapseExact(){\r\n tasks.add(new Runnable() { public void run() { Redwood.spliceHandler(VisibilityHandler.class, new RepeatedRecordHandler(RepeatedRecordHandler.EXACT), OutputHandler.class); } });\r\n return this;\r\n }"
] |
Attempts to insert a colon so that a value without a colon can
be parsed. | [
"protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) {\n if (text.indexOf(':') == -1) {\n text = text.replace(\" \", \"\");\n int numdigits = 0;\n int lastdigit = 0;\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (Character.isDigit(c)) {\n numdigits++;\n lastdigit = i;\n }\n }\n if (numdigits == 1 || numdigits == 2) {\n // insert :00\n int colon = lastdigit + 1;\n text = text.substring(0, colon) + \":00\" + text.substring(colon);\n }\n else if (numdigits > 2) {\n // insert :\n int colon = lastdigit - 1;\n text = text.substring(0, colon) + \":\" + text.substring(colon);\n }\n return parseUsingFallbacks(text, timeFormat);\n }\n else {\n return null;\n }\n }"
] | [
"@Override\n public EditMode editMode() {\n if(readInputrc) {\n try {\n return EditModeBuilder.builder().parseInputrc(new FileInputStream(inputrc())).create();\n }\n catch(FileNotFoundException e) {\n return EditModeBuilder.builder(mode()).create();\n }\n }\n else\n return EditModeBuilder.builder(mode()).create();\n }",
"public synchronized ControlPoint getControlPoint(final String deploymentName, final String entryPointName) {\n ControlPointIdentifier id = new ControlPointIdentifier(deploymentName, entryPointName);\n ControlPoint ep = entryPoints.get(id);\n if (ep == null) {\n ep = new ControlPoint(this, deploymentName, entryPointName, trackIndividualControlPoints);\n entryPoints.put(id, ep);\n }\n ep.increaseReferenceCount();\n return ep;\n }",
"public static TimeZone getStockTimeZone(String symbol) {\n // First check if it's a known stock index\n if(INDEX_TIMEZONES.containsKey(symbol)) {\n return INDEX_TIMEZONES.get(symbol);\n }\n \n if(!symbol.contains(\".\")) {\n return ExchangeTimeZone.get(\"\");\n }\n String[] split = symbol.split(\"\\\\.\");\n return ExchangeTimeZone.get(split[split.length - 1]);\n }",
"public boolean isPrivate() {\n\t\t// refer to RFC 1918\n // 10/8 prefix\n // 172.16/12 prefix (172.16.0.0 – 172.31.255.255)\n // 192.168/16 prefix\n\t\tIPv4AddressSegment seg0 = getSegment(0);\n\t\tIPv4AddressSegment seg1 = getSegment(1);\n\t\treturn seg0.matches(10)\n\t\t\t|| seg0.matches(172) && seg1.matchesWithPrefixMask(16, 4)\n\t\t\t|| seg0.matches(192) && seg1.matches(168);\n\t}",
"public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}",
"@Override\n public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir)\n throws DecompilationException\n {\n Checks.checkDirectoryToBeRead(rootDir.toFile(), \"Classes root dir\");\n File classFile = classFilePath.toFile();\n Checks.checkFileToBeRead(classFile, \"Class file\");\n Checks.checkDirectoryToBeFilled(outputDir.toFile(), \"Output directory\");\n\n log.info(\"Decompiling .class '\" + classFilePath + \"' to '\" + outputDir + \"' from: '\" + rootDir + \"'\");\n\n String name = classFilePath.normalize().toAbsolutePath().toString().substring(rootDir.toAbsolutePath().toString().length() + 1);\n final String typeName = StringUtils.removeEnd(name, \".class\");// .replace('/', '.');\n\n DecompilationResult result = new DecompilationResult();\n try\n {\n DecompilerSettings settings = getDefaultSettings(outputDir.toFile());\n this.procyonConf.setDecompilerSettings(settings); // TODO: This is horrible mess.\n\n final ITypeLoader typeLoader = new CompositeTypeLoader(new WindupClasspathTypeLoader(rootDir.toString()), new ClasspathTypeLoader());\n WindupMetadataSystem metadataSystem = new WindupMetadataSystem(typeLoader);\n File outputFile = this.decompileType(settings, metadataSystem, typeName);\n result.addDecompiled(Collections.singletonList(classFilePath.toString()), outputFile.getAbsolutePath());\n }\n catch (Throwable e)\n {\n DecompilationFailure failure = new DecompilationFailure(\"Error during decompilation of \"\n + classFilePath.toString() + \":\\n \" + e.getMessage(), Collections.singletonList(name), e);\n log.severe(failure.getMessage());\n result.addFailure(failure);\n }\n\n return result;\n }",
"public static String getOffsetCodeFromCurveName(String curveName) {\r\n\t\tif(curveName == null || curveName.length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tString[] splits = curveName.split(\"(?<=\\\\D)(?=\\\\d)\");\r\n\t\tString offsetCode = splits[splits.length-1];\r\n\t\tif(!Character.isDigit(offsetCode.charAt(0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\toffsetCode = offsetCode.split(\"(?<=[A-Za-z])(?=.)\", 2)[0];\r\n\t\toffsetCode = offsetCode.replaceAll( \"[\\\\W_]\", \"\" );\r\n\t\treturn offsetCode;\r\n\t}",
"private void postProcessTasks()\n {\n List<Task> allTasks = m_file.getTasks();\n if (allTasks.size() > 1)\n {\n Collections.sort(allTasks);\n\n int taskID = -1;\n int lastTaskID = -1;\n\n for (int i = 0; i < allTasks.size(); i++)\n {\n Task task = allTasks.get(i);\n taskID = NumberHelper.getInt(task.getID());\n // In Project the tasks IDs are always contiguous so we can spot invalid tasks by making sure all\n // IDs are represented.\n if (!task.getNull() && lastTaskID != -1 && taskID > lastTaskID + 1)\n {\n // This task looks to be invalid.\n task.setNull(true);\n }\n else\n {\n lastTaskID = taskID;\n }\n }\n }\n }",
"public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}"
] |
Update a feature object in the Hibernate session.
@param feature feature object
@throws LayerException oops | [
"public void update(Object feature) throws LayerException {\n\t\tSession session = getSessionFactory().getCurrentSession();\n\t\tsession.update(feature);\n\t}"
] | [
"public void postConstruct() throws URISyntaxException {\n WmsVersion.lookup(this.version);\n Assert.isTrue(validateBaseUrl(), \"invalid baseURL\");\n\n Assert.isTrue(this.layers.length > 0, \"There must be at least one layer defined for a WMS request\" +\n \" to make sense\");\n\n // OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are\n\n if (this.styles != null && this.styles.length != this.layers.length && this.styles.length == 1 &&\n this.styles[0].trim().isEmpty()) {\n this.styles = null;\n } else {\n Assert.isTrue(this.styles == null || this.layers.length == this.styles.length,\n String.format(\n \"If styles are defined then there must be one for each layer. Number of\" +\n \" layers: %s\\nStyles: %s\", this.layers.length,\n Arrays.toString(this.styles)));\n }\n\n if (this.imageFormat.indexOf('/') < 0) {\n LOGGER.warn(\"The format {} should be a mime type\", this.imageFormat);\n this.imageFormat = \"image/\" + this.imageFormat;\n }\n\n Assert.isTrue(this.method == HttpMethod.GET || this.method == HttpMethod.POST,\n String.format(\"Unsupported method %s for WMS layer\", this.method.toString()));\n }",
"public List<GanttDesignerRemark.Task> getTask()\n {\n if (task == null)\n {\n task = new ArrayList<GanttDesignerRemark.Task>();\n }\n return this.task;\n }",
"protected static <K, T> void groupAnswer(final Map<K, List<T>> answer, T element, K value) {\n if (answer.containsKey(value)) {\n answer.get(value).add(element);\n } else {\n List<T> groupedElements = new ArrayList<T>();\n groupedElements.add(element);\n answer.put(value, groupedElements);\n }\n }",
"protected void deleteConflictingResources(CmsObject cms, CmsModule module, Map<CmsUUID, CmsUUID> conflictingIds)\n throws CmsException, Exception {\n\n CmsProject conflictProject = cms.createProject(\n \"Deletion of conflicting resources for \" + module.getName(),\n \"Deletion of conflicting resources for \" + module.getName(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n CmsObject deleteCms = OpenCms.initCmsObject(cms);\n deleteCms.getRequestContext().setCurrentProject(conflictProject);\n for (CmsUUID vfsId : conflictingIds.values()) {\n CmsResource toDelete = deleteCms.readResource(vfsId, CmsResourceFilter.ALL);\n lock(deleteCms, toDelete);\n deleteCms.deleteResource(toDelete, CmsResource.DELETE_PRESERVE_SIBLINGS);\n }\n OpenCms.getPublishManager().publishProject(deleteCms);\n OpenCms.getPublishManager().waitWhileRunning();\n }",
"public double Function1D(double x) {\n return Math.exp(x * x / (-2 * sqrSigma)) / (Math.sqrt(2 * Math.PI) * sigma);\n }",
"public static String getExtensionByMimeType(String type) {\n MimeTypes types = getDefaultMimeTypes();\n try {\n return types.forName(type).getExtension();\n } catch (Exception e) {\n LOGGER.warn(\"Can't detect extension for MIME-type \" + type, e);\n return \"\";\n }\n }",
"public int[] next()\n {\n boolean hasNewPerm = false;\n\n escape:while( level >= 0) {\n// boolean foundZero = false;\n for( int i = iter[level]; i < data.length; i = iter[level] ) {\n iter[level]++;\n\n if( data[i] == -1 ) {\n level++;\n data[i] = level-1;\n\n if( level >= data.length ) {\n // a new permutation has been created return the results.\n hasNewPerm = true;\n System.arraycopy(data,0,ret,0,ret.length);\n level = level-1;\n data[i] = -1;\n break escape;\n } else {\n valk[level] = i;\n }\n }\n }\n\n data[valk[level]] = -1;\n iter[level] = 0;\n level = level-1;\n\n }\n\n if( hasNewPerm )\n return ret;\n return null;\n }",
"private List<StyleFilter> initStyleFilters(List<FeatureStyleInfo> styleDefinitions) throws GeomajasException {\n\t\tList<StyleFilter> styleFilters = new ArrayList<StyleFilter>();\n\t\tif (styleDefinitions == null || styleDefinitions.size() == 0) {\n\t\t\tstyleFilters.add(new StyleFilterImpl()); // use default.\n\t\t} else {\n\t\t\tfor (FeatureStyleInfo styleDef : styleDefinitions) {\n\t\t\t\tStyleFilterImpl styleFilterImpl = null;\n\t\t\t\tString formula = styleDef.getFormula();\n\t\t\t\tif (null != formula && formula.length() > 0) {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(filterService.parseFilter(formula), styleDef);\n\t\t\t\t} else {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(Filter.INCLUDE, styleDef);\n\t\t\t\t}\n\t\t\t\tstyleFilters.add(styleFilterImpl);\n\t\t\t}\n\t\t}\n\t\treturn styleFilters;\n\t}",
"private void loadCadidateString() {\n volumeUp = mGvrContext.getActivity().getResources().getString(R.string.volume_up);\n volumeDown = mGvrContext.getActivity().getResources().getString(R.string.volume_down);\n zoomIn = mGvrContext.getActivity().getResources().getString(R.string.zoom_in);\n zoomOut = mGvrContext.getActivity().getResources().getString(R.string.zoom_out);\n invertedColors = mGvrContext.getActivity().getResources().getString(R.string.inverted_colors);\n talkBack = mGvrContext.getActivity().getResources().getString(R.string.talk_back);\n disableTalkBack = mGvrContext.getActivity().getResources().getString(R.string.disable_talk_back);\n }"
] |
Renders in LI tags, Wraps with UL tags optionally. | [
"private void renderAsLI(Writer writer, ProjectModel project, Iterator<Link> links, boolean wrap) throws IOException\n {\n if (!links.hasNext())\n return;\n\n if (wrap)\n writer.append(\"<ul>\");\n while (links.hasNext())\n {\n Link link = links.next();\n writer.append(\"<li>\");\n renderLink(writer, project, link);\n writer.append(\"</li>\");\n }\n if (wrap)\n writer.append(\"</ul>\");\n }"
] | [
"public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }",
"public void delete(boolean notifyUser, boolean force) {\n String queryString = new QueryStringBuilder()\n .appendParam(\"notify\", String.valueOf(notifyUser))\n .appendParam(\"force\", String.valueOf(force))\n .toString();\n\n URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"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}",
"protected void processTaskBaseline(Row row)\n {\n Integer id = row.getInteger(\"TASK_UID\");\n Task task = m_project.getTaskByUniqueID(id);\n if (task != null)\n {\n int index = row.getInt(\"TB_BASE_NUM\");\n\n task.setBaselineDuration(index, MPDUtility.getAdjustedDuration(m_project, row.getInt(\"TB_BASE_DUR\"), MPDUtility.getDurationTimeUnits(row.getInt(\"TB_BASE_DUR_FMT\"))));\n task.setBaselineStart(index, row.getDate(\"TB_BASE_START\"));\n task.setBaselineFinish(index, row.getDate(\"TB_BASE_FINISH\"));\n task.setBaselineWork(index, row.getDuration(\"TB_BASE_WORK\"));\n task.setBaselineCost(index, row.getCurrency(\"TB_BASE_COST\"));\n }\n }",
"private void loadAllRemainingLocalizations() throws CmsException, UnsupportedEncodingException, IOException {\n\n if (!m_alreadyLoadedAllLocalizations) {\n // is only necessary for property bundles\n if (m_bundleType.equals(BundleType.PROPERTY)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n CmsResource resource = m_bundleFiles.get(l);\n if (resource != null) {\n CmsFile file = m_cms.readFile(resource);\n m_bundleFiles.put(l, file);\n SortedProperties props = new SortedProperties();\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_localizations.put(l, props);\n }\n }\n }\n }\n if (m_bundleType.equals(BundleType.XML)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n loadLocalizationFromXmlBundle(l);\n }\n }\n }\n m_alreadyLoadedAllLocalizations = true;\n }\n\n }",
"private void setConstraints(Task task, MapRow row)\n {\n ConstraintType constraintType = null;\n Date constraintDate = null;\n Date lateDate = row.getDate(\"CONSTRAINT_LATE_DATE\");\n Date earlyDate = row.getDate(\"CONSTRAINT_EARLY_DATE\");\n\n switch (row.getInteger(\"CONSTRAINT_TYPE\").intValue())\n {\n case 2: // Cannot Reschedule\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = task.getStart();\n break;\n }\n\n case 12: //Finish Between\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = lateDate;\n break;\n }\n\n case 10: // Finish On or After\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 11: // Finish On or Before\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = lateDate;\n break;\n }\n\n case 13: // Mandatory Start\n case 5: // Start On\n case 9: // Finish On\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 14: // Mandatory Finish\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 4: // Start As Late As Possible\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n break;\n }\n\n case 3: // Start As Soon As Possible\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n break;\n }\n\n case 8: // Start Between\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n constraintDate = earlyDate;\n break;\n }\n\n case 6: // Start On or Before\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 15: // Work Between\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n }\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"private void writeAssignment(ResourceAssignment mpxj)\n {\n ResourceAssignmentType xml = m_factory.createResourceAssignmentType();\n m_project.getResourceAssignment().add(xml);\n Task task = mpxj.getTask();\n Task parentTask = task.getParentTask();\n Integer parentTaskUniqueID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActivityObjectId(mpxj.getTaskUniqueID());\n xml.setActualCost(getDouble(mpxj.getActualCost()));\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setActualOvertimeUnits(getDuration(mpxj.getActualOvertimeWork()));\n xml.setActualRegularUnits(getDuration(mpxj.getActualWork()));\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualUnits(getDuration(mpxj.getActualWork()));\n xml.setAtCompletionUnits(getDuration(mpxj.getRemainingWork()));\n xml.setPlannedCost(getDouble(mpxj.getActualCost()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPlannedDuration(getDuration(mpxj.getWork()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setPlannedUnits(getDuration(mpxj.getWork()));\n xml.setPlannedUnitsPerTime(getPercentage(mpxj.getUnits()));\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRateSource(\"Resource\");\n xml.setRemainingCost(getDouble(mpxj.getActualCost()));\n xml.setRemainingDuration(getDuration(mpxj.getRemainingWork()));\n xml.setRemainingFinishDate(mpxj.getFinish());\n xml.setRemainingStartDate(mpxj.getStart());\n xml.setRemainingUnits(getDuration(mpxj.getRemainingWork()));\n xml.setRemainingUnitsPerTime(getPercentage(mpxj.getUnits()));\n xml.setResourceObjectId(mpxj.getResourceUniqueID());\n xml.setStartDate(mpxj.getStart());\n xml.setWBSObjectId(parentTaskUniqueID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.ASSIGNMENT, mpxj));\n }",
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }",
"private void setSearchScopeFilter(CmsObject cms) {\n\n final List<String> searchRoots = CmsSearchUtil.computeScopeFolders(cms, this);\n\n // If the resource types contain the type \"function\" also\n // add \"/system/modules/\" to the search path\n\n if ((null != getResourceTypes()) && containsFunctionType(getResourceTypes())) {\n searchRoots.add(\"/system/modules/\");\n }\n\n addFoldersToSearchIn(searchRoots);\n }"
] |
Creates the next permutation in the sequence.
@return An array containing the permutation. The returned array is modified each time this function is called. | [
"public int[] next()\n {\n boolean hasNewPerm = false;\n\n escape:while( level >= 0) {\n// boolean foundZero = false;\n for( int i = iter[level]; i < data.length; i = iter[level] ) {\n iter[level]++;\n\n if( data[i] == -1 ) {\n level++;\n data[i] = level-1;\n\n if( level >= data.length ) {\n // a new permutation has been created return the results.\n hasNewPerm = true;\n System.arraycopy(data,0,ret,0,ret.length);\n level = level-1;\n data[i] = -1;\n break escape;\n } else {\n valk[level] = i;\n }\n }\n }\n\n data[valk[level]] = -1;\n iter[level] = 0;\n level = level-1;\n\n }\n\n if( hasNewPerm )\n return ret;\n return null;\n }"
] | [
"public static void setFilterBoxStyle(TextField searchBox) {\n\n searchBox.setIcon(FontOpenCms.FILTER);\n\n searchBox.setPlaceholder(\n org.opencms.ui.apps.Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n org.opencms.ui.apps.Messages.GUI_EXPLORER_FILTER_0));\n searchBox.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);\n }",
"private void renderAsLI(Writer writer, ProjectModel project, Iterator<Link> links, boolean wrap) throws IOException\n {\n if (!links.hasNext())\n return;\n\n if (wrap)\n writer.append(\"<ul>\");\n while (links.hasNext())\n {\n Link link = links.next();\n writer.append(\"<li>\");\n renderLink(writer, project, link);\n writer.append(\"</li>\");\n }\n if (wrap)\n writer.append(\"</ul>\");\n }",
"public void sendMessageUntilStopCount(int stopCount) {\n\n // always send with valid data.\n for (int i = processedWorkerCount; i < workers.size(); ++i) {\n ActorRef worker = workers.get(i);\n try {\n\n /**\n * !!! This is a must; without this sleep; stuck occured at 5K.\n * AKKA seems cannot handle too much too fast message send out.\n */\n Thread.sleep(1L);\n\n } catch (InterruptedException e) {\n logger.error(\"sleep exception \" + e + \" details: \", e);\n }\n\n // send as if the sender is the origin manager; so reply back to\n // origin manager\n worker.tell(OperationWorkerMsgType.PROCESS_REQUEST, originalManager);\n\n processedWorkerCount++;\n\n if (processedWorkerCount > stopCount) {\n return;\n }\n\n logger.debug(\"REQ_SENT: {} / {} taskId {}\", \n processedWorkerCount, requestTotalCount, taskIdTrim);\n\n }// end for loop\n }",
"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 }",
"private String escapeAndJoin(String[] commandline) {\n // TODO: we should try to escape special characters here, depending on the OS.\n StringBuilder b = new StringBuilder();\n Pattern specials = Pattern.compile(\"[\\\\ ]\");\n for (String arg : commandline) {\n if (b.length() > 0) {\n b.append(\" \");\n }\n\n if (specials.matcher(arg).find()) {\n b.append('\"').append(arg).append('\"');\n } else {\n b.append(arg);\n }\n }\n return b.toString();\n }",
"public void checkVersion(ZWaveCommandClass commandClass) {\r\n\t\tZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass)this.getNode().getCommandClass(CommandClass.VERSION);\r\n\t\t\r\n\t\tif (versionCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Version command class not supported on node %d,\" +\r\n\t\t\t\t\t\"reverting to version 1 for command class %s (0x%02x)\", \r\n\t\t\t\t\tthis.getNode().getNodeId(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getLabel(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getKey()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tthis.getController().sendData(versionCommandClass.getCommandClassVersionMessage(commandClass.getCommandClass()));\r\n\t}",
"protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}",
"public static String simpleTypeName(Object obj) {\n if (obj == null) {\n return \"null\";\n }\n\n return simpleTypeName(obj.getClass(), false);\n }",
"public static final Date parseFinishDateTime(String value)\n {\n Date result = parseDateTime(value);\n if (result != null)\n {\n result = DateHelper.addDays(result, -1);\n }\n return result;\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.