query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Tokenizes the input file and extracts the required data.
@param is input stream
@throws MPXJException | [
"private void processFile(InputStream is) throws MPXJException\n {\n try\n {\n InputStreamReader reader = new InputStreamReader(is, CharsetHelper.UTF8);\n Tokenizer tk = new ReaderTokenizer(reader)\n {\n @Override protected boolean startQuotedIsValid(StringBuilder buffer)\n {\n return buffer.length() == 1 && buffer.charAt(0) == '<';\n }\n };\n\n tk.setDelimiter(DELIMITER);\n ArrayList<String> columns = new ArrayList<String>();\n String nextTokenPrefix = null;\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n columns.clear();\n TableDefinition table = null;\n\n while (tk.nextToken() == Tokenizer.TT_WORD)\n {\n String token = tk.getToken();\n if (columns.size() == 0)\n {\n if (token.charAt(0) == '#')\n {\n int index = token.lastIndexOf(':');\n if (index != -1)\n {\n String headerToken;\n if (token.endsWith(\"-\") || token.endsWith(\"=\"))\n {\n headerToken = token;\n token = null;\n }\n else\n {\n headerToken = token.substring(0, index);\n token = token.substring(index + 1);\n }\n\n RowHeader header = new RowHeader(headerToken);\n table = m_tableDefinitions.get(header.getType());\n columns.add(header.getID());\n }\n }\n else\n {\n if (token.charAt(0) == 0)\n {\n processFileType(token);\n }\n }\n }\n\n if (table != null && token != null)\n {\n if (token.startsWith(\"<\\\"\") && !token.endsWith(\"\\\">\"))\n {\n nextTokenPrefix = token;\n }\n else\n {\n if (nextTokenPrefix != null)\n {\n token = nextTokenPrefix + DELIMITER + token;\n nextTokenPrefix = null;\n }\n\n columns.add(token);\n }\n }\n }\n\n if (table != null && columns.size() > 1)\n {\n // System.out.println(table.getName() + \" \" + columns.size());\n // ColumnDefinition[] columnDefs = table.getColumns();\n // int unknownIndex = 1;\n // for (int xx = 0; xx < columns.size(); xx++)\n // {\n // String x = columns.get(xx);\n // String columnName = xx < columnDefs.length ? (columnDefs[xx] == null ? \"UNKNOWN\" + (unknownIndex++) : columnDefs[xx].getName()) : \"?\";\n // System.out.println(columnName + \": \" + x + \", \");\n // }\n // System.out.println();\n\n TextFileRow row = new TextFileRow(table, columns, m_epochDateFormat);\n List<Row> rows = m_tables.get(table.getName());\n if (rows == null)\n {\n rows = new LinkedList<Row>();\n m_tables.put(table.getName(), rows);\n }\n rows.add(row);\n }\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n }"
] | [
"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 }",
"@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 Document getProjection(List<String> fieldNames) {\n\t\tDocument projection = new Document();\n\t\tfor ( String column : fieldNames ) {\n\t\t\tprojection.put( column, 1 );\n\t\t}\n\n\t\treturn projection;\n\t}",
"public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\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 int execute(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\ttry {\n\t\t\t// the arguments are the new-id and old-id\n\t\t\tObject[] args = new Object[] { convertIdToFieldObject(newId), extractIdToFieldObject(data) };\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\tObject oldId = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT obj = objectCache.updateId(clazz, oldId, newId);\n\t\t\t\t\tif (obj != null && obj != data) {\n\t\t\t\t\t\t// if our cached value is not the data that will be updated then we need to update it specially\n\t\t\t\t\t\tidField.assignField(connectionSource, obj, newId, false, objectCache);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// adjust the object to assign the new id\n\t\t\t\tidField.assignField(connectionSource, data, newId, false, objectCache);\n\t\t\t}\n\t\t\tlogger.debug(\"updating-id with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the cast otherwise we only print the first object in args\n\t\t\t\tlogger.trace(\"updating-id arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update-id stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}",
"public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}",
"public void validateAliases(\r\n final CmsUUID uuid,\r\n final Map<String, String> aliasPaths,\r\n final AsyncCallback<Map<String, String>> callback) {\r\n\r\n CmsRpcAction<Map<String, String>> action = new CmsRpcAction<Map<String, String>>() {\r\n\r\n /**\r\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()\r\n */\r\n @Override\r\n public void execute() {\r\n\r\n start(200, true);\r\n CmsCoreProvider.getVfsService().validateAliases(uuid, aliasPaths, this);\r\n }\r\n\r\n /**\r\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)\r\n */\r\n @Override\r\n protected void onResponse(Map<String, String> result) {\r\n\r\n stop(false);\r\n callback.onSuccess(result);\r\n }\r\n\r\n };\r\n action.execute();\r\n }",
"synchronized void stop(Integer timeout) {\n final InternalState required = this.requiredState;\n if(required != InternalState.STOPPED) {\n this.requiredState = InternalState.STOPPED;\n ROOT_LOGGER.stoppingServer(serverName);\n // Only send the stop operation if the server is started\n if (internalState == InternalState.SERVER_STARTED) {\n internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);\n } else {\n transition(false);\n }\n }\n }"
] |
Create and return a new Violation for this rule and the specified values
@param lineNumber - the line number for the violation; may be null
@param sourceLine - the source line for the violation; may be null
@param message - the message for the violation; may be null
@return a new Violation object | [
"protected Violation createViolation(Integer lineNumber, String sourceLine, String message) {\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine(sourceLine);\n violation.setLineNumber(lineNumber);\n violation.setMessage(message);\n return violation;\n }"
] | [
"public byte[] join(Map<Integer, byte[]> parts) {\n checkArgument(parts.size() > 0, \"No parts provided\");\n final int[] lengths = parts.values().stream().mapToInt(v -> v.length).distinct().toArray();\n checkArgument(lengths.length == 1, \"Varying lengths of part values\");\n final byte[] secret = new byte[lengths[0]];\n for (int i = 0; i < secret.length; i++) {\n final byte[][] points = new byte[parts.size()][2];\n int j = 0;\n for (Map.Entry<Integer, byte[]> part : parts.entrySet()) {\n points[j][0] = part.getKey().byteValue();\n points[j][1] = part.getValue()[i];\n j++;\n }\n secret[i] = GF256.interpolate(points);\n }\n return secret;\n }",
"public static Set<String> getRoundingNames(String... providers) {\n return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryRoundingsSpi loaded, query functionality is not available.\"))\n .getRoundingNames(providers);\n }",
"private Integer getNumId(String idString, boolean isUri) {\n\t\tString numString;\n\t\tif (isUri) {\n\t\t\tif (!idString.startsWith(\"http://www.wikidata.org/entity/\")) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tnumString = idString.substring(\"http://www.wikidata.org/entity/Q\"\n\t\t\t\t\t.length());\n\t\t} else {\n\t\t\tnumString = idString.substring(1);\n\t\t}\n\t\treturn Integer.parseInt(numString);\n\t}",
"private static double pointsDistance(Point a, Point b) {\n int dx = b.x - a.x;\n int dy = b.y - a.y;\n return Math.sqrt(dx * dx + dy * dy);\n }",
"private void initStyleGenerators() {\n\n if (m_model.hasMasterMode()) {\n m_styleGenerators.put(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER)));\n }\n m_styleGenerators.put(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT)));\n\n }",
"private void releaseConnection()\n {\n if (m_rs != null)\n {\n try\n {\n m_rs.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_rs = null;\n }\n\n if (m_ps != null)\n {\n try\n {\n m_ps.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_ps = null;\n }\n }",
"private int bestSurroundingSet(int index, int length, int... valid) {\r\n int option1 = set[index - 1];\r\n if (index + 1 < length) {\r\n // we have two options to check\r\n int option2 = set[index + 1];\r\n if (contains(valid, option1) && contains(valid, option2)) {\r\n return Math.min(option1, option2);\r\n } else if (contains(valid, option1)) {\r\n return option1;\r\n } else if (contains(valid, option2)) {\r\n return option2;\r\n } else {\r\n return valid[0];\r\n }\r\n } else {\r\n // we only have one option to check\r\n if (contains(valid, option1)) {\r\n return option1;\r\n } else {\r\n return valid[0];\r\n }\r\n }\r\n }",
"private int getColor(int value) {\n\t\tif (value == 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tdouble scale = Math.log10(value) / Math.log10(this.topValue);\n\t\tdouble lengthScale = Math.min(1.0, scale) * (colors.length - 1);\n\t\tint index = 1 + (int) lengthScale;\n\t\tif (index == colors.length) {\n\t\t\tindex--;\n\t\t}\n\t\tdouble partScale = lengthScale - (index - 1);\n\n\t\tint r = (int) (colors[index - 1][0] + partScale\n\t\t\t\t* (colors[index][0] - colors[index - 1][0]));\n\t\tint g = (int) (colors[index - 1][1] + partScale\n\t\t\t\t* (colors[index][1] - colors[index - 1][1]));\n\t\tint b = (int) (colors[index - 1][2] + partScale\n\t\t\t\t* (colors[index][2] - colors[index - 1][2]));\n\n\t\tr = Math.min(255, r);\n\t\tb = Math.min(255, b);\n\t\tg = Math.min(255, g);\n\t\treturn (r << 16) | (g << 8) | b;\n\t}",
"public ItemRequest<Task> removeTag(String task) {\n \n String path = String.format(\"/tasks/%s/removeTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }"
] |
returns all methods not in the group
@param groupId Id of group
@return List of Methods for a group
@throws Exception exception | [
"public List<com.groupon.odo.proxylib.models.Method> getMethodsNotInGroup(int groupId) throws Exception {\n List<com.groupon.odo.proxylib.models.Method> allMethods = getAllMethods();\n List<com.groupon.odo.proxylib.models.Method> methodsNotInGroup = new ArrayList<com.groupon.odo.proxylib.models.Method>();\n List<com.groupon.odo.proxylib.models.Method> methodsInGroup = editService.getMethodsFromGroupId(groupId, null);\n\n for (int i = 0; i < allMethods.size(); i++) {\n boolean add = true;\n String methodName = allMethods.get(i).getMethodName();\n String className = allMethods.get(i).getClassName();\n\n for (int j = 0; j < methodsInGroup.size(); j++) {\n if ((methodName.equals(methodsInGroup.get(j).getMethodName())) &&\n (className.equals(methodsInGroup.get(j).getClassName()))) {\n add = false;\n }\n }\n if (add) {\n methodsNotInGroup.add(allMethods.get(i));\n }\n }\n return methodsNotInGroup;\n }"
] | [
"@SuppressWarnings(\"deprecation\")\n @Deprecated\n public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {\n validateOperation(operationObject);\n for (AttributeDefinition ad : this.parameters) {\n ad.validateAndSet(operationObject, model);\n }\n }",
"protected void convertToHours(LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Duration totalWork = assignment.getTotalAmount();\n Duration workPerDay = assignment.getAmountPerDay();\n totalWork = Duration.getInstance(totalWork.getDuration() / 60, TimeUnit.HOURS);\n workPerDay = Duration.getInstance(workPerDay.getDuration() / 60, TimeUnit.HOURS);\n assignment.setTotalAmount(totalWork);\n assignment.setAmountPerDay(workPerDay);\n }\n }",
"private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER);\r\n\r\n if (rowReaderName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+rowReaderName+\" specified as row-reader of class \"+classDef.getName()+\" does not implement the interface \"+ROW_READER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the row-reader class \"+rowReaderName+\" of class \"+classDef.getName());\r\n }\r\n }",
"public static appfwprofile[] get(nitro_service service) throws Exception{\n\t\tappfwprofile obj = new appfwprofile();\n\t\tappfwprofile[] response = (appfwprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public synchronized boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"LM.checkWrite(tx-\" + tx.getGUID() + \", \" + new Identity(obj, tx.getBroker()).toString() + \")\");\r\n LockStrategy lockStrategy = LockStrategyFactory.getStrategyFor(obj);\r\n return lockStrategy.checkWrite(tx, obj);\r\n }",
"public void deleteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n repositoryHandler.deleteModule(module.getId());\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n repositoryHandler.deleteArtifact(gavc);\n }\n }",
"public void growInternal(int amount ) {\n int tmp[] = new int[ data.length + amount ];\n\n System.arraycopy(data,0,tmp,0,data.length);\n this.data = tmp;\n }",
"public static Integer getDays(String days)\n {\n Integer result = null;\n if (days != null)\n {\n result = Integer.valueOf(Integer.parseInt(days, 2));\n }\n return (result);\n }",
"private static String toColumnName(String fieldName) {\n int lastDot = fieldName.indexOf('.');\n if (lastDot > -1) {\n return fieldName.substring(lastDot + 1);\n } else {\n return fieldName;\n }\n }"
] |
Disable all overrides for a specified path with overrideType
@param pathID ID of path containing overrides
@param clientUUID UUID of client
@param overrideType Override type identifier | [
"public void disableAllOverrides(int pathID, String clientUUID, int overrideType) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n ArrayList<Integer> enabledOverrides = new ArrayList<Integer>();\n enabledOverrides.add(Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD);\n enabledOverrides.add(Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE);\n enabledOverrides.add(Constants.PLUGIN_REQUEST_OVERRIDE_CUSTOM);\n enabledOverrides.add(Constants.PLUGIN_REQUEST_OVERRIDE_CUSTOM_POST_BODY);\n\n String overridePlaceholders = preparePlaceHolders(enabledOverrides.size());\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ? \" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \" +\n \" AND \" + Constants.ENABLED_OVERRIDES_OVERRIDE_ID +\n (overrideType == Constants.OVERRIDE_TYPE_RESPONSE ? \" NOT\" : \"\") +\n \" IN ( \" + overridePlaceholders + \" )\"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n for (int i = 3; i <= enabledOverrides.size() + 2; ++i) {\n statement.setInt(i, enabledOverrides.get(i - 3));\n }\n statement.execute();\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 }"
] | [
"@SuppressWarnings(\"checkstyle:illegalcatch\")\n private boolean sendMessage(final byte[] messageToSend) {\n try {\n connectionPool.execute(new PooledObjectConsumer<TcpConnection>() {\n @Override\n public void accept(final TcpConnection tcpConnection) throws IOException {\n tcpConnection.write(messageToSend);\n }\n });\n } catch (final Exception e) {\n addError(String.format(\"Error sending message via tcp://%s:%s\",\n getGraylogHost(), getGraylogPort()), e);\n\n return false;\n }\n\n return true;\n }",
"public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) {\n\t\tthis.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit);\n\t}",
"public int getRegisteredResourceRequestCount() {\n int count = 0;\n for(Entry<K, Queue<AsyncResourceRequest<V>>> entry: this.requestQueueMap.entrySet()) {\n // FYI: .size() is not constant time in the next call. ;)\n count += entry.getValue().size();\n }\n return count;\n }",
"private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) {\n EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget();\n EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR);\n WSAEndpointReferenceUtils.setAddress(targetEPR, address);\n\n if (props != null) {\n addProperties(targetEPR, props);\n }\n return targetEPR;\n }",
"public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {\r\n\t\tcheckNotRead();\r\n\t\tPreconditions.checkNotNull(tagName);\r\n\t\tExcludeByParentBuilder exclude = new ExcludeByParentBuilder(\r\n\t\t\t\ttagName.toUpperCase());\r\n\t\tcrawlParentsExcluded.add(exclude);\r\n\t\treturn exclude;\r\n\t}",
"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}",
"private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public static base_response unset(nitro_service client, csparameter resource, String[] args) throws Exception{\n\t\tcsparameter unsetresource = new csparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String getDumpFilePostfix(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.POSTFIXES.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.POSTFIXES.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}"
] |
Prints and stores final result of the processing. This should be called
after finishing the processing of a dump. It will print the statistics
gathered during processing and it will write a CSV file with usage counts
for every property. | [
"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 static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean isSecuredByProperty(Server server) {\n boolean isSecured = false;\n Object value = server.getEndpoint().get(\"org.talend.tesb.endpoint.secured\"); //Property name TBD\n\n if (value instanceof String) {\n try {\n isSecured = Boolean.valueOf((String) value);\n } catch (Exception ex) {\n }\n }\n\n return isSecured;\n }",
"public BufferedImage getImage() {\n ByteBuffer artwork = getRawBytes();\n artwork.rewind();\n byte[] imageBytes = new byte[artwork.remaining()];\n artwork.get(imageBytes);\n try {\n return ImageIO.read(new ByteArrayInputStream(imageBytes));\n } catch (IOException e) {\n logger.error(\"Weird! Caught exception creating image from artwork bytes\", e);\n return null;\n }\n }",
"public int color(Context ctx) {\n if (mColorInt == 0 && mColorRes != -1) {\n mColorInt = ContextCompat.getColor(ctx, mColorRes);\n }\n return mColorInt;\n }",
"private void forward() {\n\n Set<String> selected = new HashSet<>();\n\n for (CheckBox checkbox : m_componentCheckboxes) {\n CmsSetupComponent component = (CmsSetupComponent)(checkbox.getData());\n if (checkbox.getValue().booleanValue()) {\n selected.add(component.getId());\n }\n }\n String error = null;\n for (String compId : selected) {\n CmsSetupComponent component = m_componentMap.get(compId);\n for (String dep : component.getDependencies()) {\n if (!selected.contains(dep)) {\n error = \"Unfulfilled dependency: The component \"\n + component.getName()\n + \" can not be installed because its dependency \"\n + m_componentMap.get(dep).getName()\n + \" is not selected\";\n break;\n }\n }\n }\n if (error == null) {\n Set<String> modules = new HashSet<>();\n\n for (CmsSetupComponent component : m_componentMap.values()) {\n\n if (selected.contains(component.getId())) {\n\n for (CmsModule module : m_context.getSetupBean().getAvailableModules().values()) {\n if (component.match(module.getName())) {\n modules.add(module.getName());\n }\n }\n }\n }\n List<String> moduleList = new ArrayList<>(modules);\n m_context.getSetupBean().setInstallModules(CmsStringUtil.listAsString(moduleList, \"|\"));\n m_context.stepForward();\n } else {\n CmsSetupErrorDialog.showErrorDialog(error, error);\n }\n }",
"public WebSocketContext sendToPeers(String message, boolean excludeSelf) {\n return sendToConnections(message, url, manager.urlRegistry(), excludeSelf);\n }",
"@Nonnull\n public static XMLDSigValidationResult createReferenceErrors (@Nonnull @Nonempty final List <Integer> aInvalidReferences)\n {\n return new XMLDSigValidationResult (aInvalidReferences);\n }",
"public static synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}",
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}"
] |
Overridden to ensure that our timestamp handling is as expected | [
"@Override\n protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)\n throws JsonMappingException\n {\n SerializerProvider prov = visitor.getProvider();\n if ((prov != null) && useNanoseconds(prov)) {\n JsonNumberFormatVisitor v2 = visitor.expectNumberFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.BIG_DECIMAL);\n }\n } else {\n JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.LONG);\n }\n }\n }"
] | [
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public void blacklistNode(int nodeId) {\n Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();\n\n if(blackListedNodes == null) {\n blackListedNodes = new ArrayList();\n }\n blackListedNodes.add(nodeId);\n\n for(Node node: nodesInCluster) {\n\n if(node.getId() == nodeId) {\n nodesToStream.remove(node);\n break;\n }\n\n }\n\n for(String store: storeNames) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n nodeId));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n }",
"protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\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}",
"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 }",
"int add(DownloadRequest request) {\n\t\tint downloadId = getDownloadId();\n\t\t// Tag the request as belonging to this queue and add it to the set of current requests.\n\t\trequest.setDownloadRequestQueue(this);\n\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tmCurrentRequests.add(request);\n\t\t}\n\n\t\t// Process requests in the order they are added.\n\t\trequest.setDownloadId(downloadId);\n\t\tmDownloadQueue.add(request);\n\n\t\treturn downloadId;\n\t}",
"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}",
"public static Node addPartitionToNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition));\n }",
"public static void withInstance(String url, Closure c) throws SQLException {\n Sql sql = null;\n try {\n sql = newInstance(url);\n c.call(sql);\n } finally {\n if (sql != null) sql.close();\n }\n }",
"public WebSocketContext sendToUser(String message, String username) {\n return sendToConnections(message, username, manager.usernameRegistry(), true);\n }"
] |
A specific, existing tag can be deleted by making a DELETE request
on the URL for that tag.
Returns an empty data record.
@param tag The tag to delete.
@return Request object | [
"public ItemRequest<Tag> delete(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"DELETE\");\n }"
] | [
"public void unlock() {\n\n for (Locale l : m_lockedBundleFiles.keySet()) {\n LockedFile f = m_lockedBundleFiles.get(l);\n f.tryUnlock();\n }\n if (null != m_descFile) {\n m_descFile.tryUnlock();\n }\n }",
"private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}",
"public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }",
"public boolean isBitwiseOrCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\treturn super.isBitwiseOrCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}",
"public void promote() {\n URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, \"current\");\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"type\", \"file_version\");\n jsonObject.add(\"id\", this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(jsonObject.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n this.parseJSON(JsonObject.readFrom(response.getJSON()));\n }",
"void insertMacros(TokenList tokens ) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD ) {\n Macro v = lookupMacro(t.word);\n if (v != null) {\n TokenList.Token before = t.previous;\n List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();\n t = parseMacroInput(inputs,t.next);\n\n TokenList sniplet = v.execute(inputs);\n tokens.extractSubList(before.next,t);\n tokens.insertAfter(before,sniplet);\n t = sniplet.last;\n }\n }\n t = t.next;\n }\n }",
"public void setNamespace(String prefix, String namespaceURI) {\n ensureNotNull(\"Prefix\", prefix);\n ensureNotNull(\"Namespace URI\", namespaceURI);\n\n namespaces.put(prefix, namespaceURI);\n }",
"public static int scale(Double factor, int pixel) {\n return rgb(\n (int) Math.round(factor * red(pixel)),\n (int) Math.round(factor * green(pixel)),\n (int) Math.round(factor * blue(pixel))\n );\n }",
"@SuppressWarnings(\"unused\")\n public static void addTo(\n AbstractSingleComponentContainer componentContainer,\n int scrollBarrier,\n int barrierMargin,\n String styleName) {\n\n new CmsScrollPositionCss(componentContainer, scrollBarrier, barrierMargin, styleName);\n }"
] |
Reads characters into a portion of an array, then replace invalid XML characters
@throws IOException If an I/O error occurs
@see ru.yandex.qatools.allure.config.AllureNamingUtils#isBadXmlCharacter(char) by space | [
"@Override\n public int read(char[] cbuf, int off, int len) throws IOException {\n int numChars = super.read(cbuf, off, len);\n replaceBadXmlCharactersBySpace(cbuf, off, len);\n return numChars;\n }"
] | [
"public void put(@NotNull final PersistentStoreTransaction txn,\n final long localId,\n @NotNull final ByteIterable value,\n @Nullable final ByteIterable oldValue,\n final int propertyId,\n @NotNull final ComparableValueType type) {\n final Store valueIdx = getOrCreateValueIndex(txn, propertyId);\n final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));\n final Transaction envTxn = txn.getEnvironmentTransaction();\n primaryStore.put(envTxn, key, value);\n final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);\n boolean success;\n if (oldValue == null) {\n success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);\n } else {\n success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));\n }\n if (success) {\n for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {\n valueIdx.put(envTxn, secondaryKey, secondaryValue);\n }\n }\n checkStatus(success, \"Failed to put\");\n }",
"public 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 long get1D(DMatrixRMaj A , int n ) {\n\n long before = System.currentTimeMillis();\n\n double total = 0;\n\n for( int iter = 0; iter < n; iter++ ) {\n\n int index = 0;\n for( int i = 0; i < A.numRows; i++ ) {\n int end = index+A.numCols;\n while( index != end ) {\n total += A.get(index++);\n }\n }\n }\n\n long after = System.currentTimeMillis();\n\n // print to ensure that ensure that an overly smart compiler does not optimize out\n // the whole function and to show that both produce the same results.\n System.out.println(total);\n\n return after-before;\n }",
"private void logBlock(int blockIndex, int startIndex, int blockLength)\n {\n if (m_log != null)\n {\n m_log.println(\"Block Index: \" + blockIndex);\n m_log.println(\"Length: \" + blockLength + \" (\" + Integer.toHexString(blockLength) + \")\");\n m_log.println();\n m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, blockLength, true, 16, \"\"));\n m_log.flush();\n }\n }",
"public static long makeReasonable(long expectedTimeoutMillis, long bufferMillis) {\n checkArgument(expectedTimeoutMillis > 0,\n \"expectedTimeoutMillis: %s (expected: > 0)\", expectedTimeoutMillis);\n checkArgument(bufferMillis >= 0,\n \"bufferMillis: %s (expected: > 0)\", bufferMillis);\n\n final long timeout = Math.min(expectedTimeoutMillis, MAX_MILLIS);\n if (bufferMillis == 0) {\n return timeout;\n }\n\n if (timeout > MAX_MILLIS - bufferMillis) {\n return MAX_MILLIS;\n } else {\n return bufferMillis + timeout;\n }\n }",
"public com.squareup.okhttp.Call postUiAutopilotWaypointCall(Boolean addToBeginning, Boolean clearOtherWaypoints,\n Long destinationId, String datasource, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v2/ui/autopilot/waypoint/\";\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (addToBeginning != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"add_to_beginning\", addToBeginning));\n }\n\n if (clearOtherWaypoints != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"clear_other_waypoints\", clearOtherWaypoints));\n }\n\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (destinationId != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"destination_id\", destinationId));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = {\n\n };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"POST\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }",
"@SuppressWarnings(\"unchecked\")\n public void setVars(final Map<String, ? extends Object> vars) {\n this.vars = (Map<String, Object>)vars;\n }",
"private synchronized JsonSchema getInputPathJsonSchema() throws IOException {\n if (inputPathJsonSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath());\n }\n return inputPathJsonSchema;\n }",
"private ClassDescriptorDef ensureClassDef(XClass original)\r\n {\r\n String name = original.getQualifiedName();\r\n ClassDescriptorDef classDef = _model.getClass(name);\r\n\r\n if (classDef == null)\r\n {\r\n classDef = new ClassDescriptorDef(original);\r\n _model.addClass(classDef);\r\n }\r\n return classDef;\r\n }"
] |
Updates the database. Never call this during normal operations, upgrade is a user-controlled operation. | [
"private void dbUpgrade()\n {\n DbConn cnx = this.getConn();\n Map<String, Object> rs = null;\n int db_schema_version = 0;\n try\n {\n rs = cnx.runSelectSingleRow(\"version_select_latest\");\n db_schema_version = (Integer) rs.get(\"VERSION_D1\");\n }\n catch (Exception e)\n {\n // Database is to be created, so version 0 is OK.\n }\n cnx.rollback();\n\n if (SCHEMA_VERSION > db_schema_version)\n {\n jqmlogger.warn(\"Database is being upgraded from version {} to version {}\", db_schema_version, SCHEMA_VERSION);\n\n // Upgrade scripts are named from_to.sql with 5 padding (e.g. 00000_00003.sql)\n // We try to find the fastest path (e.g. a direct 00000_00005.sql for creating a version 5 schema from nothing)\n // This is a simplistic and non-optimal algorithm as we try only a single path (no going back)\n\n int loop_from = db_schema_version;\n int to = db_schema_version;\n List<String> toApply = new ArrayList<>();\n toApply.addAll(adapter.preSchemaCreationScripts());\n\n while (to != SCHEMA_VERSION)\n {\n boolean progressed = false;\n for (int loop_to = SCHEMA_VERSION; loop_to > db_schema_version; loop_to--)\n {\n String migrationFileName = String.format(\"/sql/%05d_%05d.sql\", loop_from, loop_to);\n jqmlogger.debug(\"Trying migration script {}\", migrationFileName);\n if (Db.class.getResource(migrationFileName) != null)\n {\n toApply.add(migrationFileName);\n to = loop_to;\n loop_from = loop_to;\n progressed = true;\n break;\n }\n }\n\n if (!progressed)\n {\n break;\n }\n }\n if (to != SCHEMA_VERSION)\n {\n throw new DatabaseException(\n \"There is no migration path from version \" + db_schema_version + \" to version \" + SCHEMA_VERSION);\n }\n\n for (String s : toApply)\n {\n jqmlogger.info(\"Running migration script {}\", s);\n ScriptRunner.run(cnx, s);\n }\n cnx.commit(); // Yes, really. For advanced DB!\n\n cnx.close(); // HSQLDB does not refresh its schema without this.\n cnx = getConn();\n\n cnx.runUpdate(\"version_insert\", SCHEMA_VERSION, SCHEMA_COMPATIBLE_VERSION);\n cnx.commit();\n jqmlogger.info(\"Database is now up to date\");\n }\n else\n {\n jqmlogger.info(\"Database is already up to date\");\n }\n cnx.close();\n }"
] | [
"private void computeUnnamedParams() {\n unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList()));\n }",
"public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }",
"public BufferedImage toNewBufferedImage(int type) {\n BufferedImage target = new BufferedImage(width, height, type);\n Graphics2D g2 = (Graphics2D) target.getGraphics();\n g2.drawImage(awt, 0, 0, null);\n g2.dispose();\n return target;\n }",
"protected boolean isFirstVisit(Object expression) {\r\n if (visited.contains(expression)) {\r\n return false;\r\n }\r\n visited.add(expression);\r\n return true;\r\n }",
"public final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }",
"public void addOrder(String columnName, boolean ascending) {\n if (columnName == null) {\n return;\n }\n for (int i = 0; i < columns.size(); i++) {\n if (!columnName.equals(columns.get(i).getData())) {\n continue;\n }\n order.add(new Order(i, ascending ? \"asc\" : \"desc\"));\n }\n }",
"public static int[] ConcatenateInt(List<int[]> arrays) {\n\n int size = 0;\n for (int i = 0; i < arrays.size(); i++) {\n size += arrays.get(i).length;\n }\n\n int[] all = new int[size];\n int idx = 0;\n\n for (int i = 0; i < arrays.size(); i++) {\n int[] v = arrays.get(i);\n for (int j = 0; j < v.length; j++) {\n all[idx++] = v[i];\n }\n }\n\n return all;\n }",
"public void sendValue(int nodeId, int endpoint, int value) {\n\t\tZWaveNode node = this.getNode(nodeId);\n\t\tZWaveSetCommands zwaveCommandClass = null;\n\t\tSerialMessage serialMessage = null;\n\t\t\n\t\tfor (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {\n\t\t\tzwaveCommandClass = (ZWaveSetCommands)node.resolveCommandClass(commandClass, endpoint);\n\t\t\tif (zwaveCommandClass != null)\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(\"No Command Class found on node {}, instance/endpoint {} to request level.\", nodeId, endpoint);\n\t\t\treturn;\n\t\t}\n\t\t\t \n\t\tserialMessage = node.encapsulate(zwaveCommandClass.setValueMessage(value), (ZWaveCommandClass)zwaveCommandClass, endpoint);\n\t\t\n\t\tif (serialMessage != null)\n\t\t\tthis.sendData(serialMessage);\n\t\t\n\t\t// read back level on \"ON\" command\n\t\tif (((ZWaveCommandClass)zwaveCommandClass).getCommandClass() == ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL && value == 255)\n\t\t\tthis.requestValue(nodeId, endpoint);\n\t}",
"private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature,\n String webHookPayload, String deliveryTimestamp) {\n if (actualSignature == null) {\n return false;\n }\n\n byte[] actual = Base64.decode(actualSignature);\n byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp);\n\n return Arrays.equals(expected, actual);\n }"
] |
Convenience method to allow a cause. Grrrr. | [
"public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}"
] | [
"private static String getEncodedInstance(String encodedResponse) {\n if (isReturnValue(encodedResponse) || isThrownException(encodedResponse)) {\n return encodedResponse.substring(4);\n }\n\n return encodedResponse;\n }",
"public boolean remove(long key) {\n int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n Entry previous = null;\n Entry entry = table[index];\n while (entry != null) {\n Entry next = entry.next;\n if (entry.key == key) {\n if (previous == null) {\n table[index] = next;\n } else {\n previous.next = next;\n }\n size--;\n return true;\n }\n previous = entry;\n entry = next;\n }\n return false;\n }",
"public int compareTo(Rational other)\n {\n if (denominator == other.getDenominator())\n {\n return ((Long) numerator).compareTo(other.getNumerator());\n }\n else\n {\n Long adjustedNumerator = numerator * other.getDenominator();\n Long otherAdjustedNumerator = other.getNumerator() * denominator;\n return adjustedNumerator.compareTo(otherAdjustedNumerator);\n }\n }",
"public Where<T, ID> lt(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_OPERATION));\n\t\treturn this;\n\t}",
"protected String getQueryParam() {\n\n String param = parseOptionalStringValue(m_configObject, JSON_KEY_QUERYPARAM);\n if (param == null) {\n return null != m_baseConfig ? m_baseConfig.getGeneralConfig().getQueryParam() : DEFAULT_QUERY_PARAM;\n } else {\n return param;\n }\n }",
"public static double J0(double x) {\r\n double ax;\r\n\r\n if ((ax = Math.abs(x)) < 8.0) {\r\n double y = x * x;\r\n double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7\r\n + y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));\r\n double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718\r\n + y * (59272.64853 + y * (267.8532712 + y * 1.0))));\r\n\r\n return ans1 / ans2;\r\n } else {\r\n double z = 8.0 / ax;\r\n double y = z * z;\r\n double xx = ax - 0.785398164;\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n - y * 0.934935152e-7)));\r\n\r\n return Math.sqrt(0.636619772 / ax) *\r\n (Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);\r\n }\r\n }",
"public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(final BoxAPIConnection api,\n final String externalAppUserId, final String... fields) {\n return getUsersInfoForType(api, null, null, externalAppUserId, fields);\n }",
"protected boolean exportWithMinimalMetaData(String path) {\n\n String checkPath = path.startsWith(\"/\") ? path + \"/\" : \"/\" + path + \"/\";\n for (String p : m_parameters.getResourcesToExportWithMetaData()) {\n if (checkPath.startsWith(p)) {\n return false;\n }\n }\n return true;\n }",
"public <CT> CT callBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException {\n\t\tif (connectionSource.isSingleConnection(tableInfo.getTableName())) {\n\t\t\tsynchronized (this) {\n\t\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t\t}\n\t\t} else {\n\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t}\n\t}"
] |
Utility method used to convert an arbitrary Number into an Integer.
@param value Number instance
@return Integer instance | [
"public static final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }"
] | [
"public static String encodeHost(String host, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4);\n\t}",
"private void readHours(ProjectCalendar calendar, Day day, Integer hours)\n {\n int value = hours.intValue();\n int startHour = 0;\n ProjectCalendarHours calendarHours = null;\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n\n calendar.setWorkingDay(day, false);\n\n while (value != 0)\n {\n // Move forward until we find a working hour\n while (startHour < 24 && (value & 0x1) == 0)\n {\n value = value >> 1;\n ++startHour;\n }\n\n // No more working hours, bail out\n if (startHour >= 24)\n {\n break;\n }\n\n // Move forward until we find the end of the working hours\n int endHour = startHour;\n while (endHour < 24 && (value & 0x1) != 0)\n {\n value = value >> 1;\n ++endHour;\n }\n\n cal.set(Calendar.HOUR_OF_DAY, startHour);\n Date startDate = cal.getTime();\n cal.set(Calendar.HOUR_OF_DAY, endHour);\n Date endDate = cal.getTime();\n\n if (calendarHours == null)\n {\n calendarHours = calendar.addCalendarHours(day);\n calendar.setWorkingDay(day, true);\n }\n calendarHours.addRange(new DateRange(startDate, endDate));\n startHour = endHour;\n }\n \n DateHelper.pushCalendar(cal);\n }",
"public static boolean checkAddProperty(\r\n CmsCmisTypeManager typeManager,\r\n Properties properties,\r\n String typeId,\r\n Set<String> filter,\r\n String id) {\r\n\r\n if ((properties == null) || (properties.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Properties must not be null!\");\r\n }\r\n\r\n if (id == null) {\r\n throw new IllegalArgumentException(\"Id must not be null!\");\r\n }\r\n\r\n TypeDefinition type = typeManager.getType(typeId);\r\n if (type == null) {\r\n throw new IllegalArgumentException(\"Unknown type: \" + typeId);\r\n }\r\n if (!type.getPropertyDefinitions().containsKey(id)) {\r\n throw new IllegalArgumentException(\"Unknown property: \" + id);\r\n }\r\n\r\n String queryName = type.getPropertyDefinitions().get(id).getQueryName();\r\n\r\n if ((queryName != null) && (filter != null)) {\r\n if (!filter.contains(queryName)) {\r\n return false;\r\n } else {\r\n filter.remove(queryName);\r\n }\r\n }\r\n\r\n return true;\r\n }",
"public boolean isLabelAnnotationIntroducingCharacter(char ch) {\r\n char[] cutChars = labelAnnotationIntroducingCharacters();\r\n for (char cutChar : cutChars) {\r\n if (ch == cutChar) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"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 }",
"BeatGrid getBeatGrid(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.BEAT_GRID_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.BEAT_GRID) {\n return new BeatGrid(new DataReference(slot, rekordboxId), response);\n }\n logger.error(\"Unexpected response type when requesting beat grid: {}\", response);\n return null;\n }",
"public void updateMetadataVersions() {\n Properties versionProps = MetadataVersionStoreUtils.getProperties(this.systemStoreRepository.getMetadataVersionStore());\n Long newVersion = fetchNewVersion(SystemStoreConstants.CLUSTER_VERSION_KEY,\n null,\n versionProps);\n if(newVersion != null) {\n this.currentClusterVersion = newVersion;\n }\n }",
"protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\n }",
"protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }"
] |
Returns an iterator of all direct and indirect extents of this class.
@return The extents iterator | [
"public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }"
] | [
"protected void load()\r\n {\r\n // properties file may be set as a System property.\r\n // if no property is set take default name.\r\n String fn = System.getProperty(OJB_PROPERTIES_FILE, OJB_PROPERTIES_FILE);\r\n setFilename(fn);\r\n super.load();\r\n\r\n // default repository & connection descriptor file\r\n repositoryFilename = getString(\"repositoryFile\", OJB_METADATA_FILE);\r\n\r\n // object cache class\r\n objectCacheClass = getClass(\"ObjectCacheClass\", ObjectCacheDefaultImpl.class, ObjectCache.class);\r\n\r\n // load PersistentField Class\r\n persistentFieldClass =\r\n getClass(\"PersistentFieldClass\", PersistentFieldDirectImpl.class, PersistentField.class);\r\n\r\n // load PersistenceBroker Class\r\n persistenceBrokerClass =\r\n getClass(\"PersistenceBrokerClass\", PersistenceBrokerImpl.class, PersistenceBroker.class);\r\n\r\n // load ListProxy Class\r\n listProxyClass = getClass(\"ListProxyClass\", ListProxyDefaultImpl.class);\r\n\r\n // load SetProxy Class\r\n setProxyClass = getClass(\"SetProxyClass\", SetProxyDefaultImpl.class);\r\n\r\n // load CollectionProxy Class\r\n collectionProxyClass = getClass(\"CollectionProxyClass\", CollectionProxyDefaultImpl.class);\r\n\r\n // load IndirectionHandler Class\r\n indirectionHandlerClass =\r\n getClass(\"IndirectionHandlerClass\", IndirectionHandlerJDKImpl.class, IndirectionHandler.class);\r\n \r\n // load ProxyFactory Class\r\n proxyFactoryClass =\r\n getClass(\"ProxyFactoryClass\", ProxyFactoryJDKImpl.class, ProxyFactory.class);\r\n\r\n // load configuration for ImplicitLocking parameter:\r\n useImplicitLocking = getBoolean(\"ImplicitLocking\", false);\r\n\r\n // load configuration for LockAssociations parameter:\r\n lockAssociationAsWrites = (getString(\"LockAssociations\", \"WRITE\").equalsIgnoreCase(\"WRITE\"));\r\n\r\n // load OQL Collection Class\r\n oqlCollectionClass = getClass(\"OqlCollectionClass\", DListImpl.class, ManageableCollection.class);\r\n\r\n // set the limit for IN-sql , -1 for no limits\r\n sqlInLimit = getInteger(\"SqlInLimit\", -1);\r\n\r\n //load configuration for PB pool\r\n maxActive = getInteger(PoolConfiguration.MAX_ACTIVE,\r\n PoolConfiguration.DEFAULT_MAX_ACTIVE);\r\n maxIdle = getInteger(PoolConfiguration.MAX_IDLE,\r\n PoolConfiguration.DEFAULT_MAX_IDLE);\r\n maxWait = getLong(PoolConfiguration.MAX_WAIT,\r\n PoolConfiguration.DEFAULT_MAX_WAIT);\r\n timeBetweenEvictionRunsMillis = getLong(PoolConfiguration.TIME_BETWEEN_EVICTION_RUNS_MILLIS,\r\n PoolConfiguration.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);\r\n minEvictableIdleTimeMillis = getLong(PoolConfiguration.MIN_EVICTABLE_IDLE_TIME_MILLIS,\r\n PoolConfiguration.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);\r\n whenExhaustedAction = getByte(PoolConfiguration.WHEN_EXHAUSTED_ACTION,\r\n PoolConfiguration.DEFAULT_WHEN_EXHAUSTED_ACTION);\r\n\r\n useSerializedRepository = getBoolean(\"useSerializedRepository\", false);\r\n }",
"public void scrollOnce() {\n PagerAdapter adapter = getAdapter();\n int currentItem = getCurrentItem();\n int totalCount;\n if (adapter == null || (totalCount = adapter.getCount()) <= 1) {\n return;\n }\n\n int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;\n if (nextItem < 0) {\n if (isCycle) {\n setCurrentItem(totalCount - 1, isBorderAnimation);\n }\n } else if (nextItem == totalCount) {\n if (isCycle) {\n setCurrentItem(0, isBorderAnimation);\n }\n } else {\n setCurrentItem(nextItem, true);\n }\n }",
"public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (newFooterItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);\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 }",
"public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) {\n\t\tResult result = executionEngine.execute( getFindEntitiesQuery() );\n\t\treturn result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS );\n\t}",
"public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n\n for( int i = 0; i < a.numRows; i++ ) {\n\n for( int j = 0; j < b.numCols; j++ ) {\n c.set(i,j,a.get(i,0)*b.get(0,j));\n }\n\n for( int k = 1; k < b.numRows; k++ ) {\n for( int j = 0; j < b.numCols; j++ ) {\n// c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j));\n c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j);\n }\n }\n }\n\n return System.currentTimeMillis() - timeBefore;\n }",
"public static appfwprofile_csrftag_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_csrftag_binding obj = new appfwprofile_csrftag_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_csrftag_binding response[] = (appfwprofile_csrftag_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static List<RebalanceTaskInfo> filterTaskPlanWithStores(List<RebalanceTaskInfo> existingPlanList,\n List<StoreDefinition> storeDefs) {\n List<RebalanceTaskInfo> plans = Lists.newArrayList();\n List<String> storeNames = StoreDefinitionUtils.getStoreNames(storeDefs);\n\n for(RebalanceTaskInfo existingPlan: existingPlanList) {\n RebalanceTaskInfo info = RebalanceTaskInfo.create(existingPlan.toJsonString());\n\n // Filter the plans only for stores given\n HashMap<String, List<Integer>> storeToPartitions = info.getStoreToPartitionIds();\n\n HashMap<String, List<Integer>> newStoreToPartitions = Maps.newHashMap();\n for(String storeName: storeNames) {\n if(storeToPartitions.containsKey(storeName))\n newStoreToPartitions.put(storeName, storeToPartitions.get(storeName));\n }\n info.setStoreToPartitionList(newStoreToPartitions);\n plans.add(info);\n }\n return plans;\n }",
"private void checkLocking(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);\r\n\r\n if (!\"TIMESTAMP\".equals(jdbcType) && !\"INTEGER\".equals(jdbcType))\r\n {\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_LOCKING, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has locking set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UPDATE_LOCK, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has update-lock set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n }\r\n }"
] |
Returns the bill for the month specified.
@param month for which bill to retrieve.
@param year for which bill to retrieve.
@return {@link Response}
@throws RequestException if request to transloadit server fails.
@throws LocalOperationException if something goes wrong while running non-http operations. | [
"public Response getBill(int month, int year)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/bill/\" + year + String.format(\"-%02d\", month)));\n }"
] | [
"static void doDifference(\n Map<String, String> left,\n Map<String, String> right,\n Map<String, String> onlyOnLeft,\n Map<String, String> onlyOnRight,\n Map<String, String> updated\n ) {\n onlyOnRight.clear();\n onlyOnRight.putAll(right);\n for (Map.Entry<String, String> entry : left.entrySet()) {\n String leftKey = entry.getKey();\n String leftValue = entry.getValue();\n if (right.containsKey(leftKey)) {\n String rightValue = onlyOnRight.remove(leftKey);\n if (!leftValue.equals(rightValue)) {\n updated.put(leftKey, leftValue);\n }\n } else {\n onlyOnLeft.put(leftKey, leftValue);\n }\n }\n }",
"public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (newFooterItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);\n }",
"public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) {\n int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N;\n\n if( upper ) {\n return triangleUpper(N,0,nz,-1,1,rand);\n } else {\n return triangleLower(N,0,nz,-1,1,rand);\n }\n }",
"public void store(Object obj) throws PersistenceBrokerException\n {\n obj = extractObjectToStore(obj);\n // only do something if obj != null\n if(obj == null) return;\n\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n /*\n if one of the PK fields was null, we assume the objects\n was new and needs insert\n */\n boolean insert = serviceBrokerHelper().hasNullPKField(cld, obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n /*\n if PK values are set, lookup cache or db to see whether object\n needs insert or update\n */\n if (!insert)\n {\n insert = objectCache.lookup(oid) == null\n && !serviceBrokerHelper().doesExist(cld, oid, obj);\n }\n store(obj, oid, cld, insert);\n }",
"public static final GVRPickedObject[] pickVisible(GVRScene scene) {\n sFindObjectsLock.lock();\n try {\n final GVRPickedObject[] result = NativePicker.pickVisible(scene.getNative());\n return result;\n } finally {\n sFindObjectsLock.unlock();\n }\n }",
"public List<CmsFavoriteEntry> loadFavorites() throws CmsException {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n try {\n CmsUser user = readUser();\n String data = (String)user.getAdditionalInfo(ADDINFO_KEY);\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(data)) {\n return new ArrayList<>();\n }\n JSONObject json = new JSONObject(data);\n JSONArray array = json.getJSONArray(BASE_KEY);\n for (int i = 0; i < array.length(); i++) {\n JSONObject fav = array.getJSONObject(i);\n try {\n CmsFavoriteEntry entry = new CmsFavoriteEntry(fav);\n if (validate(entry)) {\n result.add(entry);\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n\n }\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n return result;\n }",
"public static void main(String[] args) {\r\n Treebank treebank = new DiskTreebank();\r\n treebank.loadPath(args[0]);\r\n WordStemmer ls = new WordStemmer();\r\n for (Tree tree : treebank) {\r\n ls.visitTree(tree);\r\n System.out.println(tree);\r\n }\r\n }",
"public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }",
"private void printImage(PrintStream out, ItemDocument itemDocument) {\n\t\tString imageFile = null;\n\n\t\tif (itemDocument != null) {\n\t\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t\tboolean isImage = \"P18\".equals(sg.getProperty().getId());\n\t\t\t\tif (!isImage) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Statement s : sg) {\n\t\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\t\tValue value = s.getMainSnak().getValue();\n\t\t\t\t\t\tif (value instanceof StringValue) {\n\t\t\t\t\t\t\timageFile = ((StringValue) value).getString();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (imageFile != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (imageFile == null) {\n\t\t\tout.print(\",\\\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\\\"\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tString imageFileEncoded;\n\t\t\t\timageFileEncoded = URLEncoder.encode(\n\t\t\t\t\t\timageFile.replace(\" \", \"_\"), \"utf-8\");\n\t\t\t\t// Keep special title symbols unescaped:\n\t\t\t\timageFileEncoded = imageFileEncoded.replace(\"%3A\", \":\")\n\t\t\t\t\t\t.replace(\"%2F\", \"/\");\n\t\t\t\tout.print(\",\"\n\t\t\t\t\t\t+ csvStringEscape(\"http://commons.wikimedia.org/w/thumb.php?f=\"\n\t\t\t\t\t\t\t\t+ imageFileEncoded) + \"&w=50\");\n\t\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Your JRE does not support UTF-8 encoding. Srsly?!\", e);\n\t\t\t}\n\t\t}\n\t}"
] |
A property tied to the map, updated when the idle state event is fired.
@return | [
"public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() {\n if (bounds == null) {\n bounds = new ReadOnlyObjectWrapper<>(getBounds());\n addStateEventHandler(MapStateEventType.idle, () -> {\n bounds.set(getBounds());\n });\n }\n return bounds.getReadOnlyProperty();\n }"
] | [
"public static vpnvserver_appcontroller_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_appcontroller_binding obj = new vpnvserver_appcontroller_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_appcontroller_binding response[] = (vpnvserver_appcontroller_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected <T> T fromJsonString(String json, Class<T> clazz) {\n\t\treturn _gsonParser.fromJson(json, clazz);\n\t}",
"private static long getVersionId(String versionDir) {\n try {\n return Long.parseLong(versionDir.replace(\"version-\", \"\"));\n } catch(NumberFormatException e) {\n logger.trace(\"Cannot parse version directory to obtain id \" + versionDir);\n return -1;\n }\n }",
"private void appendLikeCriteria(TableAlias alias, PathInfo pathInfo, LikeCriteria c, StringBuffer buf)\r\n {\r\n appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n\r\n buf.append(m_platform.getEscapeClause(c));\r\n }",
"public ItemRequest<Webhook> deleteById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"DELETE\");\n }",
"public static String workDays(ProjectCalendar input)\n {\n StringBuilder result = new StringBuilder();\n DayType[] test = input.getDays(); // get the array from MPXJ ProjectCalendar\n for (DayType i : test)\n { // go through every day in the given array\n if (i == DayType.NON_WORKING)\n {\n result.append(\"N\"); // only put N for non-working day of the week\n }\n else\n {\n result.append(\"Y\"); // Assume WORKING day unless NON_WORKING\n }\n }\n return result.toString(); // According to USACE specs., exceptions will be specified in HOLI records\n }",
"private String createMethodSignature(Method method)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(\"(\");\n for (Class<?> type : method.getParameterTypes())\n {\n sb.append(getTypeString(type));\n }\n sb.append(\")\");\n Class<?> type = method.getReturnType();\n if (type.getName().equals(\"void\"))\n {\n sb.append(\"V\");\n }\n else\n {\n sb.append(getTypeString(type));\n }\n return sb.toString();\n }",
"public void removeMapping(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n Collection<V> newC = cf.newCollection();\r\n newC.addAll(c);\r\n newC.remove(value);\r\n map.put(key, newC);\r\n }\r\n\r\n } else {\r\n Collection<V> c = get(key);\r\n c.remove(value);\r\n }\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 }"
] |
Fetches the current online data for the given item, and fixes the
precision of integer quantities if necessary.
@param itemIdValue
the id of the document to inspect
@param propertyId
id of the property to consider | [
"protected void fixIntegerPrecisions(ItemIdValue itemIdValue,\n\t\t\tString propertyId) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Get the current statements for the property we want to fix:\n\t\t\tStatementGroup editPropertyStatements = currentItemDocument\n\t\t\t\t\t.findStatementGroup(propertyId);\n\t\t\tif (editPropertyStatements == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" no longer has any statements for \" + propertyId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tPropertyIdValue property = Datamodel\n\t\t\t\t\t.makeWikidataPropertyIdValue(propertyId);\n\t\t\tList<Statement> updateStatements = new ArrayList<>();\n\t\t\tfor (Statement s : editPropertyStatements) {\n\t\t\t\tQuantityValue qv = (QuantityValue) s.getValue();\n\t\t\t\tif (qv != null && isPlusMinusOneValue(qv)) {\n\t\t\t\t\tQuantityValue exactValue = Datamodel.makeQuantityValue(\n\t\t\t\t\t\t\tqv.getNumericValue(), qv.getNumericValue(),\n\t\t\t\t\t\t\tqv.getNumericValue());\n\t\t\t\t\tStatement exactStatement = StatementBuilder\n\t\t\t\t\t\t\t.forSubjectAndProperty(itemIdValue, property)\n\t\t\t\t\t\t\t.withValue(exactValue).withId(s.getStatementId())\n\t\t\t\t\t\t\t.withQualifiers(s.getQualifiers())\n\t\t\t\t\t\t\t.withReferences(s.getReferences())\n\t\t\t\t\t\t\t.withRank(s.getRank()).build();\n\t\t\t\t\tupdateStatements.add(exactStatement);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (updateStatements.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** \" + qid + \" quantity values for \"\n\t\t\t\t\t\t+ propertyId + \" already fixed\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tupdateStatements, propertyId);\n\n\t\t\tdataEditor.updateStatements(currentItemDocument, updateStatements,\n\t\t\t\t\tCollections.<Statement> emptyList(),\n\t\t\t\t\t\"Set exact values for [[Property:\" + propertyId + \"|\"\n\t\t\t\t\t\t\t+ propertyId + \"]] integer quantities (Task MB2)\");\n\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}"
] | [
"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}",
"public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\n }",
"public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\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 }",
"@Override\r\n public V remove(Object key) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.remove(key);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.remove(key));\r\n }\r\n }\r\n }",
"private void processVirtualHostName(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest) {\n String virtualHostName;\n if (httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME) != null) {\n virtualHostName = HttpUtilities.removePortFromHostHeaderString(httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME).getValue());\n } else {\n virtualHostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n }\n httpMethodProxyRequest.getParams().setVirtualHost(virtualHostName);\n }",
"private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }",
"public static String encodeQueryParam(String queryParam, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM);\n\t}",
"boolean deleteEntity(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n clearProperties(txn, entity);\n clearBlobs(txn, entity);\n deleteLinks(txn, entity);\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final ByteIterable key = LongBinding.longToCompressedEntry(entityLocalId);\n if (config.isDebugSearchForIncomingLinksOnDelete()) {\n // search for incoming links\n final List<String> allLinkNames = getAllLinkNames(txn);\n for (final String entityType : txn.getEntityTypes()) {\n for (final String linkName : allLinkNames) {\n //noinspection LoopStatementThatDoesntLoop\n for (final Entity referrer : txn.findLinks(entityType, entity, linkName)) {\n throw new EntityStoreException(entity +\n \" is about to be deleted, but it is referenced by \" + referrer + \", link name: \" + linkName);\n }\n }\n }\n }\n if (getEntitiesTable(txn, entityTypeId).delete(txn.getEnvironmentTransaction(), key)) {\n txn.entityDeleted(id);\n return true;\n }\n return false;\n }"
] |
Add a '>=' clause so the column must be greater-than or equals-to the value. | [
"public Where<T, ID> ge(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}"
] | [
"private Set<QualifierInstance> getRequiredQualifiers(EnhancedAnnotatedParameter<?, ? super X> enhancedDisposedParameter) {\n Set<Annotation> disposedParameterQualifiers = enhancedDisposedParameter.getMetaAnnotations(Qualifier.class);\n if (disposedParameterQualifiers.isEmpty()) {\n disposedParameterQualifiers = Collections.<Annotation> singleton(Default.Literal.INSTANCE);\n }\n return beanManager.getServices().get(MetaAnnotationStore.class).getQualifierInstances(disposedParameterQualifiers);\n }",
"private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }",
"@JsonProperty(\"paging\")\n void paging(String paging) {\n builder.paging(IndexPagingState.fromByteBuffer(ByteBufferUtils.byteBuffer(paging)));\n }",
"public boolean setMethodArguments(String pathName, String methodName, Integer ordinal, Object... arguments) {\n try {\n BasicNameValuePair[] params = new BasicNameValuePair[arguments.length + 2];\n int x = 0;\n for (Object argument : arguments) {\n params[x] = new BasicNameValuePair(\"arguments[]\", argument.toString());\n x++;\n }\n params[x] = new BasicNameValuePair(\"profileIdentifier\", this._profileName);\n params[x + 1] = new BasicNameValuePair(\"ordinal\", ordinal.toString());\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodName, params));\n\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }",
"boolean lockShared(final Integer permit, final long timeout, final TimeUnit unit) {\n boolean result = false;\n try {\n result = lockSharedInterruptibly(permit, timeout, unit);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return result;\n }",
"public void load(List<E> result) {\n ++pageCount;\n if (this.result == null || this.result.isEmpty()) {\n this.result = result;\n } else {\n this.result.addAll(result);\n }\n }",
"protected static BufferedReader createFileReader(String file_name)\n throws BeastException {\n try {\n return new BufferedReader(new FileReader(file_name));\n } catch (FileNotFoundException e) {\n Logger logger = Logger.getLogger(MASReader.class.getName());\n logger.severe(\"ERROR: \" + e.toString());\n throw new BeastException(\"ERROR: \" + e.toString(), e);\n }\n }",
"public void setOwner(Graph<DataT, NodeT> ownerGraph) {\n if (this.ownerGraph != null) {\n throw new RuntimeException(\"Changing owner graph is not allowed\");\n }\n this.ownerGraph = ownerGraph;\n }",
"@Override\r\n public void putAll(Map<? extends K, ? extends V> in) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n temp.putAll(in);\r\n map = temp;\r\n }\r\n } else {\r\n synchronized (map) {\r\n map.putAll(in);\r\n }\r\n }\r\n }"
] |
Creates a XopBean. The image on the disk is included as a byte array,
a DataHandler and java.awt.Image
@return the bean
@throws Exception | [
"private XopBean createXopBean() throws Exception {\n XopBean xop = new XopBean();\n xop.setName(\"xopName\");\n \n InputStream is = getClass().getResourceAsStream(\"/java.jpg\");\n byte[] data = IOUtils.readBytesFromStream(is);\n \n // Pass java.jpg as an array of bytes\n xop.setBytes(data);\n \n // Wrap java.jpg as a DataHandler\n xop.setDatahandler(new DataHandler(\n new ByteArrayDataSource(data, \"application/octet-stream\")));\n \n if (Boolean.getBoolean(\"java.awt.headless\")) {\n System.out.println(\"Running headless. Ignoring an Image property.\");\n } else {\n xop.setImage(getImage(\"/java.jpg\"));\n }\n \n return xop;\n }"
] | [
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> updateClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID,\n @RequestParam(required = false) Boolean active,\n @RequestParam(required = false) String friendlyName,\n @RequestParam(required = false) Boolean reset) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n if (active != null) {\n logger.info(\"Active: {}\", active);\n clientService.updateActive(profileId, clientUUID, active);\n }\n\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, clientUUID, friendlyName);\n }\n\n if (reset != null && reset) {\n clientService.reset(profileId, clientUUID);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }",
"private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }",
"private void attachLocaleGroups(CmsResource copiedPage) throws CmsException {\n\n CmsLocaleGroupService localeGroupService = getRootCms().getLocaleGroupService();\n if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) {\n try {\n localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n }",
"public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }",
"protected void createSequence(PersistenceBroker broker, FieldDescriptor field,\r\n String sequenceName, long maxKey) throws Exception\r\n {\r\n Statement stmt = null;\r\n try\r\n {\r\n stmt = broker.serviceStatementManager().getGenericStatement(field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n stmt.execute(sp_createSequenceQuery(sequenceName, maxKey));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(e);\r\n throw new SequenceManagerException(\"Could not create new row in \"+SEQ_TABLE_NAME+\" table - TABLENAME=\" +\r\n sequenceName + \" field=\" + field.getColumnName(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (stmt != null) stmt.close();\r\n }\r\n catch (SQLException sqle)\r\n {\r\n if(log.isDebugEnabled())\r\n log.debug(\"Threw SQLException while in createSequence and closing stmt\", sqle);\r\n // ignore it\r\n }\r\n }\r\n }",
"public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }",
"private long getTotalTime(ProjectCalendarDateRanges exception, Date date, boolean after)\n {\n long currentTime = DateHelper.getCanonicalTime(date).getTime();\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd(), currentTime, after);\n }\n return (total);\n }",
"public static void createEphemeralPath(ZkClient zkClient, String path, String data) {\n try {\n zkClient.createEphemeral(path, Utils.getBytes(data));\n } catch (ZkNoNodeException e) {\n createParentPath(zkClient, path);\n zkClient.createEphemeral(path, Utils.getBytes(data));\n }\n }",
"private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {\n long now = System.nanoTime();\n return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >\n slack.get();\n }"
] |
Compare the controlDOM and testDOM and save and return the differences in a list.
@return list with differences | [
"@SuppressWarnings(\"unchecked\")\r\n\tpublic List<Difference> compare() {\r\n\t\tDiff diff = new Diff(this.controlDOM, this.testDOM);\r\n\t\tDetailedDiff detDiff = new DetailedDiff(diff);\r\n\t\treturn detDiff.getAllDifferences();\r\n\t}"
] | [
"private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\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 }",
"public static <ResultT> PollingState<ResultT> createFromJSONString(String serializedPollingState) {\n ObjectMapper mapper = initMapper(new ObjectMapper());\n PollingState<ResultT> pollingState;\n try {\n pollingState = mapper.readValue(serializedPollingState, PollingState.class);\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n return pollingState;\n }",
"public SerialMessage getMultiInstanceGetMessage(CommandClass commandClass) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_INSTANCE_GET for node {} and command class {}\", this.getNode().getNodeId(), commandClass.getLabel());\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_INSTANCE_GET,\r\n\t\t\t\t\t\t\t\t(byte) commandClass.getKey()\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public static List<Sentence> splitSentences(CharSequence text) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.splitSentences(text)\n );\n }",
"public void sendLoadTrackCommand(DeviceUpdate target, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n ensureRunning();\n byte[] payload = new byte[LOAD_TRACK_PAYLOAD.length];\n System.arraycopy(LOAD_TRACK_PAYLOAD, 0, payload, 0, LOAD_TRACK_PAYLOAD.length);\n payload[0x02] = getDeviceNumber();\n payload[0x05] = getDeviceNumber();\n payload[0x09] = (byte)sourcePlayer;\n payload[0x0a] = sourceSlot.protocolValue;\n payload[0x0b] = sourceType.protocolValue;\n Util.numberToBytes(rekordboxId, payload, 0x0d, 4);\n assembleAndSendPacket(Util.PacketType.LOAD_TRACK_COMMAND, payload, target.getAddress(), UPDATE_PORT);\n }",
"public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }",
"protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(violationMessage);\n return violation;\n }",
"public static base_response unset(nitro_service client, sslocspresponder resource, String[] args) throws Exception{\n\t\tsslocspresponder unsetresource = new sslocspresponder();\n\t\tunsetresource.name = resource.name;\n\t\tunsetresource.insertclientcert = resource.insertclientcert;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Adds the specified type to this frame, and returns a new object that implements this type. | [
"public static <T extends WindupVertexFrame> T addTypeToModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().addTypeToElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, type);\n }"
] | [
"public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) {\n final DbArtifact artifact = getArtifact(gavc);\n final List<DbLicense> licenses = new ArrayList<>();\n\n for(final String name: artifact.getLicenses()){\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name);\n\n // Here is a license to identify\n if(matchingLicenses.isEmpty()){\n final DbLicense notIdentifiedLicense = new DbLicense();\n notIdentifiedLicense.setName(name);\n licenses.add(notIdentifiedLicense);\n } else {\n matchingLicenses.stream()\n .filter(filters::shouldBeInReport)\n .forEach(licenses::add);\n }\n }\n\n return licenses;\n }",
"public String genId() {\n S.Buffer sb = S.newBuffer();\n sb.a(longEncoder.longToStr(nodeIdProvider.nodeId()))\n .a(longEncoder.longToStr(startIdProvider.startId()))\n .a(longEncoder.longToStr(sequenceProvider.seqId()));\n return sb.toString();\n }",
"void decodeContentType(String rawLine) {\r\n int slash = rawLine.indexOf('/');\r\n if (slash == -1) {\r\n// if (DEBUG) getLogger().debug(\"decoding ... no slash found\");\r\n return;\r\n } else {\r\n primaryType = rawLine.substring(0, slash).trim();\r\n }\r\n int semicolon = rawLine.indexOf(';');\r\n if (semicolon == -1) {\r\n// if (DEBUG) getLogger().debug(\"decoding ... no semicolon found\");\r\n secondaryType = rawLine.substring(slash + 1).trim();\r\n return;\r\n }\r\n // have parameters\r\n secondaryType = rawLine.substring(slash + 1, semicolon).trim();\r\n Header h = new Header(rawLine);\r\n parameters = h.getParams();\r\n }",
"public MBeanOperationInfo getOperationInfo(String operationName)\n throws OperationNotFoundException, UnsupportedEncodingException {\n\n String decodedOperationName = sanitizer.urlDecode(operationName, encoding);\n Map<String, MBeanOperationInfo> operationMap = getOperationMetadata();\n if (operationMap.containsKey(decodedOperationName)) {\n return operationMap.get(decodedOperationName);\n }\n throw new OperationNotFoundException(\"Could not find operation \" + operationName + \" on MBean \" +\n objectName.getCanonicalName());\n }",
"public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public static 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 final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }",
"static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }",
"public void removeCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);\n }"
] |
Registers a BeanNameAutoProxyCreator class that wraps the bean being
monitored. The proxy is associated with the PerformanceMonitorInterceptor
for the bean, which is created when parsing the methods attribute from
the springconfiguration xml file.
@param source An Attribute node from the spring configuration
@param holder A container for the beans I will create
@param context the context currently parsing my spring config | [
"private void registerProxyCreator(Node source,\n BeanDefinitionHolder holder,\n ParserContext context) {\n\n String beanName = holder.getBeanName();\n String proxyName = beanName + \"Proxy\";\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class);\n\n initializer.addPropertyValue(\"beanNames\", beanName);\n initializer.addPropertyValue(\"interceptorNames\", interceptorName);\n\n BeanDefinitionRegistry registry = context.getRegistry();\n registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition());\n }"
] | [
"protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }",
"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 }",
"private void countPropertyMain(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property, int count) {\n\t\taddPropertyCounters(usageStatistics, property);\n\t\tusageStatistics.propertyCountsMain.put(property,\n\t\t\t\tusageStatistics.propertyCountsMain.get(property) + count);\n\t}",
"protected List<String> getPluginsPath() throws IOException {\n List<String> result = new ArrayList<>();\n Path pluginsDirectory = PROPERTIES.getAllureHome().resolve(\"plugins\").toAbsolutePath();\n if (Files.notExists(pluginsDirectory)) {\n return Collections.emptyList();\n }\n\n try (DirectoryStream<Path> plugins = Files.newDirectoryStream(pluginsDirectory, JAR_FILES)) {\n for (Path plugin : plugins) {\n result.add(plugin.toUri().toURL().toString());\n }\n }\n return result;\n }",
"static void merge(Map<ConfigurationKey, Object> original, Map<ConfigurationKey, Object> toMerge, String mergedSourceDescription) {\n for (Entry<ConfigurationKey, Object> entry : toMerge.entrySet()) {\n Object existing = original.get(entry.getKey());\n if (existing != null) {\n ConfigurationLogger.LOG.configurationKeyAlreadySet(entry.getKey().get(), existing, entry.getValue(), mergedSourceDescription);\n } else {\n original.put(entry.getKey(), entry.getValue());\n }\n }\n }",
"@Pure\n\tpublic static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure0() {\n\t\t\t@Override\n\t\t\tpublic void apply() {\n\t\t\t\tprocedure.apply(argument);\n\t\t\t}\n\t\t};\n\t}",
"public void parseAndAddDictionaries(CmsObject cms) throws CmsRoleViolationException {\n\n OpenCms.getRoleManager().checkRole(cms, CmsRole.ROOT_ADMIN);\n CmsSpellcheckDictionaryIndexer.parseAndAddZippedDictionaries(m_solrClient, cms);\n CmsSpellcheckDictionaryIndexer.parseAndAddDictionaries(m_solrClient, cms);\n }",
"public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }",
"private List<Bucket> lookup(Record record) {\n List<Bucket> buckets = new ArrayList();\n for (Property p : config.getLookupProperties()) {\n String propname = p.getName();\n Collection<String> values = record.getValues(propname);\n if (values == null)\n continue;\n\n for (String value : values) {\n String[] tokens = StringUtils.split(value);\n for (int ix = 0; ix < tokens.length; ix++) {\n Bucket b = store.lookupToken(propname, tokens[ix]);\n if (b == null || b.records == null)\n continue;\n long[] ids = b.records;\n if (DEBUG)\n System.out.println(propname + \", \" + tokens[ix] + \": \" + b.nextfree + \" (\" + b.getScore() + \")\");\n buckets.add(b);\n }\n }\n }\n\n return buckets;\n }"
] |
Get the Roman Numeral of the current value
@return | [
"public String toRomanNumeral() {\n\t\tif (this.romanString == null) {\n\t\t\tthis.romanString = \"\";\n\t\t\tint remainder = this.value;\n\t\t\tfor (int i = 0; i < BASIC_VALUES.length; i++) {\n\t\t\t\twhile (remainder >= BASIC_VALUES[i]) {\n\t\t\t\t\tthis.romanString += BASIC_ROMAN_NUMERALS[i];\n\t\t\t\t\tremainder -= BASIC_VALUES[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this.romanString;\n\t}"
] | [
"public void updateLinks(ServiceReference<S> serviceReference) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);\n boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);\n if (isAlreadyLinked && !canBeLinked) {\n linkerManagement.unlink(declaration, serviceReference);\n } else if (!isAlreadyLinked && canBeLinked) {\n linkerManagement.link(declaration, serviceReference);\n }\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 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}",
"public void histogramToStructure(int histogram[] ) {\n col_idx[0] = 0;\n int index = 0;\n for (int i = 1; i <= numCols; i++) {\n col_idx[i] = index += histogram[i-1];\n }\n nz_length = index;\n growMaxLength( nz_length , false);\n if( col_idx[numCols] != nz_length )\n throw new RuntimeException(\"Egads\");\n }",
"@Override\n public <K, V> StoreClient<K, V> getStoreClient(final String storeName,\n final InconsistencyResolver<Versioned<V>> resolver) {\n // wrap it in LazyStoreClient here so any direct calls to this method\n // returns a lazy client\n return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() {\n\n @Override\n public StoreClient<K, V> call() throws Exception {\n Store<K, V, Object> clientStore = getRawStore(storeName, resolver);\n return new RESTClient<K, V>(storeName, clientStore);\n }\n }, true);\n }",
"public synchronized void cleanWaitTaskQueue() {\n\n for (ParallelTask task : waitQ) {\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n\n }\n\n waitQ.clear();\n }",
"public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"file\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n requestJSON.add(\"action\", action.toJSONString());\n\n if (message != null && !message.isEmpty()) {\n requestJSON.add(\"message\", message);\n }\n\n if (dueAt != null) {\n requestJSON.add(\"due_at\", BoxDateFormat.format(dueAt));\n }\n\n URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedTask.new Info(responseJSON);\n }",
"protected void addFacetPart(CmsSolrQuery query) {\n\n StringBuffer value = new StringBuffer();\n value.append(\"{!key=\").append(m_config.getName());\n addFacetOptions(value);\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n value.append(\" ex=\").append(m_config.getIgnoreTags());\n }\n value.append(\"}\");\n value.append(m_config.getRange());\n query.add(\"facet.range\", value.toString());\n }",
"public static wisite_binding get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_binding obj = new wisite_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_binding response = (wisite_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Checks the widget by index
@param checkableIndex The index is in the range from 0 to size -1, where size is the number of
Checkable widgets in the group. It does not take into account any
non-Checkable widgets added to the group widget.
@return {@code True} if {@code checkableWidget} is a child of this {@code CheckableGroup} and
was not already checked; {@code false} otherwise. | [
"public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }",
"public String toMixedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.mixedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.mixedString = result = toNormalizedString(IPv6StringCache.mixedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toMixedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"public static void composeThroughMask(Raster src, WritableRaster dst, Raster sel) {\n\t\tint x = src.getMinX();\n\t\tint y = src.getMinY();\n\t\tint w = src.getWidth();\n\t\tint h = src.getHeight();\n\n\t\tint srcRGB[] = null;\n\t\tint selRGB[] = null;\n\t\tint dstRGB[] = null;\n\n\t\tfor ( int i = 0; i < h; i++ ) {\n\t\t\tsrcRGB = src.getPixels(x, y, w, 1, srcRGB);\n\t\t\tselRGB = sel.getPixels(x, y, w, 1, selRGB);\n\t\t\tdstRGB = dst.getPixels(x, y, w, 1, dstRGB);\n\n\t\t\tint k = x;\n\t\t\tfor ( int j = 0; j < w; j++ ) {\n\t\t\t\tint sr = srcRGB[k];\n\t\t\t\tint dir = dstRGB[k];\n\t\t\t\tint sg = srcRGB[k+1];\n\t\t\t\tint dig = dstRGB[k+1];\n\t\t\t\tint sb = srcRGB[k+2];\n\t\t\t\tint dib = dstRGB[k+2];\n\t\t\t\tint sa = srcRGB[k+3];\n\t\t\t\tint dia = dstRGB[k+3];\n\n\t\t\t\tfloat a = selRGB[k+3]/255f;\n\t\t\t\tfloat ac = 1-a;\n\n\t\t\t\tdstRGB[k] = (int)(a*sr + ac*dir); \n\t\t\t\tdstRGB[k+1] = (int)(a*sg + ac*dig); \n\t\t\t\tdstRGB[k+2] = (int)(a*sb + ac*dib); \n\t\t\t\tdstRGB[k+3] = (int)(a*sa + ac*dia);\n\t\t\t\tk += 4;\n\t\t\t}\n\n\t\t\tdst.setPixels(x, y, w, 1, dstRGB);\n\t\t\ty++;\n\t\t}\n\t}",
"public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }",
"public void sendLoadTrackCommand(DeviceUpdate target, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n ensureRunning();\n byte[] payload = new byte[LOAD_TRACK_PAYLOAD.length];\n System.arraycopy(LOAD_TRACK_PAYLOAD, 0, payload, 0, LOAD_TRACK_PAYLOAD.length);\n payload[0x02] = getDeviceNumber();\n payload[0x05] = getDeviceNumber();\n payload[0x09] = (byte)sourcePlayer;\n payload[0x0a] = sourceSlot.protocolValue;\n payload[0x0b] = sourceType.protocolValue;\n Util.numberToBytes(rekordboxId, payload, 0x0d, 4);\n assembleAndSendPacket(Util.PacketType.LOAD_TRACK_COMMAND, payload, target.getAddress(), UPDATE_PORT);\n }",
"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}",
"@Deprecated\n public FluoConfiguration addObservers(Iterable<ObserverSpecification> observers) {\n int next = getNextObserverId();\n for (ObserverSpecification oconf : observers) {\n addObserver(oconf, next++);\n }\n return this;\n }",
"public static base_responses update(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver updateresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new ntpserver();\n\t\t\t\tupdateresources[i].serverip = resources[i].serverip;\n\t\t\t\tupdateresources[i].servername = resources[i].servername;\n\t\t\t\tupdateresources[i].minpoll = resources[i].minpoll;\n\t\t\t\tupdateresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\tupdateresources[i].preferredntpserver = resources[i].preferredntpserver;\n\t\t\t\tupdateresources[i].autokey = resources[i].autokey;\n\t\t\t\tupdateresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 }"
] |
Returns a human-readable string representation of a reference to a
precision that is used for a time value.
@param precision
the numeric precision
@return a string representation of the precision | [
"protected static String getTimePrecisionString(byte precision) {\n\t\tswitch (precision) {\n\t\tcase TimeValue.PREC_SECOND:\n\t\t\treturn \"sec\";\n\t\tcase TimeValue.PREC_MINUTE:\n\t\t\treturn \"min\";\n\t\tcase TimeValue.PREC_HOUR:\n\t\t\treturn \"hour\";\n\t\tcase TimeValue.PREC_DAY:\n\t\t\treturn \"day\";\n\t\tcase TimeValue.PREC_MONTH:\n\t\t\treturn \"month\";\n\t\tcase TimeValue.PREC_YEAR:\n\t\t\treturn \"year\";\n\t\tcase TimeValue.PREC_DECADE:\n\t\t\treturn \"decade\";\n\t\tcase TimeValue.PREC_100Y:\n\t\t\treturn \"100 years\";\n\t\tcase TimeValue.PREC_1KY:\n\t\t\treturn \"1000 years\";\n\t\tcase TimeValue.PREC_10KY:\n\t\t\treturn \"10K years\";\n\t\tcase TimeValue.PREC_100KY:\n\t\t\treturn \"100K years\";\n\t\tcase TimeValue.PREC_1MY:\n\t\t\treturn \"1 million years\";\n\t\tcase TimeValue.PREC_10MY:\n\t\t\treturn \"10 million years\";\n\t\tcase TimeValue.PREC_100MY:\n\t\t\treturn \"100 million years\";\n\t\tcase TimeValue.PREC_1GY:\n\t\t\treturn \"1000 million years\";\n\t\tdefault:\n\t\t\treturn \"Unsupported precision \" + precision;\n\t\t}\n\t}"
] | [
"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 static sslcertkey[] get(nitro_service service, String certkey[]) throws Exception{\n\t\tif (certkey !=null && certkey.length>0) {\n\t\t\tsslcertkey response[] = new sslcertkey[certkey.length];\n\t\t\tsslcertkey obj[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++) {\n\t\t\t\tobj[i] = new sslcertkey();\n\t\t\t\tobj[i].set_certkey(certkey[i]);\n\t\t\t\tresponse[i] = (sslcertkey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }",
"public static base_response delete(nitro_service client, String labelname) throws Exception {\n\t\tdnspolicylabel deleteresource = new dnspolicylabel();\n\t\tdeleteresource.labelname = labelname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private void validateAttributesToCreateANewRendererViewHolder() {\n if (viewType == null) {\n throw new NullContentException(\n \"RendererBuilder needs a view type to create a RendererViewHolder\");\n }\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\");\n }\n if (parent == null) {\n throw new NullParentException(\n \"RendererBuilder needs a parent to create a RendererViewHolder\");\n }\n }",
"public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() {\n final List<FieldNode> result = new ArrayList<FieldNode>();\n for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) {\n final Initialisers setters = entry.getValue();\n final List<MethodNode> initialisingMethods = setters.getMethods();\n if (initialisingMethods.isEmpty()) {\n result.add(entry.getKey());\n }\n }\n for (final FieldNode unassociatedVariable : result) {\n candidatesAndInitialisers.remove(unassociatedVariable);\n }\n return result;\n }",
"protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }",
"public static base_response update(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction updateresource = new autoscaleaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.parameters = resource.parameters;\n\t\tupdateresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\tupdateresource.quiettime = resource.quiettime;\n\t\tupdateresource.vserver = resource.vserver;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Save an HTTP response to a file
@param response the response to save
@param destFile the destination file
@throws IOException if the response could not be downloaded | [
"private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }"
] | [
"static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}",
"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 static double blackModelSwaptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble swapAnnuity)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t}",
"public void loadProfile(Object key)\r\n {\r\n if (!isEnablePerThreadChanges())\r\n {\r\n throw new MetadataException(\"Can not load profile with disabled per thread mode\");\r\n }\r\n DescriptorRepository rep = (DescriptorRepository) metadataProfiles.get(key);\r\n if (rep == null)\r\n {\r\n throw new MetadataException(\"Can not find profile for key '\" + key + \"'\");\r\n }\r\n currentProfileKey.set(key);\r\n setDescriptor(rep);\r\n }",
"public WebSocketContext messageReceived(String receivedMessage) {\n this.stringMessage = S.string(receivedMessage).trim();\n isJson = stringMessage.startsWith(\"{\") || stringMessage.startsWith(\"]\");\n tryParseQueryParams();\n return this;\n }",
"WaveformDetail getWaveformDetail(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n final NumberField idField = new NumberField(rekordboxId);\n\n // First try to get the NXS2-style color waveform if we are supposed to.\n if (preferColor.get()) {\n try {\n Message response = client.simpleRequest(Message.KnownType.ANLZ_TAG_REQ, Message.KnownType.ANLZ_TAG,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField,\n new NumberField(Message.ANLZ_FILE_TAG_COLOR_WAVEFORM_DETAIL), new NumberField(Message.ALNZ_FILE_TYPE_EXT));\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n } catch (Exception e) {\n logger.info(\"No color waveform available for slot \" + slot + \", id \" + rekordboxId + \"; requesting blue version.\", e);\n }\n }\n\n Message response = client.simpleRequest(Message.KnownType.WAVE_DETAIL_REQ, Message.KnownType.WAVE_DETAIL,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField, NumberField.WORD_0);\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n }",
"public void notifySubscriberCallback(ContentNotification cn) {\n String content = fetchContentFromPublisher(cn);\n\n distributeContentToSubscribers(content, cn.getUrl());\n }",
"public int[] getDefalutValuesArray() {\n int[] defaultValues = new int[5];\n\n defaultValues[0] = GLES20.GL_LINEAR_MIPMAP_NEAREST; // MIN FILTER\n defaultValues[1] = GLES20.GL_LINEAR; // MAG FILTER\n defaultValues[2] = 1; // ANISO FILTER\n defaultValues[3] = GLES20.GL_CLAMP_TO_EDGE; // WRAP S\n defaultValues[4] = GLES20.GL_CLAMP_TO_EDGE; // WRAP T\n\n return defaultValues;\n }",
"protected boolean clearSpecial(DatabaseConnection connection, Logger logger) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tboolean cleared = false;\n\t\tif (connection == null) {\n\t\t\t// ignored\n\t\t} else if (currentSaved == null) {\n\t\t\tlogger.error(\"no connection has been saved when clear() called\");\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\tif (currentSaved.decrementAndGet() == 0) {\n\t\t\t\t// we only clear the connection if nested counter is 0\n\t\t\t\tspecialConnection.set(null);\n\t\t\t}\n\t\t\tcleared = true;\n\t\t} else {\n\t\t\tlogger.error(\"connection saved {} is not the one being cleared {}\", currentSaved.connection, connection);\n\t\t}\n\t\t// release should then be called after clear\n\t\treturn cleared;\n\t}"
] |
Perform all Cursor cleanup here. | [
"void close() {\n mIODevice = null;\n GVRSceneObject owner = getOwnerObject();\n if (owner.getParent() != null) {\n owner.getParent().removeChildObject(owner);\n }\n }"
] | [
"public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\n }",
"public ParallelTaskBuilder setReplacementVarMap(\n Map<String, String> replacementVarMap) {\n this.replacementVarMap = replacementVarMap;\n\n // TODO Check and warning of overwriting\n // set as uniform\n this.requestReplacementType = RequestReplacementType.UNIFORM_VAR_REPLACEMENT;\n return this;\n }",
"public static base_response delete(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata deleteresource = new appfwlearningdata();\n\t\tdeleteresource.profilename = resource.profilename;\n\t\tdeleteresource.starturl = resource.starturl;\n\t\tdeleteresource.cookieconsistency = resource.cookieconsistency;\n\t\tdeleteresource.fieldconsistency = resource.fieldconsistency;\n\t\tdeleteresource.formactionurl_ffc = resource.formactionurl_ffc;\n\t\tdeleteresource.crosssitescripting = resource.crosssitescripting;\n\t\tdeleteresource.formactionurl_xss = resource.formactionurl_xss;\n\t\tdeleteresource.sqlinjection = resource.sqlinjection;\n\t\tdeleteresource.formactionurl_sql = resource.formactionurl_sql;\n\t\tdeleteresource.fieldformat = resource.fieldformat;\n\t\tdeleteresource.formactionurl_ff = resource.formactionurl_ff;\n\t\tdeleteresource.csrftag = resource.csrftag;\n\t\tdeleteresource.csrfformoriginurl = resource.csrfformoriginurl;\n\t\tdeleteresource.xmldoscheck = resource.xmldoscheck;\n\t\tdeleteresource.xmlwsicheck = resource.xmlwsicheck;\n\t\tdeleteresource.xmlattachmentcheck = resource.xmlattachmentcheck;\n\t\tdeleteresource.totalxmlrequests = resource.totalxmlrequests;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}",
"private void readTableData(List<SynchroTable> tables, InputStream is) throws IOException\n {\n for (SynchroTable table : tables)\n {\n if (REQUIRED_TABLES.contains(table.getName()))\n {\n readTable(is, table);\n }\n }\n }",
"public Sites getSitesInformation() throws IOException {\n\t\tMwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES);\n\t\tif (sitesTableDump == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Create a suitable processor for such dumps and process the file:\n\t\tMwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor();\n\t\tsitesDumpFileProcessor.processDumpFileContents(\n\t\t\t\tsitesTableDump.getDumpFileStream(), sitesTableDump);\n\n\t\treturn sitesDumpFileProcessor.getSites();\n\t}",
"static void undoChanges(final PatchEntry entry, final PatchContentLoader loader) {\n final List<ContentModification> modifications = new ArrayList<ContentModification>(entry.rollbackActions);\n for (final ContentModification modification : modifications) {\n final ContentItem item = modification.getItem();\n if (item.getContentType() != ContentType.MISC) {\n // Skip modules and bundles they should be removed as part of the {@link FinalizeCallback}\n continue;\n }\n final PatchingTaskDescription description = new PatchingTaskDescription(entry.applyPatchId, modification, loader, false, false, false);\n try {\n final PatchingTask task = PatchingTask.Factory.create(description, entry);\n task.execute(entry);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.failedToUndoChange(item.toString());\n }\n }\n }",
"@SuppressWarnings(\"unchecked\")\r\n public static boolean addPropertyDefault(PropertiesImpl props, PropertyDefinition<?> propDef) {\r\n\r\n if ((props == null) || (props.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Props must not be null!\");\r\n }\r\n\r\n if (propDef == null) {\r\n return false;\r\n }\r\n\r\n List<?> defaultValue = propDef.getDefaultValue();\r\n if ((defaultValue != null) && (!defaultValue.isEmpty())) {\r\n switch (propDef.getPropertyType()) {\r\n case BOOLEAN:\r\n props.addProperty(new PropertyBooleanImpl(propDef.getId(), (List<Boolean>)defaultValue));\r\n break;\r\n case DATETIME:\r\n props.addProperty(new PropertyDateTimeImpl(propDef.getId(), (List<GregorianCalendar>)defaultValue));\r\n break;\r\n case DECIMAL:\r\n props.addProperty(new PropertyDecimalImpl(propDef.getId(), (List<BigDecimal>)defaultValue));\r\n break;\r\n case HTML:\r\n props.addProperty(new PropertyHtmlImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case ID:\r\n props.addProperty(new PropertyIdImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case INTEGER:\r\n props.addProperty(new PropertyIntegerImpl(propDef.getId(), (List<BigInteger>)defaultValue));\r\n break;\r\n case STRING:\r\n props.addProperty(new PropertyStringImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case URI:\r\n props.addProperty(new PropertyUriImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n default:\r\n throw new RuntimeException(\"Unknown datatype! Spec change?\");\r\n }\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"private void writeAssignmentBaselines(Project.Assignments.Assignment xml, ResourceAssignment mpxj)\n {\n Project.Assignments.Assignment.Baseline baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n boolean populated = false;\n\n Number cost = mpxj.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n Date date = mpxj.getBaselineFinish();\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart();\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n Duration duration = mpxj.getBaselineWork();\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(\"0\");\n xml.getBaseline().add(baseline);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n populated = false;\n\n cost = mpxj.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n date = mpxj.getBaselineFinish(loop);\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart(loop);\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n duration = mpxj.getBaselineWork(loop);\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(Integer.toString(loop));\n xml.getBaseline().add(baseline);\n }\n }\n }"
] |
Use this API to delete appfwjsoncontenttype of given name. | [
"public static base_response delete(nitro_service client, String jsoncontenttypevalue) throws Exception {\n\t\tappfwjsoncontenttype deleteresource = new appfwjsoncontenttype();\n\t\tdeleteresource.jsoncontenttypevalue = jsoncontenttypevalue;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"public Method getGetMethod(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\tMethod method = getCache.get(object.getClass().getName(), fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findGetter(object, fieldName);\n\t\t\tgetCache.set(object.getClass().getName(), fieldName, method);\n\t\t}\n\t\treturn method;\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 Iterator select(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return this.query(predicate).iterator();\r\n }",
"private static ResourceBundle tryBundle(String baseName, Locale locale, boolean wantBase) {\n\n I_CmsResourceBundle first = null; // The most specialized bundle.\n I_CmsResourceBundle last = null; // The least specialized bundle.\n\n List<String> bundleNames = CmsLocaleManager.getLocaleVariants(baseName, locale, true, true);\n for (String bundleName : bundleNames) {\n // break if we would try the base bundle, but we do not want it directly\n if (bundleName.equals(baseName) && !wantBase && (first == null)) {\n break;\n }\n I_CmsResourceBundle foundBundle = tryBundle(bundleName);\n if (foundBundle != null) {\n if (first == null) {\n first = foundBundle;\n }\n\n if (last != null) {\n last.setParent((ResourceBundle)foundBundle);\n }\n foundBundle.setLocale(locale);\n\n last = foundBundle;\n }\n }\n return (ResourceBundle)first;\n }",
"@Deprecated\r\n private BufferedImage getImage(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }",
"<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) {\n return handlers.get(artifact);\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 static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void writeNotes(int recordNumber, String text) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(recordNumber);\n m_buffer.append(m_delimiter);\n\n if (text != null)\n {\n String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);\n boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('\"') != -1);\n int length = note.length();\n char c;\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n\n for (int loop = 0; loop < length; loop++)\n {\n c = note.charAt(loop);\n\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\"\\\"\");\n break;\n }\n\n default:\n {\n m_buffer.append(c);\n break;\n }\n }\n }\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n }\n\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }"
] |
Use this API to clear bridgetable. | [
"public static base_response clear(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable clearresource = new bridgetable();\n\t\tclearresource.vlan = resource.vlan;\n\t\tclearresource.ifnum = resource.ifnum;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}"
] | [
"public static <T> DecoratorImpl<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new DecoratorImpl<T>(attributes, clazz, beanManager);\n }",
"public static String parseServers(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(0, slashIndex);\n }\n return zookeepers;\n }",
"public Boolean verifySubscriberRequestedSubscription(SubscriptionRequest sr) throws SubscriptionOriginVerificationException {\n\n LOG.info(\"(Hub) -> Subscriber, sending notification to verify the origin of the subscription {}.\", sr.getCallback());\n\n SubscriptionConfirmationRequest sc = new SubscriptionConfirmationRequest(sr.getMode(),\n sr.getTopic(), \"challenge\", \"0\");\n\n URI uri;\n try {\n uri = new URIBuilder(sr.getCallback()).setParameters(sc.toRequestParameters()).build();\n } catch (URISyntaxException e) {\n throw new SubscriptionOriginVerificationException(\"URISyntaxException while sending a confirmation of subscription\", e);\n }\n\n HttpGet httpGet = new HttpGet(uri);\n\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n CloseableHttpResponse response;\n try {\n response = httpclient.execute(httpGet);\n } catch (IOException e) {\n throw new SubscriptionOriginVerificationException(\"IOException while sending a confirmation of subscription\", e);\n }\n\n LOG.info(\"Subscriber replied with the http code {}.\", response.getStatusLine().getStatusCode());\n\n Integer returnedCode = response.getStatusLine().getStatusCode();\n\n // if code is a success code return true, else false\n return (199 < returnedCode) && (returnedCode < 300);\n }",
"public static FullTypeSignature getTypeSignature(String typeSignatureString,\n\t\t\tboolean useInternalFormFullyQualifiedName) {\n\t\tString key;\n\t\tif (!useInternalFormFullyQualifiedName) {\n\t\t\tkey = typeSignatureString.replace('.', '/')\n\t\t\t\t\t.replace('$', '.');\n\t\t} else {\n\t\t\tkey = typeSignatureString;\n\t\t}\n\n\t\t// we always use the internal form as a key for cache\n\t\tFullTypeSignature typeSignature = typeSignatureCache\n\t\t\t\t.get(key);\n\t\tif (typeSignature == null) {\n\t\t\tClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser(\n\t\t\t\t\ttypeSignatureString);\n\t\t\ttypeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);\n\t\t\ttypeSignature = typeSignatureParser.parseTypeSignature();\n\t\t\ttypeSignatureCache.put(typeSignatureString, typeSignature);\n\t\t}\n\t\treturn typeSignature;\n\t}",
"public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {\n return getRetentions(api, new QueryFilter(), fields);\n }",
"public static appfwsignatures get(nitro_service service, String name) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tobj.set_name(name);\n\t\tappfwsignatures response = (appfwsignatures) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void writeAttributeTypes(String name, FieldType[] types) throws IOException\n {\n m_writer.writeStartObject(name);\n for (FieldType field : types)\n {\n m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue());\n }\n m_writer.writeEndObject();\n }",
"public void moveDown(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if ((index >= 0) && (index < (m_container.getComponentCount() - 1))) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index + 1);\n }\n updateButtonBars();\n }",
"private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }"
] |
Create a canonical represenation of the data type value. Defaults to the value converter.
@since 2.9 | [
"protected String getFormattedDatatypeValue(ICompositeNode node, AbstractRule rule, String text) throws ValueConverterException {\n\t\tObject value = valueConverter.toValue(text, rule.getName(), node);\n\t\ttext = valueConverter.toString(value, rule.getName());\n\t\treturn text;\n\t}"
] | [
"public static base_responses update(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver updateresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new ntpserver();\n\t\t\t\tupdateresources[i].serverip = resources[i].serverip;\n\t\t\t\tupdateresources[i].servername = resources[i].servername;\n\t\t\t\tupdateresources[i].minpoll = resources[i].minpoll;\n\t\t\t\tupdateresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\tupdateresources[i].preferredntpserver = resources[i].preferredntpserver;\n\t\t\t\tupdateresources[i].autokey = resources[i].autokey;\n\t\t\t\tupdateresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static String encodePort(String port, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(port, encoding, HierarchicalUriComponents.Type.PORT);\n\t}",
"public HttpConnection setRequestBody(final InputStream input, final long inputLength) {\n try {\n return setRequestBody(new InputStreamWrappingGenerator(input, inputLength),\n inputLength);\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"Error copying input stream for request body\", e);\n throw new RuntimeException(e);\n }\n }",
"private void init(boolean upgrade)\n {\n initAdapter();\n initQueries();\n if (upgrade)\n {\n dbUpgrade();\n }\n\n // First contact with the DB is version checking (if no connection opened by pool).\n // If DB is in wrong version or not available, just wait for it to be ready.\n boolean versionValid = false;\n while (!versionValid)\n {\n try\n {\n checkSchemaVersion();\n versionValid = true;\n }\n catch (Exception e)\n {\n String msg = e.getLocalizedMessage();\n if (e.getCause() != null)\n {\n msg += \" - \" + e.getCause().getLocalizedMessage();\n }\n jqmlogger.error(\"Database not ready: \" + msg + \". Waiting for database...\");\n try\n {\n Thread.sleep(10000);\n }\n catch (Exception e2)\n {\n }\n }\n }\n }",
"private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }",
"public static base_response delete(nitro_service client, String username) throws Exception {\n\t\tsystemuser deleteresource = new systemuser();\n\t\tdeleteresource.username = username;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public Optional<URL> getServiceUrl() {\n Optional<Service> optionalService = client.services().inNamespace(namespace)\n .list().getItems()\n .stream()\n .findFirst();\n\n return optionalService\n .map(this::createUrlForService)\n .orElse(Optional.empty());\n }",
"public static double normP(DMatrixRMaj A , double p ) {\n if( p == 1 ) {\n return normP1(A);\n } else if( p == 2 ) {\n return normP2(A);\n } else if( Double.isInfinite(p)) {\n return normPInf(A);\n }\n if( MatrixFeatures_DDRM.isVector(A) ) {\n return elementP(A,p);\n } else {\n throw new IllegalArgumentException(\"Doesn't support induced norms yet.\");\n }\n }",
"private void populateSortedCustomFieldsList ()\n {\n m_sortedCustomFieldsList = new ArrayList<CustomField>();\n for (CustomField field : m_projectFile.getCustomFields())\n {\n FieldType fieldType = field.getFieldType();\n if (fieldType != null)\n {\n m_sortedCustomFieldsList.add(field);\n }\n }\n\n // Sort to ensure consistent order in file\n Collections.sort(m_sortedCustomFieldsList, new Comparator<CustomField>()\n {\n @Override public int compare(CustomField customField1, CustomField customField2)\n {\n FieldType o1 = customField1.getFieldType();\n FieldType o2 = customField2.getFieldType();\n String name1 = o1.getClass().getSimpleName() + \".\" + o1.getName() + \" \" + customField1.getAlias();\n String name2 = o2.getClass().getSimpleName() + \".\" + o2.getName() + \" \" + customField2.getAlias();\n return name1.compareTo(name2);\n }\n });\n }"
] |
Computes the mean or average of all the elements.
@return mean | [
"public double mean() {\n double total = 0;\n\n final int N = getNumElements();\n for( int i = 0; i < N; i++ ) {\n total += get(i);\n }\n\n return total/N;\n }"
] | [
"public void populateContainer(Class<? extends FieldType> type, FieldContainer container, Integer id, byte[][] fixedData, Var2Data varData)\n {\n //System.out.println(container.getClass().getSimpleName()+\": \" + id);\n for (FieldItem item : m_map.values())\n {\n if (item.getType().getClass().equals(type))\n {\n //System.out.println(item.m_type);\n Object value = item.read(id, fixedData, varData);\n //System.out.println(item.m_type.getClass().getSimpleName() + \".\" + item.m_type + \": \" + value);\n container.set(item.getType(), value);\n }\n }\n }",
"public static appfwglobal_auditsyslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditsyslogpolicy_binding obj = new appfwglobal_auditsyslogpolicy_binding();\n\t\tappfwglobal_auditsyslogpolicy_binding response[] = (appfwglobal_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();\r\n if (json.has(\"groups\")) {\r\n for (JsonElement e : json.getAsJsonArray(\"groups\")) {\r\n String groupName = e.getAsJsonObject().get(\"by\").getAsString();\r\n List<T> orows = new ArrayList<T>();\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement rows : e.getAsJsonObject().getAsJsonArray(\"rows\")) {\r\n orows.add(jsonToObject(client.getGson(), rows, \"doc\", classOfT));\r\n }\r\n result.put(groupName, orows);\r\n }// end for(groups)\r\n }// end hasgroups\r\n else {\r\n log.warning(\"No grouped results available. Use query() if non grouped query\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }",
"public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }",
"public void updateExceptions() {\n\n m_exceptionsList.setDates(m_model.getExceptions());\n if (m_model.getExceptions().size() > 0) {\n m_exceptionsPanel.setVisible(true);\n } else {\n m_exceptionsPanel.setVisible(false);\n }\n }",
"public static void writeHints(File file, Map<String,List<Long>> hints) throws IOException {\n Closer closer = Closer.create();\n try {\n BufferedWriter w = closer.register(Files.newWriter(file, Charsets.UTF_8));\n if (!(hints instanceof SortedMap)) {\n hints = new TreeMap<String,List<Long>>(hints);\n }\n \n Joiner joiner = Joiner.on(',');\n for (Map.Entry<String,List<Long>> e : hints.entrySet()) {\n w.write(e.getKey());\n w.write(\"=\");\n joiner.appendTo(w, e.getValue());\n w.write(\"\\n\");\n }\n } catch (Throwable t) {\n throw closer.rethrow(t);\n } finally {\n closer.close();\n }\n }",
"public void forAllTables(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _torqueModel.getTables(); it.hasNext(); )\r\n {\r\n _curTableDef = (TableDef)it.next();\r\n generate(template);\r\n }\r\n _curTableDef = null;\r\n }",
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }",
"private void checkAnonymous(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n\r\n if (!\"anonymous\".equals(access))\r\n {\r\n throw new ConstraintException(\"The access property of the field \"+fieldDef.getName()+\" defined in class \"+fieldDef.getOwner().getName()+\" cannot be changed\");\r\n }\r\n\r\n if ((fieldDef.getName() == null) || (fieldDef.getName().length() == 0))\r\n {\r\n throw new ConstraintException(\"An anonymous field defined in class \"+fieldDef.getOwner().getName()+\" has no name\");\r\n }\r\n }"
] |
Gets the object whose index is the integer argument.
@param i the integer index to be queried for the corresponding argument
@return the object whose index is the integer argument. | [
"public E get(int i) {\r\n if (i < 0 || i >= objects.size())\r\n throw new ArrayIndexOutOfBoundsException(\"Index \" + i + \r\n \" outside the bounds [0,\" + \r\n size() + \")\");\r\n return objects.get(i);\r\n }"
] | [
"private void readWBS(ChildTaskContainer parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Integer taskID = row.getInteger(\"TASK_ID\");\n Task task = readTask(parent, taskID);\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readWBS(task, childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }",
"public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = true;\n if (m_criteria != null)\n {\n result = m_criteria.evaluate(container, promptValues);\n\n //\n // If this row has failed, but it is a summary row, and we are\n // including related summary rows, then we need to recursively test\n // its children\n //\n if (!result && m_showRelatedSummaryRows && container instanceof Task)\n {\n for (Task task : ((Task) container).getChildTasks())\n {\n if (evaluate(task, promptValues))\n {\n result = true;\n break;\n }\n }\n }\n }\n\n return (result);\n }",
"public static void copyProperties(Object dest, Object orig){\n\t\ttry {\n\t\t\tif (orig != null && dest != null){\n\t\t\t\tBeanUtils.copyProperties(dest, orig);\n\n\t\t\t\tPropertyUtils putils = new PropertyUtils();\n\t PropertyDescriptor origDescriptors[] = putils.getPropertyDescriptors(orig);\n\n\t\t\t\tfor (PropertyDescriptor origDescriptor : origDescriptors) {\n\t\t\t\t\tString name = origDescriptor.getName();\n\t\t\t\t\tif (\"class\".equals(name)) {\n\t\t\t\t\t\tcontinue; // No point in trying to set an object's class\n\t\t\t\t\t}\n\n\t\t\t\t\tClass propertyType = origDescriptor.getPropertyType();\n\t\t\t\t\tif (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType)))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (!putils.isReadable(orig, name)) { //because of bad convention\n\t\t\t\t\t\tMethod m = orig.getClass().getMethod(\"is\" + name.substring(0, 1).toUpperCase() + name.substring(1), (Class<?>[]) null);\n\t\t\t\t\t\tObject value = m.invoke(orig, (Object[]) null);\n\n\t\t\t\t\t\tif (putils.isWriteable(dest, name)) {\n\t\t\t\t\t\t\tBeanUtilsBean.getInstance().copyProperty(dest, name, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new DJException(\"Could not copy properties for shared object: \" + orig +\", message: \" + e.getMessage(),e);\n\t\t}\n\t}",
"public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {\n \n int width = originalImage.getWidth();\n \n int height = originalImage.getHeight();\n \n int widthPercent = (widthOut * 100) / width;\n \n int newHeight = (height * widthPercent) / 100;\n \n BufferedImage resizedImage =\n new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);\n g.dispose();\n \n return resizedImage;\n }",
"protected SingleBusLocatorRegistrar getRegistrar(Bus bus) {\n SingleBusLocatorRegistrar registrar = busRegistrars.get(bus);\n if (registrar == null) {\n check(locatorClient, \"serviceLocator\", \"registerService\");\n registrar = new SingleBusLocatorRegistrar(bus);\n registrar.setServiceLocator(locatorClient);\n registrar.setEndpointPrefix(endpointPrefix);\n Map<String, String> endpointPrefixes = new HashMap<String, String>();\n endpointPrefixes.put(\"HTTP\", endpointPrefixHttp);\n endpointPrefixes.put(\"HTTPS\", endpointPrefixHttps);\n registrar.setEndpointPrefixes(endpointPrefixes);\n busRegistrars.put(bus, registrar);\n addLifeCycleListener(bus);\n }\n return registrar;\n }",
"public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) {\n Resources res = context.getResources();\n Duration duration = readableDuration.toDuration();\n\n final int hours = (int) duration.getStandardHours();\n if (hours != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours);\n }\n\n final int minutes = (int) duration.getStandardMinutes();\n if (minutes != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes);\n }\n\n final int seconds = (int) duration.getStandardSeconds();\n return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds);\n }",
"public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }",
"public static List<Representation> parseRepresentations(JsonObject jsonObject) {\n List<Representation> representations = new ArrayList<Representation>();\n for (JsonValue representationJson : jsonObject.get(\"entries\").asArray()) {\n Representation representation = new Representation(representationJson.asObject());\n representations.add(representation);\n }\n return representations;\n }",
"public void deleteOrganization(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n repositoryHandler.deleteOrganization(dbOrganization.getName());\n repositoryHandler.removeModulesOrganization(dbOrganization);\n }"
] |
Set a new Cursor position if active and enabled.
@param x x value of the position
@param y y value of the position
@param z z value of the position | [
"public void setPosition(float x, float y, float z) {\n if (isActive()) {\n mIODevice.setPosition(x, y, z);\n }\n }"
] | [
"public static double huntKennedyCMSOptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble valueUnadjusted\t= blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t\tdouble valueAdjusted\t= blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);\n\n\t\treturn a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;\n\t}",
"public static String chomp(String s) {\r\n if(s.length() == 0)\r\n return s;\r\n int l_1 = s.length() - 1;\r\n if (s.charAt(l_1) == '\\n') {\r\n return s.substring(0, l_1);\r\n }\r\n return s;\r\n }",
"public boolean mapsCell(String cell) {\n return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell));\n }",
"public void showCurrentDates(Collection<CmsPair<Date, Boolean>> dates) {\n\n m_overviewList.setDatesWithCheckState(dates);\n m_overviewPopup.center();\n\n }",
"protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }",
"protected void capture3DScreenShot(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshot3DCallback == null) {\n return;\n }\n final Bitmap[] bitmaps = new Bitmap[6];\n renderSixCamerasAndReadback(mMainScene.getMainCameraRig(), bitmaps, renderTarget, isMultiview);\n returnScreenshot3DToCaller(mScreenshot3DCallback, bitmaps, mReadbackBufferWidth, mReadbackBufferHeight);\n\n mScreenshot3DCallback = null;\n }",
"private void readRelationships(net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n for (Depend depend : gpTask.getDepend())\n {\n Task task1 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n Task task2 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(depend.getId()) + 1));\n if (task1 != null && task2 != null)\n {\n Duration lag = Duration.getInstance(NumberHelper.getInt(depend.getDifference()), TimeUnit.DAYS);\n Relation relation = task2.addPredecessor(task1, getRelationType(depend.getType()), lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"public static void addOverrideToPath() throws Exception {\n Client client = new Client(\"ProfileName\", false);\n\n // Use the fully qualified name for a plugin override.\n client.addMethodToResponseOverride(\"Test Path\", \"com.groupon.odo.sample.Common.delay\");\n\n // The third argument is the ordinal - the nth instance of this override added to this path\n // The final arguments count and type are determined by the override. \"delay\" used in this sample\n // has a single int argument - # of milliseconds delay to simulate\n client.setMethodArguments(\"Test Path\", \"com.groupon.odo.sample.Common.delay\", 1, \"100\");\n }",
"public static String toXml(DeploymentDescriptor descriptor) {\n try {\n\n Marshaller marshaller = getContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, \"http://www.jboss.org/jbpm deployment-descriptor.xsd\");\n marshaller.setSchema(schema);\n StringWriter stringWriter = new StringWriter();\n\n // clone the object and cleanup transients\n DeploymentDescriptor clone = ((DeploymentDescriptorImpl) descriptor).clearClone();\n\n marshaller.marshal(clone, stringWriter);\n String output = stringWriter.toString();\n\n return output;\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to generate xml from deployment descriptor\", e);\n }\n }"
] |
Start pushing the element off to the right. | [
"private void rotatorPushRight( int m )\n {\n double b11 = off[m];\n double b21 = diag[m+1];\n\n computeRotator(b21,-b11);\n\n // apply rotator on the right\n off[m] = 0;\n diag[m+1] = b21*c-b11*s;\n\n if( m+2 < N) {\n double b22 = off[m+1];\n off[m+1] = b22*c;\n bulge = b22*s;\n } else {\n bulge = 0;\n }\n\n// SimpleMatrix Q = createQ(m,m+1, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+1,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }"
] | [
"public void setValue(T value)\n {\n try\n {\n lock.writeLock().lock();\n this.value = value;\n }\n finally\n {\n lock.writeLock().unlock();\n }\n }",
"public static String lookupIfEmpty( final String value,\n final Map<String, String> props,\n final String key ) {\n return value != null ? value : props.get(key);\n }",
"private void deleteRecursive(final File file) {\n if (file.isDirectory()) {\n final String[] files = file.list();\n if (files != null) {\n for (String name : files) {\n deleteRecursive(new File(file, name));\n }\n }\n }\n\n if (!file.delete()) {\n ControllerLogger.ROOT_LOGGER.cannotDeleteFileOrDirectory(file);\n }\n }",
"public static Pair<String, String> stringIntern(Pair<String, String> p) {\r\n return new MutableInternedPair(p);\r\n }",
"private ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }",
"public int updateRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {\n\t\tlogger.debug(\"running raw update statement: {}\", statement);\n\t\tif (arguments.length > 0) {\n\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\tlogger.trace(\"update arguments: {}\", (Object) arguments);\n\t\t}\n\t\tCompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.UPDATE, noFieldTypes,\n\t\t\t\tDatabaseConnection.DEFAULT_RESULT_FLAGS, false);\n\t\ttry {\n\t\t\tassignStatementArguments(compiledStatement, arguments);\n\t\t\treturn compiledStatement.runUpdate();\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"public static double blackModelDgitialCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;\n\t}",
"public static<A, Z> Function1<A, Z> lift(Func1<A, Z> f) {\n\treturn bridge.lift(f);\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 }"
] |
decides which icon to apply or hide this view
@param imageHolder
@param imageView
@param iconColor
@param tint | [
"public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) {\n if (imageHolder != null && imageView != null) {\n Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint);\n if (drawable != null) {\n imageView.setImageDrawable(drawable);\n imageView.setVisibility(View.VISIBLE);\n } else if (imageHolder.getBitmap() != null) {\n imageView.setImageBitmap(imageHolder.getBitmap());\n imageView.setVisibility(View.VISIBLE);\n } else {\n imageView.setVisibility(View.GONE);\n }\n } else if (imageView != null) {\n imageView.setVisibility(View.GONE);\n }\n }"
] | [
"public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }",
"public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.ObjectInputStream\",\"java.io.ObjectOutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(output);\n ObjectInputStream ois = new ObjectInputStream(input);\n try {\n T result = closure.call(new Object[]{ois, oos});\n\n InputStream temp1 = ois;\n ois = null;\n temp1.close();\n temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = oos;\n oos = null;\n temp2.close();\n temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(ois);\n closeWithWarning(input);\n closeWithWarning(oos);\n closeWithWarning(output);\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 static SortedMap<String, Object> asMap() {\n SortedMap<String, Object> metrics = Maps.newTreeMap();\n METRICS_SOURCE.applyMetrics(metrics);\n return metrics;\n }",
"public void forceApply(String conflictResolution) {\n\n URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"conflict_resolution\", conflictResolution);\n request.setBody(requestJSON.toString());\n request.send();\n }",
"public void performStep() {\n // check for zeros\n for( int i = helper.x2-1; i >= helper.x1; i-- ) {\n if( helper.isZero(i) ) {\n helper.splits[helper.numSplits++] = i;\n helper.x1 = i+1;\n return;\n }\n }\n\n double lambda;\n\n if( followingScript ) {\n if( helper.steps > 10 ) {\n followingScript = false;\n return;\n } else {\n // Using the true eigenvalues will in general lead to the fastest convergence\n // typically takes 1 or 2 steps\n lambda = eigenvalues[helper.x2];\n }\n } else {\n // the current eigenvalue isn't working so try something else\n lambda = helper.computeShift();\n }\n\n // similar transforms\n helper.performImplicitSingleStep(lambda,false);\n }",
"public static <T> T getBundle(final Class<T> type) {\n return doPrivileged(new PrivilegedAction<T>() {\n public T run() {\n final Locale locale = Locale.getDefault();\n final String lang = locale.getLanguage();\n final String country = locale.getCountry();\n final String variant = locale.getVariant();\n\n Class<? extends T> bundleClass = null;\n if (variant != null && !variant.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, variant), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && country != null && !country.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && lang != null && !lang.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", null, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n throw new IllegalArgumentException(\"Invalid bundle \" + type + \" (implementation not found)\");\n }\n final Field field;\n try {\n field = bundleClass.getField(\"INSTANCE\");\n } catch (NoSuchFieldException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" has no instance field\");\n }\n try {\n return type.cast(field.get(null));\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" could not be instantiated\", e);\n }\n }\n });\n }",
"public static void main(String[] args) throws Exception {\n Logger logger = Logger.getLogger(\"MASReader.main\");\n\n Properties beastConfigProperties = new Properties();\n String beastConfigPropertiesFile = null;\n if (args.length > 0) {\n beastConfigPropertiesFile = args[0];\n beastConfigProperties.load(new FileInputStream(\n beastConfigPropertiesFile));\n logger.info(\"Properties file selected -> \"\n + beastConfigPropertiesFile);\n } else {\n logger.severe(\"No properties file found. Set the path of properties file as argument.\");\n throw new BeastException(\n \"No properties file found. Set the path of properties file as argument.\");\n }\n String loggerConfigPropertiesFile;\n if (args.length > 1) {\n Properties loggerConfigProperties = new Properties();\n loggerConfigPropertiesFile = args[1];\n try {\n FileInputStream loggerConfigFile = new FileInputStream(\n loggerConfigPropertiesFile);\n loggerConfigProperties.load(loggerConfigFile);\n LogManager.getLogManager().readConfiguration(loggerConfigFile);\n logger.info(\"Logging properties configured successfully. Logger config file: \"\n + loggerConfigPropertiesFile);\n } catch (IOException ex) {\n logger.warning(\"WARNING: Could not open configuration file\");\n logger.warning(\"WARNING: Logging not configured (console output only)\");\n }\n } else {\n loggerConfigPropertiesFile = null;\n }\n\n MASReader.generateJavaFiles(\n beastConfigProperties.getProperty(\"requirementsFolder\"), \"\\\"\"\n + beastConfigProperties.getProperty(\"MASPlatform\")\n + \"\\\"\",\n beastConfigProperties.getProperty(\"srcTestRootFolder\"),\n beastConfigProperties.getProperty(\"storiesPackage\"),\n beastConfigProperties.getProperty(\"caseManagerPackage\"),\n loggerConfigPropertiesFile,\n beastConfigProperties.getProperty(\"specificationPhase\"));\n\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 }"
] |
Generates a Map of query parameters for Artifact regarding the filters
@return Map<String, Object> | [
"public Map<String, Object> getArtifactFieldsFilters() {\n\t\tfinal Map<String, Object> params = new HashMap<String, Object>();\n\n for(final Filter filter: filters){\n params.putAll(filter.artifactFilterFields());\n }\n\n\t\treturn params;\n\t}"
] | [
"public static URL findConfigResource(String resourceName) {\n if (Strings.isNullOrEmpty(resourceName)) {\n return null;\n }\n\n final URL url = resourceName.startsWith(ROOT) ? DefaultConfiguration.class.getResource(resourceName)\n : DefaultConfiguration.class.getResource(ROOT + resourceName);\n\n if (url != null) {\n return url;\n }\n\n // This is useful to get resource under META-INF directory\n String[] resourceNamePrefix = new String[] {\"META-INF/fabric8/\", \"META-INF/fabric8/\"};\n\n for (String resource : resourceNamePrefix) {\n String fullResourceName = resource + resourceName;\n\n URL candidate = KubernetesResourceLocator.class.getResource(fullResourceName.startsWith(ROOT) ? fullResourceName : ROOT + fullResourceName);\n if (candidate != null) {\n return candidate;\n }\n }\n\n return null;\n }",
"public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\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_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (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(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception 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 return servers;\n }",
"public T execute(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {\n\t\tif (objectCache != null) {\n\t\t\tT result = objectCache.get(clazz, id);\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\tObject[] args = new Object[] { convertIdToFieldObject(id) };\n\t\t// @SuppressWarnings(\"unchecked\")\n\t\tObject result = databaseConnection.queryForOne(statement, args, argFieldTypes, this, objectCache);\n\t\tif (result == null) {\n\t\t\tlogger.debug(\"{} using '{}' and {} args, got no results\", label, statement, args.length);\n\t\t} else if (result == DatabaseConnection.MORE_THAN_ONE) {\n\t\t\tlogger.error(\"{} using '{}' and {} args, got >1 results\", label, statement, args.length);\n\t\t\tlogArgs(args);\n\t\t\tthrow new SQLException(label + \" got more than 1 result: \" + statement);\n\t\t} else {\n\t\t\tlogger.debug(\"{} using '{}' and {} args, got 1 result\", label, statement, args.length);\n\t\t}\n\t\tlogArgs(args);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT castResult = (T) result;\n\t\treturn castResult;\n\t}",
"private void readWeekDay(ProjectCalendar mpxjCalendar, WeekDay day)\n {\n if (day.isIsDayWorking())\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day.getDay());\n for (Document.Calendars.Calendar.WeekDays.WeekDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n hours.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }",
"protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException {\n final ManagementResponseHeader response = ManagementResponseHeader.create(header, error);\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }",
"public String[] getMethods(String pluginClass) throws Exception {\n ArrayList<String> methodNames = new ArrayList<String>();\n\n Method[] methods = getClass(pluginClass).getDeclaredMethods();\n for (Method method : methods) {\n logger.info(\"Checking {}\", method.getName());\n\n com.groupon.odo.proxylib.models.Method methodInfo = this.getMethod(pluginClass, method.getName());\n if (methodInfo == null) {\n continue;\n }\n\n // check annotations\n Boolean matchesAnnotation = false;\n if (methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_CLASS) ||\n methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_V2_CLASS)) {\n matchesAnnotation = true;\n }\n\n if (!methodNames.contains(method.getName()) && matchesAnnotation) {\n methodNames.add(method.getName());\n }\n }\n\n return methodNames.toArray(new String[0]);\n }",
"public static void saveContentMap(Map<String, String> map, File file) throws IOException {\n\n FileWriter out = new FileWriter(file);\n for (String key : map.keySet()) {\n if (map.get(key) != null) {\n out.write(key.replace(\":\", \"#escapedtwodots#\") + \":\"\n + map.get(key).replace(\":\", \"#escapedtwodots#\") + \"\\r\\n\");\n }\n }\n out.close();\n }",
"public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }",
"private ProjectFile handleDatabaseInDirectory(File directory) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n if (file.isDirectory())\n {\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n int bytesRead = fis.read(buffer);\n fis.close();\n\n //\n // If the file is smaller than the buffer we are peeking into,\n // it's probably not a valid schedule file.\n //\n if (bytesRead != BUFFER_SIZE)\n {\n continue;\n }\n\n if (matchesFingerprint(buffer, BTRIEVE_FINGERPRINT))\n {\n return handleP3BtrieveDatabase(directory);\n }\n\n if (matchesFingerprint(buffer, STW_FINGERPRINT))\n {\n return handleSureTrakDatabase(directory);\n }\n }\n }\n return null;\n }"
] |
Readable yyyyMMdd int representation of a day, which is also sortable. | [
"public static int getDayAsReadableInt(long time) {\n Calendar cal = calendarThreadLocal.get();\n cal.setTimeInMillis(time);\n return getDayAsReadableInt(cal);\n }"
] | [
"protected boolean hasTimeStampHeader() {\n String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS);\n boolean result = false;\n if(originTime != null) {\n try {\n // TODO: remove the originTime field from request header,\n // because coordinator should not accept the request origin time\n // from the client.. In this commit, we only changed\n // \"this.parsedRequestOriginTimeInMs\" from\n // \"Long.parseLong(originTime)\" to current system time,\n // The reason that we did not remove the field from request\n // header right now, is because this commit is a quick fix for\n // internal performance test to be available as soon as\n // possible.\n\n this.parsedRequestOriginTimeInMs = System.currentTimeMillis();\n if(this.parsedRequestOriginTimeInMs < 0) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Origin time cannot be negative \");\n\n } else {\n result = true;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime);\n }\n } else {\n logger.error(\"Error when validating request. Missing origin time parameter.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing origin time parameter.\");\n }\n return result;\n }",
"public String getPendingChanges() {\n JsonObject jsonObject = this.getPendingJSONObject();\n if (jsonObject == null) {\n return null;\n }\n\n return jsonObject.toString();\n }",
"public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);\n\t\tDatabaseResults results = null;\n\t\ttry {\n\t\t\tresults = compiledStatement.runQuery(null);\n\t\t\tif (results.first()) {\n\t\t\t\treturn results.getLong(0);\n\t\t\t} else {\n\t\t\t\tthrow new SQLException(\"No result found in queryForLong: \" + preparedStmt.getStatement());\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(results, \"results\");\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void enableKeyboardAutoHiding() {\n keyboardListener = new OnScrollListener() {\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n if (dx != 0 || dy != 0) {\n imeManager.hideSoftInputFromWindow(\n Hits.this.getWindowToken(),\n InputMethodManager.HIDE_NOT_ALWAYS);\n }\n super.onScrolled(recyclerView, dx, dy);\n }\n };\n addOnScrollListener(keyboardListener);\n }",
"public void hideKeyboard() {\n InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0);\n }",
"private void calculateValueTextHeight() {\n Rect valueRect = new Rect();\n Rect legendRect = new Rect();\n String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? \" \" + mIndicatorTextUnit : \"\");\n\n // calculate the boundaries for both texts\n mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect);\n mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect);\n\n // calculate string positions in overlay\n mValueTextHeight = valueRect.height();\n mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding);\n mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f));\n\n int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width();\n\n // check if text reaches over screen\n if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) {\n mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding));\n mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding));\n } else {\n mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding);\n }\n }",
"public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,\r\n edu.stanford.nlp.sequences.FeatureFactory<IN> featureFactory) {\r\n pad.set(AnswerAnnotation.class, flags.backgroundSymbol);\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n ArrayList<List<String>> features = new ArrayList<List<String>>();\r\n\r\n // for (int i = 0; i < windowSize; i++) {\r\n // List featuresC = new ArrayList();\r\n // for (int j = 0; j < FeatureFactory.win[i].length; j++) {\r\n // featuresC.addAll(featureFactory.features(info, loc,\r\n // FeatureFactory.win[i][j]));\r\n // }\r\n // features.add(featuresC);\r\n // }\r\n\r\n Collection<Clique> done = new HashSet<Clique>();\r\n for (int i = 0; i < windowSize; i++) {\r\n List<String> featuresC = new ArrayList<String>();\r\n List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);\r\n windowCliques.removeAll(done);\r\n done.addAll(windowCliques);\r\n for (Clique c : windowCliques) {\r\n featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons\r\n }\r\n features.add(featuresC);\r\n }\r\n\r\n int[] labels = new int[windowSize];\r\n\r\n for (int i = 0; i < windowSize; i++) {\r\n String answer = pInfo.get(loc + i - windowSize + 1).get(AnswerAnnotation.class);\r\n labels[i] = classIndex.indexOf(answer);\r\n }\r\n\r\n printFeatureLists(pInfo.get(loc), features);\r\n\r\n CRFDatum<List<String>, CRFLabel> d = new CRFDatum<List<String>, CRFLabel>(features, new CRFLabel(labels));\r\n // System.err.println(d);\r\n return d;\r\n }",
"protected void endPersistence(final BufferedWriter writer) throws IOException {\n // Append any additional users to the end of the file.\n for (Object currentKey : toSave.keySet()) {\n String key = (String) currentKey;\n if (!key.contains(DISABLE_SUFFIX_KEY)) {\n writeProperty(writer, key, null);\n }\n }\n\n toSave = null;\n }",
"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 }"
] |
Add a method to the enabled response overrides for a path
@param pathName name of path
@param methodName name of method
@return true if success, false otherwise | [
"public boolean addMethodToResponseOverride(String pathName, String methodName) {\n // need to find out the ID for the method\n // TODO: change api for adding methods to take the name instead of ID\n try {\n Integer overrideId = getOverrideIdForMethodName(methodName);\n\n // now post to path api to add this is a selected override\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"addOverride\", overrideId.toString()),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName), params));\n // check enabled endpoints array to see if this overrideID exists\n JSONArray enabled = response.getJSONArray(\"enabledEndpoints\");\n for (int x = 0; x < enabled.length(); x++) {\n if (enabled.getJSONObject(x).getInt(\"overrideId\") == overrideId) {\n return true;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }"
] | [
"public static Node updateNode(Node node, List<Integer> partitionsList) {\n return new Node(node.getId(),\n node.getHost(),\n node.getHttpPort(),\n node.getSocketPort(),\n node.getAdminPort(),\n node.getZoneId(),\n partitionsList);\n }",
"public static AppDescriptor of(String appName, String packageName) {\n String[] packages = packageName.split(S.COMMON_SEP);\n return of(appName, packageName, Version.ofPackage(packages[0]));\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 }",
"ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) {\n if (domain.getCodeSource() == null) {\n // no codesource to cache on\n return create(domain);\n }\n ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource());\n if (proxyProtectionDomain == null) {\n // as this is not atomic create() may be called multiple times for the same domain\n // we ignore that\n proxyProtectionDomain = create(domain);\n ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain);\n if (existing != null) {\n proxyProtectionDomain = existing;\n }\n }\n return proxyProtectionDomain;\n }",
"public void addImportedPackages(Set<String> importedPackages) {\n\t\taddImportedPackages(importedPackages.toArray(new String[importedPackages.size()]));\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 }",
"private void saveToXmlVfsBundle() throws CmsException {\n\n if (m_lockedBundleFiles.get(null) != null) { // If the file was not locked, no changes were made, i.e., storing is not necessary.\n for (Locale l : m_locales) {\n SortedProperties props = m_localizations.get(l);\n if (null != props) {\n if (m_xmlBundle.hasLocale(l)) {\n m_xmlBundle.removeLocale(l);\n }\n m_xmlBundle.addLocale(m_cms, l);\n int i = 0;\n List<Object> keys = new ArrayList<Object>(props.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n String value = props.getProperty(key.toString());\n if (!value.isEmpty()) {\n m_xmlBundle.addValue(m_cms, \"Message\", l, i);\n i++;\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Key\", l).setStringValue(m_cms, key.toString());\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Value\", l).setStringValue(m_cms, value);\n }\n }\n }\n }\n CmsFile bundleFile = m_lockedBundleFiles.get(null).getFile();\n bundleFile.setContents(m_xmlBundle.marshal());\n m_cms.writeFile(bundleFile);\n }\n }\n }",
"public void prepareStatus() {\n globalLineCounter = new AtomicLong(0);\n time = new AtomicLong(System.currentTimeMillis());\n startTime = System.currentTimeMillis();\n lastCount = 0;\n\n // Status thread regularly reports on what is happening\n Thread statusThread = new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Status thread interrupted\");\n }\n\n long thisTime = System.currentTimeMillis();\n long currentCount = globalLineCounter.get();\n\n if (thisTime - time.get() > 1000) {\n long oldTime = time.get();\n time.set(thisTime);\n double avgRate = 1000.0 * currentCount / (thisTime - startTime);\n double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime);\n lastCount = currentCount;\n System.out.println(currentCount + \" AvgRage:\" + ((int) avgRate) + \" lines/sec instRate:\"\n + ((int) instRate) + \" lines/sec Unassigned Work: \"\n + remainingBlocks.get() + \" blocks\");\n }\n }\n }\n };\n statusThread.start();\n }",
"public void forAllCollectionDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getCollections(); it.hasNext(); )\r\n {\r\n _curCollectionDef = (CollectionDescriptorDef)it.next();\r\n if (!isFeatureIgnored(LEVEL_COLLECTION) &&\r\n !_curCollectionDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curCollectionDef = null;\r\n }"
] |
Replace full request content.
@param requestContentTemplate
the request content template
@param replacementString
the replacement string
@return the string | [
"public static String replaceFullRequestContent(\n String requestContentTemplate, String replacementString) {\n return (requestContentTemplate.replace(\n PcConstants.COMMAND_VAR_DEFAULT_REQUEST_CONTENT,\n replacementString));\n }"
] | [
"private Envelope getLayerEnvelope(ProxyLayerSupport layer) {\n\t\tBbox bounds = layer.getLayerInfo().getMaxExtent();\n\t\treturn new Envelope(bounds.getX(), bounds.getMaxX(), bounds.getY(), bounds.getMaxY());\n\t}",
"private void verityLicenseIsConflictFree(final DbLicense newComer) {\n if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) {\n return;\n }\n\n final DbLicense existing = repoHandler.getLicense(newComer.getName());\n final List<DbLicense> licenses = repoHandler.getAllLicenses();\n\n if(null == existing) {\n licenses.add(newComer);\n } else {\n existing.setRegexp(newComer.getRegexp());\n }\n\n\n final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS);\n if (reportOp.isPresent()) {\n final Report reportDef = reportOp.get();\n ReportRequest reportRequest = new ReportRequest();\n reportRequest.setReportId(reportDef.getId());\n\n Map<String, String> params = new HashMap<>();\n\n //\n // TODO: Make the organization come as an external parameter from the client side.\n // This may have impact on the UI, as when the user will update a license he will\n // have to specify which organization he's editing the license for (in case there\n // are more organizations defined in the collection).\n //\n params.put(\"organization\", \"Axway\");\n reportRequest.setParamValues(params);\n\n final RepositoryHandler wrapped = wrapperBuilder\n .start(repoHandler)\n .replaceGetMethod(\"getAllLicenses\", licenses)\n .build();\n\n final ReportExecution execution = reportDef.execute(wrapped, reportRequest);\n\n List<String[]> data = execution.getData();\n\n final Optional<String[]> first = data\n .stream()\n .filter(strings -> strings[2].contains(newComer.getName()))\n .findFirst();\n\n if(first.isPresent()) {\n final String[] strings = first.get();\n final String message = String.format(\n \"Pattern conflict for string entry %s matching multiple licenses: %s\",\n strings[1], strings[2]);\n LOG.info(message);\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(message)\n .build());\n } else {\n if(!data.isEmpty() && !data.get(0)[2].isEmpty()) {\n LOG.info(\"There are remote conflicts between existing licenses and artifact strings\");\n }\n }\n } else {\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"Cannot find report by id %s\", MULTIPLE_LICENSE_MATCHING_STRINGS));\n }\n }\n }",
"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}",
"public static boolean isVector(DMatrixSparseCSC a) {\n return (a.numCols == 1 && a.numRows > 1) || (a.numRows == 1 && a.numCols>1);\n }",
"public double loglikelihood(List<IN> lineInfos) {\r\n double cll = 0.0;\r\n\r\n for (int i = 0; i < lineInfos.size(); i++) {\r\n Datum<String, String> d = makeDatum(lineInfos, i, featureFactory);\r\n Counter<String> c = classifier.logProbabilityOf(d);\r\n\r\n double total = Double.NEGATIVE_INFINITY;\r\n for (String s : c.keySet()) {\r\n total = SloppyMath.logAdd(total, c.getCount(s));\r\n }\r\n cll -= c.getCount(d.label()) - total;\r\n }\r\n // quadratic prior\r\n // HN: TODO: add other priors\r\n\r\n if (classifier instanceof LinearClassifier) {\r\n double sigmaSq = flags.sigma * flags.sigma;\r\n LinearClassifier<String, String> lc = (LinearClassifier<String, String>)classifier;\r\n for (String feature: lc.features()) {\r\n for (String classLabel: classIndex) {\r\n double w = lc.weight(feature, classLabel);\r\n cll += w * w / 2.0 / sigmaSq;\r\n }\r\n }\r\n }\r\n return cll;\r\n }",
"public static base_response rename(nitro_service client, responderpolicy resource, String new_name) throws Exception {\n\t\tresponderpolicy renameresource = new responderpolicy();\n\t\trenameresource.name = resource.name;\n\t\treturn renameresource.rename_resource(client,new_name);\n\t}",
"static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final\n ViewQueryParameters<K, V> initialParameters) {\n\n // Decode the base64 token into JSON\n String json = new String(Base64.decodeBase64(paginationToken), Charset.forName(\"UTF-8\"));\n\n // Get a suitable Gson, we need any adapter registered for the K key type\n Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters);\n\n // Deserialize the pagination token JSON, using the appropriate K, V types\n PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class);\n\n // Create new query parameters using the initial ViewQueryParameters as a starting point.\n ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy();\n\n // Merge the values from the token into the new query parameters\n tokenPageParameters.descending = token.descending;\n tokenPageParameters.endkey = token.endkey;\n tokenPageParameters.endkey_docid = token.endkey_docid;\n tokenPageParameters.inclusive_end = token.inclusive_end;\n tokenPageParameters.startkey = token.startkey;\n tokenPageParameters.startkey_docid = token.startkey_docid;\n\n return new PageMetadata<K, V>(token.direction, token\n .pageNumber, tokenPageParameters);\n }",
"public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }",
"public void postProcess() {\n\t\tif (foreignColumnName != null) {\n\t\t\tforeignAutoRefresh = true;\n\t\t}\n\t\tif (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {\n\t\t\tmaxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;\n\t\t}\n\t}"
] |
Calling this twice will not actually overwrite the gauge
@param collectionSizeGauge | [
"public void registerCollectionSizeGauge(\n\t\t\tCollectionSizeGauge collectionSizeGauge) {\n\t\tString name = createMetricName(LocalTaskExecutorService.class,\n\t\t\t\t\"queue-size\");\n\t\tmetrics.register(name, collectionSizeGauge);\n\t}"
] | [
"public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }",
"public static void setTranslucentNavigationFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);\n }\n }",
"public 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 <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) {\n Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap));\n newMap.putAll(inputMap);\n\n Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap);\n return linkedMap;\n }",
"public void validateInjectionPoint(InjectionPoint ij, BeanManagerImpl beanManager) {\n validateInjectionPointForDefinitionErrors(ij, ij.getBean(), beanManager);\n validateMetadataInjectionPoint(ij, ij.getBean(), ValidatorLogger.INJECTION_INTO_NON_BEAN);\n validateEventMetadataInjectionPoint(ij);\n validateInjectionPointForDeploymentProblems(ij, ij.getBean(), beanManager);\n }",
"public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }",
"public DJCrosstab build(){\r\n\t\tif (crosstab.getMeasures().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one measure\");\r\n\t\t}\r\n\t\tif (crosstab.getColumns().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one column\");\r\n\t\t}\r\n\t\tif (crosstab.getRows().isEmpty()){\r\n\t\t\tthrow new LayoutException(\"Crosstabs must have at least one row\");\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t//Ensure default dimension values\r\n\t\tfor (DJCrosstabColumn col : crosstab.getColumns()) {\r\n\t\t\tif (col.getWidth() == -1 && cellWidth != -1)\r\n\t\t\t\tcol.setWidth(cellWidth);\r\n\r\n\t\t\tif (col.getWidth() == -1 )\r\n\t\t\t\tcol.setWidth(DEFAULT_CELL_WIDTH);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1 && columnHeaderHeight != -1)\r\n\t\t\t\tcol.setHeaderHeight(columnHeaderHeight);\r\n\r\n\t\t\tif (col.getHeaderHeight() == -1)\r\n\t\t\t\tcol.setHeaderHeight(DEFAULT_COLUMN_HEADER_HEIGHT);\r\n\t\t}\r\n\r\n\t\tfor (DJCrosstabRow row : crosstab.getRows()) {\r\n\t\t\tif (row.getHeight() == -1 && cellHeight != -1)\r\n\t\t\t\trow.setHeight(cellHeight);\r\n\r\n\t\t\tif (row.getHeight() == -1 )\r\n\t\t\t\trow.setHeight(DEFAULT_CELL_HEIGHT);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1 && rowHeaderWidth != -1)\r\n\t\t\t\trow.setHeaderWidth(rowHeaderWidth);\r\n\r\n\t\t\tif (row.getHeaderWidth() == -1)\r\n\t\t\t\trow.setHeaderWidth(DEFAULT_ROW_HEADER_WIDTH);\r\n\r\n\t\t}\r\n\t\treturn crosstab;\r\n\t}",
"public static String insertDumpInformation(String pattern,\n\t\t\tString dateStamp, String project) {\n\t\tif (pattern == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn pattern.replace(\"{DATE}\", dateStamp).replace(\"{PROJECT}\",\n\t\t\t\t\tproject);\n\t\t}\n\t}",
"public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }"
] |
For missing objects associated by one-to-one with another object in the
result set, register the fact that the object is missing with the
session.
copied form Loader#registerNonExists | [
"private void registerNonExists(\n\t\tfinal org.hibernate.engine.spi.EntityKey[] keys,\n\t\tfinal Loadable[] persisters,\n\t\tfinal SharedSessionContractImplementor session) {\n\n\t\tfinal int[] owners = getOwners();\n\t\tif ( owners != null ) {\n\n\t\t\tEntityType[] ownerAssociationTypes = getOwnerAssociationTypes();\n\t\t\tfor ( int i = 0; i < keys.length; i++ ) {\n\n\t\t\t\tint owner = owners[i];\n\t\t\t\tif ( owner > -1 ) {\n\t\t\t\t\torg.hibernate.engine.spi.EntityKey ownerKey = keys[owner];\n\t\t\t\t\tif ( keys[i] == null && ownerKey != null ) {\n\n\t\t\t\t\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t\t\t\t\t/*final boolean isPrimaryKey;\n\t\t\t\t\t\tfinal boolean isSpecialOneToOne;\n\t\t\t\t\t\tif ( ownerAssociationTypes == null || ownerAssociationTypes[i] == null ) {\n\t\t\t\t\t\t\tisPrimaryKey = true;\n\t\t\t\t\t\t\tisSpecialOneToOne = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tisPrimaryKey = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName()==null;\n\t\t\t\t\t\t\tisSpecialOneToOne = ownerAssociationTypes[i].getLHSPropertyName()!=null;\n\t\t\t\t\t\t}*/\n\n\t\t\t\t\t\t//TODO: can we *always* use the \"null property\" approach for everything?\n\t\t\t\t\t\t/*if ( isPrimaryKey && !isSpecialOneToOne ) {\n\t\t\t\t\t\t\tpersistenceContext.addNonExistantEntityKey(\n\t\t\t\t\t\t\t\t\tnew EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() )\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ( isSpecialOneToOne ) {*/\n\t\t\t\t\t\tboolean isOneToOneAssociation = ownerAssociationTypes != null &&\n\t\t\t\t\t\t\t\townerAssociationTypes[i] != null &&\n\t\t\t\t\t\t\t\townerAssociationTypes[i].isOneToOne();\n\t\t\t\t\t\tif ( isOneToOneAssociation ) {\n\t\t\t\t\t\t\tpersistenceContext.addNullProperty( ownerKey,\n\t\t\t\t\t\t\t\t\townerAssociationTypes[i].getPropertyName() );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/*}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpersistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey(\n\t\t\t\t\t\t\t\t\tpersisters[i].getEntityName(),\n\t\t\t\t\t\t\t\t\townerAssociationTypes[i].getRHSUniqueKeyPropertyName(),\n\t\t\t\t\t\t\t\t\townerKey.getIdentifier(),\n\t\t\t\t\t\t\t\t\tpersisters[owner].getIdentifierType(),\n\t\t\t\t\t\t\t\t\tsession.getEntityMode()\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}\n\t\t\t}\n\t\t}\n\t}"
] | [
"public static String next(CharSequence self) {\n StringBuilder buffer = new StringBuilder(self);\n if (buffer.length() == 0) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char last = buffer.charAt(buffer.length() - 1);\n if (last == Character.MAX_VALUE) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char next = last;\n next++;\n buffer.setCharAt(buffer.length() - 1, next);\n }\n }\n return buffer.toString();\n }",
"public void removeCustomOverride(int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"custom_response\", \"\", getProfileIdFromPathID(path_id), client_uuid, path_id);\n }",
"boolean deleteEntity(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n clearProperties(txn, entity);\n clearBlobs(txn, entity);\n deleteLinks(txn, entity);\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final ByteIterable key = LongBinding.longToCompressedEntry(entityLocalId);\n if (config.isDebugSearchForIncomingLinksOnDelete()) {\n // search for incoming links\n final List<String> allLinkNames = getAllLinkNames(txn);\n for (final String entityType : txn.getEntityTypes()) {\n for (final String linkName : allLinkNames) {\n //noinspection LoopStatementThatDoesntLoop\n for (final Entity referrer : txn.findLinks(entityType, entity, linkName)) {\n throw new EntityStoreException(entity +\n \" is about to be deleted, but it is referenced by \" + referrer + \", link name: \" + linkName);\n }\n }\n }\n }\n if (getEntitiesTable(txn, entityTypeId).delete(txn.getEnvironmentTransaction(), key)) {\n txn.entityDeleted(id);\n return true;\n }\n return false;\n }",
"private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }",
"private int getSegmentForX(int x) {\n if (autoScroll.get()) {\n int playHead = (x - (getWidth() / 2));\n int offset = Util.timeToHalfFrame(getFurthestPlaybackPosition()) / scale.get();\n return (playHead + offset) * scale.get();\n }\n return x * scale.get();\n }",
"public static nspbr6[] get(nitro_service service) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\tnspbr6[] response = (nspbr6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n\tpublic <T> T get(Object key, Resource resource, Provider<T> provider) {\n\t\tif(resource == null) {\n\t\t\treturn provider.get();\n\t\t}\n\t\tCacheAdapter adapter = getOrCreate(resource);\n\t\tT element = adapter.<T>internalGet(key);\n\t\tif (element==null) {\n\t\t\telement = provider.get();\n\t\t\tcacheMiss(adapter);\n\t\t\tadapter.set(key, element);\n\t\t} else {\n\t\t\tcacheHit(adapter);\n\t\t}\n\t\tif (element == CacheAdapter.NULL) {\n\t\t\treturn null;\n\t\t}\n\t\treturn element;\n\t}",
"public EventBus emit(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }"
] |
Convert an MPXJ Duration instance into an integer duration in minutes
ready to be written to an MPX file.
@param properties project properties, used for duration units conversion
@param duration Duration instance
@return integer duration in minutes | [
"public static Integer getDurationValue(ProjectProperties properties, Duration duration)\n {\n Integer result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.MINUTES)\n {\n duration = duration.convertUnits(TimeUnit.MINUTES, properties);\n }\n result = Integer.valueOf((int) duration.getDuration());\n }\n return (result);\n }"
] | [
"static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex,\n ArtifactResolver resolver)\n throws VersionRangeResolutionException, ArtifactResolutionException {\n boolean latest = gav.endsWith(\":LATEST\");\n if (latest || gav.endsWith(\":RELEASE\")) {\n Artifact a = new DefaultArtifact(gav);\n\n if (latest) {\n versionRegex = versionRegex == null ? ANY : versionRegex;\n } else {\n versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex;\n }\n\n String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId())\n ? project.getVersion()\n : null;\n\n return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest);\n } else {\n String projectGav = getProjectArtifactCoordinates(project, null);\n Artifact ret = null;\n\n if (projectGav.equals(gav)) {\n ret = findProjectArtifact(project);\n }\n\n return ret == null ? resolver.resolveArtifact(gav) : ret;\n }\n }",
"public static void startCheck(String extra) {\n startCheckTime = System.currentTimeMillis();\n nextCheckTime = startCheckTime;\n Log.d(Log.SUBSYSTEM.TRACING, \"FPSCounter\" , \"[%d] startCheck %s\", startCheckTime, extra);\n }",
"public void transformConfig() throws Exception {\n\n List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, \"transforms.xml\"));\n for (TransformEntry entry : entries) {\n transform(entry.getConfigFile(), entry.getXslt());\n }\n m_isDone = true;\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 static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public void removeFilter(String filterName)\n {\n Filter filter = getFilterByName(filterName);\n if (filter != null)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.remove(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.remove(filter);\n }\n m_filtersByName.remove(filterName);\n m_filtersByID.remove(filter.getID());\n }\n }",
"public static byte[] toUnixLineEndings( InputStream input ) throws IOException {\n String encoding = \"ISO-8859-1\";\n FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding));\n filter.setEol(FixCrLfFilter.CrLf.newInstance(\"unix\"));\n\n ByteArrayOutputStream filteredFile = new ByteArrayOutputStream();\n Utils.copy(new ReaderInputStream(filter, encoding), filteredFile);\n\n return filteredFile.toByteArray();\n }",
"@Override\n public HandlerRegistration addSearchFinishHandler(final SearchFinishEvent.SearchFinishHandler handler) {\n return addHandler(handler, SearchFinishEvent.TYPE);\n }",
"public static base_responses add(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser addresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new systemuser();\n\t\t\t\taddresources[i].username = resources[i].username;\n\t\t\t\taddresources[i].password = resources[i].password;\n\t\t\t\taddresources[i].externalauth = resources[i].externalauth;\n\t\t\t\taddresources[i].promptstring = resources[i].promptstring;\n\t\t\t\taddresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Creates the name of the .story file to be wrote with the testcase. The
name of the scenario must be given with spaces.
@param scenarioName
- The scenario name, with spaces
@return the .story file name. | [
"protected static String createDotStoryName(String scenarioName) {\n String[] words = scenarioName.trim().split(\" \");\n String result = \"\";\n for (int i = 0; i < words.length; i++) {\n String word1 = words[i];\n String word2 = word1.toLowerCase();\n if (!word1.equals(word2)) {\n String finalWord = \"\";\n for (int j = 0; j < word1.length(); j++) {\n if (i != 0) {\n char c = word1.charAt(j);\n if (Character.isUpperCase(c)) {\n if (j==0) {\n finalWord += Character.toLowerCase(c);\n } else {\n finalWord += \"_\" + Character.toLowerCase(c); \n }\n } else {\n finalWord += c;\n }\n } else {\n finalWord = word2;\n break;\n }\n }\n\n result += finalWord;\n } else {\n result += word2;\n }\n // I don't add the '_' to the last word.\n if (!(i == words.length - 1))\n result += \"_\";\n }\n return result;\n }"
] | [
"public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }",
"protected void addLabelForNumbers(ItemIdValue itemIdValue) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if we still have exactly one numeric value:\n\t\t\tQuantityValue number = currentItemDocument\n\t\t\t\t\t.findStatementQuantityValue(\"P1181\");\n\t\t\tif (number == null) {\n\t\t\t\tSystem.out.println(\"*** No unique numeric value for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the item is in a known numeric class:\n\t\t\tif (!currentItemDocument.hasStatementValue(\"P31\", numberClasses)) {\n\t\t\t\tSystem.out\n\t\t\t\t\t\t.println(\"*** \"\n\t\t\t\t\t\t\t\t+ qid\n\t\t\t\t\t\t\t\t+ \" is not in a known class of integer numbers. Skipping.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the value is integer and build label string:\n\t\t\tString numberString;\n\t\t\ttry {\n\t\t\t\tBigInteger intValue = number.getNumericValue()\n\t\t\t\t\t\t.toBigIntegerExact();\n\t\t\t\tnumberString = intValue.toString();\n\t\t\t} catch (ArithmeticException e) {\n\t\t\t\tSystem.out.println(\"*** Numeric value for \" + qid\n\t\t\t\t\t\t+ \" is not an integer: \" + number.getNumericValue());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Construct data to write:\n\t\t\tItemDocumentBuilder itemDocumentBuilder = ItemDocumentBuilder\n\t\t\t\t\t.forItemId(itemIdValue).withRevisionId(\n\t\t\t\t\t\t\tcurrentItemDocument.getRevisionId());\n\t\t\tArrayList<String> languages = new ArrayList<>(\n\t\t\t\t\tarabicNumeralLanguages.length);\n\t\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\t\tif (!currentItemDocument.getLabels().containsKey(\n\t\t\t\t\t\tarabicNumeralLanguages[i])) {\n\t\t\t\t\titemDocumentBuilder.withLabel(numberString,\n\t\t\t\t\t\t\tarabicNumeralLanguages[i]);\n\t\t\t\t\tlanguages.add(arabicNumeralLanguages[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (languages.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** Labels already complete for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tnumberString, languages);\n\n\t\t\tdataEditor.editItemDocument(itemDocumentBuilder.build(), false,\n\t\t\t\t\t\"Set labels to numeric value (Task MB1)\");\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public static void printToFile(String filename, String message) {\r\n printToFile(new File(filename), message, false);\r\n }",
"private long getWeightedMatchScore(Iterable<String> requestUriParts, Iterable<String> destUriParts) {\n // The score calculated below is a base 5 number\n // The score will have one digit for one part of the URI\n // This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13\n // We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during\n // score calculation\n long score = 0;\n for (Iterator<String> rit = requestUriParts.iterator(), dit = destUriParts.iterator();\n rit.hasNext() && dit.hasNext(); ) {\n String requestPart = rit.next();\n String destPart = dit.next();\n if (requestPart.equals(destPart)) {\n score = (score * 5) + 4;\n } else if (PatternPathRouterWithGroups.GROUP_PATTERN.matcher(destPart).matches()) {\n score = (score * 5) + 3;\n } else {\n score = (score * 5) + 2;\n }\n }\n return score;\n }",
"public void setModel(Database databaseModel, DescriptorRepository objModel)\r\n {\r\n _dbModel = databaseModel;\r\n _preparedModel = new PreparedModel(objModel, databaseModel);\r\n }",
"public boolean find() {\r\n if (findIterator == null) {\r\n findIterator = root.iterator();\r\n }\r\n if (findCurrent != null && matches()) {\r\n return true;\r\n }\r\n while (findIterator.hasNext()) {\r\n findCurrent = findIterator.next();\r\n resetChildIter(findCurrent);\r\n if (matches()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }",
"private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }",
"public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}"
] |
Internal method used to retrieve a byte array from one
or more embedded data blocks. Consecutive data blocks may
need to be concatenated by this method in order to retrieve
the complete set of data.
@param blocks list of data blocks
@param length expected length of the data
@return byte array | [
"private byte[] getData(List<byte[]> blocks, int length)\n {\n byte[] result;\n\n if (blocks.isEmpty() == false)\n {\n if (length < 4)\n {\n length = 4;\n }\n\n result = new byte[length];\n int offset = 0;\n byte[] data;\n\n while (offset < length)\n {\n data = blocks.remove(0);\n System.arraycopy(data, 0, result, offset, data.length);\n offset += data.length;\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }"
] | [
"public static void main(String[] args) throws IOException {\n\t\tExampleHelpers.configureLogging();\n\t\tJsonSerializationProcessor.printDocumentation();\n\n\t\tJsonSerializationProcessor jsonSerializationProcessor = new JsonSerializationProcessor();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(jsonSerializationProcessor);\n\t\tjsonSerializationProcessor.close();\n\t}",
"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 }",
"public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){\n\t\t\tdouble minDistance = Double.MAX_VALUE;\n\t\t\tPoint2D.Double minDistancePoint = null;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/nPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < nPointsPerSegment; j++){\n\t\t \t\tPoint2D.Double candidate = new Point2D.Double(x, spline.value(x));\n\t\t \t\tdouble d = p.distance(candidate);\n\t\t \t\tif(d<minDistance){\n\t\t \t\t\tminDistance = d;\n\t\t \t\t\tminDistancePoint = candidate;\n\t\t \t\t}\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t return minDistancePoint;\n\t}",
"private void writeWBS(Task mpxj)\n {\n if (mpxj.getUniqueID().intValue() != 0)\n {\n WBSType xml = m_factory.createWBSType();\n m_project.getWBS().add(xml);\n String code = mpxj.getWBS();\n code = code == null || code.length() == 0 ? DEFAULT_WBS_CODE : code;\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setCode(code);\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setName(mpxj.getName());\n\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(parentObjectID);\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSequenceNumber(Integer.valueOf(m_wbsSequence++));\n\n xml.setStatus(\"Active\");\n }\n\n writeChildTasks(mpxj);\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period) {\n return runEvery(task, delay, period, null);\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 }",
"private void updateLetsEncrypt() {\n\n getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0));\n\n CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig();\n if ((config == null) || !config.isValidAndEnabled()) {\n return;\n }\n CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config);\n boolean ok = converter.run(getReport(), OpenCms.getSiteManager());\n if (ok) {\n getReport().println(\n org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0),\n I_CmsReport.FORMAT_OK);\n }\n\n }",
"public ParallelTaskBuilder prepareHttpGet(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n \n cb.getHttpMeta().setHttpMethod(HttpMethod.GET);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n \n return cb;\n }",
"@Deprecated\n public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) {\n Utils.notNull(nodes);\n this.nodes = new HashSet<Node>(nodes);\n return this;\n }"
] |
Compares two annotated types and returns true if they are the same | [
"public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }"
] | [
"private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }",
"public List<String> scan() {\n try {\n JarFile jar = new JarFile(jarURL.getFile());\n try {\n List<String> result = new ArrayList<>();\n Enumeration<JarEntry> en = jar.entries();\n while (en.hasMoreElements()) {\n JarEntry entry = en.nextElement();\n String path = entry.getName();\n boolean match = includes.size() == 0;\n if (!match) {\n for (String pattern : includes) {\n if ( patternMatches(pattern, path)) {\n match = true;\n break;\n }\n }\n }\n if (match) {\n for (String pattern : excludes) {\n if ( patternMatches(pattern, path)) {\n match = false;\n break;\n }\n }\n }\n if (match) {\n result.add(path);\n }\n }\n return result;\n } finally {\n jar.close();\n }\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }",
"public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"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}",
"public Object extractJavaFieldValue(Object object) throws SQLException {\n\n\t\tObject val = extractRawJavaFieldValue(object);\n\n\t\t// if this is a foreign object then we want its reference field\n\t\tif (foreignRefField != null && val != null) {\n\t\t\tval = foreignRefField.extractRawJavaFieldValue(val);\n\t\t}\n\n\t\treturn val;\n\t}",
"@Override\n public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor)\n throws Exception {\n clientRequestExecutor.close();\n int numDestroyed = destroyed.incrementAndGet();\n if(stats != null) {\n stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT);\n }\n\n if(logger.isDebugEnabled())\n logger.debug(\"Destroyed socket \" + numDestroyed + \" connection to \" + dest.getHost()\n + \":\" + dest.getPort());\n }",
"public void set( int row , int col , double value ) {\n ops.set(mat, row, col, value);\n }",
"private void ensureIndexIsUnlocked(String dataDir) {\n\n Collection<File> lockFiles = new ArrayList<File>(2);\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"index\") + \"write.lock\"));\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"spellcheck\")\n + \"write.lock\"));\n for (File lockFile : lockFiles) {\n if (lockFile.exists()) {\n lockFile.delete();\n LOG.warn(\n \"Forcely unlocking index with data dir \\\"\"\n + dataDir\n + \"\\\" by removing file \\\"\"\n + lockFile.getAbsolutePath()\n + \"\\\".\");\n }\n }\n }"
] |
Starts the enforcer. | [
"final void begin() {\n if (this.properties.isDateRollEnforced()) {\n final Thread thread = new Thread(this,\n \"Log4J Time-based File-roll Enforcer\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }"
] | [
"public static String encodeUserInfo(String userInfo, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(userInfo, encoding, HierarchicalUriComponents.Type.USER_INFO);\n\t}",
"private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {\n if (cause.getMessage() == null) {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());\n } else {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + \": \" + cause.getMessage());\n }\n for (final StackTraceElement ste : cause.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (cause.getCause() != null) {\n addCauseToBacktrace(cause.getCause(), bTrace);\n }\n }",
"protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }",
"@Inline(value = \"$1.putAll($2)\", statementExpression = true)\n\tpublic static <K, V> void operator_add(Map<K, V> outputMap, Map<? extends K, ? extends V> inputMap) {\n\t\toutputMap.putAll(inputMap);\n\t}",
"public List<Index<Field>> allIndexes() {\n List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();\n indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));\n return indexesOfAnyType;\n }",
"public BsonDocument toUpdateDocument() {\n final List<BsonElement> unsets = new ArrayList<>();\n for (final String removedField : this.removedFields) {\n unsets.add(new BsonElement(removedField, new BsonBoolean(true)));\n }\n final BsonDocument updateDocument = new BsonDocument();\n\n if (this.updatedFields.size() > 0) {\n updateDocument.append(\"$set\", this.updatedFields);\n }\n\n if (unsets.size() > 0) {\n updateDocument.append(\"$unset\", new BsonDocument(unsets));\n }\n\n return updateDocument;\n }",
"static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }",
"@RequestMapping(value = \"api/edit/disableAll\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableAll(Model model, int profileID,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) {\n editService.disableAll(profileID, clientUUID);\n return null;\n }",
"private static String convertISO88591toUTF8(String value) {\n try {\n return new String(value.getBytes(CharEncoding.ISO_8859_1), CharEncoding.UTF_8);\n }\n catch (UnsupportedEncodingException ex) {\n // ignore and fallback to original encoding\n return value;\n }\n }"
] |
Use this API to fetch all the nsrpcnode resources that are configured on netscaler. | [
"public static nsrpcnode[] get(nitro_service service) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tnsrpcnode[] response = (nsrpcnode[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"protected final boolean isValidEndTypeForPattern() {\n\n if (getEndType() == null) {\n return false;\n }\n switch (getPatternType()) {\n case DAILY:\n case WEEKLY:\n case MONTHLY:\n case YEARLY:\n return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));\n case INDIVIDUAL:\n case NONE:\n return getEndType().equals(EndType.SINGLE);\n default:\n return false;\n }\n }",
"public RedwoodConfiguration hideChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.hideChannels(channels); } });\r\n return this;\r\n }",
"@Override\n public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename,\n long startOffsetBytes, long timeoutMillis) {\n Preconditions.checkArgument(startOffsetBytes >= 0, \"%s: offset must be non-negative: %s\", this,\n startOffsetBytes);\n final int n = dst.remaining();\n Preconditions.checkArgument(n > 0, \"%s: dst full: %s\", this, dst);\n final int want = Math.min(READ_LIMIT_BYTES, n);\n\n final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);\n req.setHeader(\n new HTTPHeader(RANGE, \"bytes=\" + startOffsetBytes + \"-\" + (startOffsetBytes + want - 1)));\n final HTTPRequestInfo info = new HTTPRequestInfo(req);\n return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {\n @Override\n protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {\n long totalLength;\n switch (resp.getResponseCode()) {\n case 200:\n totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);\n break;\n case 206:\n totalLength = getLengthFromContentRange(resp);\n break;\n case 404:\n throw new FileNotFoundException(\"Could not find: \" + filename);\n case 416:\n throw new BadRangeException(\"Requested Range not satisfiable; perhaps read past EOF? \"\n + URLFetchUtils.describeRequestAndResponse(info, resp));\n default:\n throw HttpErrorHandler.error(info, resp);\n }\n byte[] content = resp.getContent();\n Preconditions.checkState(content.length <= want, \"%s: got %s > wanted %s\", this,\n content.length, want);\n dst.put(content);\n return getMetadataFromResponse(filename, resp, totalLength);\n }\n\n @Override\n protected Throwable convertException(Throwable e) {\n return OauthRawGcsService.convertException(info, e);\n }\n };\n }",
"public String getCsv() {\n\n StringWriter writer = new StringWriter();\n try (CSVWriter csv = new CSVWriter(writer)) {\n List<String> headers = new ArrayList<>();\n for (String col : m_columns) {\n headers.add(col);\n }\n csv.writeNext(headers.toArray(new String[] {}));\n for (List<Object> row : m_data) {\n List<String> colCsv = new ArrayList<>();\n for (Object col : row) {\n colCsv.add(String.valueOf(col));\n }\n csv.writeNext(colCsv.toArray(new String[] {}));\n }\n return writer.toString();\n } catch (IOException e) {\n return null;\n }\n }",
"protected static boolean fileDoesNotExist(String file, String path,\n String dest_dir) {\n\n File f = new File(dest_dir);\n if (!f.isDirectory())\n return false;\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n\n File javaFile = new File(f, file);\n boolean result = !javaFile.exists();\n\n return result;\n }",
"public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }",
"public static String keyVersionToString(ByteArray key,\n Map<Value, Set<ClusterNode>> versionMap,\n String storeName,\n Integer partitionId) {\n StringBuilder record = new StringBuilder();\n for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) {\n Value value = versionSet.getKey();\n Set<ClusterNode> nodeSet = versionSet.getValue();\n\n record.append(\"BAD_KEY,\");\n record.append(storeName + \",\");\n record.append(partitionId + \",\");\n record.append(ByteUtils.toHexString(key.get()) + \",\");\n record.append(nodeSet.toString().replace(\", \", \";\") + \",\");\n record.append(value.toString());\n }\n return record.toString();\n }",
"public final String getPath(final String key) {\n StringBuilder result = new StringBuilder();\n addPathTo(result);\n result.append(\".\");\n result.append(getPathElement(key));\n return result.toString();\n }",
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }"
] |
Set default values for the TimeAndSizeRollingAppender appender
@param appender | [
"private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}"
] | [
"protected void onLegendDataChanged() {\n\n int legendCount = mLegendList.size();\n float margin = (mGraphWidth / legendCount);\n float currentOffset = 0;\n\n for (LegendModel model : mLegendList) {\n model.setLegendBounds(new RectF(currentOffset, 0, currentOffset + margin, mLegendHeight));\n currentOffset += margin;\n }\n\n Utils.calculateLegendInformation(mLegendList, 0, mGraphWidth, mLegendPaint);\n\n invalidateGlobal();\n }",
"public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) {\n if(!metadataStore.getCluster().hasNodeWithId(nodeId)) {\n throw new InvalidMetadataException(\"NodeId \" + nodeId + \" is not or no longer in this cluster\");\n }\n }",
"private void registerPerformanceMonitor(String beanName,\n BeanDefinitionRegistry registry) {\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n if (!registry.containsBeanDefinition(perfMonitorName)) {\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);\n registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());\n }\n }",
"public void fireEvent(final WorkerEvent event, final Worker worker, final String queue, final Job job, \n final Object runner, final Object result, final Throwable t) {\n final ConcurrentSet<WorkerListener> listeners = this.eventListenerMap.get(event);\n if (listeners != null) {\n for (final WorkerListener listener : listeners) {\n if (listener != null) {\n try {\n listener.onEvent(event, worker, queue, job, runner, result, t);\n } catch (Exception e) {\n log.error(\"Failure executing listener \" + listener + \" for event \" + event \n + \" from queue \" + queue + \" on worker \" + worker, e);\n }\n }\n }\n }\n }",
"@Override\n public void registerChildren(ManagementResourceRegistration resourceRegistration) {\n // Register wildcard children last to prevent duplicate registration errors when override definitions exist\n for (ResourceDefinition rd : singletonChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n for (ResourceDefinition rd : wildcardChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n }",
"private void readCalendars()\n {\n //\n // Create the calendars\n //\n for (MapRow row : getTable(\"NCALTAB\"))\n {\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setUniqueID(row.getInteger(\"UNIQUE_ID\"));\n calendar.setName(row.getString(\"NAME\"));\n calendar.setWorkingDay(Day.SUNDAY, row.getBoolean(\"SUNDAY\"));\n calendar.setWorkingDay(Day.MONDAY, row.getBoolean(\"MONDAY\"));\n calendar.setWorkingDay(Day.TUESDAY, row.getBoolean(\"TUESDAY\"));\n calendar.setWorkingDay(Day.WEDNESDAY, row.getBoolean(\"WEDNESDAY\"));\n calendar.setWorkingDay(Day.THURSDAY, row.getBoolean(\"THURSDAY\"));\n calendar.setWorkingDay(Day.FRIDAY, row.getBoolean(\"FRIDAY\"));\n calendar.setWorkingDay(Day.SATURDAY, row.getBoolean(\"SATURDAY\"));\n\n for (Day day : Day.values())\n {\n if (calendar.isWorkingDay(day))\n {\n // TODO: this is an approximation\n calendar.addDefaultCalendarHours(day);\n }\n }\n }\n\n //\n // Set up the hierarchy and add exceptions\n //\n Table exceptionsTable = getTable(\"CALXTAB\");\n for (MapRow row : getTable(\"NCALTAB\"))\n {\n ProjectCalendar child = m_projectFile.getCalendarByUniqueID(row.getInteger(\"UNIQUE_ID\"));\n ProjectCalendar parent = m_projectFile.getCalendarByUniqueID(row.getInteger(\"BASE_CALENDAR_ID\"));\n if (child != null && parent != null)\n {\n child.setParent(parent);\n }\n\n addCalendarExceptions(exceptionsTable, child, row.getInteger(\"FIRST_CALENDAR_EXCEPTION_ID\"));\n\n m_eventManager.fireCalendarReadEvent(child);\n }\n }",
"private Resolvable createMetadataProvider(Class<?> rawType) {\n Set<Type> types = Collections.<Type>singleton(rawType);\n return new ResolvableImpl(rawType, types, declaringBean, qualifierInstances, delegate);\n }",
"public void onDrawFrame(float frameTime) {\n final GVRSceneObject owner = getOwnerObject();\n if (owner == null) {\n return;\n }\n\n final int size = mRanges.size();\n final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();\n\n for (final Object[] range : mRanges) {\n ((GVRSceneObject)range[1]).setEnable(false);\n }\n\n for (int i = size - 1; i >= 0; --i) {\n final Object[] range = mRanges.get(i);\n final GVRSceneObject child = (GVRSceneObject) range[1];\n if (child.getParent() != owner) {\n Log.w(TAG, \"the scene object for distance greater than \" + range[0] + \" is not a child of the owner; skipping it\");\n continue;\n }\n\n final float[] values = child.getBoundingVolumeRawValues();\n mCenter.set(values[0], values[1], values[2], 1.0f);\n mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);\n\n mVector.sub(mCenter);\n mVector.negate();\n\n float distance = mVector.dot(mVector);\n\n if (distance >= (Float) range[0]) {\n child.setEnable(true);\n break;\n }\n }\n }",
"public static base_response update(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite updateresource = new gslbsite();\n\t\tupdateresource.sitename = resource.sitename;\n\t\tupdateresource.metricexchange = resource.metricexchange;\n\t\tupdateresource.nwmetricexchange = resource.nwmetricexchange;\n\t\tupdateresource.sessionexchange = resource.sessionexchange;\n\t\tupdateresource.triggermonitor = resource.triggermonitor;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
replace region length | [
"public String getPrefix(INode prefixNode) {\n\t\tif (prefixNode instanceof ILeafNode) {\n\t\t\tif (((ILeafNode) prefixNode).isHidden() && prefixNode.getGrammarElement() != null)\n\t\t\t\treturn \"\";\n\t\t\treturn getNodeTextUpToCompletionOffset(prefixNode);\n\t\t}\n\t\tStringBuilder result = new StringBuilder(prefixNode.getTotalLength());\n\t\tdoComputePrefix((ICompositeNode) prefixNode, result);\n\t\treturn result.toString();\n\t}"
] | [
"public static nstimeout get(nitro_service service) throws Exception{\n\t\tnstimeout obj = new nstimeout();\n\t\tnstimeout[] response = (nstimeout[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getList(Model model) throws Exception {\n logger.info(\"Using a GET request to list profiles\");\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }",
"private GraphicalIndicatorCriteria processCriteria(FieldType type)\n {\n GraphicalIndicatorCriteria criteria = new GraphicalIndicatorCriteria(m_properties);\n criteria.setLeftValue(type);\n\n int indicatorType = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setIndicator(indicatorType);\n\n if (m_dataOffset + 4 < m_data.length)\n {\n int operatorValue = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n TestOperator operator = (operatorValue == 0 ? TestOperator.IS_ANY_VALUE : TestOperator.getInstance(operatorValue - 0x3E7));\n criteria.setOperator(operator);\n\n if (operator != TestOperator.IS_ANY_VALUE)\n {\n processOperandValue(0, type, criteria);\n\n if (operator == TestOperator.IS_WITHIN || operator == TestOperator.IS_NOT_WITHIN)\n {\n processOperandValue(1, type, criteria);\n }\n }\n }\n\n return (criteria);\n }",
"synchronized void asyncReconnect(final URI reconnectUri, String authKey, final ReconnectCallback callback) {\n if (getState() != State.OPEN) {\n return;\n }\n // Update the configuration with the new credentials\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(createClientCallbackHandler(userName, authKey));\n config.setUri(reconnectUri);\n this.configuration = config;\n\n final ReconnectRunner reconnectTask = this.reconnectRunner;\n if (reconnectTask == null) {\n final ReconnectRunner task = new ReconnectRunner();\n task.callback = callback;\n task.future = executorService.submit(task);\n } else {\n reconnectTask.callback = callback;\n }\n }",
"public static <T> ManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new ManagedBean<T>(attributes, clazz, createId(attributes, clazz), beanManager);\n }",
"DeleteResult deleteMany(final MongoNamespace namespace,\n final Bson filter) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();\n final DeleteResult result;\n final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n try {\n final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);\n final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);\n final Set<BsonValue> idsToDelete =\n localCollection\n .find(filter)\n .map(new Function<BsonDocument, BsonValue>() {\n @Override\n @NonNull\n public BsonValue apply(@NonNull final BsonDocument bsonDocument) {\n undoCollection.insertOne(bsonDocument);\n return BsonUtils.getDocumentId(bsonDocument);\n }\n }).into(new HashSet<>());\n\n result = localCollection.deleteMany(filter);\n\n for (final BsonValue documentId : idsToDelete) {\n final CoreDocumentSynchronizationConfig config =\n syncConfig.getSynchronizedDocument(namespace, documentId);\n\n if (config == null) {\n continue;\n }\n\n final ChangeEvent<BsonDocument> event =\n ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);\n\n // this block is to trigger coalescence for a delete after insert\n if (config.getLastUncommittedChangeEvent() != null\n && config.getLastUncommittedChangeEvent().getOperationType()\n == OperationType.INSERT) {\n desyncDocumentsFromRemote(nsConfig, config.getDocumentId())\n .commitAndClear();\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n continue;\n }\n\n config.setSomePendingWritesAndSave(logicalT, event);\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n eventsToEmit.add(event);\n }\n checkAndDeleteNamespaceListener(namespace);\n } finally {\n lock.unlock();\n }\n for (final ChangeEvent<BsonDocument> event : eventsToEmit) {\n eventDispatcher.emitEvent(nsConfig, event);\n }\n return result;\n } finally {\n ongoingOperationsGroup.exit();\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 FieldDescriptor getAutoIncrementField()\r\n {\r\n if (m_autoIncrementField == null)\r\n {\r\n FieldDescriptor[] fds = getPkFields();\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n FieldDescriptor fd = fds[i];\r\n if (fd.isAutoIncrement())\r\n {\r\n m_autoIncrementField = fd;\r\n break;\r\n }\r\n }\r\n }\r\n if (m_autoIncrementField == null)\r\n {\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"Could not find autoincrement attribute for class: \"\r\n + this.getClassNameOfObject());\r\n }\r\n return m_autoIncrementField;\r\n }",
"public Duration getWork(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getWorkTimeUnit());\n }"
] |
Instruct a query to use a specific index.
@param designDocument Design document to use.
@param indexName Index name to use.
@return {@code QueryBuilder} object for method chaining. | [
"public QueryBuilder useIndex(String designDocument, String indexName) {\n useIndex = new String[]{designDocument, indexName};\n return this;\n }"
] | [
"public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID,\r\n String folderID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_FOLDER).add(\"id\", folderID), null);\r\n }",
"public static List<Node> getSiblings(Node parent, Node element) {\n\t\tList<Node> result = new ArrayList<>();\n\t\tNodeList list = parent.getChildNodes();\n\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\tNode el = list.item(i);\n\n\t\t\tif (el.getNodeName().equals(element.getNodeName())) {\n\t\t\t\tresult.add(el);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}",
"public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalStateException(message);\n\n return value;\n }",
"public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }",
"public static Map<String, ByteRunAutomaton> byteRunAutomatonMap(\n Map<String, Automaton> automatonMap) {\n HashMap<String, ByteRunAutomaton> byteRunAutomatonMap = new HashMap<>();\n if (automatonMap != null) {\n for (Entry<String, Automaton> entry : automatonMap.entrySet()) {\n byteRunAutomatonMap.put(entry.getKey(),\n new ByteRunAutomaton(entry.getValue()));\n }\n }\n return byteRunAutomatonMap;\n }",
"private static String guessPackaging(ProjectModel projectModel)\n {\n String projectType = projectModel.getProjectType();\n if (projectType != null)\n return projectType;\n\n LOG.warning(\"WINDUP-983 getProjectType() returned null for: \" + projectModel.getRootFileModel().getPrettyPath());\n\n String suffix = StringUtils.substringAfterLast(projectModel.getRootFileModel().getFileName(), \".\");\n if (\"jar war ear sar har \".contains(suffix+\" \")){\n projectModel.setProjectType(suffix); // FIXME: Remove when WINDUP-983 is fixed.\n return suffix;\n }\n\n // Should we try something more? Used APIs? What if it's a source?\n\n return \"unknown\";\n }",
"public static <T> T createObject(final Class<T> clazz, final Object... args) throws NoSuchConstructorException,\n AmbiguousConstructorException, ReflectiveOperationException {\n return findConstructor(clazz, args).newInstance(args);\n }",
"public static void generateJRXML(DynamicReport dr, LayoutManager layoutManager, Map _parameters, String xmlEncoding, OutputStream outputStream) throws JRException {\n JasperReport jr = generateJasperReport(dr, layoutManager, _parameters);\n if (xmlEncoding == null)\n xmlEncoding = DEFAULT_XML_ENCODING;\n JRXmlWriter.writeReport(jr, outputStream, xmlEncoding);\n }",
"public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) {\n // Make sure versions missing from the file-system are cleaned up from the internal state\n for (Long version: versionToEnabledMap.keySet()) {\n File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (existingVersionDirs.length == 0) {\n removeVersion(version, alsoSyncRemoteState);\n }\n }\n\n // Make sure we have all versions on the file-system in the internal state\n File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir);\n if (versionDirs != null) {\n for (File versionDir: versionDirs) {\n long versionNumber = ReadOnlyUtils.getVersionId(versionDir);\n boolean versionEnabled = isVersionEnabled(versionDir);\n versionToEnabledMap.put(versionNumber, versionEnabled);\n }\n }\n\n // Identify the current version (based on a symlink in the file-system)\n File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir);\n if (currentVersionDir != null) {\n currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir);\n } else {\n currentVersion = -1; // Should we throw instead?\n }\n\n logger.info(\"Successfully synced internal state from local file-system: \" + this.toString());\n }"
] |
Use this API to kill systemsession resources. | [
"public static base_responses kill(nitro_service client, systemsession resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemsession killresources[] = new systemsession[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tkillresources[i] = new systemsession();\n\t\t\t\tkillresources[i].sid = resources[i].sid;\n\t\t\t\tkillresources[i].all = resources[i].all;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, killresources,\"kill\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public Record getChild(String key)\n {\n Record result = null;\n if (key != null)\n {\n for (Record record : m_records)\n {\n if (key.equals(record.getField()))\n {\n result = record;\n break;\n }\n }\n }\n return result;\n }",
"protected void beforeMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.beforeMaterialization(this, _id);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public T removeModule(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createModuleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }",
"public String[] getItemsSelected() {\n List<String> selected = new LinkedList<>();\n for (int i = getIndexOffset(); i < listBox.getItemCount(); i++) {\n if (listBox.isItemSelected(i)) {\n selected.add(listBox.getValue(i));\n }\n }\n return selected.toArray(new String[selected.size()]);\n }",
"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 BoxFile.Info commit(String digest, List<BoxFileUploadSessionPart> parts,\n Map<String, String> attributes, String ifMatch, String ifNoneMatch) {\n\n URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);\n\n if (ifMatch != null) {\n request.addHeader(HttpHeaders.IF_MATCH, ifMatch);\n }\n\n if (ifNoneMatch != null) {\n request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch);\n }\n\n //Creates the body of the request\n String body = this.getCommitBody(parts, attributes);\n request.setBody(body);\n\n BoxAPIResponse response = request.send();\n //Retry the commit operation after the given number of seconds if the HTTP response code is 202.\n if (response.getResponseCode() == 202) {\n String retryInterval = response.getHeaderField(\"retry-after\");\n if (retryInterval != null) {\n try {\n Thread.sleep(new Integer(retryInterval) * 1000);\n } catch (InterruptedException ie) {\n throw new BoxAPIException(\"Commit retry failed. \", ie);\n }\n\n return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch);\n }\n }\n\n if (response instanceof BoxJSONResponse) {\n //Create the file instance from the response\n return this.getFile((BoxJSONResponse) response);\n } else {\n throw new BoxAPIException(\"Commit response content type is not application/json. The response code : \"\n + response.getResponseCode());\n }\n }",
"private void plan() {\n // Mapping of stealer node to list of primary partitions being moved\n final TreeMultimap<Integer, Integer> stealerToStolenPrimaryPartitions = TreeMultimap.create();\n\n // Output initial and final cluster\n if(outputDir != null)\n RebalanceUtils.dumpClusters(currentCluster, finalCluster, outputDir);\n\n // Determine which partitions must be stolen\n for(Node stealerNode: finalCluster.getNodes()) {\n List<Integer> stolenPrimaryPartitions = RebalanceUtils.getStolenPrimaryPartitions(currentCluster,\n finalCluster,\n stealerNode.getId());\n if(stolenPrimaryPartitions.size() > 0) {\n numPrimaryPartitionMoves += stolenPrimaryPartitions.size();\n stealerToStolenPrimaryPartitions.putAll(stealerNode.getId(),\n stolenPrimaryPartitions);\n }\n }\n\n // Determine plan batch-by-batch\n int batches = 0;\n Cluster batchCurrentCluster = Cluster.cloneCluster(currentCluster);\n List<StoreDefinition> batchCurrentStoreDefs = this.currentStoreDefs;\n List<StoreDefinition> batchFinalStoreDefs = this.finalStoreDefs;\n Cluster batchFinalCluster = RebalanceUtils.getInterimCluster(this.currentCluster,\n this.finalCluster);\n\n while(!stealerToStolenPrimaryPartitions.isEmpty()) {\n\n int partitions = 0;\n List<Entry<Integer, Integer>> partitionsMoved = Lists.newArrayList();\n for(Entry<Integer, Integer> stealerToPartition: stealerToStolenPrimaryPartitions.entries()) {\n partitionsMoved.add(stealerToPartition);\n batchFinalCluster = UpdateClusterUtils.createUpdatedCluster(batchFinalCluster,\n stealerToPartition.getKey(),\n Lists.newArrayList(stealerToPartition.getValue()));\n partitions++;\n if(partitions == batchSize)\n break;\n }\n\n // Remove the partitions moved\n for(Iterator<Entry<Integer, Integer>> partitionMoved = partitionsMoved.iterator(); partitionMoved.hasNext();) {\n Entry<Integer, Integer> entry = partitionMoved.next();\n stealerToStolenPrimaryPartitions.remove(entry.getKey(), entry.getValue());\n }\n\n if(outputDir != null)\n RebalanceUtils.dumpClusters(batchCurrentCluster,\n batchFinalCluster,\n outputDir,\n \"batch-\" + Integer.toString(batches) + \".\");\n\n // Generate a plan to compute the tasks\n final RebalanceBatchPlan RebalanceBatchPlan = new RebalanceBatchPlan(batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs);\n batchPlans.add(RebalanceBatchPlan);\n\n numXZonePartitionStoreMoves += RebalanceBatchPlan.getCrossZonePartitionStoreMoves();\n numPartitionStoreMoves += RebalanceBatchPlan.getPartitionStoreMoves();\n nodeMoveMap.add(RebalanceBatchPlan.getNodeMoveMap());\n zoneMoveMap.add(RebalanceBatchPlan.getZoneMoveMap());\n\n batches++;\n batchCurrentCluster = Cluster.cloneCluster(batchFinalCluster);\n // batchCurrentStoreDefs can only be different from\n // batchFinalStoreDefs for the initial batch.\n batchCurrentStoreDefs = batchFinalStoreDefs;\n }\n\n logger.info(this);\n }",
"public double compare(String v1, String v2) {\n // FIXME: it should be possible here to say that, actually, we\n // didn't learn anything from comparing these two values, so that\n // probability is set to 0.5.\n\n if (comparator == null)\n return 0.5; // we ignore properties with no comparator\n\n // first, we call the comparator, to get a measure of how similar\n // these two values are. note that this is not the same as what we\n // are going to return, which is a probability.\n double sim = comparator.compare(v1, v2);\n\n // we have been configured with a high probability (for equal\n // values) and a low probability (for different values). given\n // sim, which is a measure of the similarity somewhere in between\n // equal and different, we now compute our estimate of the\n // probability.\n\n // if sim = 1.0, we return high. if sim = 0.0, we return low. for\n // values in between we need to compute a little. the obvious\n // formula to use would be (sim * (high - low)) + low, which\n // spreads the values out equally spaced between high and low.\n\n // however, if the similarity is higher than 0.5 we don't want to\n // consider this negative evidence, and so there's a threshold\n // there. also, users felt Duke was too eager to merge records,\n // and wanted probabilities to fall off faster with lower\n // probabilities, and so we square sim in order to achieve this.\n\n if (sim >= 0.5)\n return ((high - 0.5) * (sim * sim)) + 0.5;\n else\n return low;\n }",
"public static String join(Collection<String> s, String delimiter, boolean doQuote) {\r\n StringBuffer buffer = new StringBuffer();\r\n Iterator<String> iter = s.iterator();\r\n while (iter.hasNext()) {\r\n if (doQuote) {\r\n buffer.append(\"\\\"\" + iter.next() + \"\\\"\");\r\n } else {\r\n buffer.append(iter.next());\r\n }\r\n if (iter.hasNext()) {\r\n buffer.append(delimiter);\r\n }\r\n }\r\n return buffer.toString();\r\n }"
] |
Returns the indices that would sort an array.
@param array Array.
@param ascending Ascending order.
@return Array of indices. | [
"public static int[] Argsort(final float[] array, final boolean ascending) {\n Integer[] indexes = new Integer[array.length];\n for (int i = 0; i < indexes.length; i++) {\n indexes[i] = i;\n }\n Arrays.sort(indexes, new Comparator<Integer>() {\n @Override\n public int compare(final Integer i1, final Integer i2) {\n return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]);\n }\n });\n return asArray(indexes);\n }"
] | [
"public static base_response delete(nitro_service client, String domain) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = domain;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }",
"public void forAllIndexColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curIndexDef.getColumns(); it.hasNext(); )\r\n {\r\n _curColumnDef = _curTableDef.getColumn((String)it.next());\r\n generate(template);\r\n }\r\n _curColumnDef = null;\r\n }",
"private static void parseDockers(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"dockers\")) {\n ArrayList<Point> dockers = new ArrayList<Point>();\n\n JSONArray dockersObject = modelJSON.getJSONArray(\"dockers\");\n for (int i = 0; i < dockersObject.length(); i++) {\n Double x = dockersObject.getJSONObject(i).getDouble(\"x\");\n Double y = dockersObject.getJSONObject(i).getDouble(\"y\");\n dockers.add(new Point(x,\n y));\n }\n if (dockers.size() > 0) {\n current.setDockers(dockers);\n }\n }\n }",
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }",
"public void renumberUniqueIDs()\n {\n int uid = firstUniqueID();\n for (T entity : this)\n {\n entity.setUniqueID(Integer.valueOf(uid++));\n }\n }",
"public static int getHostSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) {\n\t\tif(bytesPerSegment > 1) {\n\t\t\tif(bytesPerSegment == 2) {\n\t\t\t\treturn networkPrefixLength >> 4;\n\t\t\t}\n\t\t\treturn networkPrefixLength / bitsPerSegment;\n\t\t}\n\t\treturn networkPrefixLength >> 3;\n\t}",
"public static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size)\n throws CmsUgcException {\n\n if (!config.getUploadParentFolder().isPresent()) {\n String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message);\n }\n\n if (config.getMaxUploadSize().isPresent()) {\n if (config.getMaxUploadSize().get().longValue() < size) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message);\n }\n }\n\n if (config.getValidExtensions().isPresent()) {\n List<String> validExtensions = config.getValidExtensions().get();\n boolean foundExtension = false;\n for (String extension : validExtensions) {\n if (name.toLowerCase().endsWith(extension.toLowerCase())) {\n foundExtension = true;\n break;\n }\n }\n if (!foundExtension) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message);\n }\n }\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 }"
] |
Obtains a Ethiopic zoned date-time from another date-time object.
@param temporal the date-time object to convert, not null
@return the Ethiopic zoned date-time, not null
@throws DateTimeException if unable to create the date-time | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<EthiopicDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<EthiopicDate>) super.zonedDateTime(temporal);\n }"
] | [
"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}",
"void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }",
"private static File getUserDirectory(final String prefix, final String suffix, final File parent) {\n final String dirname = formatDirName(prefix, suffix);\n return new File(parent, dirname);\n }",
"public static int cudnnRestoreDropoutDescriptor(\n cudnnDropoutDescriptor dropoutDesc, \n cudnnHandle handle, \n float dropout, \n Pointer states, \n long stateSizeInBytes, \n long seed)\n {\n return checkResult(cudnnRestoreDropoutDescriptorNative(dropoutDesc, handle, dropout, states, stateSizeInBytes, seed));\n }",
"public void showTrajectoryAndSpline(){\n\t\t\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[rotatedTrajectory.size()];\n\t\t double[] yData = new double[rotatedTrajectory.size()];\n\t\t for(int i = 0; i < rotatedTrajectory.size(); i++){\n\t\t \txData[i] = rotatedTrajectory.get(i).x;\n\t\t \tyData[i] = rotatedTrajectory.get(i).y;\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(\"Spline+Track\", \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\t \n\t\t //Add spline support points\n\t\t double[] subxData = new double[splineSupportPoints.size()];\n\t\t double[] subyData = new double[splineSupportPoints.size()];\n\t\t \n\t\t for(int i = 0; i < splineSupportPoints.size(); i++){\n\t\t \tsubxData[i] = splineSupportPoints.get(i).x;\n\t\t \tsubyData[i] = splineSupportPoints.get(i).y;\n\t\t }\n\t\t Series s = chart.addSeries(\"Spline Support Points\", subxData, subyData);\n\t\t s.setLineStyle(SeriesLineStyle.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t //ADd spline points\n\t\t int numberInterpolatedPointsPerSegment = 20;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] sxData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t \n\t\t double[] syData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/numberInterpolatedPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < numberInterpolatedPointsPerSegment; j++){\n\n\t\t \t\tsxData[i*numberInterpolatedPointsPerSegment+j] = x;\n\t\t \t\tsyData[i*numberInterpolatedPointsPerSegment+j] = spline.value(x);\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t s = chart.addSeries(\"Spline\", sxData, syData);\n\t\t s.setLineStyle(SeriesLineStyle.DASH_DASH);\n\t\t s.setMarker(SeriesMarker.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t \n\t\t //Show it\n\t\t new SwingWrapper(chart).displayChart();\n\t\t} \n\t}",
"private boolean shouldIgnore(String typeReference)\n {\n typeReference = typeReference.replace('/', '.').replace('\\\\', '.');\n return JavaClassIgnoreResolver.singletonInstance().matches(typeReference);\n }",
"public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }",
"public double distanceFrom(LatLong end) {\n\n double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180;\n double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180;\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(getLatitude() * Math.PI / 180)\n * Math.cos(end.getLatitude() * Math.PI / 180)\n * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\n double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EarthRadiusMeters * c;\n return d;\n }",
"protected Element createTextElement(String data, float width)\n {\n Element el = createTextElement(width);\n Text text = doc.createTextNode(data);\n el.appendChild(text);\n return el;\n }"
] |
Set the dates for the specified photo.
This method requires authentication with 'write' permission.
@param photoId
The photo ID
@param datePosted
The date the photo was posted or null
@param dateTaken
The date the photo was taken or null
@param dateTakenGranularity
The granularity of the taken date or null
@throws FlickrException | [
"public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_DATES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n if (datePosted != null) {\r\n parameters.put(\"date_posted\", Long.toString(datePosted.getTime() / 1000));\r\n }\r\n\r\n if (dateTaken != null) {\r\n parameters.put(\"date_taken\", ((DateFormat) DATE_FORMATS.get()).format(dateTaken));\r\n }\r\n\r\n if (dateTakenGranularity != null) {\r\n parameters.put(\"date_taken_granularity\", dateTakenGranularity);\r\n }\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }"
] | [
"@Override\n public ImageSource apply(ImageSource input) {\n final int[][] pixelMatrix = new int[3][3];\n\n int w = input.getWidth();\n int h = input.getHeight();\n\n int[][] output = new int[h][w];\n\n for (int j = 1; j < h - 1; j++) {\n for (int i = 1; i < w - 1; i++) {\n pixelMatrix[0][0] = input.getR(i - 1, j - 1);\n pixelMatrix[0][1] = input.getRGB(i - 1, j);\n pixelMatrix[0][2] = input.getRGB(i - 1, j + 1);\n pixelMatrix[1][0] = input.getRGB(i, j - 1);\n pixelMatrix[1][2] = input.getRGB(i, j + 1);\n pixelMatrix[2][0] = input.getRGB(i + 1, j - 1);\n pixelMatrix[2][1] = input.getRGB(i + 1, j);\n pixelMatrix[2][2] = input.getRGB(i + 1, j + 1);\n\n int edge = (int) convolution(pixelMatrix);\n int rgb = (edge << 16 | edge << 8 | edge);\n output[j][i] = rgb;\n }\n }\n\n MatrixSource source = new MatrixSource(output);\n return source;\n }",
"public void setGamma(float rGamma, float gGamma, float bGamma) {\n\t\tthis.rGamma = rGamma;\n\t\tthis.gGamma = gGamma;\n\t\tthis.bGamma = bGamma;\n\t\tinitialized = false;\n\t}",
"public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }",
"@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > LINGER_ITERATIONS && deadPool.isEmpty() && completionKeyToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n e.printStackTrace();\n isRunning.set(false);\n }\n }",
"public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }",
"private void addCustomFields(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (CustomField field : file.getCustomFields())\n {\n final CustomField c = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n FieldType type = c.getFieldType();\n \n return type == null ? \"(unknown)\" : type.getFieldTypeClass() + \".\" + type.toString();\n }\n };\n parentNode.add(childNode);\n }\n }",
"public List<CmsProject> getAllAccessibleProjects(CmsObject cms, String ouFqn, boolean includeSubOus)\n throws CmsException {\n\n CmsOrganizationalUnit orgUnit = readOrganizationalUnit(cms, ouFqn);\n return (m_securityManager.getAllAccessibleProjects(cms.getRequestContext(), orgUnit, includeSubOus));\n }",
"@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withoutTag(String key) {\n if (this.inner().getTags() != null) {\n this.inner().getTags().remove(key);\n }\n return (FluentModelImplT) this;\n }",
"public void setAngle(float angle) {\n this.angle = angle;\n float cos = (float) Math.cos(angle);\n float sin = (float) Math.sin(angle);\n m00 = cos;\n m01 = sin;\n m10 = -sin;\n m11 = cos;\n }"
] |
A specific, existing section can be deleted by making a DELETE request
on the URL for that section.
Note that sections must be empty to be deleted.
The last remaining section in a board view cannot be deleted.
Returns an empty data block.
@param section The section to delete.
@return Request object | [
"public ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\n }"
] | [
"public static void reset() {\n for (Object name : Collections.list(MAP_KEY_TO_SCOPE.keys())) {\n closeScope(name);\n }\n ConfigurationHolder.configuration.onScopeForestReset();\n ScopeImpl.resetUnBoundProviders();\n }",
"public void disableAllOverrides(int pathID, String clientUUID) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ? \" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n statement.execute();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public void addCell(TableLayoutCell cell) {\n GridBagConstraints constraints = cell.getConstraints();\n constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding);\n add(cell.getComponent(), constraints);\n }",
"public static synchronized void register(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factory != null ) {\n if ( factories == null ) {\n factories = new HashMap<String, List<Callable<Class< ? >>>>();\n }\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l == null ) {\n l = new ArrayList<Callable<Class< ? >>>();\n factories.put( serviceName,\n l );\n }\n l.add( factory );\n }\n }",
"public PathElement getElement(int index) {\n final List<PathElement> list = pathAddressList;\n return list.get(index);\n }",
"public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) {\n if (imageHolder != null && imageView != null) {\n Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint);\n if (drawable != null) {\n imageView.setImageDrawable(drawable);\n imageView.setVisibility(View.VISIBLE);\n } else if (imageHolder.getBitmap() != null) {\n imageView.setImageBitmap(imageHolder.getBitmap());\n imageView.setVisibility(View.VISIBLE);\n } else {\n imageView.setVisibility(View.GONE);\n }\n } else if (imageView != null) {\n imageView.setVisibility(View.GONE);\n }\n }",
"public static HashMap<String, JSONObject> flatRessources(JSONObject object) throws JSONException {\n HashMap<String, JSONObject> result = new HashMap<String, JSONObject>();\n\n // no cycle in hierarchies!!\n if (object.has(\"resourceId\") && object.has(\"childShapes\")) {\n result.put(object.getString(\"resourceId\"),\n object);\n JSONArray childShapes = object.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapes.length(); i++) {\n result.putAll(flatRessources(childShapes.getJSONObject(i)));\n }\n }\n ;\n\n return result;\n }",
"private void readProjectExtendedAttributes(Project project)\n {\n Project.ExtendedAttributes attributes = project.getExtendedAttributes();\n if (attributes != null)\n {\n for (Project.ExtendedAttributes.ExtendedAttribute ea : attributes.getExtendedAttribute())\n {\n readFieldAlias(ea);\n }\n }\n }",
"protected Object getObjectFromResultSet() throws PersistenceBrokerException\r\n {\r\n\r\n try\r\n {\r\n // if all primitive attributes of the object are contained in the ResultSet\r\n // the fast direct mapping can be used\r\n return super.getObjectFromResultSet();\r\n }\r\n // if the full loading failed we assume that at least PK attributes are contained\r\n // in the ResultSet and perform a slower Identity based loading...\r\n // This may of course also fail and can throw another PersistenceBrokerException\r\n catch (PersistenceBrokerException e)\r\n {\r\n Identity oid = getIdentityFromResultSet();\r\n return getBroker().getObjectByIdentity(oid);\r\n }\r\n\r\n }"
] |
Gets the index to use in the search.
@return the index to use in the search | [
"private I_CmsSearchIndex getIndex() {\n\n I_CmsSearchIndex index = null;\n // get the configured index or the selected index\n if (isInitialCall()) {\n // the search form is in the initial state\n // get the configured index\n index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName());\n } else {\n // the search form is not in the inital state, the submit button was used already or the\n // search index was changed already\n // get the selected index in the search dialog\n index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter(\"indexName.0\"));\n }\n return index;\n }"
] | [
"public static base_responses update(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile updateresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dbdbprofile();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\tupdateresources[i].stickiness = resources[i].stickiness;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void setCurrencyDigits(Integer currDigs)\n {\n if (currDigs == null)\n {\n currDigs = DEFAULT_CURRENCY_DIGITS;\n }\n set(ProjectField.CURRENCY_DIGITS, currDigs);\n }",
"public static String getDateCreatedTimeRangeFilterQuery(String searchField, long startTime, long endTime) {\n\n String sStartTime = null;\n String sEndTime = null;\n\n // Convert startTime to ISO 8601 format\n if ((startTime > Long.MIN_VALUE) && (startTime < Long.MAX_VALUE)) {\n sStartTime = CmsSearchUtil.getDateAsIso8601(new Date(startTime));\n }\n\n // Convert endTime to ISO 8601 format\n if ((endTime > Long.MIN_VALUE) && (endTime < Long.MAX_VALUE)) {\n sEndTime = CmsSearchUtil.getDateAsIso8601(new Date(endTime));\n }\n\n // Build Solr range string\n final String rangeString = CmsSearchUtil.getSolrRangeString(sStartTime, sEndTime);\n\n // Build Solr filter string\n return String.format(\"%s:%s\", searchField, rangeString);\n }",
"public UpdateDescription merge(@Nullable final UpdateDescription otherDescription) {\n if (otherDescription != null) {\n for (final Map.Entry<String, BsonValue> entry : this.updatedFields.entrySet()) {\n if (otherDescription.removedFields.contains(entry.getKey())) {\n this.updatedFields.remove(entry.getKey());\n }\n }\n for (final String removedField : this.removedFields) {\n if (otherDescription.updatedFields.containsKey(removedField)) {\n this.removedFields.remove(removedField);\n }\n }\n\n this.removedFields.addAll(otherDescription.removedFields);\n this.updatedFields.putAll(otherDescription.updatedFields);\n }\n\n return this;\n }",
"private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }",
"private 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}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal);\n }",
"public static Class<?>[] toClassArray(Collection<Class<?>> collection) {\n\t\tif (collection == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn collection.toArray(new Class<?>[collection.size()]);\n\t}",
"private int convertMoneyness(double moneyness) {\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\treturn (int) Math.round(moneyness * 100);\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\treturn - (int) Math.round(moneyness * 10000);\r\n\t\t} else {\r\n\t\t\treturn (int) Math.round(moneyness * 10000);\r\n\t\t}\r\n\t}"
] |
Demonstrates obtaining the request history data from a test run | [
"public static void getHistory() throws Exception{\n Client client = new Client(\"ProfileName\", false);\n\n // Obtain the 100 history entries starting from offset 0\n History[] history = client.refreshHistory(100, 0);\n\n client.clearHistory();\n }"
] | [
"private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }",
"public double Function1D(double x) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }",
"private List<Row> join(List<Row> leftRows, String leftColumn, String rightTable, List<Row> rightRows, String rightColumn)\n {\n List<Row> result = new LinkedList<Row>();\n\n RowComparator leftComparator = new RowComparator(new String[]\n {\n leftColumn\n });\n RowComparator rightComparator = new RowComparator(new String[]\n {\n rightColumn\n });\n Collections.sort(leftRows, leftComparator);\n Collections.sort(rightRows, rightComparator);\n\n ListIterator<Row> rightIterator = rightRows.listIterator();\n Row rightRow = rightIterator.hasNext() ? rightIterator.next() : null;\n\n for (Row leftRow : leftRows)\n {\n Integer leftValue = leftRow.getInteger(leftColumn);\n boolean match = false;\n\n while (rightRow != null)\n {\n Integer rightValue = rightRow.getInteger(rightColumn);\n int comparison = leftValue.compareTo(rightValue);\n if (comparison == 0)\n {\n match = true;\n break;\n }\n\n if (comparison < 0)\n {\n if (rightIterator.hasPrevious())\n {\n rightRow = rightIterator.previous();\n }\n break;\n }\n\n rightRow = rightIterator.next();\n }\n\n if (match && rightRow != null)\n {\n Map<String, Object> newMap = new HashMap<String, Object>(((MapRow) leftRow).getMap());\n\n for (Entry<String, Object> entry : ((MapRow) rightRow).getMap().entrySet())\n {\n String key = entry.getKey();\n if (newMap.containsKey(key))\n {\n key = rightTable + \".\" + key;\n }\n newMap.put(key, entry.getValue());\n }\n\n result.add(new MapRow(newMap));\n }\n }\n\n return result;\n }",
"private String formatTaskType(TaskType value)\n {\n return (LocaleData.getString(m_locale, (value == TaskType.FIXED_DURATION ? LocaleData.YES : LocaleData.NO)));\n }",
"public void setDropShadowColor(int color) {\n GradientDrawable.Orientation orientation = getDropShadowOrientation();\n\n final int endColor = color & 0x00FFFFFF;\n mDropShadowDrawable = new GradientDrawable(orientation,\n new int[] {\n color,\n endColor,\n });\n invalidate();\n }",
"private static String wordShapeDigits(final String s) {\r\n char[] outChars = null;\r\n\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (Character.isDigit(c)) {\r\n if (outChars == null) {\r\n outChars = s.toCharArray();\r\n }\r\n outChars[i] = '9';\r\n }\r\n }\r\n if (outChars == null) {\r\n // no digit found\r\n return s;\r\n } else {\r\n return new String(outChars);\r\n }\r\n }",
"public static base_response unset(nitro_service client, onlinkipv6prefix resource, String[] args) throws Exception{\n\t\tonlinkipv6prefix unsetresource = new onlinkipv6prefix();\n\t\tunsetresource.ipv6prefix = resource.ipv6prefix;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException {\n final ManagementResponseHeader response = ManagementResponseHeader.create(header, error);\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }",
"protected void parseBracketCreateMatrix(TokenList tokens, Sequence sequence) {\n List<TokenList.Token> left = new ArrayList<TokenList.Token>();\n\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.BRACKET_LEFT ) {\n left.add(t);\n } else if( t.getSymbol() == Symbol.BRACKET_RIGHT ) {\n if( left.isEmpty() )\n throw new RuntimeException(\"No matching left bracket for right\");\n\n TokenList.Token start = left.remove(left.size() - 1);\n\n // Compute everything inside the [ ], this will leave a\n // series of variables and semi-colons hopefully\n TokenList bracketLet = tokens.extractSubList(start.next,t.previous);\n parseBlockNoParentheses(bracketLet, sequence, true);\n MatrixConstructor constructor = constructMatrix(bracketLet);\n\n // define the matrix op and inject into token list\n Operation.Info info = Operation.matrixConstructor(constructor);\n sequence.addOperation(info.op);\n\n tokens.insert(start.previous, new TokenList.Token(info.output));\n\n // remove the brackets\n tokens.remove(start);\n tokens.remove(t);\n }\n\n t = next;\n }\n\n if( !left.isEmpty() )\n throw new RuntimeException(\"Dangling [\");\n }"
] |
Converts an MPXJ Duration instance into the string representation
of a Planner duration.
Planner represents durations as a number of seconds in its
file format, however it displays durations as days and hours,
and seems to assume that a working day is 8 hours.
@param value string representation of a duration
@return Duration instance | [
"private String getDurationString(Duration value)\n {\n String result = null;\n\n if (value != null)\n {\n double seconds = 0;\n\n switch (value.getUnits())\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n seconds = value.getDuration() * 60;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n seconds = value.getDuration() * (60 * 60);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n seconds = value.getDuration() * (minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n seconds = value.getDuration() * (24 * 60 * 60);\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = m_projectFile.getProjectProperties().getMinutesPerWeek().doubleValue();\n seconds = value.getDuration() * (minutesPerWeek * 60);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n seconds = value.getDuration() * (7 * 24 * 60 * 60);\n break;\n }\n\n case MONTHS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n seconds = value.getDuration() * (30 * 24 * 60 * 60);\n break;\n }\n\n case YEARS:\n {\n double minutesPerDay = m_projectFile.getProjectProperties().getMinutesPerDay().doubleValue();\n double daysPerMonth = m_projectFile.getProjectProperties().getDaysPerMonth().doubleValue();\n seconds = value.getDuration() * (12 * daysPerMonth * minutesPerDay * 60);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n seconds = value.getDuration() * (365 * 24 * 60 * 60);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n result = Long.toString((long) seconds);\n }\n\n return (result);\n }"
] | [
"public static <T extends WindupVertexFrame> T addTypeToModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().addTypeToElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, type);\n }",
"protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) {\n Object returnObject = invokeJavascript(function);\n if (returnObject instanceof JSObject) {\n try {\n Constructor<T> constructor = returnType.getConstructor(JSObject.class);\n return constructor.newInstance((JSObject) returnObject);\n } catch (Exception ex) {\n throw new IllegalStateException(ex);\n }\n } else {\n return (T) returnObject;\n }\n }",
"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 }",
"@Override\n public void updateStoreDefinition(StoreDefinition storeDef) {\n this.storeDef = storeDef;\n if(storeDef.hasRetentionPeriod())\n this.retentionTimeMs = storeDef.getRetentionDays() * Time.MS_PER_DAY;\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 }",
"protected Boolean getIgnoreReleaseDate() {\n\n Boolean isIgnoreReleaseDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_RELEASE_DATE);\n return (null == isIgnoreReleaseDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreReleaseDate())\n : isIgnoreReleaseDate;\n }",
"public static Boolean askConfirm(Boolean confirm, String opDesc) throws IOException {\n if(confirm) {\n System.out.println(\"Confirmed \" + opDesc + \" in command-line.\");\n return true;\n } else {\n System.out.println(\"Are you sure you want to \" + opDesc + \"? (yes/no)\");\n BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));\n String text = buffer.readLine().toLowerCase(Locale.ENGLISH);\n boolean go = text.equals(\"yes\") || text.equals(\"y\");\n if (!go) {\n System.out.println(\"Did not confirm; \" + opDesc + \" aborted.\");\n }\n return go;\n }\n }",
"public static Key toKey(RowColumn rc) {\n if ((rc == null) || (rc.getRow().equals(Bytes.EMPTY))) {\n return null;\n }\n Text row = ByteUtil.toText(rc.getRow());\n if ((rc.getColumn().equals(Column.EMPTY)) || !rc.getColumn().isFamilySet()) {\n return new Key(row);\n }\n Text cf = ByteUtil.toText(rc.getColumn().getFamily());\n if (!rc.getColumn().isQualifierSet()) {\n return new Key(row, cf);\n }\n Text cq = ByteUtil.toText(rc.getColumn().getQualifier());\n if (!rc.getColumn().isVisibilitySet()) {\n return new Key(row, cf, cq);\n }\n Text cv = ByteUtil.toText(rc.getColumn().getVisibility());\n return new Key(row, cf, cq, cv);\n }",
"public void createLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference<S> serviceReference : linkerManagement.getMatchedBinderServiceRef()) {\n if (linkerManagement.canBeLinked(declaration, serviceReference)) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }"
] |
Creates a map between a work pattern ID and a list of time entry rows.
@param rows time entry rows
@return time entry map | [
"public Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"TIME_ENTRYID\");\n List<Row> list = map.get(workPatternID);\n if (list == null)\n {\n list = new LinkedList<Row>();\n map.put(workPatternID, list);\n }\n list.add(row);\n }\n return map;\n }"
] | [
"public static base_response add(nitro_service client, vlan resource) throws Exception {\n\t\tvlan addresource = new vlan();\n\t\taddresource.id = resource.id;\n\t\taddresource.aliasname = resource.aliasname;\n\t\taddresource.ipv6dynamicrouting = resource.ipv6dynamicrouting;\n\t\treturn addresource.add_resource(client);\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 ComplexNumber Multiply(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real * scalar, z1.imaginary * scalar);\r\n }",
"public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc));\n final ClientResponse response = resource\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = FAILED_TO_GET_CORPORATE_FILTERS;\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<String>>(){});\n\n }",
"public static Module createModule(final String name,final String version){\n final Module module = new Module();\n\n module.setName(name);\n module.setVersion(version);\n module.setPromoted(false);\n\n return module;\n\n }",
"public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }",
"protected LayoutManager getLayOutManagerObj(ActionInvocation _invocation) {\n\t\tif (layoutManager == null || \"\".equals(layoutManager)){\n\t\t\tLOG.warn(\"No valid LayoutManager, using ClassicLayoutManager\");\n\t\t\treturn new ClassicLayoutManager();\n\t\t}\n\n\t\tObject los = conditionalParse(layoutManager, _invocation);\n\n\t\tif (los instanceof LayoutManager){\n\t\t\treturn (LayoutManager) los;\n\t\t}\n\n\t\tLayoutManager lo = null;\n\t\tif (los instanceof String){\n\t\t\tif (LAYOUT_CLASSIC.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ClassicLayoutManager();\n\t\t\telse if (LAYOUT_LIST.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ListLayoutManager();\n\t\t\telse {\n\t\t\t\ttry {\n\t\t\t\t\tlo = (LayoutManager) Class.forName((String) los).newInstance();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.warn(\"No valid LayoutManager: \" + e.getMessage(),e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lo;\n\t}",
"public static boolean check(String passwd, String hashed) {\n try {\n String[] parts = hashed.split(\"\\\\$\");\n\n if (parts.length != 5 || !parts[1].equals(\"s0\")) {\n throw new IllegalArgumentException(\"Invalid hashed value\");\n }\n\n long params = Long.parseLong(parts[2], 16);\n byte[] salt = decode(parts[3].toCharArray());\n byte[] derived0 = decode(parts[4].toCharArray());\n\n int N = (int) Math.pow(2, params >> 16 & 0xffff);\n int r = (int) params >> 8 & 0xff;\n int p = (int) params & 0xff;\n\n byte[] derived1 = SCrypt.scrypt(passwd.getBytes(\"UTF-8\"), salt, N, r, p, 32);\n\n if (derived0.length != derived1.length) return false;\n\n int result = 0;\n for (int i = 0; i < derived0.length; i++) {\n result |= derived0[i] ^ derived1[i];\n }\n return result == 0;\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"JVM doesn't support UTF-8?\");\n } catch (GeneralSecurityException e) {\n throw new IllegalStateException(\"JVM doesn't support SHA1PRNG or HMAC_SHA256?\");\n }\n }",
"static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {\n int patIdxStart = 0;\n int patIdxEnd = tokenizedPattern.length - 1;\n int strIdxStart = 0;\n int strIdxEnd = strDirs.length - 1;\n\n // up to first '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxStart];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {\n return false;\n }\n patIdxStart++;\n strIdxStart++;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n } else {\n if (patIdxStart > patIdxEnd) {\n // String not exhausted, but pattern is. Failure.\n return false;\n }\n }\n\n // up to last '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxEnd];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {\n return false;\n }\n patIdxEnd--;\n strIdxEnd--;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n }\n\n while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {\n int patIdxTmp = -1;\n for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {\n if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n patIdxTmp = i;\n break;\n }\n }\n if (patIdxTmp == patIdxStart + 1) {\n // '**/**' situation, so skip one\n patIdxStart++;\n continue;\n }\n // Find the pattern between padIdxStart & padIdxTmp in str between\n // strIdxStart & strIdxEnd\n int patLength = (patIdxTmp - patIdxStart - 1);\n int strLength = (strIdxEnd - strIdxStart + 1);\n int foundIdx = -1;\n strLoop:\n for (int i = 0; i <= strLength - patLength; i++) {\n for (int j = 0; j < patLength; j++) {\n String subPat = tokenizedPattern[patIdxStart + j + 1];\n String subStr = strDirs[strIdxStart + i + j];\n if (!match(subPat, subStr, isCaseSensitive)) {\n continue strLoop;\n }\n }\n\n foundIdx = strIdxStart + i;\n break;\n }\n\n if (foundIdx == -1) {\n return false;\n }\n\n patIdxStart = patIdxTmp;\n strIdxStart = foundIdx + patLength;\n }\n\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n\n return true;\n }"
] |
Creates a clone using java serialization
@param from Object to be cloned
@param <T> type of the cloned object
@return Clone of the object | [
"@SuppressWarnings(\"unchecked\")\n public static <T extends Serializable> T makeClone(T from) {\n return (T) SerializationUtils.clone(from);\n }"
] | [
"private static void unpackFace(File outputDirectory) throws IOException {\n ClassLoader loader = AllureMain.class.getClassLoader();\n for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) {\n Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName());\n if (matcher.find()) {\n String resourcePath = matcher.group(1);\n File dest = new File(outputDirectory, resourcePath);\n Files.createParentDirs(dest);\n try (FileOutputStream output = new FileOutputStream(dest);\n InputStream input = info.url().openStream()) {\n IOUtils.copy(input, output);\n LOGGER.debug(\"{} successfully copied.\", resourcePath);\n }\n }\n }\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 Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {\n MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();\n\n Object[] values = new Object[parameterInfoArray.length];\n String[] types = new String[parameterInfoArray.length];\n\n MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);\n\n for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {\n MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];\n String type = parameterInfo.getType();\n types[parameterNum] = type;\n values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);\n }\n\n return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);\n }",
"public boolean exists() {\n\t\t// Try file existence: can we find the file in the file system?\n\t\ttry {\n\t\t\treturn getFile().exists();\n\t\t}\n\t\tcatch (IOException ex) {\n\t\t\t// Fall back to stream existence: can we open the stream?\n\t\t\ttry {\n\t\t\t\tInputStream is = getInputStream();\n\t\t\t\tis.close();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcatch (Throwable isEx) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}",
"private void parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }",
"public static String detokenize(List<String> tokens) {\n return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens));\n }",
"public static cachepolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_policybinding_binding obj = new cachepolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_policybinding_binding response[] = (cachepolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static appfwlearningsettings get(nitro_service service, String profilename) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tobj.set_profilename(profilename);\n\t\tappfwlearningsettings response = (appfwlearningsettings) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static RowColumn toRowColumn(Key key) {\n if (key == null) {\n return RowColumn.EMPTY;\n }\n if ((key.getRow() == null) || key.getRow().getLength() == 0) {\n return RowColumn.EMPTY;\n }\n Bytes row = ByteUtil.toBytes(key.getRow());\n if ((key.getColumnFamily() == null) || key.getColumnFamily().getLength() == 0) {\n return new RowColumn(row);\n }\n Bytes cf = ByteUtil.toBytes(key.getColumnFamily());\n if ((key.getColumnQualifier() == null) || key.getColumnQualifier().getLength() == 0) {\n return new RowColumn(row, new Column(cf));\n }\n Bytes cq = ByteUtil.toBytes(key.getColumnQualifier());\n if ((key.getColumnVisibility() == null) || key.getColumnVisibility().getLength() == 0) {\n return new RowColumn(row, new Column(cf, cq));\n }\n Bytes cv = ByteUtil.toBytes(key.getColumnVisibility());\n return new RowColumn(row, new Column(cf, cq, cv));\n }"
] |
Permanently close the ClientRequestExecutor pool. Resources subsequently
checked in will be destroyed. | [
"@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 }"
] | [
"@Override\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }",
"protected EntityKey getEntityKey(Tuple tuple, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {\n\t\tObject[] columnValues = new Object[ associatedEntityKeyMetadata.getAssociationKeyColumns().length];\n\t\tint i = 0;\n\n\t\tfor ( String associationKeyColumn : associatedEntityKeyMetadata.getAssociationKeyColumns() ) {\n\t\t\tcolumnValues[i] = tuple.get( associationKeyColumn );\n\t\t\ti++;\n\t\t}\n\n\t\treturn new EntityKey( associatedEntityKeyMetadata.getEntityKeyMetadata(), columnValues );\n\t}",
"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 GeoPermissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // response:\r\n // <perms id=\"240935723\" ispublic=\"1\" iscontact=\"0\" isfriend=\"0\" isfamily=\"0\"/>\r\n GeoPermissions perms = new GeoPermissions();\r\n Element permsElement = response.getPayload();\r\n perms.setPublic(\"1\".equals(permsElement.getAttribute(\"ispublic\")));\r\n perms.setContact(\"1\".equals(permsElement.getAttribute(\"iscontact\")));\r\n perms.setFriend(\"1\".equals(permsElement.getAttribute(\"isfriend\")));\r\n perms.setFamily(\"1\".equals(permsElement.getAttribute(\"isfamily\")));\r\n perms.setId(permsElement.getAttribute(\"id\"));\r\n // I ignore the id attribute. should be the same as the given\r\n // photo id.\r\n return perms;\r\n }",
"@TargetApi(VERSION_CODES.KITKAT)\n public static void hideSystemUI(Activity activity) {\n // Set the IMMERSIVE flag.\n // Set the content to appear under the system bars so that the content\n // doesn't resize when the system bars hideSelf and show.\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hideSelf nav bar\n | View.SYSTEM_UI_FLAG_FULLSCREEN // hideSelf status bar\n | View.SYSTEM_UI_FLAG_IMMERSIVE\n );\n }",
"public float getNormalZ(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"public static double SymmetricChiSquareDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n double den = p[i] * q[i];\n if (den != 0) {\n double p1 = p[i] - q[i];\n double p2 = p[i] + q[i];\n r += (p1 * p1 * p2) / den;\n }\n }\n\n return r;\n }",
"public static DMatrixRMaj insideSpan(DMatrixRMaj[] span , double min , double max , Random rand ) {\n DMatrixRMaj A = new DMatrixRMaj(span.length,1);\n\n DMatrixRMaj B = new DMatrixRMaj(span[0].getNumElements(),1);\n\n for( int i = 0; i < span.length; i++ ) {\n B.set(span[i]);\n double val = rand.nextDouble()*(max-min)+min;\n CommonOps_DDRM.scale(val,B);\n\n CommonOps_DDRM.add(A,B,A);\n\n }\n\n return A;\n }",
"private boolean checkDeploymentDir(File directory) {\n if (!directory.exists()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNonexistent(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.isDirectory()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.isNotADirectory(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canRead()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotReadable(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canWrite()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotWritable(deploymentDir.getAbsolutePath());\n }\n } else {\n deploymentDirAccessible = true;\n }\n\n return deploymentDirAccessible;\n }"
] |
Deletes the concrete representation of the specified object in the underlying
persistence system. This method is intended for use in top-level api or
by internal calls.
@param obj The object to delete.
@param ignoreReferences With this flag the automatic deletion/unlinking
of references can be suppressed (independent of the used auto-delete setting in metadata),
except {@link org.apache.ojb.broker.metadata.SuperReferenceDescriptor}
these kind of reference (descriptor) will always be performed. If <em>true</em>
all "normal" referenced objects will be ignored, only the specified object is handled.
@throws PersistenceBrokerException | [
"public void delete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n if(isTxCheck() && !isInTransaction())\n {\n if(logger.isEnabledFor(Logger.ERROR))\n {\n String msg = \"No running PB-tx found. Please, only delete objects in context of a PB-transaction\" +\n \" to avoid side-effects - e.g. when rollback of complex objects.\";\n try\n {\n throw new Exception(\"** Delete object without active PersistenceBroker transaction **\");\n }\n catch(Exception e)\n {\n logger.error(msg, e);\n }\n }\n }\n try\n {\n doDelete(obj, ignoreReferences);\n }\n finally\n {\n markedForDelete.clear();\n }\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 static void checkStringNotNullOrEmpty(String parameterName,\n String value) {\n if (TextUtils.isEmpty(value)) {\n throw Exceptions.IllegalArgument(\"Current input string %s is %s.\",\n parameterName, value == null ? \"null\" : \"empty\");\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public HttpMethodInfo handle(HttpRequest request,\n HttpResponder responder, Map<String, String> groupValues) throws Exception {\n //TODO: Refactor group values.\n try {\n if (httpMethods.contains(request.method())) {\n //Setup args for reflection call\n Object [] args = new Object[paramsInfo.size()];\n\n int idx = 0;\n for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {\n if (info.containsKey(PathParam.class)) {\n args[idx] = getPathParamValue(info, groupValues);\n }\n if (info.containsKey(QueryParam.class)) {\n args[idx] = getQueryParamValue(info, request.uri());\n }\n if (info.containsKey(HeaderParam.class)) {\n args[idx] = getHeaderParamValue(info, request);\n }\n idx++;\n }\n\n return new HttpMethodInfo(method, handler, responder, args, exceptionHandler);\n } else {\n //Found a matching resource but could not find the right HttpMethod so return 405\n throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format\n (\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n }\n } catch (Throwable e) {\n throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Error in executing request: %s %s\", request.method(),\n request.uri()), e);\n }\n }",
"public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }",
"public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {\n List<T> foundServices = new ArrayList<>();\n Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();\n\n while (checkHasNextSafely(iterator)) {\n try {\n T item = iterator.next();\n foundServices.add(item);\n LOGGER.debug(String.format(\"Found %s [%s]\", serviceType.getSimpleName(), item.toString()));\n } catch (ServiceConfigurationError e) {\n LOGGER.trace(\"Can't find services using Java SPI\", e);\n LOGGER.error(e.getMessage());\n }\n }\n return foundServices;\n }",
"public Iterable<BoxGroupMembership.Info> getAllMemberships(String ... fields) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = USER_MEMBERSHIPS_URL_TEMPLATE.buildWithQuery(\n BoxUser.this.getAPI().getBaseURL(), builder.toString(), BoxUser.this.getID());\n return new BoxGroupMembershipIterator(BoxUser.this.getAPI(), url);\n }\n };\n }",
"private void processRemarks(GanttDesignerRemark remark)\n {\n for (GanttDesignerRemark.Task remarkTask : remark.getTask())\n {\n Integer id = remarkTask.getRow();\n Task task = m_projectFile.getTaskByID(id);\n String notes = task.getNotes();\n if (notes.isEmpty())\n {\n notes = remarkTask.getContent();\n }\n else\n {\n notes = notes + '\\n' + remarkTask.getContent();\n }\n task.setNotes(notes);\n }\n }",
"public static void addToMediaStore(Context context, File file) {\n String[] path = new String[]{file.getPath()};\n MediaScannerConnection.scanFile(context, path, null, null);\n }",
"@Override\n public View getView(int position, View convertView,\n ViewGroup parent) {\n return (wrapped.getView(position, convertView, parent));\n }"
] |
Returns the first 24 photos for a given tag cluster.
<p>
This method does not require authentication.
</p>
@param tag
@param clusterId
@return PhotoList
@throws FlickrException | [
"public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\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 photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }"
] | [
"@CheckReturnValue\n private LocalSyncWriteModelContainer resolveConflict(\n final NamespaceSynchronizationConfig nsConfig,\n final CoreDocumentSynchronizationConfig docConfig,\n final ChangeEvent<BsonDocument> remoteEvent\n ) {\n return resolveConflict(nsConfig, docConfig, docConfig.getLastUncommittedChangeEvent(),\n remoteEvent);\n }",
"public void setCapture(boolean capture, float fps) {\n capturing = capture;\n NativeTextureCapturer.setCapture(getNative(), capture, fps);\n }",
"private List<String> parseParams(String param) {\n\t\tAssert.hasText(param, \"param must not be empty nor null\");\n\t\tList<String> paramsToUse = new ArrayList<>();\n\t\tMatcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);\n\t\tint start = 0;\n\t\twhile (regexMatcher.find()) {\n\t\t\tString p = removeQuoting(param.substring(start, regexMatcher.start()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t\tstart = regexMatcher.start();\n\t\t}\n\t\tif (param != null && param.length() > 0) {\n\t\t\tString p = removeQuoting(param.substring(start, param.length()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t}\n\t\treturn paramsToUse;\n\t}",
"public void ifMemberTagValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n if (isTagValueEqual(attributes, FOR_FIELD)) {\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (isTagValueEqual(attributes, FOR_METHOD)) {\r\n generate(template);\r\n }\r\n }\r\n }",
"public static String format(String format) {\n\n if (format == null) {\n format = DEFAULT_FORMAT;\n } else {\n if (format.contains(\"M\")) {\n format = format.replace(\"M\", \"m\");\n }\n\n if (format.contains(\"Y\")) {\n format = format.replace(\"Y\", \"y\");\n }\n\n if (format.contains(\"D\")) {\n format = format.replace(\"D\", \"d\");\n }\n }\n return format;\n }",
"private String formatDateTimeNull(Date value)\n {\n return (value == null ? m_formats.getNullText() : m_formats.getDateTimeFormat().format(value));\n }",
"public static base_response delete(nitro_service client, String Dnssuffix) throws Exception {\n\t\tdnssuffix deleteresource = new dnssuffix();\n\t\tdeleteresource.Dnssuffix = Dnssuffix;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"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 }",
"private int determineForkedJvmCount(TestsCollection testCollection) {\n int cores = Runtime.getRuntime().availableProcessors();\n int jvmCount;\n if (this.parallelism.equals(PARALLELISM_AUTO)) {\n if (cores >= 8) {\n // Maximum parallel jvms is 4, conserve some memory and memory bandwidth.\n jvmCount = 4;\n } else if (cores >= 4) {\n // Make some space for the aggregator.\n jvmCount = 3;\n } else if (cores == 3) {\n // Yes, three-core chips are a thing.\n jvmCount = 2;\n } else {\n // even for dual cores it usually makes no sense to fork more than one\n // JVM.\n jvmCount = 1;\n }\n } else if (this.parallelism.equals(PARALLELISM_MAX)) {\n jvmCount = Runtime.getRuntime().availableProcessors();\n } else {\n try {\n jvmCount = Math.max(1, Integer.parseInt(parallelism));\n } catch (NumberFormatException e) {\n throw new BuildException(\"parallelism must be 'auto', 'max' or a valid integer: \"\n + parallelism);\n }\n }\n\n if (!testCollection.hasReplicatedSuites()) {\n jvmCount = Math.min(testCollection.testClasses.size(), jvmCount);\n }\n return jvmCount;\n }"
] |
Request the list of all tracks in the specified slot, given a dbserver connection to a player that has already
been set up.
@param slot identifies the media slot we are querying
@param client the dbserver client that is communicating with the appropriate player
@return the retrieved track list entry items
@throws IOException if there is a communication problem
@throws InterruptedException if the thread is interrupted while trying to lock the client for menu operations
@throws TimeoutException if we are unable to lock the client for menu operations | [
"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 }"
] | [
"@UiHandler(\"m_endTime\")\n void onEndTimeChange(CmsDateBoxEvent event) {\n\n if (handleChange() && !event.isUserTyping()) {\n m_controller.setEndTime(event.getDate());\n }\n }",
"public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) {\n dbbCC.setAccessible(true);\n Object b = null;\n try {\n b = dbbCC.newInstance(new Long(addr), new Integer(size), att);\n return ByteBuffer.class.cast(b);\n }\n catch(Exception e) {\n throw new IllegalStateException(String.format(\"Failed to create DirectByteBuffer: %s\", e.getMessage()));\n }\n }",
"public static base_responses add(nitro_service client, cacheselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheselector addresources[] = new cacheselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cacheselector();\n\t\t\t\taddresources[i].selectorname = resources[i].selectorname;\n\t\t\t\taddresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\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}",
"public HashMap<String, IndexInput> getIndexInputList() {\n HashMap<String, IndexInput> clonedIndexInputList = new HashMap<String, IndexInput>();\n for (Entry<String, IndexInput> entry : indexInputList.entrySet()) {\n clonedIndexInputList.put(entry.getKey(), entry.getValue().clone());\n }\n return clonedIndexInputList;\n }",
"private void query(String zipcode) {\n /* Setup YQL query statement using dynamic zipcode. The statement searches geo.places\n for the zipcode and returns XML which includes the WOEID. For more info about YQL go\n to: http://developer.yahoo.com/yql/ */\n String qry = URLEncoder.encode(\"SELECT woeid FROM geo.places WHERE text=\" + zipcode + \" LIMIT 1\");\n\n // Generate request URI using the query statement\n URL url;\n try {\n // get URL content\n url = new URL(\"http://query.yahooapis.com/v1/public/yql?q=\" + qry);\n URLConnection conn = url.openConnection();\n\n InputStream content = conn.getInputStream();\n parseResponse(content);\n\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }",
"public static double[][] diag(double[] vector){\n\n\t\t// Note: According to the Java Language spec, an array is initialized with the default value, here 0.\n\t\tdouble[][] diagonalMatrix = new double[vector.length][vector.length];\n\n\t\tfor(int index = 0; index < vector.length; index++) {\n\t\t\tdiagonalMatrix[index][index] = vector[index];\n\t\t}\n\n\t\treturn diagonalMatrix;\n\t}",
"public static final String printWorkGroup(WorkGroup value)\n {\n return (Integer.toString(value == null ? WorkGroup.DEFAULT.getValue() : value.getValue()));\n }",
"@Override\n public void init(NamedList args) {\n\n Object regex = args.remove(PARAM_REGEX);\n if (null == regex) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REGEX);\n }\n try {\n m_regex = Pattern.compile(regex.toString());\n } catch (PatternSyntaxException e) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Invalid regex: \" + regex, e);\n }\n\n Object replacement = args.remove(PARAM_REPLACEMENT);\n if (null == replacement) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REPLACEMENT);\n }\n m_replacement = replacement.toString();\n\n Object source = args.remove(PARAM_SOURCE);\n if (null == source) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_SOURCE);\n }\n m_source = source.toString();\n\n Object target = args.remove(PARAM_TARGET);\n if (null == target) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_TARGET);\n }\n m_target = target.toString();\n\n }"
] |
Logs an error message for unhandled exception thrown from the target method.
@param joinPoint - the joint point cut that contains information about the target
@param throwable - the cause of the exception from the target method invocation | [
"@AfterThrowing(pointcut = \"execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))\", throwing = \"throwable\")\n public void logErrorFromThrownException(final JoinPoint joinPoint, final Throwable throwable) {\n final String className = joinPoint.getTarget().getClass().getName();\n final String methodName = joinPoint.getSignature().getName();\n\n logger.error(\"Could not write to cassandra! Method: \" + className + \".\"+ methodName + \"()\", throwable);\n }"
] | [
"private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null && baseCal.getName() != null)\n {\n cal.setParent(baseCal);\n }\n else\n {\n // Remove invalid calendar to avoid serious problems later.\n m_file.removeCalendar(cal);\n }\n }\n }",
"public String login(Authentication authentication) {\n\t\tString token = getToken();\n\t\treturn login(token, authentication);\n\t}",
"public boolean needToSetCategoryFolder() {\n\n if (m_adeModuleVersion == null) {\n return true;\n }\n CmsModuleVersion categoryFolderUpdateVersion = new CmsModuleVersion(\"9.0.0\");\n return (m_adeModuleVersion.compareTo(categoryFolderUpdateVersion) == -1);\n }",
"private JSONArray readOptionalArray(JSONObject json, String key) {\n\n try {\n return json.getJSONArray(key);\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON array failed. Default to provided default value.\", e);\n }\n return null;\n }",
"synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }",
"private void updateArt(TrackMetadataUpdate update, AlbumArt art) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), art); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), art);\n }\n }\n }\n deliverAlbumArtUpdate(update.player, art);\n }",
"public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {\n if (searchView != null) {\n searchView.setOnCloseListener(new SearchView.OnCloseListener() {\n @Override public boolean onClose() {\n return listener.onClose();\n }\n });\n } else if (supportView != null) {\n supportView.setOnCloseListener(listener);\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }",
"public synchronized Message menuRequestTyped(Message.KnownType requestType, Message.MenuIdentifier targetMenu,\n CdjStatus.TrackSourceSlot slot, CdjStatus.TrackType trackType, Field... arguments)\n throws IOException {\n\n if (!menuLock.isHeldByCurrentThread()) {\n throw new IllegalStateException(\"renderMenuItems() cannot be called without first successfully calling tryLockingForMenuOperation()\");\n }\n\n Field[] combinedArguments = new Field[arguments.length + 1];\n combinedArguments[0] = buildRMST(targetMenu, slot, trackType);\n System.arraycopy(arguments, 0, combinedArguments, 1, arguments.length);\n final Message response = simpleRequest(requestType, Message.KnownType.MENU_AVAILABLE, combinedArguments);\n final NumberField reportedRequestType = (NumberField)response.arguments.get(0);\n if (reportedRequestType.getValue() != requestType.protocolValue) {\n throw new IOException(\"Menu request did not return result for same type as request; sent type: \" +\n requestType.protocolValue + \", received type: \" + reportedRequestType.getValue() +\n \", response: \" + response);\n }\n return response;\n }",
"private void sort()\n {\n DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph = new DefaultDirectedWeightedGraph<>(\n DefaultEdge.class);\n\n for (RuleProvider provider : providers)\n {\n graph.addVertex(provider);\n }\n\n addProviderRelationships(graph);\n\n checkForCycles(graph);\n\n List<RuleProvider> result = new ArrayList<>(this.providers.size());\n TopologicalOrderIterator<RuleProvider, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph);\n while (iterator.hasNext())\n {\n RuleProvider provider = iterator.next();\n result.add(provider);\n }\n\n this.providers = Collections.unmodifiableList(result);\n\n int index = 0;\n for (RuleProvider provider : this.providers)\n {\n if (provider instanceof AbstractRuleProvider)\n ((AbstractRuleProvider) provider).setExecutionIndex(index++);\n }\n }"
] |
Triggers the building process, builds, creates and starts the docker container associated with the requested
container object, creates the container object and returns it
@return the created container object
@throws IllegalAccessException
if there is an error accessing the container object fields
@throws IOException
if there is an I/O error while preparing the docker build
@throws InvocationTargetException
if there is an error while calling the DockerFile archive creation | [
"public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }"
] | [
"public void loadClassifier(File file, Properties props) throws ClassCastException, IOException,\r\n ClassNotFoundException {\r\n Timing.startDoing(\"Loading classifier from \" + file.getAbsolutePath());\r\n BufferedInputStream bis;\r\n if (file.getName().endsWith(\".gz\")) {\r\n bis = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)));\r\n } else {\r\n bis = new BufferedInputStream(new FileInputStream(file));\r\n }\r\n loadClassifier(bis, props);\r\n bis.close();\r\n Timing.endDoing();\r\n }",
"private void registerProxyCreator(Node source,\n BeanDefinitionHolder holder,\n ParserContext context) {\n\n String beanName = holder.getBeanName();\n String proxyName = beanName + \"Proxy\";\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class);\n\n initializer.addPropertyValue(\"beanNames\", beanName);\n initializer.addPropertyValue(\"interceptorNames\", interceptorName);\n\n BeanDefinitionRegistry registry = context.getRegistry();\n registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition());\n }",
"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}",
"protected boolean hasContentType() {\n\n boolean result = false;\n if(this.request.getHeader(RestMessageHeaders.CONTENT_TYPE) != null) {\n result = true;\n } else {\n logger.error(\"Error when validating put request. Missing Content-Type header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Type header\");\n }\n return result;\n }",
"private void ensurePrecisionAndScale(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, null);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, null);\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION))\r\n {\r\n String defaultPrecision = JdbcTypeHelper.getDefaultPrecisionFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultPrecision != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no precision setting though its jdbc type requires it (in most databases); using default precision of \"+defaultPrecision);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, defaultPrecision);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, \"1\");\r\n }\r\n }\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n String defaultScale = JdbcTypeHelper.getDefaultScaleFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultScale != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no scale setting though its jdbc type requires it (in most databases); using default scale of \"+defaultScale);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, defaultScale);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION) || fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, \"0\");\r\n }\r\n }\r\n }",
"public void setDateMin(Date dateMin) {\n this.dateMin = dateMin;\n\n if (isAttached() && dateMin != null) {\n getPicker().set(\"min\", JsDate.create((double) dateMin.getTime()));\n }\n }",
"public void add(ResourceCollection rc) {\n if (rc instanceof FileSet) {\n FileSet fs = (FileSet) rc;\n fs.setProject(getProject());\n }\n resources.add(rc);\n }",
"public PlanarImage toDirectColorModel(RenderedImage img) {\n\t\tBufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);\n\t\tBufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img\n\t\t\t\t.getColorModel().isAlphaPremultiplied(), null);\n\t\tColorConvertOp op = new ColorConvertOp(null);\n\t\top.filter(source, dest);\n\t\treturn PlanarImage.wrapRenderedImage(dest);\n\t}",
"public void check(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureElementClassRef(collDef, checkLevel);\r\n checkInheritedForeignkey(collDef, checkLevel);\r\n ensureCollectionClass(collDef, checkLevel);\r\n checkProxyPrefetchingLimit(collDef, checkLevel);\r\n checkOrderby(collDef, checkLevel);\r\n checkQueryCustomizer(collDef, checkLevel);\r\n }"
] |
Parses the result and returns the failure description. If the result was successful, an empty string is
returned.
@param result the result of executing an operation
@return the failure message or an empty string | [
"public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }"
] | [
"public Collection<Contact> getList() throws FlickrException {\r\n \t ContactList<Contact> contacts = new ContactList<Contact>();\r\n \r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n contacts.setPage(contactsElement.getAttribute(\"page\"));\r\n contacts.setPages(contactsElement.getAttribute(\"pages\"));\r\n contacts.setPerPage(contactsElement.getAttribute(\"perpage\"));\r\n contacts.setTotal(contactsElement.getAttribute(\"total\"));\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n String lPathAlias = contactElement.getAttribute(\"path_alias\");\r\n contact.setPathAlias(lPathAlias == null || \"\".equals(lPathAlias) ? null : lPathAlias);\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }",
"public EventBus emitSync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }",
"public FailureDetectorConfig setCluster(Cluster cluster) {\n Utils.notNull(cluster);\n this.cluster = cluster;\n /*\n * FIXME: this is the hacky way to refresh the admin connection\n * verifier, but it'll just work. The clean way to do so is to have a\n * centralized metadata management, and all references of cluster object\n * point to that.\n */\n if(this.connectionVerifier instanceof AdminConnectionVerifier) {\n ((AdminConnectionVerifier) connectionVerifier).setCluster(cluster);\n }\n return this;\n }",
"public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }",
"private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }",
"private void readTask(String projectIdentifier, Map<String, Task> map, Document.Projects.Project.Task task)\n {\n Task parentTask = map.get(getParentOutlineNumber(task.getOutlineNumber()));\n Task mpxjTask = parentTask.addTask();\n\n TimeUnit units = task.getBaseDurationTimeUnit();\n\n mpxjTask.setCost(task.getActualCost());\n mpxjTask.setDuration(getDuration(units, task.getActualDuration()));\n mpxjTask.setFinish(task.getActualFinishDate());\n mpxjTask.setStart(task.getActualStartDate());\n mpxjTask.setBaselineDuration(getDuration(units, task.getBaseDuration()));\n mpxjTask.setBaselineFinish(task.getBaseFinishDate());\n mpxjTask.setBaselineCost(task.getBaselineCost());\n // task.getBaselineFinishDate()\n // task.getBaselineFinishTemplateOffset()\n // task.getBaselineStartDate()\n // task.getBaselineStartTemplateOffset()\n mpxjTask.setBaselineStart(task.getBaseStartDate());\n // task.getCallouts()\n mpxjTask.setPercentageComplete(task.getComplete());\n mpxjTask.setDeadline(task.getDeadlineDate());\n // task.getDeadlineTemplateOffset()\n // task.getHyperlinks()\n // task.getMarkerID()\n mpxjTask.setName(task.getName());\n mpxjTask.setNotes(task.getNote());\n mpxjTask.setPriority(task.getPriority());\n // task.getRecalcBase1()\n // task.getRecalcBase2()\n mpxjTask.setType(task.getSchedulingType());\n // task.getStyleProject()\n // task.getTemplateOffset()\n // task.getValidatedByProject()\n\n if (task.isIsMilestone())\n {\n mpxjTask.setMilestone(true);\n mpxjTask.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n mpxjTask.setBaselineDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }\n\n String taskIdentifier = projectIdentifier + \".\" + task.getID();\n m_taskIdMap.put(task.getID(), mpxjTask);\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(taskIdentifier.getBytes()));\n\n map.put(task.getOutlineNumber(), mpxjTask);\n\n for (Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment : task.getResourceAssignments().getResourceAssignment())\n {\n readResourceAssignment(mpxjTask, assignment);\n }\n }",
"synchronized void started() {\n try {\n if(isConnected()) {\n channelHandler.executeRequest(new ServerStartedRequest(), null).getResult().await();\n }\n } catch (Exception e) {\n ServerLogger.AS_ROOT_LOGGER.debugf(e, \"failed to send started notification\");\n }\n }",
"protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }",
"public void removeAllAnimations() {\n for (int i = 0, size = mAnimationList.size(); i < size; i++) {\n mAnimationList.get(i).removeAnimationListener(mAnimationListener);\n }\n mAnimationList.clear();\n }"
] |
This implementation does not support the 'offset' and 'maxResultSize' parameters. | [
"public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException {\n\t\tif (null == filter) {\n\t\t\tfilter = Filter.INCLUDE;\n\t\t}\n\t\tList<Object> filteredList = new ArrayList<Object>();\n\t\ttry {\n\t\t\tsynchronized (featuresById) {\n\t\t\t\tfor (Object feature : featuresById.values()) {\n\t\t\t\t\tif (filter.evaluate(feature)) {\n\t\t\t\t\t\tfilteredList.add(feature);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new LayerException(e, ExceptionCode.FILTER_EVALUATION_PROBLEM, filter, getId());\n\t\t}\n\t\t// Sorting of elements.\n\t\tif (comparator != null) {\n\t\t\tCollections.sort(filteredList, comparator);\n\t\t}\n\t\tif (maxResultSize > 0) {\n\t\t\tint fromIndex = Math.max(0, offset);\n\t\t\tint toIndex = Math.min(offset + maxResultSize, filteredList.size());\n\t\t\ttoIndex = Math.max(fromIndex, toIndex);\n\t\t\treturn filteredList.subList(fromIndex, toIndex).iterator();\n\t\t} else {\n\t\t\treturn filteredList.iterator();\n\t\t}\n\t}"
] | [
"public static base_response unset(nitro_service client, cmpparameter resource, String[] args) throws Exception{\n\t\tcmpparameter unsetresource = new cmpparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static Properties loadProps(String filename) {\n Properties props = new Properties();\n FileInputStream fis = null;\n try {\n fis = new FileInputStream(filename);\n props.load(fis);\n return props;\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n } finally {\n Closer.closeQuietly(fis);\n }\n\n }",
"public void addDependencyGraph(DAGraph<DataT, NodeT> dependencyGraph) {\n this.rootNode.addDependency(dependencyGraph.rootNode.key());\n Map<String, NodeT> sourceNodeTable = dependencyGraph.nodeTable;\n Map<String, NodeT> targetNodeTable = this.nodeTable;\n this.merge(sourceNodeTable, targetNodeTable);\n dependencyGraph.parentDAGs.add(this);\n if (this.hasParents()) {\n this.bubbleUpNodeTable(this, new LinkedList<String>());\n }\n }",
"static void produceInputStreamWithEntry( final DataConsumer consumer,\n final InputStream inputStream,\n final TarArchiveEntry entry ) throws IOException {\n try {\n consumer.onEachFile(inputStream, entry);\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n }",
"public int executeUpdateSQL(\r\n String sqlStatement,\r\n ClassDescriptor cld,\r\n ValueContainer[] values1,\r\n ValueContainer[] values2)\r\n throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeUpdateSQL: \" + sqlStatement);\r\n\r\n int result;\r\n int index;\r\n PreparedStatement stmt = null;\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n try\r\n {\r\n stmt = sm.getPreparedStatement(cld, sqlStatement,\r\n Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));\r\n index = sm.bindValues(stmt, values1, 1);\r\n sm.bindValues(stmt, values2, index);\r\n result = stmt.executeUpdate();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the Update SQL query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n ValueContainer[] tmp = addValues(values1, values2);\r\n throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n return result;\r\n }",
"public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,\n\t\t\tint resultFlags, ObjectCache objectCache) throws SQLException {\n\t\tprepareQueryForAll();\n\t\treturn buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags);\n\t}",
"public static base_response clear(nitro_service client, route6 resource) throws Exception {\n\t\troute6 clearresource = new route6();\n\t\tclearresource.routetype = resource.routetype;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}",
"public static void addToString(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n boolean forPartial) {\n String typename = (forPartial ? \"partial \" : \"\") + datatype.getType().getSimpleName();\n Predicate<PropertyCodeGenerator> isOptional = generator -> {\n Initially initially = generator.initialState();\n return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial));\n };\n boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional);\n boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional)\n && !generatorsByProperty.isEmpty();\n\n code.addLine(\"\")\n .addLine(\"@%s\", Override.class)\n .addLine(\"public %s toString() {\", String.class);\n if (allOptional) {\n bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename);\n } else if (anyOptional) {\n bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional);\n } else {\n bodyWithConcatenation(code, generatorsByProperty, typename);\n }\n code.addLine(\"}\");\n }"
] |
Sets hour, minutes, seconds and milliseconds to the given values. Leaves date info untouched. | [
"public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }"
] | [
"private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom)\n {\n if (projectModel.getProjectType() == null)\n return true;\n switch (projectModel.getProjectType()){\n case \"ear\":\n break;\n case \"war\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31));\n break;\n case \"ejb\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN));\n break;\n case \"ejb-client\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT));\n break;\n }\n return false;\n }",
"public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}",
"public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {\n\t\tdocument.writeElement(\"vml:shape\", asChild);\n\t\tPoint p = (Point) o;\n\t\tString adj = document.getFormatter().format(p.getX()) + \",\"\n\t\t\t\t+ document.getFormatter().format(p.getY());\n\t\tdocument.writeAttribute(\"adj\", adj);\n\t}",
"public void setBackgroundColor(float r, float g, float b, float a) {\n setBackgroundColorR(r);\n setBackgroundColorG(g);\n setBackgroundColorB(b);\n setBackgroundColorA(a);\n }",
"public static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"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}",
"static ParsedHost validateHostImpl(HostName fromHost) throws HostNameException {\n\t\tfinal String str = fromHost.toString();\n\t\tHostNameParameters validationOptions = fromHost.getValidationOptions();\n\t\treturn validateHost(fromHost, str, validationOptions);\n\t}",
"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 }",
"private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {\n ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);\n ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);\n\n list.add(ldapAuthorization);\n\n Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n required.remove(attribute);\n switch (attribute) {\n case CONNECTION: {\n LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);\n break;\n }\n default: {\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n }\n\n if (required.isEmpty() == false) {\n throw missingRequired(reader, required);\n }\n\n Set<Element> foundElements = new HashSet<Element>();\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n if (foundElements.add(element) == false) {\n throw unexpectedElement(reader); // Only one of each allowed.\n }\n switch (element) {\n case USERNAME_TO_DN: {\n switch (namespace.getMajorVersion()) {\n case 1: // 1.5 up to but not including 2.0\n parseUsernameToDn_1_5(reader, addr, list);\n break;\n default: // 2.0 and onwards\n parseUsernameToDn_2_0(reader, addr, list);\n break;\n }\n\n break;\n }\n case GROUP_SEARCH: {\n switch (namespace) {\n case DOMAIN_1_5:\n case DOMAIN_1_6:\n parseGroupSearch_1_5(reader, addr, list);\n break;\n default:\n parseGroupSearch_1_7_and_2_0(reader, addr, list);\n break;\n }\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }"
] |
Returns screen height and width
@param context
Any non-null Android Context
@param p
Optional Point to reuse. If null, a new Point will be created.
@return .x is screen width; .y is screen height. | [
"private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }"
] | [
"public boolean checkRead(TransactionImpl tx, Object obj)\r\n {\r\n if (hasReadLock(tx, obj))\r\n {\r\n return true;\r\n }\r\n LockEntry writer = getWriter(obj);\r\n if (writer.isOwnedBy(tx))\r\n {\r\n return true;\r\n }\r\n return false;\r\n }",
"protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException {\n\t\t// initialize the connections auto-commit flags\n\t\tconn1.setAutoCommit(true);\n\t\tconn2.setAutoCommit(true);\n\t\ttry {\n\t\t\t// change conn1's auto-commit to be false\n\t\t\tconn1.setAutoCommit(false);\n\t\t\tif (conn2.isAutoCommit()) {\n\t\t\t\t// if the 2nd connection's auto-commit is still true then we have multiple connections\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// if the 2nd connection's auto-commit is also false then we have a single connection\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// restore its auto-commit\n\t\t\tconn1.setAutoCommit(true);\n\t\t}\n\t}",
"public void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }",
"private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }",
"private Map<String, Integer> runSampling(\n final ProctorContext proctorContext,\n final Set<String> targetTestNames,\n final TestType testType,\n final int determinationsToRun\n ) {\n final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);\n final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();\n for (final String testGroup : targetTestGroups) {\n testGroupToOccurrences.put(testGroup, 0);\n }\n\n for (int i = 0; i < determinationsToRun; ++i) {\n final Identifiers identifiers = TestType.RANDOM.equals(testType)\n ? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)\n : Identifiers.of(testType, Long.toString(random.nextLong()));\n final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);\n for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {\n final String testName = e.getKey();\n if (targetTestNames.contains(testName)) {\n final int group = e.getValue().getValue();\n final String testGroup = testName + group;\n testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);\n }\n }\n }\n\n return testGroupToOccurrences;\n }",
"public void addChildTask(Task child)\n {\n child.m_parent = this;\n m_children.add(child);\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }",
"static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }",
"public static base_response add(nitro_service client, dnssuffix resource) throws Exception {\n\t\tdnssuffix addresource = new dnssuffix();\n\t\taddresource.Dnssuffix = resource.Dnssuffix;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = m_calendarMap.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n }"
] |
needs to be resolved once extension beans are deployed | [
"private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) {\n ClassFileServices classFileServices = services.get(ClassFileServices.class);\n if (classFileServices != null) {\n final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class);\n try {\n final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods());\n services.add(FastProcessAnnotatedTypeResolver.class, resolver);\n } catch (UnsupportedObserverMethodException e) {\n BootstrapLogger.LOG.notUsingFastResolver(e.getObserver());\n return;\n }\n }\n }"
] | [
"private static JsonParser newJsonParserForNode(JsonNode jsonNode) throws IOException {\n JsonParser parser = new JsonFactory().createParser(jsonNode.toString());\n parser.nextToken();\n return parser;\n }",
"public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addFacet(String... attributes) {\n for (String attribute : attributes) {\n final Integer value = facetRequestCount.get(attribute);\n facetRequestCount.put(attribute, value == null ? 1 : value + 1);\n if (value == null || value == 0) {\n facets.add(attribute);\n }\n }\n rebuildQueryFacets();\n return this;\n }",
"private ProjectFile handleZipFile(InputStream stream) throws Exception\n {\n File dir = null;\n\n try\n {\n dir = InputStreamHelper.writeZipStreamToTempDir(stream);\n ProjectFile result = handleDirectory(dir);\n if (result != null)\n {\n return result;\n }\n }\n\n finally\n {\n FileHelper.deleteQuietly(dir);\n }\n\n return null;\n }",
"public void setRoles(List<NamedRoleInfo> roles) {\n\t\tthis.roles = roles;\n\t\tList<AuthorizationInfo> authorizations = new ArrayList<AuthorizationInfo>();\n\t\tfor (NamedRoleInfo role : roles) {\n\t\t\tauthorizations.addAll(role.getAuthorizations());\n\t\t}\n\t\tsuper.setAuthorizations(authorizations);\n\t}",
"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 Collection<BoxFileVersion> getVersions() {\n URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n JsonArray entries = jsonObject.get(\"entries\").asArray();\n Collection<BoxFileVersion> versions = new ArrayList<BoxFileVersion>();\n for (JsonValue entry : entries) {\n versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID()));\n }\n\n return versions;\n }",
"public final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }",
"public static List<Object> listOfEntities(SharedSessionContractImplementor session, Type[] resultTypes, ClosableIterator<Tuple> tuples) {\n\t\tClass<?> returnedClass = resultTypes[0].getReturnedClass();\n\t\tTupleBasedEntityLoader loader = getLoader( session, returnedClass );\n\t\tOgmLoadingContext ogmLoadingContext = new OgmLoadingContext();\n\t\togmLoadingContext.setTuples( getTuplesAsList( tuples ) );\n\t\treturn loader.loadEntitiesFromTuples( session, LockOptions.NONE, ogmLoadingContext );\n\t}"
] |
Add precedence -10 because we need that ContainerRegistry is available in the Arquillian scope. | [
"public void configure(@Observes(precedence = -10) ArquillianDescriptor arquillianDescriptor) {\n Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties();\n CubeConfiguration cubeConfiguration = CubeConfiguration.fromMap(config);\n configurationProducer.set(cubeConfiguration);\n }"
] | [
"public UUID getUUID(FastTrackField type)\n {\n String value = getString(type);\n UUID result = null;\n if (value != null && !value.isEmpty() && value.length() >= 36)\n {\n if (value.startsWith(\"{\"))\n {\n value = value.substring(1, value.length() - 1);\n }\n if (value.length() > 16)\n {\n value = value.substring(0, 36);\n }\n result = UUID.fromString(value);\n }\n return result;\n }",
"private Video generateRandomVideo() {\n Video video = new Video();\n configureFavoriteStatus(video);\n configureLikeStatus(video);\n configureLiveStatus(video);\n configureTitleAndThumbnail(video);\n return video;\n }",
"public void addEmailStats(final InternetAddress[] recipients, final boolean storageUsed) {\n this.storageUsed = storageUsed;\n for (InternetAddress recipient: recipients) {\n emailDests.add(recipient.getAddress());\n }\n }",
"public static lbvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_auditnslogpolicy_binding obj = new lbvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_auditnslogpolicy_binding response[] = (lbvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static final Bytes of(byte[] data, int offset, int length) {\n Objects.requireNonNull(data);\n if (length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return new Bytes(copy);\n }",
"@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }",
"public void addCollaborator(String appName, String collaborator) {\n connection.execute(new SharingAdd(appName, collaborator), apiKey);\n }",
"public AbstractSqlCreator setParameter(String name, Object value) {\n ppsc.setParameter(name, value);\n return this;\n }",
"private int bindStatementValue(PreparedStatement stmt, int index, Object attributeOrQuery, Object value, ClassDescriptor cld)\r\n throws SQLException\r\n {\r\n FieldDescriptor fld = null;\r\n // if value is a subQuery bind it\r\n if (value instanceof Query)\r\n {\r\n Query subQuery = (Query) value;\r\n return bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n\r\n // if attribute is a subQuery bind it\r\n if (attributeOrQuery instanceof Query)\r\n {\r\n Query subQuery = (Query) attributeOrQuery;\r\n bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n else\r\n {\r\n fld = cld.getFieldDescriptorForPath((String) attributeOrQuery);\r\n }\r\n\r\n if (fld != null)\r\n {\r\n // BRJ: use field conversions and platform\r\n if (value != null)\r\n {\r\n m_platform.setObjectForStatement(stmt, index, fld.getFieldConversion().javaToSql(value), fld.getJdbcType().getType());\r\n }\r\n else\r\n {\r\n m_platform.setNullForStatement(stmt, index, fld.getJdbcType().getType());\r\n }\r\n }\r\n else\r\n {\r\n if (value != null)\r\n {\r\n stmt.setObject(index, value);\r\n }\r\n else\r\n {\r\n stmt.setNull(index, Types.NULL);\r\n }\r\n }\r\n\r\n return ++index; // increment before return\r\n }"
] |
Create servlet deployment.
Can be overridden with custom servlet deployment. e.g. exact resources listing in restricted env like GAE
@param context the servlet context
@param bootstrap the bootstrap
@return new servlet deployment | [
"protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) {\n\n ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder();\n extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader()));\n if (isDevModeEnabled) {\n extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), \"N/A\"));\n }\n\n final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build();\n final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);\n final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB);\n\n final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(),\n Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY)));\n\n if (Jandex.isJandexAvailable(resourceLoader)) {\n try {\n Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER);\n strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context)));\n } catch (Exception e) {\n throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e);\n }\n } else {\n strategy.registerHandler(new ServletContextBeanArchiveHandler(context));\n }\n strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context));\n Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery();\n\n String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION);\n\n if (isolation == null || Boolean.valueOf(isolation)) {\n CommonLogger.LOG.archiveIsolationEnabled();\n } else {\n CommonLogger.LOG.archiveIsolationDisabled();\n Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();\n flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives));\n beanDeploymentArchives = flatDeployment;\n }\n\n for (BeanDeploymentArchive archive : beanDeploymentArchives) {\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n }\n\n CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) {\n @Override\n protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive();\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n return archive;\n }\n };\n\n if (strategy.getClassFileServices() != null) {\n deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices());\n }\n return deployment;\n }"
] | [
"public static boolean invert(final DMatrixRMaj cov , final DMatrixRMaj cov_inv ) {\n if( cov.numCols <= 4 ) {\n if( cov.numCols != cov.numRows ) {\n throw new IllegalArgumentException(\"Must be a square matrix.\");\n }\n\n if( cov.numCols >= 2 )\n UnrolledInverseFromMinor_DDRM.inv(cov,cov_inv);\n else\n cov_inv.data[0] = 1.0/cov.data[0];\n\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.symmPosDef(cov.numRows);\n // wrap it to make sure the covariance is not modified.\n solver = new LinearSolverSafe<DMatrixRMaj>(solver);\n if( !solver.setA(cov) )\n return false;\n solver.invert(cov_inv);\n }\n return true;\n }",
"public static int compactDistance(String s1, String s2) {\n if (s1.length() == 0)\n return s2.length();\n if (s2.length() == 0)\n return s1.length();\n\n // the maximum edit distance there is any point in reporting.\n int maxdist = Math.min(s1.length(), s2.length()) / 2;\n \n // we allocate just one column instead of the entire matrix, in\n // order to save space. this also enables us to implement the\n // algorithm somewhat faster. the first cell is always the\n // virtual first row.\n int s1len = s1.length();\n int[] column = new int[s1len + 1];\n\n // first we need to fill in the initial column. we use a separate\n // loop for this, because in this case our basis for comparison is\n // not the previous column, but a virtual first column.\n int ix2 = 0;\n char ch2 = s2.charAt(ix2);\n column[0] = 1; // virtual first row\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // Lowest of three: above (column[ix1 - 1]), aboveleft: ix1 - 1,\n // left: ix1. Latter cannot possibly be lowest, so is\n // ignored.\n column[ix1] = Math.min(column[ix1 - 1], ix1 - 1) + cost;\n }\n\n // okay, now we have an initialized first column, and we can\n // compute the rest of the matrix.\n int above = 0;\n for (ix2 = 1; ix2 < s2.length(); ix2++) {\n ch2 = s2.charAt(ix2);\n above = ix2 + 1; // virtual first row\n\n int smallest = s1len * 2; // used to implement cutoff\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // above: above\n // aboveleft: column[ix1 - 1]\n // left: column[ix1]\n int value = Math.min(Math.min(above, column[ix1 - 1]), column[ix1]) +\n cost;\n column[ix1 - 1] = above; // write previous\n above = value; // keep current\n smallest = Math.min(smallest, value);\n }\n column[s1len] = above;\n\n // check if we can stop because we'll be going over the max distance\n if (smallest > maxdist)\n return smallest;\n }\n\n // ok, we're done\n return above;\n }",
"public static final String printTime(Date value)\n {\n return (value == null ? null : TIME_FORMAT.get().format(value));\n }",
"public int compareTo(Rational other)\n {\n if (denominator == other.getDenominator())\n {\n return ((Long) numerator).compareTo(other.getNumerator());\n }\n else\n {\n Long adjustedNumerator = numerator * other.getDenominator();\n Long otherAdjustedNumerator = other.getNumerator() * denominator;\n return adjustedNumerator.compareTo(otherAdjustedNumerator);\n }\n }",
"public static sslparameter get(nitro_service service) throws Exception{\n\t\tsslparameter obj = new sslparameter();\n\t\tsslparameter[] response = (sslparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public final void configureAccess(final Template template, final ApplicationContext context) {\n final Configuration configuration = template.getConfiguration();\n\n AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);\n accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());\n this.access = accessAssertion;\n }",
"public static void findSomeStringProperties(ApiConnection connection)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tWikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, siteIri);\n\t\twbdf.getFilter().excludeAllProperties();\n\t\twbdf.getFilter().setLanguageFilter(Collections.singleton(\"en\"));\n\n\t\tArrayList<PropertyIdValue> stringProperties = new ArrayList<>();\n\n\t\tSystem.out\n\t\t\t\t.println(\"*** Trying to find string properties for the example ... \");\n\t\tint propertyNumber = 1;\n\t\twhile (stringProperties.size() < 5) {\n\t\t\tArrayList<String> fetchProperties = new ArrayList<>();\n\t\t\tfor (int i = propertyNumber; i < propertyNumber + 10; i++) {\n\t\t\t\tfetchProperties.add(\"P\" + i);\n\t\t\t}\n\t\t\tpropertyNumber += 10;\n\t\t\tMap<String, EntityDocument> results = wbdf\n\t\t\t\t\t.getEntityDocuments(fetchProperties);\n\t\t\tfor (EntityDocument ed : results.values()) {\n\t\t\t\tPropertyDocument pd = (PropertyDocument) ed;\n\t\t\t\tif (DatatypeIdValue.DT_STRING.equals(pd.getDatatype().getIri())\n\t\t\t\t\t\t&& pd.getLabels().containsKey(\"en\")) {\n\t\t\t\t\tstringProperties.add(pd.getEntityId());\n\t\t\t\t\tSystem.out.println(\"* Found string property \"\n\t\t\t\t\t\t\t+ pd.getEntityId().getId() + \" (\"\n\t\t\t\t\t\t\t+ pd.getLabels().get(\"en\") + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstringProperty1 = stringProperties.get(0);\n\t\tstringProperty2 = stringProperties.get(1);\n\t\tstringProperty3 = stringProperties.get(2);\n\t\tstringProperty4 = stringProperties.get(3);\n\t\tstringProperty5 = stringProperties.get(4);\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}",
"public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }",
"public void checkAllGroupsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (OneOfGroup group: this.mapping.values()) {\n\n if (group.satisfiedBy.isEmpty()) {\n errors.append(\"\\n\");\n errors.append(\"\\t* The OneOf choice: \").append(group.name)\n .append(\" was not satisfied. One (and only one) of the \");\n errors.append(\"following fields is required in the request data: \")\n .append(toNames(group.choices));\n }\n\n Collection<OneOfSatisfier> oneOfSatisfiers =\n Collections2.filter(group.satisfiedBy, input -> !input.isCanSatisfy);\n if (oneOfSatisfiers.size() > 1) {\n errors.append(\"\\n\");\n errors.append(\"\\t* The OneOf choice: \").append(group.name)\n .append(\" was satisfied by too many fields. Only one choice \");\n errors.append(\"may be in the request data. The fields found were: \")\n .append(toNames(toFields(group.satisfiedBy)));\n }\n }\n\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @OneOf dependencies of '\" + currentPath +\n \"': \\n\" + errors);\n }"
] |
Constructs a Google APIs HTTP client with the associated credentials. | [
"public HttpRequestFactory makeClient(DatastoreOptions options) {\n Credential credential = options.getCredential();\n HttpTransport transport = options.getTransport();\n if (transport == null) {\n transport = credential == null ? new NetHttpTransport() : credential.getTransport();\n transport = transport == null ? new NetHttpTransport() : transport;\n }\n return transport.createRequestFactory(credential);\n }"
] | [
"private static void validateIfAvroSchema(SerializerDefinition serializerDef) {\n if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerDef.getName().equals(AVRO_GENERIC_TYPE_NAME)) {\n SchemaEvolutionValidator.validateAllAvroSchemas(serializerDef);\n // check backwards compatibility if needed\n if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)) {\n SchemaEvolutionValidator.checkSchemaCompatibility(serializerDef);\n }\n }\n }",
"public static base_responses save(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup saveresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cachecontentgroup();\n\t\t\t\tsaveresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}",
"protected Path normalizePath(final Path parent, final String path) {\n return parent.resolve(path).toAbsolutePath().normalize();\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 static String encodePort(String port, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(port, encoding, HierarchicalUriComponents.Type.PORT);\n\t}",
"private static void checkPreconditions(final int maxSize, final String suffix) {\n\t\tif( maxSize <= 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"maxSize should be > 0 but was %d\", maxSize));\n\t\t}\n\t\tif( suffix == null ) {\n\t\t\tthrow new NullPointerException(\"suffix should not be null\");\n\t\t}\n\t}",
"public ValueContainer[] getValuesForObject(FieldDescriptor[] fields, Object obj, boolean convertToSql, boolean assignAutoincrement) throws PersistenceBrokerException\r\n {\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fd = fields[i];\r\n Object cv = fd.getPersistentField().get(obj);\r\n\r\n /*\r\n handle autoincrement attributes if\r\n - is a autoincrement field\r\n - field represents a 'null' value, is nullified\r\n and generate a new value\r\n */\r\n if(assignAutoincrement && fd.isAutoIncrement() && representsNull(fd, cv))\r\n {\r\n /*\r\n setAutoIncrementValue returns a value that is\r\n properly typed for the java-world. This value\r\n needs to be converted to it's corresponding\r\n sql type so that the entire result array contains\r\n objects that are properly typed for sql.\r\n */\r\n cv = setAutoIncrementValue(fd, obj);\r\n }\r\n if(convertToSql)\r\n {\r\n // apply type and value conversion\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n // create ValueContainer\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n return result;\r\n }",
"public Search groupField(String fieldName, boolean isNumber) {\r\n assertNotEmpty(fieldName, \"fieldName\");\r\n if (isNumber) {\r\n databaseHelper.query(\"group_field\", fieldName + \"<number>\");\r\n } else {\r\n databaseHelper.query(\"group_field\", fieldName);\r\n }\r\n return this;\r\n }",
"@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 }"
] |
Gets information about a trashed file that's limited to a list of specified fields.
@param fileID the ID of the trashed file.
@param fields the fields to retrieve.
@return info about the trashed file containing only the specified fields. | [
"public BoxFile.Info getFileInfo(String fileID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FILE_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }"
] | [
"public boolean getNumericBoolean(int field)\n {\n boolean result = false;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Integer.parseInt(m_fields[field]) == 1;\n }\n\n return (result);\n }",
"public static base_response update(nitro_service client, nstimeout resource) throws Exception {\n\t\tnstimeout updateresource = new nstimeout();\n\t\tupdateresource.zombie = resource.zombie;\n\t\tupdateresource.client = resource.client;\n\t\tupdateresource.server = resource.server;\n\t\tupdateresource.httpclient = resource.httpclient;\n\t\tupdateresource.httpserver = resource.httpserver;\n\t\tupdateresource.tcpclient = resource.tcpclient;\n\t\tupdateresource.tcpserver = resource.tcpserver;\n\t\tupdateresource.anyclient = resource.anyclient;\n\t\tupdateresource.anyserver = resource.anyserver;\n\t\tupdateresource.halfclose = resource.halfclose;\n\t\tupdateresource.nontcpzombie = resource.nontcpzombie;\n\t\tupdateresource.reducedfintimeout = resource.reducedfintimeout;\n\t\tupdateresource.newconnidletimeout = resource.newconnidletimeout;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public int getOpacity() {\n\t\tint opacity = Math\n\t\t\t\t.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));\n\t\tif (opacity < 5) {\n\t\t\treturn 0x00;\n\t\t} else if (opacity > 250) {\n\t\t\treturn 0xFF;\n\t\t} else {\n\t\t\treturn opacity;\n\t\t}\n\t}",
"private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }",
"@Override\n public T getById(Object id)\n {\n return context.getFramed().getFramedVertex(this.type, id);\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 }",
"private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }",
"public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}",
"public void setSingletonVariable(String name, WindupVertexFrame frame)\n {\n setVariable(name, Collections.singletonList(frame));\n }"
] |
Will wait a maximum of 1 minute for each node to response with their result. If an error occurs on any
member, we will always attempt to continue execution and collect as many results as possible.
@param execSvc
@param members
@param callable
@return | [
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }"
] | [
"private Collection parseCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n collection.setId(collectionElement.getAttribute(\"id\"));\n collection.setServer(collectionElement.getAttribute(\"server\"));\n collection.setSecret(collectionElement.getAttribute(\"secret\"));\n collection.setChildCount(collectionElement.getAttribute(\"child_count\"));\n collection.setIconLarge(collectionElement.getAttribute(\"iconlarge\"));\n collection.setIconSmall(collectionElement.getAttribute(\"iconsmall\"));\n collection.setDateCreated(collectionElement.getAttribute(\"datecreate\"));\n collection.setTitle(XMLUtilities.getChildValue(collectionElement, \"title\"));\n collection.setDescription(XMLUtilities.getChildValue(collectionElement, \"description\"));\n\n Element iconPhotos = XMLUtilities.getChild(collectionElement, \"iconphotos\");\n if (iconPhotos != null) {\n NodeList photoElements = iconPhotos.getElementsByTagName(\"photo\");\n for (int i = 0; i < photoElements.getLength(); i++) {\n Element photoElement = (Element) photoElements.item(i);\n collection.addPhoto(PhotoUtils.createPhoto(photoElement));\n }\n }\n\n return collection;\n }",
"public static List<String> parse(final String[] args, final Object... objs) throws IOException\n {\n final List<String> ret = Colls.list();\n\n final List<Arg> allArgs = Colls.list();\n final HashMap<String, Arg> shortArgs = new HashMap<String, Arg>();\n final HashMap<String, Arg> longArgs = new HashMap<String, Arg>();\n\n parseArgs(objs, allArgs, shortArgs, longArgs);\n\n for (int i = 0; i < args.length; i++)\n {\n final String s = args[i];\n\n final Arg a;\n\n if (s.startsWith(\"--\"))\n {\n a = longArgs.get(s.substring(2));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else if (s.startsWith(\"-\"))\n {\n a = shortArgs.get(s.substring(1));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else\n {\n a = null;\n ret.add(s);\n }\n\n if (a != null)\n {\n if (a.isSwitch)\n {\n a.setField(\"true\");\n }\n else\n {\n if (i + 1 >= args.length)\n {\n System.out.println(\"Missing parameter for: \" + s);\n }\n if (a.isCatchAll())\n {\n final List<String> ca = Colls.list();\n for (++i; i < args.length; ++i)\n {\n ca.add(args[i]);\n }\n a.setCatchAll(ca);\n }\n else\n {\n ++i;\n a.setField(args[i]);\n }\n }\n a.setPresent();\n }\n }\n\n for (final Arg a : allArgs)\n {\n if (!a.isOk())\n {\n throw new IOException(\"Missing mandatory argument: \" + a);\n }\n }\n\n return ret;\n }",
"public Object get(Object key)\r\n {\r\n purge();\r\n Entry entry = getEntry(key);\r\n if (entry == null) return null;\r\n return entry.getValue();\r\n }",
"public static void pow(ComplexPolar_F64 a , int N , ComplexPolar_F64 result )\n {\n result.r = Math.pow(a.r,N);\n result.theta = N*a.theta;\n }",
"public static base_response delete(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute deleteresource = new lbroute();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public void warn(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.WARNING, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}",
"public String getRandomHoliday(String earliest, String latest) {\n String dateString = \"\";\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime earlyDate = parser.parseDateTime(earliest);\n DateTime lateDate = parser.parseDateTime(latest);\n List<Holiday> holidays = new LinkedList<>();\n\n int min = Integer.parseInt(earlyDate.toString().substring(0, 4));\n int max = Integer.parseInt(lateDate.toString().substring(0, 4));\n int range = max - min + 1;\n int randomYear = (int) (Math.random() * range) + min;\n\n for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {\n holidays.add(s);\n }\n Collections.shuffle(holidays);\n\n for (Holiday holiday : holidays) {\n dateString = convertToReadableDate(holiday.forYear(randomYear));\n if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {\n break;\n }\n }\n return dateString;\n }",
"public static float distance(final float ax, final float ay,\n final float bx, final float by) {\n return (float) Math.sqrt(\n (ax - bx) * (ax - bx) +\n (ay - by) * (ay - by)\n );\n }",
"public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }"
] |
Displays a sample model for the report request.
@return A string describing the structure of a certain report execution | [
"public String[] getReportSamples() {\n final Map<String, String> sampleValues = new HashMap<>();\n sampleValues.put(\"name1\", \"Secure Transpiler Mars\");\n sampleValues.put(\"version1\", \"4.7.0\");\n sampleValues.put(\"name2\", \"Secure Transpiler Bounty\");\n sampleValues.put(\"version2\", \"5.0.0\");\n sampleValues.put(\"license\", \"CDDL-1.1\");\n sampleValues.put(\"name\", \"Secure Pretender\");\n sampleValues.put(\"version\", \"2.7.0\");\n sampleValues.put(\"organization\", \"Axway\");\n\n return ReportsRegistry.allReports()\n .stream()\n .map(report -> ReportUtils.generateSampleRequest(report, sampleValues))\n .map(request -> {\n try {\n String desc = \"\";\n final Optional<Report> byId = ReportsRegistry.findById(request.getReportId());\n\n if(byId.isPresent()) {\n desc = byId.get().getDescription() + \"<br/><br/>\";\n }\n\n return String.format(TWO_PLACES, desc, JsonUtils.serialize(request));\n } catch(IOException e) {\n return \"Error \" + e.getMessage();\n }\n })\n .collect(Collectors.toList())\n .toArray(new String[] {});\n }"
] | [
"public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"public void setCanvasWidthHeight(int width, int height) {\n hudWidth = width;\n hudHeight = height;\n HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888);\n canvas = new Canvas(HUD);\n texture = null;\n }",
"public static BufferedImage convertImageToARGB( Image image ) {\n\t\tif ( image instanceof BufferedImage && ((BufferedImage)image).getType() == BufferedImage.TYPE_INT_ARGB )\n\t\t\treturn (BufferedImage)image;\n\t\tBufferedImage p = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics2D g = p.createGraphics();\n\t\tg.drawImage( image, 0, 0, null );\n\t\tg.dispose();\n\t\treturn p;\n\t}",
"public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n // sqrt( (x2-x1)^2 + (y2-y2)^2 )\r\n Double xDiff = point1._1() - point2._1();\r\n Double yDiff = point1._2() - point2._2();\r\n return Math.sqrt(xDiff * xDiff + yDiff * yDiff);\r\n }",
"@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }",
"public boolean link(D declaration, ServiceReference<S> declarationBinderRef) {\n S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);\n LOG.debug(declaration + \" match the filter of \" + declarationBinder + \" : bind them together\");\n declaration.bind(declarationBinderRef);\n try {\n declarationBinder.addDeclaration(declaration);\n } catch (Exception e) {\n declaration.unbind(declarationBinderRef);\n LOG.debug(declarationBinder + \" throw an exception when giving to it the Declaration \"\n + declaration, e);\n return false;\n }\n return true;\n }",
"public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public static double normP1( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return CommonOps_DDRM.elementSumAbs(A);\n } else {\n return inducedP1(A);\n }\n }",
"public static double Sin(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x - (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n double sign = 1;\r\n int factS = 5;\r\n double result = x - mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }"
] |
Retrieve list of assignment extended attributes.
@return list of extended attributes | [
"private List<AssignmentField> getAllAssignmentExtendedAttributes()\n {\n ArrayList<AssignmentField> result = new ArrayList<AssignmentField>();\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_MULTI_VALUE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_OUTLINE_CODE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_TEXT));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_TEXT));\n return result;\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n public void put(String key, Versioned<Object> value) {\n // acquire write lock\n writeLock.lock();\n\n try {\n if(this.storeNames.contains(key) || key.equals(STORES_KEY)) {\n\n // Check for backwards compatibility\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) value.getValue();\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n // If the put is on the entire stores.xml key, delete the\n // additional stores which do not exist in the specified\n // stores.xml\n Set<String> storeNamesToDelete = new HashSet<String>();\n for(String storeName: this.storeNames) {\n storeNamesToDelete.add(storeName);\n }\n\n // Add / update the list of store definitions specified in the\n // value\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n\n // Update the STORES directory and the corresponding entry in\n // metadata cache\n Set<String> specifiedStoreNames = new HashSet<String>();\n for(StoreDefinition storeDef: storeDefinitions) {\n specifiedStoreNames.add(storeDef.getName());\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(),\n versionedValueStr,\n \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n if(key.equals(STORES_KEY)) {\n storeNamesToDelete.removeAll(specifiedStoreNames);\n resetStoreDefinitions(storeNamesToDelete);\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n updateRoutingStrategies(getCluster(), getStoreDefList());\n\n } else if(METADATA_KEYS.contains(key)) {\n // try inserting into inner store first\n putInner(key, convertObjectToString(key, value));\n\n // cache all keys if innerStore put succeeded\n metadataCache.put(key, value);\n\n // do special stuff if needed\n if(CLUSTER_KEY.equals(key)) {\n updateRoutingStrategies((Cluster) value.getValue(), getStoreDefList());\n } else if(NODE_ID_KEY.equals(key)) {\n initNodeId(getNodeIdNoLock());\n } else if(SYSTEM_STORES_KEY.equals(key))\n throw new VoldemortException(\"Cannot overwrite system store definitions\");\n\n } else {\n throw new VoldemortException(\"Unhandled Key:\" + key + \" for MetadataStore put()\");\n }\n } finally {\n writeLock.unlock();\n }\n }",
"private String pathToProperty(String path) {\n if (path == null || !path.startsWith(\"/\")) {\n throw new IllegalArgumentException(\"Path must be prefixed with a \\\"/\\\".\");\n }\n return path.substring(1);\n }",
"protected void printCenterWithLead(String lead, String format, Object ... args) {\n String text = S.fmt(format, args);\n int len = 80 - lead.length();\n info(S.concat(lead, S.center(text, len)));\n }",
"private void deriveProjectCalendar()\n {\n //\n // Count the number of times each calendar is used\n //\n Map<ProjectCalendar, Integer> map = new HashMap<ProjectCalendar, Integer>();\n for (Task task : m_project.getTasks())\n {\n ProjectCalendar calendar = task.getCalendar();\n Integer count = map.get(calendar);\n if (count == null)\n {\n count = Integer.valueOf(1);\n }\n else\n {\n count = Integer.valueOf(count.intValue() + 1);\n }\n map.put(calendar, count);\n }\n\n //\n // Find the most frequently used calendar\n //\n int maxCount = 0;\n ProjectCalendar defaultCalendar = null;\n\n for (Entry<ProjectCalendar, Integer> entry : map.entrySet())\n {\n if (entry.getValue().intValue() > maxCount)\n {\n maxCount = entry.getValue().intValue();\n defaultCalendar = entry.getKey();\n }\n }\n\n //\n // Set the default calendar for the project\n // and remove it's use as a task-specific calendar.\n //\n if (defaultCalendar != null)\n {\n m_project.setDefaultCalendar(defaultCalendar);\n for (Task task : m_project.getTasks())\n {\n if (task.getCalendar() == defaultCalendar)\n {\n task.setCalendar(null);\n }\n }\n }\n }",
"public ServerRedirect addServerMapping(String sourceHost, String destinationHost, String hostHeader) {\n JSONObject response = null;\n\n ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();\n params.add(new BasicNameValuePair(\"srcUrl\", sourceHost));\n params.add(new BasicNameValuePair(\"destUrl\", destinationHost));\n params.add(new BasicNameValuePair(\"profileIdentifier\", this._profileName));\n if (hostHeader != null) {\n params.add(new BasicNameValuePair(\"hostHeader\", hostHeader));\n }\n\n try {\n BasicNameValuePair paramArray[] = new BasicNameValuePair[params.size()];\n params.toArray(paramArray);\n response = new JSONObject(doPost(BASE_SERVER, paramArray));\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return getServerRedirectFromJSON(response);\n }",
"protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {\n HttpHeaders headers = request.getHeaders();\n headers.set(HOST, destination.getUri().getAuthority());\n headers.remove(TE);\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 }",
"private Double getPercentage(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue() / 100);\n }\n\n return result;\n }",
"public void migrate() {\n if (databaseIsUpToDate()) {\n LOGGER.info(format(\"Keyspace %s is already up to date at version %d\", database.getKeyspaceName(),\n database.getVersion()));\n return;\n }\n\n List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());\n migrations.forEach(database::execute);\n LOGGER.info(format(\"Migrated keyspace %s to version %d\", database.getKeyspaceName(), database.getVersion()));\n database.close();\n }"
] |
Remove all existing subscriptions | [
"public void removeAll() {\n LOGGER.debug(\"Removing {} reverse connections from subscription manager\", reverse.size());\n Iterator<HomekitClientConnection> i = reverse.keySet().iterator();\n while (i.hasNext()) {\n HomekitClientConnection connection = i.next();\n LOGGER.debug(\"Removing connection {}\", connection.hashCode());\n removeConnection(connection);\n }\n LOGGER.debug(\"Subscription sizes are {} and {}\", reverse.size(), subscriptions.size());\n }"
] | [
"public GroovyConstructorDoc[] constructors() {\n Collections.sort(constructors);\n return constructors.toArray(new GroovyConstructorDoc[constructors.size()]);\n }",
"@NonNull public Context getContext() {\n if (searchView != null) {\n return searchView.getContext();\n } else if (supportView != null) {\n return supportView.getContext();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }",
"protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public Iterable<BoxMetadataCascadePolicy.Info> getMetadataCascadePolicies(String... fields) {\n Iterable<BoxMetadataCascadePolicy.Info> cascadePoliciesInfo =\n BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields);\n\n return cascadePoliciesInfo;\n }",
"public static lbvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tlbvserver[] response = (lbvserver[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) {\n return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName);\n }",
"public static base_response delete(nitro_service client, String serverip) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = serverip;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private boolean isDebug(CmsObject cms, CmsSolrQuery query) {\r\n\r\n String[] debugSecretValues = query.remove(REQUEST_PARAM_DEBUG_SECRET);\r\n String debugSecret = (debugSecretValues == null) || (debugSecretValues.length < 1)\r\n ? null\r\n : debugSecretValues[0];\r\n if ((null != debugSecret) && !debugSecret.trim().isEmpty() && (null != m_handlerDebugSecretFile)) {\r\n try {\r\n CmsFile secretFile = cms.readFile(m_handlerDebugSecretFile);\r\n String secret = new String(secretFile.getContents(), CmsFileUtil.getEncoding(cms, secretFile));\r\n return secret.trim().equals(debugSecret.trim());\r\n } catch (Exception e) {\r\n LOG.info(\r\n \"Failed to read secret file for index \\\"\"\r\n + getName()\r\n + \"\\\" at path \\\"\"\r\n + m_handlerDebugSecretFile\r\n + \"\\\".\");\r\n }\r\n }\r\n return false;\r\n }",
"public Story storyOfText(Configuration configuration, String storyAsText, String storyId) {\n return configuration.storyParser().parseStory(storyAsText, storyId);\n }"
] |
Convert tenor given as offset in months to year fraction.
@param maturityInMonths The maturity as offset in months.
@param tenorInMonths The tenor as offset in months.
@return THe tenor as year fraction. | [
"private double convertTenor(int maturityInMonths, int tenorInMonths) {\r\n\t\tSchedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths);\r\n\t\treturn schedule.getPayment(schedule.getNumberOfPeriods()-1);\r\n\t}"
] | [
"public final void cancelOld(\n final long starttimeThreshold, final long checkTimeThreshold, final String message) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.and(\n builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING),\n builder.or(\n builder.lessThan(root.get(\"entry\").get(\"startTime\"), starttimeThreshold),\n builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold))\n )\n ));\n update.set(root.get(\"status\"), PrintJobStatus.Status.CANCELLED);\n update.set(root.get(\"error\"), message);\n getSession().createQuery(update).executeUpdate();\n }",
"public void readTags(InputStream tagsXML)\n {\n SAXParserFactory factory = SAXParserFactory.newInstance();\n try\n {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(tagsXML, new TagsSaxHandler(this));\n }\n catch (ParserConfigurationException | SAXException | IOException ex)\n {\n throw new RuntimeException(\"Failed parsing the tags definition: \" + ex.getMessage(), ex);\n }\n }",
"public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }",
"public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST license\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\n }",
"private void initDurationButtonGroup() {\n\n m_groupDuration = new CmsRadioButtonGroup();\n\n m_endsAfterRadioButton = new CmsRadioButton(\n EndType.TIMES.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_0));\n m_endsAfterRadioButton.setGroup(m_groupDuration);\n m_endsAtRadioButton = new CmsRadioButton(\n EndType.DATE.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_DATE_0));\n m_endsAtRadioButton.setGroup(m_groupDuration);\n m_groupDuration.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (null != value) {\n m_controller.setEndType(value);\n }\n }\n }\n });\n\n }",
"public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }",
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}",
"public synchronized void maybeThrottle(int eventsSeen) {\n if (maxRatePerSecond > 0) {\n long now = time.milliseconds();\n try {\n rateSensor.record(eventsSeen, now);\n } catch (QuotaViolationException e) {\n // If we're over quota, we calculate how long to sleep to compensate.\n double currentRate = e.getValue();\n if (currentRate > this.maxRatePerSecond) {\n double excessRate = currentRate - this.maxRatePerSecond;\n long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);\n if(logger.isDebugEnabled()) {\n logger.debug(\"Throttler quota exceeded:\\n\" +\n \"eventsSeen \\t= \" + eventsSeen + \" in this call of maybeThrotte(),\\n\" +\n \"currentRate \\t= \" + currentRate + \" events/sec,\\n\" +\n \"maxRatePerSecond \\t= \" + this.maxRatePerSecond + \" events/sec,\\n\" +\n \"excessRate \\t= \" + excessRate + \" events/sec,\\n\" +\n \"sleeping for \\t\" + sleepTimeMs + \" ms to compensate.\\n\" +\n \"rateConfig.timeWindowMs() = \" + rateConfig.timeWindowMs());\n }\n if (sleepTimeMs > rateConfig.timeWindowMs()) {\n logger.warn(\"Throttler sleep time (\" + sleepTimeMs + \" ms) exceeds \" +\n \"window size (\" + rateConfig.timeWindowMs() + \" ms). This will likely \" +\n \"result in not being able to honor the rate limit accurately.\");\n // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size\n // too high could cause this problem.\n }\n time.sleep(sleepTimeMs);\n } else if (logger.isDebugEnabled()) {\n logger.debug(\"Weird. Got QuotaValidationException but measured rate not over rateLimit: \" +\n \"currentRate = \" + currentRate + \" , rateLimit = \" + this.maxRatePerSecond);\n }\n }\n }\n }"
] |
Check if a position is within a circle
@param x x position
@param y y position
@param centerX center x of circle
@param centerY center y of circle
@return true if within circle, false otherwise | [
"static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }"
] | [
"private long getEndTime(ISuite suite, IInvokedMethod method)\n {\n // Find the latest end time for all tests in the suite.\n for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())\n {\n ITestContext testContext = entry.getValue().getTestContext();\n for (ITestNGMethod m : testContext.getAllTestMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n // If we can't find a matching test method it must be a configuration method.\n for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n }\n throw new IllegalStateException(\"Could not find matching end time.\");\n }",
"public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) {\n dbbCC.setAccessible(true);\n Object b = null;\n try {\n b = dbbCC.newInstance(new Long(addr), new Integer(size), att);\n return ByteBuffer.class.cast(b);\n }\n catch(Exception e) {\n throw new IllegalStateException(String.format(\"Failed to create DirectByteBuffer: %s\", e.getMessage()));\n }\n }",
"protected String consumeWord(ImapRequestLineReader request,\n CharacterValidator validator)\n throws ProtocolException {\n StringBuilder atom = new StringBuilder();\n\n char next = request.nextWordChar();\n while (!isWhitespace(next)) {\n if (validator.isValid(next)) {\n atom.append(next);\n request.consume();\n } else {\n throw new ProtocolException(\"Invalid character: '\" + next + '\\'');\n }\n next = request.nextChar();\n }\n return atom.toString();\n }",
"public static String getJavaClassFromSchemaInfo(String schemaInfo) {\n final String ONLY_JAVA_CLIENTS_SUPPORTED = \"Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=foo.Bar</schema-info> where foo.Bar is the fully qualified name of the message.\";\n\n if(StringUtils.isEmpty(schemaInfo))\n throw new IllegalArgumentException(\"This serializer requires a non-empty schema-info.\");\n\n String[] languagePairs = StringUtils.split(schemaInfo, ',');\n if(languagePairs.length > 1)\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n String[] javaPair = StringUtils.split(languagePairs[0], '=');\n if(javaPair.length != 2 || !javaPair[0].trim().equals(\"java\"))\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n return javaPair[1].trim();\n }",
"public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) {\n\t\tif (s3 == null || s3BucketName == null) {\n\t\t\tString errorMessage = \"S3 client and/or S3 bucket name cannot be null.\";\n\t\t\tLOG.error(errorMessage);\n\t\t\tthrow new AmazonClientException(errorMessage);\n\t\t}\n\t\tif (isLargePayloadSupportEnabled()) {\n\t\t\tLOG.warn(\"Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName.\");\n\t\t}\n\t\tthis.s3 = s3;\n\t\tthis.s3BucketName = s3BucketName;\n\t\tlargePayloadSupport = true;\n\t\tLOG.info(\"Large-payload support enabled.\");\n\t}",
"public void addFilter(Filter filter)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.add(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.add(filter);\n }\n\n m_filtersByName.put(filter.getName(), filter);\n m_filtersByID.put(filter.getID(), filter);\n }",
"public void signOff(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key);\n if (null == connections) {\n return;\n }\n connections.remove(connection);\n }",
"private <T extends TimephasedItem<?>> int getStartIndex(DateRange range, List<T> assignments, int startIndex)\n {\n int result = -1;\n if (assignments != null)\n {\n long rangeStart = range.getStart().getTime();\n long rangeEnd = range.getEnd().getTime();\n\n for (int loop = startIndex; loop < assignments.size(); loop++)\n {\n T assignment = assignments.get(loop);\n int compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeStart);\n\n //\n // The start of the target range falls after the assignment end -\n // move on to test the next assignment.\n //\n if (compareResult > 0)\n {\n continue;\n }\n\n //\n // The start of the target range falls within the assignment -\n // return the index of this assignment to the caller.\n //\n if (compareResult == 0)\n {\n result = loop;\n break;\n }\n\n //\n // At this point, we know that the start of the target range is before\n // the assignment start. We need to determine if the end of the\n // target range overlaps the assignment.\n //\n compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeEnd);\n if (compareResult >= 0)\n {\n result = loop;\n break;\n }\n }\n }\n return result;\n }",
"public void startScenario( Class<?> testClass, Method method, List<NamedArgument> arguments ) {\n listener.scenarioStarted( testClass, method, arguments );\n\n if( method.isAnnotationPresent( Pending.class ) ) {\n Pending annotation = method.getAnnotation( Pending.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n } else if( method.isAnnotationPresent( NotImplementedYet.class ) ) {\n NotImplementedYet annotation = method.getAnnotation( NotImplementedYet.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n }\n\n }"
] |
Fired whenever a browser event is received.
@param event Event to process | [
"@Override\r\n public void onBrowserEvent(Event event) {\r\n\r\n super.onBrowserEvent(event);\r\n\r\n switch (DOM.eventGetType(event)) {\r\n case Event.ONMOUSEUP:\r\n Event.releaseCapture(m_slider.getElement());\r\n m_capturedMouse = false;\r\n break;\r\n case Event.ONMOUSEDOWN:\r\n Event.setCapture(m_slider.getElement());\r\n m_capturedMouse = true;\r\n //$FALL-THROUGH$\r\n case Event.ONMOUSEMOVE:\r\n if (m_capturedMouse) {\r\n event.preventDefault();\r\n float x = ((event.getClientX() - (m_colorUnderlay.getAbsoluteLeft())) + Window.getScrollLeft());\r\n float y = ((event.getClientY() - (m_colorUnderlay.getAbsoluteTop())) + Window.getScrollTop());\r\n\r\n if (m_parent != null) {\r\n m_parent.onMapSelected(x, y);\r\n }\r\n\r\n setSliderPosition(x, y);\r\n }\r\n //$FALL-THROUGH$\r\n default:\r\n\r\n }\r\n }"
] | [
"protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }",
"public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n DockerUtils.pullImage(imageTag, username, password, host);\n return true;\n }\n });\n }",
"public void cross(Vector3d v1, Vector3d v2) {\n double tmpx = v1.y * v2.z - v1.z * v2.y;\n double tmpy = v1.z * v2.x - v1.x * v2.z;\n double tmpz = v1.x * v2.y - v1.y * v2.x;\n\n x = tmpx;\n y = tmpy;\n z = tmpz;\n }",
"public void addPathToRequestResponseTable(int profileId, String clientUUID, int pathId) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection\n .prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \"(\" + Constants.REQUEST_RESPONSE_PATH_ID + \",\"\n + Constants.GENERIC_PROFILE_ID + \",\"\n + Constants.GENERIC_CLIENT_UUID + \",\"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \",\"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \",\"\n + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\");\n statement.setInt(1, pathId);\n statement.setInt(2, profileId);\n statement.setString(3, clientUUID);\n statement.setInt(4, -1);\n statement.setInt(5, 0);\n statement.setInt(6, 0);\n statement.setString(7, \"\");\n statement.setString(8, \"\");\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"private void changeClusterAndStores(String clusterKey,\n final Cluster cluster,\n String storesKey,\n final List<StoreDefinition> storeDefs) {\n metadataStore.writeLock.lock();\n try {\n VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock));\n\n // now put new stores\n updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock));\n\n } catch(Exception e) {\n logger.info(\"Error while changing cluster to \" + cluster + \"for key \" + clusterKey);\n throw new VoldemortException(e);\n } finally {\n metadataStore.writeLock.unlock();\n }\n }",
"@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 void removeObservation( int index ) {\n final int N = y.numRows-1;\n final double d[] = y.data;\n\n // shift\n for( int i = index; i < N; i++ ) {\n d[i] = d[i+1];\n }\n y.numRows--;\n }",
"public static float noise2(float x, float y) {\n int bx0, bx1, by0, by1, b00, b10, b01, b11;\n float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;\n int i, j;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n t = y + N;\n by0 = ((int)t) & BM;\n by1 = (by0+1) & BM;\n ry0 = t - (int)t;\n ry1 = ry0 - 1.0f;\n\n i = p[bx0];\n j = p[bx1];\n\n b00 = p[i + by0];\n b10 = p[j + by0];\n b01 = p[i + by1];\n b11 = p[j + by1];\n\n sx = sCurve(rx0);\n sy = sCurve(ry0);\n\n q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];\n q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];\n a = lerp(sx, u, v);\n\n q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];\n q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];\n b = lerp(sx, u, v);\n\n return 1.5f*lerp(sy, a, b);\n }",
"public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() {\n return new ExecutorConfig<GROUP>()\n .withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>());\n }"
] |
Retrieves and validates the content type from the REST requests
@return true if has content type. | [
"protected boolean hasContentType() {\n\n boolean result = false;\n if(this.request.getHeader(RestMessageHeaders.CONTENT_TYPE) != null) {\n result = true;\n } else {\n logger.error(\"Error when validating put request. Missing Content-Type header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Type header\");\n }\n return result;\n }"
] | [
"public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"void stop() {\n try {\n dm.stop(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to stop \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory, e);\n }\n declarationsFiles.clear();\n declarationRegistrationManager.unregisterAll();\n }",
"public FormInput inputField(InputType type, Identification identification) {\r\n\t\tFormInput input = new FormInput(type, identification);\r\n\t\tthis.formInputs.add(input);\r\n\t\treturn input;\r\n\t}",
"public void hideKeyboard() {\n InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0);\n }",
"public Where<T, ID> idEq(ID id) 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, id, SimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"@Override\n public void onKeyDown(KeyDownEvent event) {\n\tchar c = MiscUtils.getCharCode(event.getNativeEvent());\n\tonKeyCodeEvent(event, box.getValue()+c);\n }",
"public WaveformPreview requestWaveformPreviewFrom(final DataReference dataReference) {\n ensureRunning();\n for (WaveformPreview cached : previewHotCache.values()) {\n if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestPreviewInternal(dataReference, false);\n }",
"public double[][] getU() {\n double[][] X = new double[n][n];\n double[][] U = X;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i <= j) {\n U[i][j] = LU[i][j];\n } else {\n U[i][j] = 0.0;\n }\n }\n }\n return X;\n }",
"public synchronized void start() throws SocketException {\n if (!isRunning()) {\n DeviceFinder.getInstance().addLifecycleListener(lifecycleListener);\n DeviceFinder.getInstance().addDeviceAnnouncementListener(announcementListener);\n DeviceFinder.getInstance().start();\n for (DeviceAnnouncement device: DeviceFinder.getInstance().getCurrentDevices()) {\n requestPlayerDBServerPort(device);\n }\n\n new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (isRunning()) {\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n logger.warn(\"Interrupted sleeping to close idle dbserver clients\");\n }\n closeIdleClients();\n }\n logger.info(\"Idle dbserver client closer shutting down.\");\n }\n }, \"Idle dbserver client closer\").start();\n\n running.set(true);\n deliverLifecycleAnnouncement(logger, true);\n }\n }"
] |
Use this API to fetch appflowpolicy_binding resource of given name . | [
"public static appflowpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_binding obj = new appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_binding response = (appflowpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static final Bytes of(byte[] array) {\n Objects.requireNonNull(array);\n if (array.length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[array.length];\n System.arraycopy(array, 0, copy, 0, array.length);\n return new Bytes(copy);\n }",
"public void setPadding(float padding, Layout.Axis axis) {\n OrientedLayout layout = null;\n switch(axis) {\n case X:\n layout = mShiftLayout;\n break;\n case Y:\n layout = mShiftLayout;\n break;\n case Z:\n layout = mStackLayout;\n break;\n }\n if (layout != null) {\n if (!equal(layout.getDividerPadding(axis), padding)) {\n layout.setDividerPadding(padding, axis);\n\n if (layout.getOrientationAxis() == axis) {\n requestLayout();\n }\n }\n }\n\n }",
"public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\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) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"protected <E> E read(Supplier<E> sup) {\n try {\n this.lock.readLock().lock();\n return sup.get();\n } finally {\n this.lock.readLock().unlock();\n }\n }",
"public void push( Token token ) {\n size++;\n if( first == null ) {\n first = token;\n last = token;\n token.previous = null;\n token.next = null;\n } else {\n last.next = token;\n token.previous = last;\n token.next = null;\n last = token;\n }\n }",
"public <E extends Enum<E> & FieldType> E nextField(Class<E> clazz, UserFieldDataType type)\n {\n for (String name : m_names[type.ordinal()])\n {\n int i = NumberHelper.getInt(m_counters.get(name)) + 1;\n try\n {\n E e = Enum.valueOf(clazz, name + i);\n m_counters.put(name, Integer.valueOf(i));\n return e;\n }\n catch (IllegalArgumentException ex)\n {\n // try the next name\n }\n }\n\n // no more fields available\n throw new IllegalArgumentException(\"No fields for type \" + type + \" available\");\n }",
"public static int lengthOfCodePoint(int codePoint)\n {\n if (codePoint < 0) {\n throw new InvalidCodePointException(codePoint);\n }\n if (codePoint < 0x80) {\n // normal ASCII\n // 0xxx_xxxx\n return 1;\n }\n if (codePoint < 0x800) {\n return 2;\n }\n if (codePoint < 0x1_0000) {\n return 3;\n }\n if (codePoint < 0x11_0000) {\n return 4;\n }\n // Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal\n throw new InvalidCodePointException(codePoint);\n }",
"public static void inner_reorder_lower(DMatrix1Row A , DMatrix1Row B )\n {\n final int cols = A.numCols;\n B.reshape(cols,cols);\n\n Arrays.fill(B.data,0);\n for (int i = 0; i <cols; i++) {\n for (int j = 0; j <=i; j++) {\n B.data[i*cols+j] += A.data[i]*A.data[j];\n }\n\n for (int k = 1; k < A.numRows; k++) {\n int indexRow = k*cols;\n double valI = A.data[i+indexRow];\n int indexB = i*cols;\n for (int j = 0; j <= i; j++) {\n B.data[indexB++] += valI*A.data[indexRow++];\n }\n }\n }\n }"
] |
Use this API to update dbdbprofile. | [
"public static base_response update(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile updateresource = new dbdbprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.interpretquery = resource.interpretquery;\n\t\tupdateresource.stickiness = resource.stickiness;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.conmultiplex = resource.conmultiplex;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"void execute(ExecutableBuilder builder,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n Future<Void> task = executorService.submit(() -> {\n builder.build().execute();\n return null;\n });\n try {\n if (timeout <= 0) { //Synchronous\n task.get();\n } else { // Guarded execution\n try {\n task.get(timeout, unit);\n } catch (TimeoutException ex) {\n // First make the context unusable\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).timeout();\n }\n // Then cancel the task.\n task.cancel(true);\n throw ex;\n }\n }\n } catch (InterruptedException ex) {\n // Could have been interrupted by user (Ctrl-C)\n Thread.currentThread().interrupt();\n cancelTask(task, builder.getCommandContext(), null);\n // Interrupt running operation.\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).interrupted();\n }\n throw ex;\n }\n }",
"public Set<Action.ActionEffect> getActionEffects() {\n switch(getImpact()) {\n case CLASSLOADING:\n case WRITE:\n return WRITES;\n case READ_ONLY:\n return READS;\n default:\n throw new IllegalStateException();\n }\n\n }",
"public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\n }",
"public void setMaintenanceMode(String appName, boolean enable) {\n connection.execute(new AppUpdate(appName, enable), apiKey);\n }",
"private void addTypes(Injector injector, List<Class<?>> types) {\n for (Binding<?> binding : injector.getBindings().values()) {\n Key<?> key = binding.getKey();\n Type type = key.getTypeLiteral().getType();\n if (hasAnnotatedMethods(type)) {\n types.add(((Class<?>)type));\n }\n }\n if (injector.getParent() != null) {\n addTypes(injector.getParent(), types);\n }\n }",
"public void fit( double samplePoints[] , double[] observations ) {\n // Create a copy of the observations and put it into a matrix\n y.reshape(observations.length,1,false);\n System.arraycopy(observations,0, y.data,0,observations.length);\n\n // reshape the matrix to avoid unnecessarily declaring new memory\n // save values is set to false since its old values don't matter\n A.reshape(y.numRows, coef.numRows,false);\n\n // set up the A matrix\n for( int i = 0; i < observations.length; i++ ) {\n\n double obs = 1;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n A.set(i,j,obs);\n obs *= samplePoints[i];\n }\n }\n\n // process the A matrix and see if it failed\n if( !solver.setA(A) )\n throw new RuntimeException(\"Solver failed\");\n\n // solver the the coefficients\n solver.solve(y,coef);\n }",
"public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink, String password) {\n BoxAPIConnection newAPI = new SharedLinkAPIConnection(api, sharedLink, password);\n URL url = SHARED_ITEM_URL_TEMPLATE.build(newAPI.getBaseURL());\n BoxAPIRequest request = new BoxAPIRequest(newAPI, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject json = JsonObject.readFrom(response.getJSON());\n return (BoxItem.Info) BoxResource.parseInfo(newAPI, json);\n }",
"protected final boolean isValidEndTypeForPattern() {\n\n if (getEndType() == null) {\n return false;\n }\n switch (getPatternType()) {\n case DAILY:\n case WEEKLY:\n case MONTHLY:\n case YEARLY:\n return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));\n case INDIVIDUAL:\n case NONE:\n return getEndType().equals(EndType.SINGLE);\n default:\n return false;\n }\n }",
"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}"
] |
Adds a chain of vertices to the end of this list. | [
"public void addAll(Vertex vtx) {\n if (head == null) {\n head = vtx;\n } else {\n tail.next = vtx;\n }\n vtx.prev = tail;\n while (vtx.next != null) {\n vtx = vtx.next;\n }\n tail = vtx;\n }"
] | [
"public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public boolean updateSelectedItemsList(int dataIndex, boolean select) {\n boolean done = false;\n boolean contains = isSelected(dataIndex);\n if (select) {\n if (!contains) {\n if (!mMultiSelectionSupported) {\n clearSelection(false);\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList add index = %d\", dataIndex);\n mSelectedItemsList.add(dataIndex);\n done = true;\n }\n } else {\n if (contains) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList remove index = %d\", dataIndex);\n mSelectedItemsList.remove(dataIndex);\n done = true;\n }\n }\n return done;\n }",
"public Where<T, ID> le(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"public BoxAPIResponse send(ProgressListener listener) {\n if (this.api == null) {\n this.backoffCounter.reset(BoxGlobalSettings.getMaxRequestAttempts());\n } else {\n this.backoffCounter.reset(this.api.getMaxRequestAttempts());\n }\n\n while (this.backoffCounter.getAttemptsRemaining() > 0) {\n try {\n return this.trySend(listener);\n } catch (BoxAPIException apiException) {\n if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {\n throw apiException;\n }\n\n try {\n this.resetBody();\n } catch (IOException ioException) {\n throw apiException;\n }\n\n try {\n this.backoffCounter.waitBackoff();\n } catch (InterruptedException interruptedException) {\n Thread.currentThread().interrupt();\n throw apiException;\n }\n }\n }\n\n throw new RuntimeException();\n }",
"public static void clearallLocalDBs() {\n for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) {\n for (final String dbName : entry.getKey().listDatabaseNames()) {\n entry.getKey().getDatabase(dbName).drop();\n }\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<String, Field> getValueAsMap() {\n return (Map<String, Field>) type.convert(getValue(), Type.MAP);\n }",
"public static boolean validate(final String ip) {\n Matcher matcher = pattern.matcher(ip);\n return matcher.matches();\n }",
"public RedwoodConfiguration showOnlyChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } });\r\n return this;\r\n }",
"public void update(int width, int height, byte[] grayscaleData)\n {\n NativeBitmapImage.updateFromMemory(getNative(), width, height, grayscaleData);\n }"
] |
Pause component timer for current instance
@param type - of component | [
"public static void pauseTimer(final String type) {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return;\n }\n\n instance.components.get(type).pauseTimer();\n }"
] | [
"private void updateSortedServices() {\n List<T> copiedList = new ArrayList<T>(serviceMap.values());\n sortedServices = Collections.unmodifiableList(copiedList);\n if (changeListener != null) {\n changeListener.changed();\n }\n }",
"public static sslvserver_sslcipher_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcipher_binding obj = new sslvserver_sslcipher_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcipher_binding response[] = (sslvserver_sslcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags)\n {\n boolean includeTagsEnabled = !includeTags.isEmpty();\n\n for (String tag : tags)\n {\n boolean isIncluded = includeTags.contains(tag);\n boolean isExcluded = excludeTags.contains(tag);\n\n if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded))\n {\n return true;\n }\n }\n\n return false;\n }",
"public AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }",
"private static JSONArray parseChildShapesRecursive(ArrayList<Shape> childShapes) throws JSONException {\n if (childShapes != null) {\n JSONArray childShapesArray = new JSONArray();\n\n for (Shape childShape : childShapes) {\n JSONObject childShapeObject = new JSONObject();\n\n childShapeObject.put(\"resourceId\",\n childShape.getResourceId().toString());\n childShapeObject.put(\"properties\",\n parseProperties(childShape.getProperties()));\n childShapeObject.put(\"stencil\",\n parseStencil(childShape.getStencilId()));\n childShapeObject.put(\"childShapes\",\n parseChildShapesRecursive(childShape.getChildShapes()));\n childShapeObject.put(\"outgoing\",\n parseOutgoings(childShape.getOutgoings()));\n childShapeObject.put(\"bounds\",\n parseBounds(childShape.getBounds()));\n childShapeObject.put(\"dockers\",\n parseDockers(childShape.getDockers()));\n\n if (childShape.getTarget() != null) {\n childShapeObject.put(\"target\",\n parseTarget(childShape.getTarget()));\n }\n\n childShapesArray.put(childShapeObject);\n }\n\n return childShapesArray;\n }\n\n return new JSONArray();\n }",
"protected void handleResponse(int responseCode, InputStream inputStream) {\n BufferedReader rd = null;\n try {\n // Buffer the result into a string\n rd = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder sb = new StringBuilder();\n String line;\n while((line = rd.readLine()) != null) {\n sb.append(line);\n }\n log.info(\"HttpHook [\" + hookName + \"] received \" + responseCode + \" response: \" + sb);\n } catch (IOException e) {\n log.error(\"Error while reading response for HttpHook [\" + hookName + \"]\", e);\n } finally {\n if (rd != null) {\n try {\n rd.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }",
"public static base_response add(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder addresource = new sslocspresponder();\n\t\taddresource.name = resource.name;\n\t\taddresource.url = resource.url;\n\t\taddresource.cache = resource.cache;\n\t\taddresource.cachetimeout = resource.cachetimeout;\n\t\taddresource.batchingdepth = resource.batchingdepth;\n\t\taddresource.batchingdelay = resource.batchingdelay;\n\t\taddresource.resptimeout = resource.resptimeout;\n\t\taddresource.respondercert = resource.respondercert;\n\t\taddresource.trustresponder = resource.trustresponder;\n\t\taddresource.producedattimeskew = resource.producedattimeskew;\n\t\taddresource.signingcert = resource.signingcert;\n\t\taddresource.usenonce = resource.usenonce;\n\t\taddresource.insertclientcert = resource.insertclientcert;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void gobble(Iterator iter)\n {\n if (eatTheRest)\n {\n while (iter.hasNext())\n {\n tokens.add(iter.next());\n }\n }\n }",
"private static String wordShapeDigits(final String s) {\r\n char[] outChars = null;\r\n\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (Character.isDigit(c)) {\r\n if (outChars == null) {\r\n outChars = s.toCharArray();\r\n }\r\n outChars[i] = '9';\r\n }\r\n }\r\n if (outChars == null) {\r\n // no digit found\r\n return s;\r\n } else {\r\n return new String(outChars);\r\n }\r\n }"
] |
Use this API to disable Interface resources of given names. | [
"public static base_responses disable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface disableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tdisableresources[i] = new Interface();\n\t\t\t\tdisableresources[i].id = id[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"private void init() {\n validatePreSignedUrls();\n\n try {\n conn = new AWSAuthConnection(access_key, secret_access_key);\n // Determine the bucket name if prefix is set or if pre-signed URLs are being used\n if (prefix != null && prefix.length() > 0) {\n ListAllMyBucketsResponse bucket_list = conn.listAllMyBuckets(null);\n List buckets = bucket_list.entries;\n if (buckets != null) {\n boolean found = false;\n for (Object tmp : buckets) {\n if (tmp instanceof Bucket) {\n Bucket bucket = (Bucket) tmp;\n if (bucket.name.startsWith(prefix)) {\n location = bucket.name;\n found = true;\n }\n }\n }\n if (!found) {\n location = prefix + \"-\" + java.util.UUID.randomUUID().toString();\n }\n }\n }\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n location = parsedPut.getBucket();\n }\n if (!conn.checkBucketExists(location)) {\n conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage();\n }\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3Bucket(location, e.getLocalizedMessage());\n }\n }",
"ResultAction executeOperation() {\n\n assert isControllingThread();\n try {\n /** Execution has begun */\n executing = true;\n\n processStages();\n\n if (resultAction == ResultAction.KEEP) {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());\n } else {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());\n }\n } catch (RuntimeException e) {\n handleUncaughtException(e);\n ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);\n } finally {\n // On failure close any attached response streams\n if (resultAction != ResultAction.KEEP && !isBooting()) {\n synchronized (this) {\n if (responseStreams != null) {\n int i = 0;\n for (OperationResponse.StreamEntry is : responseStreams.values()) {\n try {\n is.getStream().close();\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.debugf(e, \"Failed closing stream at index %d\", i);\n }\n i++;\n }\n responseStreams.clear();\n }\n }\n }\n }\n\n\n return resultAction;\n }",
"public Sequence compile( String equation , boolean assignment, boolean debug ) {\n\n functions.setManagerTemp(managerTemp);\n\n Sequence sequence = new Sequence();\n TokenList tokens = extractTokens(equation,managerTemp);\n\n if( tokens.size() < 3 )\n throw new RuntimeException(\"Too few tokens\");\n\n TokenList.Token t0 = tokens.getFirst();\n\n if( t0.word != null && t0.word.compareToIgnoreCase(\"macro\") == 0 ) {\n parseMacro(tokens,sequence);\n } else {\n insertFunctionsAndVariables(tokens);\n insertMacros(tokens);\n if (debug) {\n System.out.println(\"Parsed tokens:\\n------------\");\n tokens.print();\n System.out.println();\n }\n\n // Get the results variable\n if (t0.getType() != Type.VARIABLE && t0.getType() != Type.WORD) {\n compileTokens(sequence,tokens);\n // If there's no output then this is acceptable, otherwise it's assumed to be a bug\n // If there's no output then a configuration was changed\n Variable variable = tokens.getFirst().getVariable();\n if( variable != null ) {\n if( assignment )\n throw new IllegalArgumentException(\"No assignment to an output variable could be found. Found \" + t0);\n else {\n sequence.output = variable; // set this to be the output for print()\n }\n }\n\n } else {\n compileAssignment(sequence, tokens, t0);\n }\n\n if (debug) {\n System.out.println(\"Operations:\\n------------\");\n for (int i = 0; i < sequence.operations.size(); i++) {\n System.out.println(sequence.operations.get(i).name());\n }\n }\n }\n\n return sequence;\n }",
"public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }",
"@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}",
"public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {\n\t\tif (clazz1 == null) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tif (clazz2 == null) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz1.isAssignableFrom(clazz2)) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz2.isAssignableFrom(clazz1)) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tClass<?> ancestor = clazz1;\n\t\tdo {\n\t\t\tancestor = ancestor.getSuperclass();\n\t\t\tif (ancestor == null || Object.class.equals(ancestor)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\twhile (!ancestor.isAssignableFrom(clazz2));\n\t\treturn ancestor;\n\t}",
"public static base_responses update(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder updateresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslocspresponder();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].cache = resources[i].cache;\n\t\t\t\tupdateresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\tupdateresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\tupdateresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\tupdateresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\tupdateresources[i].respondercert = resources[i].respondercert;\n\t\t\t\tupdateresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\tupdateresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\tupdateresources[i].signingcert = resources[i].signingcert;\n\t\t\t\tupdateresources[i].usenonce = resources[i].usenonce;\n\t\t\t\tupdateresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static int cudnnPoolingForward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnPoolingForwardNative(handle, poolingDesc, alpha, xDesc, x, beta, yDesc, y));\n }",
"private static boolean isValidPropertyClass(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n return Number.class.isAssignableFrom(type) || type == String.class || Date.class.isAssignableFrom(type) || type == Boolean.class;\n }"
] |
Use this API to fetch appfwjsoncontenttype resource of given name . | [
"public static appfwjsoncontenttype get(nitro_service service, String jsoncontenttypevalue) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tobj.set_jsoncontenttypevalue(jsoncontenttypevalue);\n\t\tappfwjsoncontenttype response = (appfwjsoncontenttype) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public boolean overrides(Link other) {\n if (other.getStatus() == LinkStatus.ASSERTED &&\n status != LinkStatus.ASSERTED)\n return false;\n else if (status == LinkStatus.ASSERTED &&\n other.getStatus() != LinkStatus.ASSERTED)\n return true;\n\n // the two links are from equivalent sources of information, so we\n // believe the most recent\n\n return timestamp > other.getTimestamp();\n }",
"private void logOriginalRequestHistory(String requestType,\n HttpServletRequest request, History history) {\n logger.info(\"Storing original request history\");\n history.setRequestType(requestType);\n history.setOriginalRequestHeaders(HttpUtilities.getHeaders(request));\n history.setOriginalRequestURL(request.getRequestURL().toString());\n history.setOriginalRequestParams(request.getQueryString() == null ? \"\" : request.getQueryString());\n logger.info(\"Done storing\");\n }",
"private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {\n if(response == null) {\n logger.warn(\"RoutingTimedout on waiting for async ops; parallelResponseToWait: \"\n + numNodesPendingResponse + \"; preferred-1: \" + (preferred - 1)\n + \"; quorumOK: \" + quorumSatisfied + \"; zoneOK: \" + zonesSatisfied);\n } else {\n numNodesPendingResponse = numNodesPendingResponse - 1;\n numResponsesGot = numResponsesGot + 1;\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handling async put error\");\n }\n if(response.getValue() instanceof QuotaExceededException) {\n /**\n * TODO Not sure if we need to count this Exception for\n * stats or silently ignore and just log a warning. While\n * QuotaExceededException thrown from other places mean the\n * operation failed, this one does not fail the operation\n * but instead stores slops. Introduce a new Exception in\n * client side to just monitor how mamy Async writes fail on\n * exceeding Quota?\n * \n */\n if(logger.isDebugEnabled()) {\n logger.debug(\"Received quota exceeded exception after a successful \"\n + pipeline.getOperation().getSimpleName() + \" call on node \"\n + response.getNode().getId() + \", store '\"\n + pipelineData.getStoreName() + \"', master-node '\"\n + pipelineData.getMaster().getId() + \"'\");\n }\n } else if(handleResponseError(response, pipeline, failureDetector)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key\n + \"} severe async put error, exiting parallel put stage\");\n }\n\n return;\n }\n if(PipelineRoutedStore.isSlopableFailure(response.getValue())\n || response.getValue() instanceof QuotaExceededException) {\n /**\n * We want to slop ParallelPuts which fail due to\n * QuotaExceededException.\n * \n * TODO Though this is not the right way of doing things, in\n * order to avoid inconsistencies and data loss, we chose to\n * slop the quota failed parallel puts.\n * \n * As a long term solution - 1) either Quota management\n * should be hidden completely in a routing layer like\n * Coordinator or 2) the Server should be able to\n * distinguish between serial and parallel puts and should\n * only quota for serial puts\n * \n */\n pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());\n }\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handled async put error\");\n }\n\n } else {\n pipelineData.incrementSuccesses();\n failureDetector.recordSuccess(response.getNode(), response.getRequestTime());\n pipelineData.getZoneResponses().add(response.getNode().getZoneId());\n }\n }\n }",
"public float rotateToFaceCamera(final Widget widget) {\n final float yaw = getMainCameraRigYaw();\n GVRTransform t = getMainCameraRig().getHeadTransform();\n widget.rotateWithPivot(t.getRotationW(), 0, t.getRotationY(), 0, 0, 0, 0);\n return yaw;\n }",
"public boolean isIPv4Compatible() {\n\t\treturn getSegment(0).isZero() && getSegment(1).isZero() && getSegment(2).isZero() &&\n\t\t\t\tgetSegment(3).isZero() && getSegment(4).isZero() && getSegment(5).isZero();\n\t}",
"private void initPropertyBundle() throws CmsLoaderException, CmsException, IOException {\n\n for (Locale l : m_locales) {\n String filePath = m_sitepath + m_basename + \"_\" + l.toString();\n CmsResource resource = null;\n if (m_cms.existsResource(\n filePath,\n CmsResourceFilter.requireType(\n OpenCms.getResourceManager().getResourceType(BundleType.PROPERTY.toString())))) {\n resource = m_cms.readResource(filePath);\n SortedProperties props = new SortedProperties();\n CmsFile file = m_cms.readFile(resource);\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_keyset.updateKeySet(null, props.keySet());\n m_bundleFiles.put(l, resource);\n }\n }\n\n }",
"public static policydataset get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tobj.set_name(name);\n\t\tpolicydataset response = (policydataset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }",
"protected void processProjectListItem(Map<Integer, String> result, Row row)\n {\n Integer id = row.getInteger(\"PROJ_ID\");\n String name = row.getString(\"PROJ_NAME\");\n result.put(id, name);\n }"
] |
Adds a "Post Run" task to the collection.
@param taskItem the "Post Run" task | [
"public void add(final IndexableTaskItem taskItem) {\n this.dependsOnTaskGroup.addPostRunDependentTaskGroup(taskItem.taskGroup());\n this.collection.add(taskItem);\n }"
] | [
"public static String wordShape(String inStr, int wordShaper, Collection<String> knownLCWords) {\r\n // this first bit is for backwards compatibility with how things were first\r\n // implemented, where the word shaper name encodes whether to useLC.\r\n // If the shaper is in the old compatibility list, then a specified\r\n // list of knownLCwords is ignored\r\n if (knownLCWords != null && dontUseLC(wordShaper)) {\r\n knownLCWords = null;\r\n }\r\n switch (wordShaper) {\r\n case NOWORDSHAPE:\r\n return inStr;\r\n case WORDSHAPEDAN1:\r\n return wordShapeDan1(inStr);\r\n case WORDSHAPECHRIS1:\r\n return wordShapeChris1(inStr);\r\n case WORDSHAPEDAN2:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2USELC:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIO:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIOUSELC:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1USELC:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPECHRIS2:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS2USELC:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS3:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS3USELC:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS4:\r\n return wordShapeChris4(inStr, false, knownLCWords);\r\n case WORDSHAPEDIGITS:\r\n return wordShapeDigits(inStr);\r\n default:\r\n throw new IllegalStateException(\"Bad WordShapeClassifier\");\r\n }\r\n }",
"public static vpnvserver_responderpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_responderpolicy_binding obj = new vpnvserver_responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_responderpolicy_binding response[] = (vpnvserver_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public FloatBuffer getFloatVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n FloatBuffer data = buffer.asFloatBuffer();\n if (!NativeVertexBuffer.getFloatVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }",
"private String listToCSV(List<String> list) {\n String csvStr = \"\";\n for (String item : list) {\n csvStr += \",\" + item;\n }\n\n return csvStr.length() > 1 ? csvStr.substring(1) : csvStr;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public Color segmentColor(final int segment, final boolean front) {\n final ByteBuffer bytes = getData();\n if (isColor) {\n final int base = segment * 6;\n final int backHeight = segmentHeight(segment, false);\n if (backHeight == 0) {\n return Color.BLACK;\n }\n final int maxLevel = front? 255 : 191;\n final int red = Util.unsign(bytes.get(base + 3)) * maxLevel / backHeight;\n final int green = Util.unsign(bytes.get(base + 4)) * maxLevel / backHeight;\n final int blue = Util.unsign(bytes.get(base + 5)) * maxLevel / backHeight;\n return new Color(red, green, blue);\n } else {\n final int intensity = getData().get(segment * 2 + 1) & 0x07;\n return (intensity >= 5) ? INTENSE_COLOR : NORMAL_COLOR;\n }\n }",
"public String toRomanNumeral() {\n\t\tif (this.romanString == null) {\n\t\t\tthis.romanString = \"\";\n\t\t\tint remainder = this.value;\n\t\t\tfor (int i = 0; i < BASIC_VALUES.length; i++) {\n\t\t\t\twhile (remainder >= BASIC_VALUES[i]) {\n\t\t\t\t\tthis.romanString += BASIC_ROMAN_NUMERALS[i];\n\t\t\t\t\tremainder -= BASIC_VALUES[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this.romanString;\n\t}",
"public LogStreamResponse getLogs(Log.LogRequestBuilder logRequest) {\n return connection.execute(new Log(logRequest), apiKey);\n }",
"private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\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 }"
] |
Send a get artifacts request
@param hasLicense
@return list of artifact
@throws GrapesCommunicationException | [
"public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());\n final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get artifacts\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(ArtifactList.class);\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n public Map<String, Field> getValueAsMap() {\n return (Map<String, Field>) type.convert(getValue(), Type.MAP);\n }",
"private String getPropertyLabel(PropertyIdValue propertyIdValue) {\n\t\tPropertyRecord propertyRecord = this.propertyRecords\n\t\t\t\t.get(propertyIdValue);\n\t\tif (propertyRecord == null || propertyRecord.propertyDocument == null) {\n\t\t\treturn propertyIdValue.getId();\n\t\t} else {\n\t\t\treturn getLabel(propertyIdValue, propertyRecord.propertyDocument);\n\t\t}\n\t}",
"public static boolean isResourceTypeIdFree(int id) {\n\n try {\n OpenCms.getResourceManager().getResourceType(id);\n } catch (CmsLoaderException e) {\n return true;\n }\n return false;\n }",
"public static base_responses apply(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 applyresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tapplyresources[i] = new nspbr6();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, applyresources,\"apply\");\n\t\t}\n\t\treturn result;\n\t}",
"public static Integer getDay(Day day)\n {\n Integer result = null;\n if (day != null)\n {\n result = DAY_MAP.get(day);\n }\n return (result);\n }",
"private void validate() {\n if (Strings.emptyToNull(random) == null) {\n random = Strings.emptyToNull(getProject().getProperty(SYSPROP_RANDOM_SEED())); \n }\n \n if (random == null) {\n throw new BuildException(\"Required attribute 'seed' must not be empty. Look at <junit4:pickseed>.\");\n }\n \n long[] seeds = SeedUtils.parseSeedChain(random);\n if (seeds.length < 1) {\n throw new BuildException(\"Random seed is required.\");\n }\n \n if (values.isEmpty() && !allowUndefined) {\n throw new BuildException(\"No values to pick from and allowUndefined=false.\");\n }\n }",
"private void writeMap(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> map = (Map<String, Object>) value;\n m_writer.writeStartObject(fieldName);\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n Object entryValue = entry.getValue();\n if (entryValue != null)\n {\n DataType type = TYPE_MAP.get(entryValue.getClass().getName());\n if (type == null)\n {\n type = DataType.STRING;\n entryValue = entryValue.toString();\n }\n writeField(entry.getKey(), type, entryValue);\n }\n }\n m_writer.writeEndObject();\n }",
"public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }",
"private static void embedSvgGraphic(\n final SVGElement svgRoot,\n final SVGElement newSvgRoot, final Document newDocument,\n final Dimension targetSize, final Double rotation) {\n final String originalWidth = svgRoot.getAttributeNS(null, \"width\");\n final String originalHeight = svgRoot.getAttributeNS(null, \"height\");\n /*\n * To scale the SVG graphic and to apply the rotation, we distinguish two\n * cases: width and height is set on the original SVG or not.\n *\n * Case 1: Width and height is set\n * If width and height is set, we wrap the original SVG into 2 new SVG elements\n * and a container element.\n *\n * Example:\n * Original SVG:\n * <svg width=\"100\" height=\"100\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg width=\"100%\" height=\"100%\" viewBox=\"0 0 100 100\">\n * <svg width=\"100\" height=\"100\"></svg>\n * </svg>\n * </g>\n * </svg>\n *\n * The requested size is set on the outermost <svg>. Then, the rotation is applied to the\n * <g> container and the scaling is achieved with the viewBox parameter on the 2nd <svg>.\n *\n *\n * Case 2: Width and height is not set\n * In this case the original SVG is wrapped into just one container and one new SVG element.\n * The rotation is set on the container, and the scaling happens automatically.\n *\n * Example:\n * Original SVG:\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n * </g>\n * </svg>\n */\n if (!StringUtils.isEmpty(originalWidth) && !StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Element wrapperSvg = newDocument.createElementNS(SVG_NS, \"svg\");\n wrapperSvg.setAttributeNS(null, \"width\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"height\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"viewBox\", \"0 0 \" + originalWidth\n + \" \" + originalHeight);\n wrapperContainer.appendChild(wrapperSvg);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperSvg.appendChild(svgRootImported);\n } else if (StringUtils.isEmpty(originalWidth) && StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperContainer.appendChild(svgRootImported);\n } else {\n throw new IllegalArgumentException(\n \"Unsupported or invalid north-arrow SVG graphic: The same unit (px, em, %, ...) must be\" +\n \" \" +\n \"used for `width` and `height`.\");\n }\n }"
] |
Schedules the task with a fixed delay period and an initialDelay period. This functions
like the normal java Timer.
@param task
@param initialDelay
@param fixedDelay | [
"public void schedule(BackoffTask task, long initialDelay, long fixedDelay) {\n \tsynchronized (queue) {\n\t \tstart();\n\t queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay));\n \t}\n }"
] | [
"@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}",
"private String getValueFromProp(final String propValue) {\n\n String value = propValue;\n // remove quotes\n value = value.trim();\n if ((value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.substring(1, value.length() - 1);\n }\n return value;\n }",
"public AT_Row setPaddingRight(int paddingRight) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public void signIn(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.put(connection, connection);\n }",
"private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }",
"public void checkAllRequirementsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (Field field: this.dependantsInJson) {\n final Collection<String> requirements = this.dependantToRequirementsMap.get(field);\n if (!requirements.isEmpty()) {\n errors.append(\"\\n\");\n String type = field.getType().getName();\n if (field.getType().isArray()) {\n type = field.getType().getComponentType().getName() + \"[]\";\n }\n errors.append(\"\\t* \").append(type).append(' ').append(field.getName()).append(\" depends on \")\n .append(requirements);\n }\n }\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @Requires dependencies of '\" +\n currentPath + \"': \" + errors);\n }",
"public PhotoList<Photo> getUntagged(int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UNTAGGED);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }",
"public Where<T, ID> or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) {\n\t\tClause[] clauses = buildClauseArray(others, \"OR\");\n\t\tClause secondClause = pop(\"OR\");\n\t\tClause firstClause = pop(\"OR\");\n\t\taddClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.OR_OPERATION));\n\t\treturn this;\n\t}",
"private static void parseDockers(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"dockers\")) {\n ArrayList<Point> dockers = new ArrayList<Point>();\n\n JSONArray dockersObject = modelJSON.getJSONArray(\"dockers\");\n for (int i = 0; i < dockersObject.length(); i++) {\n Double x = dockersObject.getJSONObject(i).getDouble(\"x\");\n Double y = dockersObject.getJSONObject(i).getDouble(\"y\");\n dockers.add(new Point(x,\n y));\n }\n if (dockers.size() > 0) {\n current.setDockers(dockers);\n }\n }\n }"
] |
Creates an immutable copy that we can cache. | [
"public MethodKey createCopy() {\n int size = getParameterCount();\n Class[] paramTypes = new Class[size];\n for (int i = 0; i < size; i++) {\n paramTypes[i] = getParameterType(i);\n }\n return new DefaultMethodKey(sender, name, paramTypes, isCallToSuper);\n }"
] | [
"public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected void reportProgress(String taskDecription) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.setTaskName(taskDecription);\n }\n }",
"public void terminateAllConnections(){\r\n\t\tthis.terminationLock.lock();\r\n\t\ttry{\r\n\t\t\t// close off all connections.\r\n\t\t\tfor (int i=0; i < this.pool.partitionCount; i++) {\r\n\t\t\t\tthis.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\t\t\t\tList<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); \r\n\t\t\t\tthis.pool.partitions[i].getFreeConnections().drainTo(clist);\r\n\t\t\t\tfor (ConnectionHandle c: clist){\r\n\t\t\t\t\tthis.pool.destroyConnection(c);\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t} finally {\r\n\t\t\tthis.terminationLock.unlock();\r\n\t\t}\r\n\t}",
"private static void writeUtf16Bom(OutputStream stream, boolean bigEndian) throws IOException {\n if (bigEndian) {\n stream.write(-2);\n stream.write(-1);\n } else {\n stream.write(-1);\n stream.write(-2);\n }\n }",
"public static ProtocolConnectionManager create(final Connection connection, final ConnectionOpenHandler openHandler) {\n return create(new EstablishedConnection(connection, openHandler));\n }",
"public List<T> parseList(JsonParser jsonParser) throws IOException {\n List<T> list = new ArrayList<>();\n if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n list.add(parse(jsonParser));\n }\n }\n return list;\n }",
"public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }",
"public String putDocument(Document document) {\n\t\tString key = UUID.randomUUID().toString();\n\t\tdocumentMap.put(key, document);\n\t\treturn key;\n\t}",
"public void purge(String cacheKey) {\n try {\n if (useMemoryCache) {\n if (memoryCache != null) {\n memoryCache.remove(cacheKey);\n }\n }\n\n if (useDiskCache) {\n if (diskLruCache != null) {\n diskLruCache.remove(cacheKey);\n }\n }\n } catch (Exception e) {\n Log.w(TAG, \"Could not remove entry in cache purge\", e);\n }\n }"
] |
Creates a scenario with 3 different steps classes.
To share state between the different steps instances use the
{@link com.tngtech.jgiven.annotation.ScenarioState} annotation
@param givenClass the Given steps class
@param whenClass the When steps class
@param thenClass the Then steps class
@return the new scenario | [
"public static <GIVEN, WHEN, THEN> Scenario<GIVEN, WHEN, THEN> create( Class<GIVEN> givenClass, Class<WHEN> whenClass,\n Class<THEN> thenClass ) {\n return new Scenario<GIVEN, WHEN, THEN>( givenClass, whenClass, thenClass );\n }"
] | [
"public static DocumentBuilder getXmlParser() {\r\n DocumentBuilder db = null;\r\n try {\r\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n dbf.setValidating(false);\r\n\r\n //Disable DTD loading and validation\r\n //See http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\r\n\r\n db = dbf.newDocumentBuilder();\r\n db.setErrorHandler(new SAXErrorHandler());\r\n\r\n } catch (ParserConfigurationException e) {\r\n System.err.printf(\"%s: Unable to create XML parser\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n\r\n } catch(UnsupportedOperationException e) {\r\n System.err.printf(\"%s: API error while setting up XML parser. Check your JAXP version\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n }\r\n\r\n return db;\r\n }",
"private ProjectFile readFile(File file) throws MPXJException\n {\n try\n {\n String url = \"jdbc:sqlite:\" + file.getAbsolutePath();\n Properties props = new Properties();\n m_connection = org.sqlite.JDBC.createConnection(url, props);\n\n m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n m_dayTimeIntervals = xpath.compile(\"/array/dayTimeInterval\");\n m_entityMap = new HashMap<String, Integer>();\n return read();\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT, ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n\n m_documentBuilder = null;\n m_dayTimeIntervals = null;\n m_entityMap = null;\n }\n }",
"public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }",
"public void afterMaterialization(IndirectionHandler handler, Object materializedObject)\r\n {\r\n try\r\n {\r\n Identity oid = handler.getIdentity();\r\n if (log.isDebugEnabled())\r\n log.debug(\"deferred registration: \" + oid);\r\n if(!isOpen())\r\n {\r\n log.error(\"Proxy object materialization outside of a running tx, obj=\" + oid);\r\n try{throw new Exception(\"Proxy object materialization outside of a running tx, obj=\" + oid);}catch(Exception e)\r\n {\r\n e.printStackTrace();\r\n }\r\n }\r\n ClassDescriptor cld = getBroker().getClassDescriptor(materializedObject.getClass());\r\n RuntimeObject rt = new RuntimeObject(materializedObject, oid, cld, false, false);\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n catch (Throwable t)\r\n {\r\n log.error(\"Register materialized object with this tx failed\", t);\r\n throw new LockNotGrantedException(t.getMessage());\r\n }\r\n unregisterFromIndirectionHandler(handler);\r\n }",
"public static base_responses disable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 disableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tdisableresources[i] = new nsacl6();\n\t\t\t\tdisableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}",
"static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }",
"public Operation.Info create( char op , Variable input ) {\n switch( op ) {\n case '\\'':\n return Operation.transpose(input, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }",
"@Nonnull\n private ReferencedEnvelope getFeatureBounds(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final MapAttributeValues mapValues, final ExecutionContext context) {\n final MapfishMapContext mapContext = createMapContext(mapValues);\n\n String layerName = mapValues.zoomToFeatures.layer;\n ReferencedEnvelope bounds = new ReferencedEnvelope();\n for (MapLayer layer: mapValues.getLayers()) {\n context.stopIfCanceled();\n\n if ((!StringUtils.isEmpty(layerName) && layerName.equals(layer.getName())) ||\n (StringUtils.isEmpty(layerName) && layer instanceof AbstractFeatureSourceLayer)) {\n AbstractFeatureSourceLayer featureLayer = (AbstractFeatureSourceLayer) layer;\n FeatureSource<?, ?> featureSource =\n featureLayer.getFeatureSource(clientHttpRequestFactory, mapContext);\n FeatureCollection<?, ?> features;\n try {\n features = featureSource.getFeatures();\n } catch (IOException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n\n if (!features.isEmpty()) {\n final ReferencedEnvelope curBounds = features.getBounds();\n bounds.expandToInclude(curBounds);\n }\n }\n }\n\n return bounds;\n }",
"private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}"
] |
flushes log queue, this actually writes combined log message into system log | [
"void flushLogQueue() {\n Set<String> problems = new LinkedHashSet<String>();\n synchronized (messageQueue) {\n Iterator<LogEntry> i = messageQueue.iterator();\n while (i.hasNext()) {\n problems.add(\"\\t\\t\" + i.next().getMessage() + \"\\n\");\n i.remove();\n }\n }\n if (!problems.isEmpty()) {\n logger.transformationWarnings(target.getHostName(), problems);\n }\n }"
] | [
"public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}",
"public void setBeliefValue(String agent_name, final String belief_name,\n final Object new_value, Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n bia.getBeliefbase().getBelief(belief_name)\n .setFact(new_value);\n return null;\n }\n }).get(new ThreadSuspendable());\n }",
"void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}",
"private void initPropertyBundle() throws CmsLoaderException, CmsException, IOException {\n\n for (Locale l : m_locales) {\n String filePath = m_sitepath + m_basename + \"_\" + l.toString();\n CmsResource resource = null;\n if (m_cms.existsResource(\n filePath,\n CmsResourceFilter.requireType(\n OpenCms.getResourceManager().getResourceType(BundleType.PROPERTY.toString())))) {\n resource = m_cms.readResource(filePath);\n SortedProperties props = new SortedProperties();\n CmsFile file = m_cms.readFile(resource);\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_keyset.updateKeySet(null, props.keySet());\n m_bundleFiles.put(l, resource);\n }\n }\n\n }",
"private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }",
"int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }",
"public static final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return result;\n }",
"private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }",
"private String formatRelationList(List<Relation> value)\n {\n String result = null;\n\n if (value != null && value.size() != 0)\n {\n StringBuilder sb = new StringBuilder();\n for (Relation relation : value)\n {\n if (sb.length() != 0)\n {\n sb.append(m_delimiter);\n }\n\n sb.append(formatRelation(relation));\n }\n\n result = sb.toString();\n }\n\n return (result);\n }"
] |
Plots the MSD curve for trajectory t
@param t Trajectory to calculate the msd curve
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param msdeval Evaluates the mean squared displacment | [
"public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}"
] | [
"private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }",
"@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\n }\n }",
"@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 byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }",
"static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }",
"public List<StepCandidate> prioritise(String stepAsText, List<StepCandidate> candidates) {\n return prioritisingStrategy.prioritise(stepAsText, candidates);\n }",
"public static boolean isSuccess(JsonRtn jsonRtn) {\n if (jsonRtn == null) {\n return false;\n }\n\n String errCode = jsonRtn.getErrCode();\n if (StringUtils.isEmpty(errCode) || StringUtils.equals(WECHAT_JSON_RTN_SUCCESS_CODE, errCode)) {\n return true;\n }\n\n return false;\n }",
"double getThreshold(String x, String y, double p) {\r\n\t\treturn 2 * Math.max(x.length(), y.length()) * (1 - p);\r\n\t}",
"public void setEnable(boolean flag)\n {\n if (mEnabled == flag)\n {\n return;\n }\n mEnabled = flag;\n if (flag)\n {\n mContext.registerDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().addListener(this);\n mAudioEngine.resume();\n }\n else\n {\n mContext.unregisterDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().removeListener(this);\n mAudioEngine.pause();\n }\n }"
] |
Get the TagsInterface for working with Flickr Tags.
@return The TagsInterface | [
"@Override\n public TagsInterface getTagsInterface() {\n if (tagsInterface == null) {\n tagsInterface = new TagsInterface(apiKey, sharedSecret, transport);\n }\n return tagsInterface;\n }"
] | [
"public T addModule(final String moduleName, final String slot, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.ADD, NO_CONTENT));\n return returnThis();\n }",
"private void processPredecessor(Task task, MapRow row)\n {\n Task predecessor = m_taskMap.get(row.getUUID(\"PREDECESSOR_UUID\"));\n if (predecessor != null)\n {\n task.addPredecessor(predecessor, row.getRelationType(\"RELATION_TYPE\"), row.getDuration(\"LAG\"));\n }\n }",
"private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public Task<Void> updateSyncFrequency(@NonNull final SyncFrequency syncFrequency) {\n return this.dispatcher.dispatchTask(new Callable<Void>() {\n @Override\n public Void call() throws Exception {\n SyncImpl.this.proxy.updateSyncFrequency(syncFrequency);\n return null;\n }\n });\n }",
"public List<Gallery> getList(String userId, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n parameters.put(\"user_id\", userId);\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element element = response.getPayload();\r\n GalleryList<Gallery> galleries = new GalleryList<Gallery>();\r\n galleries.setPage(element.getAttribute(\"page\"));\r\n galleries.setPages(element.getAttribute(\"pages\"));\r\n galleries.setPerPage(element.getAttribute(\"per_page\"));\r\n galleries.setTotal(element.getAttribute(\"total\"));\r\n\r\n NodeList galleryNodes = element.getElementsByTagName(\"gallery\");\r\n for (int i = 0; i < galleryNodes.getLength(); i++) {\r\n Element galleryElement = (Element) galleryNodes.item(i);\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"primary_photo_farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"primary_photo_secret\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n\r\n galleries.add(gallery);\r\n }\r\n return galleries;\r\n }",
"protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public void forAllValuePairs(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME, \"attributes\");\r\n String defaultValue = attributes.getProperty(ATTRIBUTE_DEFAULT_RIGHT, \"\");\r\n String attributePairs = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), name);\r\n\r\n if ((attributePairs == null) || (attributePairs.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n String token;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(attributePairs); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos >= 0)\r\n {\r\n _curPairLeft = token.substring(0, pos);\r\n _curPairRight = (pos < token.length() - 1 ? token.substring(pos + 1) : defaultValue);\r\n }\r\n else\r\n {\r\n _curPairLeft = token;\r\n _curPairRight = defaultValue;\r\n }\r\n if (_curPairLeft.length() > 0)\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }",
"protected void processResourceBaseline(Row row)\n {\n Integer id = row.getInteger(\"RES_UID\");\n Resource resource = m_project.getResourceByUniqueID(id);\n if (resource != null)\n {\n int index = row.getInt(\"RB_BASE_NUM\");\n\n resource.setBaselineWork(index, row.getDuration(\"RB_BASE_WORK\"));\n resource.setBaselineCost(index, row.getCurrency(\"RB_BASE_COST\"));\n }\n }",
"public EventBus emitAsync(String event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }"
] |
Checks if the query should be executed using the debug mode where the security restrictions do not apply.
@param cms the current context.
@param query the query to execute.
@return a flag, indicating, if the query should be performed in debug mode. | [
"private boolean isDebug(CmsObject cms, CmsSolrQuery query) {\r\n\r\n String[] debugSecretValues = query.remove(REQUEST_PARAM_DEBUG_SECRET);\r\n String debugSecret = (debugSecretValues == null) || (debugSecretValues.length < 1)\r\n ? null\r\n : debugSecretValues[0];\r\n if ((null != debugSecret) && !debugSecret.trim().isEmpty() && (null != m_handlerDebugSecretFile)) {\r\n try {\r\n CmsFile secretFile = cms.readFile(m_handlerDebugSecretFile);\r\n String secret = new String(secretFile.getContents(), CmsFileUtil.getEncoding(cms, secretFile));\r\n return secret.trim().equals(debugSecret.trim());\r\n } catch (Exception e) {\r\n LOG.info(\r\n \"Failed to read secret file for index \\\"\"\r\n + getName()\r\n + \"\\\" at path \\\"\"\r\n + m_handlerDebugSecretFile\r\n + \"\\\".\");\r\n }\r\n }\r\n return false;\r\n }"
] | [
"@Override\n public void removeCapabilityRequirement(RuntimeRequirementRegistration requirementRegistration) {\n // We don't know if this got registered as an runtime-only requirement or a hard one\n // so clean it from both maps\n writeLock.lock();\n try {\n removeRequirement(requirementRegistration, false);\n removeRequirement(requirementRegistration, true);\n } finally {\n writeLock.unlock();\n }\n }",
"public int getLeadingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong front = network ? getDivision(0).getMaxValue() : 0;\n\t\tint prefixLen = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != front) {\n\t\t\t\treturn prefixLen + seg.getLeadingBitCount(network);\n\t\t\t}\n\t\t\tprefixLen += seg.getBitCount();\n\t\t}\n\t\treturn prefixLen;\n\t}",
"protected AbstractColumn buildSimpleColumn() {\n\t\tSimpleColumn column = new SimpleColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumnProperty.getFieldProperties().putAll(fieldProperties);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setFieldDescription(fieldDescription);\n\t\treturn column;\n\t}",
"public synchronized void hide() {\n if (focusedQuad != null) {\n\n mDefocusAnimationFactory.create(focusedQuad)\n .setRequestLayoutOnTargetChange(false)\n .start().finish();\n\n focusedQuad = null;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"hide Picker!\");\n }",
"public List<LogSegment> trunc(int newStart) {\n if (newStart < 0) {\n throw new IllegalArgumentException(\"Starting index must be positive.\");\n }\n while (true) {\n List<LogSegment> curr = contents.get();\n int newLength = Math.max(curr.size() - newStart, 0);\n List<LogSegment> updatedList = new ArrayList<LogSegment>(curr.subList(Math.min(newStart, curr.size() - 1),\n curr.size()));\n if (contents.compareAndSet(curr, updatedList)) {\n return curr.subList(0, curr.size() - newLength);\n }\n }\n }",
"public void ifHasMemberWithTag(String template, Properties attributes) throws XDocletException\r\n {\r\n ArrayList allMemberNames = new ArrayList();\r\n HashMap allMembers = new HashMap();\r\n boolean hasTag = false;\r\n\r\n addMembers(allMemberNames, allMembers, getCurrentClass(), null, null, null);\r\n for (Iterator it = allMemberNames.iterator(); it.hasNext(); ) {\r\n XMember member = (XMember) allMembers.get(it.next());\r\n\r\n if (member instanceof XField) {\r\n setCurrentField((XField)member);\r\n if (hasTag(attributes, FOR_FIELD)) {\r\n hasTag = true;\r\n }\r\n setCurrentField(null);\r\n }\r\n else if (member instanceof XMethod) {\r\n setCurrentMethod((XMethod)member);\r\n if (hasTag(attributes, FOR_METHOD)) {\r\n hasTag = true;\r\n }\r\n setCurrentMethod(null);\r\n }\r\n if (hasTag) {\r\n generate(template);\r\n break;\r\n }\r\n }\r\n }",
"public void close() {\n boolean isPreviouslyClosed = isClosed.getAndSet(true);\n if (isPreviouslyClosed) {\n return;\n }\n\n AdminClient client;\n while ((client = clientCache.poll()) != null) {\n client.close();\n }\n }",
"private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }",
"public static List<int[]> createList( int N )\n {\n int data[] = new int[ N ];\n for( int i = 0; i < data.length; i++ ) {\n data[i] = -1;\n }\n\n List<int[]> ret = new ArrayList<int[]>();\n\n createList(data,0,-1,ret);\n\n return ret;\n }"
] |
Generates the context diagram for a single class | [
"private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)\n\t throws IOException {\n Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {\n public int compare(ClassDoc cd1, ClassDoc cd2) {\n return cd1.name().compareTo(cd2.name());\n }\n });\n for (ClassDoc classDoc : root.classes())\n classDocs.add(classDoc);\n\n\tContextView view = null;\n\tfor (ClassDoc classDoc : classDocs) {\n\t try {\n\t\tif(view == null)\n\t\t view = new ContextView(outputFolder, classDoc, root, opt);\n\t\telse\n\t\t view.setContextCenter(classDoc);\n\t\tUmlGraph.buildGraph(root, view, classDoc);\n\t\trunGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);\n\t\talterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),\n\t\t\tclassDoc.name() + \".html\", Pattern.compile(\".*(Class|Interface|Enum) \" + classDoc.name() + \".*\") , root);\n\t } catch (Exception e) {\n\t\tthrow new RuntimeException(\"Error generating \" + classDoc.name(), e);\n\t }\n\t}\n }"
] | [
"private static void listRelationships(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.print(task.getID());\n System.out.print('\\t');\n System.out.print(task.getName());\n System.out.print('\\t');\n\n dumpRelationList(task.getPredecessors());\n System.out.print('\\t');\n dumpRelationList(task.getSuccessors());\n System.out.println();\n }\n }",
"public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) {\n dest.clear();\n\n if (key != null) {\n dest.key = new Key(key);\n }\n\n for (int i = 0; i < timeStamps.size(); i++) {\n long time = timeStamps.get(i);\n if (timestampTest.test(time)) {\n dest.add(time, values.get(i));\n }\n }\n }",
"private void addDefaults()\n {\n this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Mandatory\", MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), \"Optional\", OPTIONAL, 1000, true));\n this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), \"Potential Issues\", POTENTIAL, 1000, true));\n this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Cloud Mandatory\", CLOUD_MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), \"Information\", INFORMATION, 1000, true));\n }",
"private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }",
"public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\n }",
"private String searchForPersistentSubType(XClass type)\r\n {\r\n ArrayList queue = new ArrayList();\r\n XClass subType;\r\n\r\n queue.add(type);\r\n while (!queue.isEmpty())\r\n {\r\n subType = (XClass)queue.get(0);\r\n queue.remove(0);\r\n if (_model.hasClass(subType.getQualifiedName()))\r\n {\r\n return subType.getQualifiedName();\r\n }\r\n addDirectSubTypes(subType, queue);\r\n }\r\n return null;\r\n }",
"private void writePriorityField(String fieldName, Object value) throws IOException\n {\n m_writer.writeNameValuePair(fieldName, ((Priority) value).getValue());\n }",
"public static double SymmetricKullbackLeibler(double[] p, double[] q) {\n double dist = 0;\n for (int i = 0; i < p.length; i++) {\n dist += (p[i] - q[i]) * (Math.log(p[i]) - Math.log(q[i]));\n }\n\n return dist;\n }",
"public double compute( DMatrix1Row mat ) {\n if( width != mat.numCols || width != mat.numRows ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n\n // make sure everything is in the proper state before it starts\n initStructures();\n\n// System.arraycopy(mat.data,0,minorMatrix[0],0,mat.data.length);\n\n int level = 0;\n while( true ) {\n int levelWidth = width-level;\n int levelIndex = levelIndexes[level];\n\n if( levelIndex == levelWidth ) {\n if( level == 0 ) {\n return levelResults[0];\n }\n int prevLevelIndex = levelIndexes[level-1]++;\n\n double val = mat.get((level-1)*width+levelRemoved[level-1]);\n if( prevLevelIndex % 2 == 0 ) {\n levelResults[level-1] += val * levelResults[level];\n } else {\n levelResults[level-1] -= val * levelResults[level];\n }\n\n putIntoOpen(level-1);\n\n levelResults[level] = 0;\n levelIndexes[level] = 0;\n level--;\n } else {\n int excluded = openRemove( levelIndex );\n\n levelRemoved[level] = excluded;\n\n if( levelWidth == minWidth ) {\n createMinor(mat);\n double subresult = mat.get(level*width+levelRemoved[level]);\n\n subresult *= UnrolledDeterminantFromMinor_DDRM.det(tempMat);\n\n if( levelIndex % 2 == 0 ) {\n levelResults[level] += subresult;\n } else {\n levelResults[level] -= subresult;\n }\n\n // put it back into the list\n putIntoOpen(level);\n levelIndexes[level]++;\n } else {\n level++;\n }\n }\n }\n }"
] |
The length of the region left to the completion offset that is part of the
replace region. | [
"public int getReplaceContextLength() {\n\t\tif (replaceContextLength == null) {\n\t\t\tint replacementOffset = getReplaceRegion().getOffset();\n\t\t\tITextRegion currentRegion = getCurrentNode().getTextRegion();\n\t\t\tint replaceContextLength = currentRegion.getLength() - (replacementOffset - currentRegion.getOffset());\n\t\t\tthis.replaceContextLength = replaceContextLength;\n\t\t\treturn replaceContextLength;\n\t\t}\n\t\treturn replaceContextLength.intValue();\n\t}"
] | [
"public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }",
"private String getPropertyName(Expression expression) {\n\t\tif (!(expression instanceof PropertyName)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a PropertyName.\");\n\t\t}\n\t\tString name = ((PropertyName) expression).getPropertyName();\n\t\tif (name.endsWith(FilterService.ATTRIBUTE_ID)) {\n\t\t\t// replace by Hibernate id property, always refers to the id, even if named differently\n\t\t\tname = name.substring(0, name.length() - FilterService.ATTRIBUTE_ID.length()) + HIBERNATE_ID;\n\t\t}\n\t\treturn name;\n\t}",
"private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }",
"private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}",
"public static <T> T createObject(final Class<T> clazz, final Object... args) throws NoSuchConstructorException,\n AmbiguousConstructorException, ReflectiveOperationException {\n return findConstructor(clazz, args).newInstance(args);\n }",
"public int getJdbcType(String ojbType) throws SQLException\r\n {\r\n int result;\r\n if(ojbType == null) ojbType = \"\";\r\n\t\tojbType = ojbType.toLowerCase();\r\n if (ojbType.equals(\"bit\"))\r\n result = Types.BIT;\r\n else if (ojbType.equals(\"tinyint\"))\r\n result = Types.TINYINT;\r\n else if (ojbType.equals(\"smallint\"))\r\n result = Types.SMALLINT;\r\n else if (ojbType.equals(\"integer\"))\r\n result = Types.INTEGER;\r\n else if (ojbType.equals(\"bigint\"))\r\n result = Types.BIGINT;\r\n\r\n else if (ojbType.equals(\"float\"))\r\n result = Types.FLOAT;\r\n else if (ojbType.equals(\"real\"))\r\n result = Types.REAL;\r\n else if (ojbType.equals(\"double\"))\r\n result = Types.DOUBLE;\r\n\r\n else if (ojbType.equals(\"numeric\"))\r\n result = Types.NUMERIC;\r\n else if (ojbType.equals(\"decimal\"))\r\n result = Types.DECIMAL;\r\n\r\n else if (ojbType.equals(\"char\"))\r\n result = Types.CHAR;\r\n else if (ojbType.equals(\"varchar\"))\r\n result = Types.VARCHAR;\r\n else if (ojbType.equals(\"longvarchar\"))\r\n result = Types.LONGVARCHAR;\r\n\r\n else if (ojbType.equals(\"date\"))\r\n result = Types.DATE;\r\n else if (ojbType.equals(\"time\"))\r\n result = Types.TIME;\r\n else if (ojbType.equals(\"timestamp\"))\r\n result = Types.TIMESTAMP;\r\n\r\n else if (ojbType.equals(\"binary\"))\r\n result = Types.BINARY;\r\n else if (ojbType.equals(\"varbinary\"))\r\n result = Types.VARBINARY;\r\n else if (ojbType.equals(\"longvarbinary\"))\r\n result = Types.LONGVARBINARY;\r\n\r\n\t\telse if (ojbType.equals(\"clob\"))\r\n \t\tresult = Types.CLOB;\r\n\t\telse if (ojbType.equals(\"blob\"))\r\n\t\t\tresult = Types.BLOB;\r\n else\r\n throw new SQLException(\r\n \"The type '\"+ ojbType + \"' is not a valid jdbc type.\");\r\n return result;\r\n }",
"public static void unregisterMbean(MBeanServer server, ObjectName name) {\n try {\n server.unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"public boolean checkXpathStartsWithXpathEventableCondition(Document dom,\n\t\t\tEventableCondition eventableCondition, String xpath) throws XPathExpressionException {\n\t\tif (eventableCondition == null || Strings\n\t\t\t\t.isNullOrEmpty(eventableCondition.getInXPath())) {\n\t\t\tthrow new CrawljaxException(\"Eventable has no XPath condition\");\n\t\t}\n\t\tList<String> expressions =\n\t\t\t\tXPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());\n\n\t\treturn checkXPathUnderXPaths(xpath, expressions);\n\t}",
"public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
This method is called to alert project listeners to the fact that
a resource has been written to a project file.
@param resource resource instance | [
"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 }"
] | [
"@Override\n\tpublic Result getResult() throws Exception {\n\t\tResult returnResult = result;\n\n\t\t// If we've chained to other Actions, we need to find the last result\n\t\twhile (returnResult instanceof ActionChainResult) {\n\t\t\tActionProxy aProxy = ((ActionChainResult) returnResult).getProxy();\n\n\t\t\tif (aProxy != null) {\n\t\t\t\tResult proxyResult = aProxy.getInvocation().getResult();\n\n\t\t\t\tif ((proxyResult != null) && (aProxy.getExecuteResult())) {\n\t\t\t\t\treturnResult = proxyResult;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn returnResult;\n\t}",
"@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 }",
"public void inverse(GVRPose src)\n {\n if (getSkeleton() != src.getSkeleton())\n throw new IllegalArgumentException(\"GVRPose.copy: input pose is incompatible with this pose\");\n src.sync();\n int numbones = getNumBones();\n Bone srcBone = src.mBones[0];\n Bone dstBone = mBones[0];\n\n mNeedSync = true;\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n srcBone.LocalMatrix.set(dstBone.WorldMatrix);\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(0), dstBone.toString());\n\n }\n for (int i = 1; i < numbones; ++i)\n {\n srcBone = src.mBones[i];\n dstBone = mBones[i];\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n dstBone.Changed = WORLD_ROT | WORLD_POS;\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(i), dstBone.toString());\n }\n }\n sync();\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 T addFile(final String name, final List<String> path, final byte[] newHash, final boolean isDirectory) {\n return addFile(name, path, newHash, isDirectory, null);\n }",
"public void restartDyno(String appName, String dynoId) {\n connection.execute(new DynoRestart(appName, dynoId), apiKey);\n }",
"private final void handleHttpWorkerResponse(\n ResponseOnSingeRequest respOnSingleReq) throws Exception {\n // Successful response from GenericAsyncHttpWorker\n\n // Jeff 20310411: use generic response\n\n String responseContent = respOnSingleReq.getResponseBody();\n response.setResponseContent(respOnSingleReq.getResponseBody());\n\n /**\n * Poller logic if pollable: check if need to poll/ or already complete\n * 1. init poller data and HttpPollerProcessor 2. check if task\n * complete, if not, send the request again.\n */\n if (request.isPollable()) {\n boolean scheduleNextPoll = false;\n boolean errorFindingUuid = false;\n\n // set JobId of the poller\n if (!pollerData.isUuidHasBeenSet()) {\n String jobId = httpPollerProcessor\n .getUuidFromResponse(respOnSingleReq);\n\n if (jobId.equalsIgnoreCase(PcConstants.NA)) {\n errorFindingUuid = true;\n pollingErrorCount++;\n logger.error(\"!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. \"\n\n + \"DEBUG: REGEX_JOBID: \"\n + httpPollerProcessor.getJobIdRegex()\n\n + \"RESPONSE: \"\n + respOnSingleReq.getResponseBody()\n + \" polling Error count\"\n + pollingErrorCount\n + \" at \" + PcDateUtils.getNowDateTimeStrStandard());\n // fail fast\n pollerData.setError(true);\n pollerData.setComplete(true);\n\n } else {\n pollerData.setJobIdAndMarkHasBeenSet(jobId);\n // if myResponse has other errors, mark poll data as error.\n pollerData.setError(httpPollerProcessor\n .ifThereIsErrorInResponse(respOnSingleReq));\n }\n\n }\n if (!pollerData.isError()) {\n\n pollerData\n .setComplete(httpPollerProcessor\n .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));\n pollerData.setCurrentProgress(httpPollerProcessor\n .getProgressFromResponse(respOnSingleReq));\n }\n\n // poll again only if not complete AND no error; 2015: change to\n // over limit\n scheduleNextPoll = !pollerData.isComplete()\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError());\n\n // Schedule next poll and return. (not to answer back to manager yet\n // )\n if (scheduleNextPoll\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError())) {\n\n pollMessageCancellable = getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(httpPollerProcessor\n .getPollIntervalMillis(),\n TimeUnit.MILLISECONDS), getSelf(),\n OperationWorkerMsgType.POLL_PROGRESS,\n getContext().system().dispatcher(), getSelf());\n\n logger.info(\"\\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND\"\n + String.format(\"PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent,\n PcDateUtils.getNowDateTimeStrStandard()));\n\n String responseContentNew = errorFindingUuid ? responseContent\n + \"_PollingErrorCount:\" + pollingErrorCount\n : responseContent;\n logger.info(responseContentNew);\n // log\n pollerData.getPollingHistoryMap().put(\n \"RECV_\" + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\"PROGRESS:%.3f, BODY:%s\",\n pollerData.getCurrentProgress(),\n responseContent));\n return;\n } else {\n pollerData\n .getPollingHistoryMap()\n .put(\"RECV_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\n \"POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent));\n }\n\n }// end if (request.isPollable())\n\n reply(respOnSingleReq.isFailObtainResponse(),\n respOnSingleReq.getErrorMessage(),\n respOnSingleReq.getStackTrace(),\n respOnSingleReq.getStatusCode(),\n respOnSingleReq.getStatusCodeInt(),\n respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());\n\n }",
"public synchronized void setSendingStatus(boolean send) throws IOException {\n if (isSendingStatus() == send) {\n return;\n }\n\n if (send) { // Start sending status packets.\n ensureRunning();\n if ((getDeviceNumber() < 1) || (getDeviceNumber() > 4)) {\n throw new IllegalStateException(\"Can only send status when using a standard player number, 1 through 4.\");\n }\n\n BeatFinder.getInstance().start();\n BeatFinder.getInstance().addLifecycleListener(beatFinderLifecycleListener);\n\n final AtomicBoolean stillRunning = new AtomicBoolean(true);\n sendingStatus = stillRunning; // Allow other threads to stop us when necessary.\n\n Thread sender = new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (stillRunning.get()) {\n sendStatus();\n try {\n Thread.sleep(getStatusInterval());\n } catch (InterruptedException e) {\n logger.warn(\"beat-link VirtualCDJ status sender thread was interrupted; continuing\");\n }\n }\n }\n }, \"beat-link VirtualCdj status sender\");\n sender.setDaemon(true);\n sender.start();\n\n if (isSynced()) { // If we are supposed to be synced, we need to respond to master beats and tempo changes.\n addMasterListener(ourSyncMasterListener);\n }\n\n if (isPlaying()) { // Start the beat sender too, if we are supposed to be playing.\n beatSender.set(new BeatSender(metronome));\n }\n } else { // Stop sending status packets, and responding to master beats and tempo changes if we were synced.\n BeatFinder.getInstance().removeLifecycleListener(beatFinderLifecycleListener);\n removeMasterListener(ourSyncMasterListener);\n\n sendingStatus.set(false); // Stop the status sending thread.\n sendingStatus = null; // Indicate that we are no longer sending status.\n final BeatSender activeSender = beatSender.get(); // And stop the beat sender if we have one.\n if (activeSender != null) {\n activeSender.shutDown();\n beatSender.set(null);\n }\n }\n }",
"private void readFile(InputStream is) throws IOException\n {\n StreamHelper.skip(is, 64);\n int index = 64;\n\n ArrayList<Integer> offsetList = new ArrayList<Integer>();\n List<String> nameList = new ArrayList<String>();\n\n while (true)\n {\n byte[] table = new byte[32];\n is.read(table);\n index += 32;\n\n int offset = PEPUtility.getInt(table, 0);\n offsetList.add(Integer.valueOf(offset));\n if (offset == 0)\n {\n break;\n }\n\n nameList.add(PEPUtility.getString(table, 5).toUpperCase());\n }\n\n StreamHelper.skip(is, offsetList.get(0).intValue() - index);\n\n for (int offsetIndex = 1; offsetIndex < offsetList.size() - 1; offsetIndex++)\n {\n String name = nameList.get(offsetIndex - 1);\n Class<? extends Table> tableClass = TABLE_CLASSES.get(name);\n if (tableClass == null)\n {\n tableClass = Table.class;\n }\n\n Table table;\n try\n {\n table = tableClass.newInstance();\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n m_tables.put(name, table);\n table.read(is);\n }\n }"
] |
trim "act." from conf keys | [
"private static Map<String, Object> processConf(Map<String, ?> conf) {\n Map<String, Object> m = new HashMap<String, Object>(conf.size());\n for (String s : conf.keySet()) {\n Object o = conf.get(s);\n if (s.startsWith(\"act.\")) s = s.substring(4);\n m.put(s, o);\n m.put(Config.canonical(s), o);\n }\n return m;\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 }",
"private void registerProxyCreator(Node source,\n BeanDefinitionHolder holder,\n ParserContext context) {\n\n String beanName = holder.getBeanName();\n String proxyName = beanName + \"Proxy\";\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class);\n\n initializer.addPropertyValue(\"beanNames\", beanName);\n initializer.addPropertyValue(\"interceptorNames\", interceptorName);\n\n BeanDefinitionRegistry registry = context.getRegistry();\n registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition());\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}",
"private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }",
"public OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }",
"public CollectionRequest<Story> findByTask(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Story>(this, Story.class, path, \"GET\");\n }",
"public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}",
"public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }",
"private void readResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n for (Project.Resources.Resource.Baseline baseline : xmlResource.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjResource.setBaselineCost(cost);\n mpxjResource.setBaselineWork(work);\n }\n else\n {\n mpxjResource.setBaselineCost(number, cost);\n mpxjResource.setBaselineWork(number, work);\n }\n }\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.