query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Compare an array of bytes with a subsection of a larger array of bytes.
@param lhs small array of bytes
@param rhs large array of bytes
@param rhsOffset offset into larger array of bytes
@return true if a match is found | [
"private boolean compareBytes(byte[] lhs, byte[] rhs, int rhsOffset)\n {\n boolean result = true;\n for (int loop = 0; loop < lhs.length; loop++)\n {\n if (lhs[loop] != rhs[rhsOffset + loop])\n {\n result = false;\n break;\n }\n }\n return (result);\n }"
] | [
"public <T> T convert(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\ttry {\r\n\t\t\treturn (T) multiConverter.convert(context, source, destinationType);\r\n\t\t} catch (ConverterException e) {\r\n\t\t\tthrow e;\r\n\t\t} catch (Exception e) {\r\n\t\t\t// There is a problem with one converter. This should not happen.\r\n\t\t\t// Either there is a bug in this converter or it is not properly\r\n\t\t\t// configured\r\n\t\t\tthrow new ConverterException(\r\n\t\t\t\t\tMessageFormat\r\n\t\t\t\t\t\t\t.format(\r\n\t\t\t\t\t\t\t\t\t\"Could not convert given object with class ''{0}'' to object with type signature ''{1}''\",\r\n\t\t\t\t\t\t\t\t\tsource == null ? \"null\" : source.getClass()\r\n\t\t\t\t\t\t\t\t\t\t\t.getName(), destinationType), e);\r\n\t\t}\r\n\t}",
"public static ModelNode getAccessControl(ModelControllerClient client, OperationRequestAddress address, boolean operations) {\n return getAccessControl(client, null, address, operations);\n }",
"public static base_responses unset(nitro_service client, String certkey[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey unsetresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tunsetresources[i] = new sslcertkey();\n\t\t\t\tunsetresources[i].certkey = certkey[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }",
"private void processFile(InputStream is) throws MPXJException\n {\n int line = 1;\n\n try\n {\n //\n // Test the header and extract the separator. If this is successful,\n // we reset the stream back as far as we can. The design of the\n // BufferedInputStream class means that we can't get back to character\n // zero, so the first record we will read will get \"RMHDR\" rather than\n // \"ERMHDR\" in the first field position.\n //\n BufferedInputStream bis = new BufferedInputStream(is);\n byte[] data = new byte[6];\n data[0] = (byte) bis.read();\n bis.mark(1024);\n bis.read(data, 1, 5);\n\n if (!new String(data).equals(\"ERMHDR\"))\n {\n throw new MPXJException(MPXJException.INVALID_FILE);\n }\n\n bis.reset();\n\n InputStreamReader reader = new InputStreamReader(bis, getCharset());\n Tokenizer tk = new ReaderTokenizer(reader);\n tk.setDelimiter('\\t');\n List<String> record = new ArrayList<String>();\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n readRecord(tk, record);\n if (!record.isEmpty())\n {\n if (processRecord(record))\n {\n break;\n }\n }\n ++line;\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR + \" (failed at line \" + line + \")\", ex);\n }\n }",
"public void addValue(double value)\n {\n if (dataSetSize == dataSet.length)\n {\n // Increase the capacity of the array.\n int newLength = (int) (GROWTH_RATE * dataSetSize);\n double[] newDataSet = new double[newLength];\n System.arraycopy(dataSet, 0, newDataSet, 0, dataSetSize);\n dataSet = newDataSet;\n }\n dataSet[dataSetSize] = value;\n updateStatsWithNewValue(value);\n ++dataSetSize;\n }",
"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 }",
"private void process(String input, String output) throws MPXJException, IOException\n {\n //\n // Extract the project data\n //\n MPPReader reader = new MPPReader();\n m_project = reader.read(input);\n\n String varDataFileName;\n String projectDirName;\n int mppFileType = NumberHelper.getInt(m_project.getProjectProperties().getMppFileType());\n switch (mppFileType)\n {\n case 8:\n {\n projectDirName = \" 1\";\n varDataFileName = \"FixDeferFix 0\";\n break;\n }\n\n case 9:\n {\n projectDirName = \" 19\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 12:\n {\n projectDirName = \" 112\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 14:\n {\n projectDirName = \" 114\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported file type \" + mppFileType);\n }\n }\n\n //\n // Load the raw file\n //\n FileInputStream is = new FileInputStream(input);\n POIFSFileSystem fs = new POIFSFileSystem(is);\n is.close();\n\n //\n // Locate the root of the project file system\n //\n DirectoryEntry root = fs.getRoot();\n m_projectDir = (DirectoryEntry) root.getEntry(projectDirName);\n\n //\n // Process Tasks\n //\n Map<String, String> replacements = new HashMap<String, String>();\n for (Task task : m_project.getTasks())\n {\n mapText(task.getName(), replacements);\n }\n processReplacements(((DirectoryEntry) m_projectDir.getEntry(\"TBkndTask\")), varDataFileName, replacements, true);\n\n //\n // Process Resources\n //\n replacements.clear();\n for (Resource resource : m_project.getResources())\n {\n mapText(resource.getName(), replacements);\n mapText(resource.getInitials(), replacements);\n }\n processReplacements((DirectoryEntry) m_projectDir.getEntry(\"TBkndRsc\"), varDataFileName, replacements, true);\n\n //\n // Process project properties\n //\n replacements.clear();\n ProjectProperties properties = m_project.getProjectProperties();\n mapText(properties.getProjectTitle(), replacements);\n processReplacements(m_projectDir, \"Props\", replacements, true);\n\n replacements.clear();\n mapText(properties.getProjectTitle(), replacements);\n mapText(properties.getSubject(), replacements);\n mapText(properties.getAuthor(), replacements);\n mapText(properties.getKeywords(), replacements);\n mapText(properties.getComments(), replacements);\n processReplacements(root, \"\\005SummaryInformation\", replacements, false);\n\n replacements.clear();\n mapText(properties.getManager(), replacements);\n mapText(properties.getCompany(), replacements);\n mapText(properties.getCategory(), replacements);\n processReplacements(root, \"\\005DocumentSummaryInformation\", replacements, false);\n\n //\n // Write the replacement raw file\n //\n FileOutputStream os = new FileOutputStream(output);\n fs.writeFilesystem(os);\n os.flush();\n os.close();\n fs.close();\n }",
"public Collection<User> getFavorites(String photoId, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n\r\n parameters.put(\"method\", METHOD_GET_FAVORITES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\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 List<User> users = new ArrayList<User>();\r\n\r\n Element userRoot = response.getPayload();\r\n NodeList userNodes = userRoot.getElementsByTagName(\"person\");\r\n for (int i = 0; i < userNodes.getLength(); i++) {\r\n Element userElement = (Element) userNodes.item(i);\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n user.setUsername(userElement.getAttribute(\"username\"));\r\n user.setFaveDate(userElement.getAttribute(\"favedate\"));\r\n users.add(user);\r\n }\r\n return users;\r\n }"
] |
Retrieve the currently cached value for the given document. | [
"public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }"
] | [
"public boolean matchesWithMask(IPAddress other, IPAddress mask) {\n\t\treturn getSection().matchesWithMask(other.getSection(), mask.getSection());\n\t}",
"public static Integer getDurationUnits(RecurringTask recurrence)\n {\n Duration duration = recurrence.getDuration();\n Integer result = null;\n\n if (duration != null)\n {\n result = UNITS_MAP.get(duration.getUnits());\n }\n\n return (result);\n }",
"public void execute() {\n try {\n while(true) {\n Event event = null;\n\n try {\n event = eventQueue.poll(timeout, unit);\n } catch(InterruptedException e) {\n throw new InsufficientOperationalNodesException(operation.getSimpleName()\n + \" operation interrupted!\", e);\n }\n\n if(event == null)\n throw new VoldemortException(operation.getSimpleName()\n + \" returned a null event\");\n\n if(event.equals(Event.ERROR)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName()\n + \" request, events complete due to error\");\n\n break;\n } else if(event.equals(Event.COMPLETED)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, events complete\");\n\n break;\n }\n\n Action action = eventActions.get(event);\n\n if(action == null)\n throw new IllegalStateException(\"action was null for event \" + event);\n\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, action \"\n + action.getClass().getSimpleName() + \" to handle \" + event\n + \" event\");\n\n action.execute(this);\n }\n } finally {\n finished = true;\n }\n }",
"public String createTorqueSchema(Properties attributes) throws XDocletException\r\n {\r\n String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME);\r\n\r\n _torqueModel = new TorqueModelDef(dbName, _model);\r\n return \"\";\r\n }",
"@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }",
"protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException\r\n {\r\n /*\r\n arminw:\r\n if broker isn't in PB-tx, start tx\r\n */\r\n if (!getBroker().isInTransaction())\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"call beginTransaction() on PB instance\");\r\n broker.beginTransaction();\r\n }\r\n\r\n // Notify objects of impending commits.\r\n performTransactionAwareBeforeCommit();\r\n\r\n // Now perfom the real work\r\n objectEnvelopeTable.writeObjects(isFlush);\r\n // now we have to perform the named objects\r\n namedRootsMap.performDeletion();\r\n namedRootsMap.performInsert();\r\n namedRootsMap.afterWriteCleanup();\r\n }",
"protected PersistenceBrokerInternal createNewBrokerInstance(PBKey key) throws PBFactoryException\r\n {\r\n if (key == null) throw new PBFactoryException(\"Could not create new broker with PBkey argument 'null'\");\r\n // check if the given key really exists\r\n if (MetadataManager.getInstance().connectionRepository().getDescriptor(key) == null)\r\n {\r\n throw new PBFactoryException(\"Given PBKey \" + key + \" does not match in metadata configuration\");\r\n }\r\n if (log.isEnabledFor(Logger.INFO))\r\n {\r\n // only count created instances when INFO-Log-Level\r\n log.info(\"Create new PB instance for PBKey \" + key +\r\n \", already created persistence broker instances: \" + instanceCount);\r\n // useful for testing\r\n ++this.instanceCount;\r\n }\r\n\r\n PersistenceBrokerInternal instance = null;\r\n Class[] types = {PBKey.class, PersistenceBrokerFactoryIF.class};\r\n Object[] args = {key, this};\r\n try\r\n {\r\n instance = (PersistenceBrokerInternal) ClassHelper.newInstance(implementationClass, types, args);\r\n OjbConfigurator.getInstance().configure(instance);\r\n instance = (PersistenceBrokerInternal) InterceptorFactory.getInstance().createInterceptorFor(instance);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Creation of a new PB instance failed\", e);\r\n throw new PBFactoryException(\"Creation of a new PB instance failed\", e);\r\n }\r\n return instance;\r\n }",
"public 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 static<T> Vendor<T> vendor(Func0<T> f) {\n\treturn j.vendor(f);\n }"
] |
Returns the earlier of two dates, handling null values. A non-null Date
is always considered to be earlier than a null Date.
@param d1 Date instance
@param d2 Date instance
@return Date earliest date | [
"public static Date min(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) < 0) ? d1 : d2;\n }\n return result;\n }"
] | [
"public static base_responses add(nitro_service client, dnsview resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsview addresources[] = new dnsview[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsview();\n\t\t\t\taddresources[i].viewname = resources[i].viewname;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private List<DumpProcessingAction> handleArguments(String[] args) {\n\t\tCommandLine cmd;\n\t\tCommandLineParser parser = new GnuParser();\n\n\t\ttry {\n\t\t\tcmd = parser.parse(options, args);\n\t\t} catch (ParseException e) {\n\t\t\tlogger.error(\"Failed to parse arguments: \" + e.getMessage());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\t// Stop processing if a help text is to be printed:\n\t\tif ((cmd.hasOption(CMD_OPTION_HELP)) || (args.length == 0)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<DumpProcessingAction> configuration = new ArrayList<>();\n\n\t\thandleGlobalArguments(cmd);\n\n\t\tif (cmd.hasOption(CMD_OPTION_ACTION)) {\n\t\t\tDumpProcessingAction action = handleActionArguments(cmd);\n\t\t\tif (action != null) {\n\t\t\t\tconfiguration.add(action);\n\t\t\t}\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CONFIG_FILE)) {\n\t\t\ttry {\n\t\t\t\tList<DumpProcessingAction> configFile = readConfigFile(cmd\n\t\t\t\t\t\t.getOptionValue(CMD_OPTION_CONFIG_FILE));\n\t\t\t\tconfiguration.addAll(configFile);\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"Failed to read configuration file \\\"\"\n\t\t\t\t\t\t+ cmd.getOptionValue(CMD_OPTION_CONFIG_FILE) + \"\\\": \"\n\t\t\t\t\t\t+ e.toString());\n\t\t\t}\n\n\t\t}\n\n\t\treturn configuration;\n\n\t}",
"public String getRealm() {\n if (UNDEFINED.equals(realm)) {\n Principal principal = securityIdentity.getPrincipal();\n String realm = null;\n if (principal instanceof RealmPrincipal) {\n realm = ((RealmPrincipal)principal).getRealm();\n }\n this.realm = realm;\n\n }\n\n return this.realm;\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}",
"public static File writeStreamToTempFile(InputStream inputStream, String tempFileSuffix) throws IOException\n {\n FileOutputStream outputStream = null;\n\n try\n {\n File file = File.createTempFile(\"mpxj\", tempFileSuffix);\n outputStream = new FileOutputStream(file);\n byte[] buffer = new byte[1024];\n while (true)\n {\n int bytesRead = inputStream.read(buffer);\n if (bytesRead == -1)\n {\n break;\n }\n outputStream.write(buffer, 0, bytesRead);\n }\n return file;\n }\n\n finally\n {\n if (outputStream != null)\n {\n outputStream.close();\n }\n }\n }",
"public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}",
"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 JsonObject getJsonObject() {\n\n JsonObject obj = new JsonObject();\n obj.add(\"field\", this.field);\n\n obj.add(\"value\", this.value);\n\n return obj;\n }",
"public static void sendMimeMessage(MimeMessage mimeMessage) {\r\n try {\r\n Transport.send(mimeMessage);\r\n } catch (MessagingException e) {\r\n throw new IllegalStateException(\"Can not send message \" + mimeMessage, e);\r\n }\r\n }"
] |
Returns the JSON String representation of the payload
according to Apple APNS specification
@return the String representation as expected by Apple | [
"public String build() {\n if (!root.containsKey(\"mdm\")) {\n insertCustomAlert();\n root.put(\"aps\", aps);\n }\n try {\n return mapper.writeValueAsString(root);\n } catch (final Exception e) {\n throw new RuntimeException(e);\n }\n }"
] | [
"protected void logIncompatibleValueError(PropertyIdValue propertyIdValue,\n\t\t\tString datatype, String valueType) {\n\t\tlogger.warn(\"Property \" + propertyIdValue.getId() + \" has type \\\"\"\n\t\t\t\t+ datatype + \"\\\" but a value of type \" + valueType\n\t\t\t\t+ \". Data ignored.\");\n\t}",
"public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD;\r\n }",
"public static int convertBytesToInt(byte[] bytes, int offset)\n {\n return (BITWISE_BYTE_TO_INT & bytes[offset + 3])\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8)\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16)\n | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24);\n }",
"public static base_responses unset(nitro_service client, onlinkipv6prefix resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix unsetresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new onlinkipv6prefix();\n\t\t\t\tunsetresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"@GuardedBy(\"elementsLock\")\n\t@Override\n\tpublic boolean markChecked(CandidateElement element) {\n\t\tString generalString = element.getGeneralString();\n\t\tString uniqueString = element.getUniqueString();\n\t\tsynchronized (elementsLock) {\n\t\t\tif (elements.contains(uniqueString)) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\telements.add(generalString);\n\t\t\t\telements.add(uniqueString);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}",
"private 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 Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\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 }",
"@Override\n public boolean visit(VariableDeclarationStatement node)\n {\n for (int i = 0; i < node.fragments().size(); ++i)\n {\n String nodeType = node.getType().toString();\n VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i);\n state.getNames().add(frag.getName().getIdentifier());\n state.getNameInstance().put(frag.getName().toString(), nodeType.toString());\n }\n\n processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION,\n compilationUnit.getLineNumber(node.getStartPosition()),\n compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString());\n return super.visit(node);\n }"
] |
This is a generic function for retrieving any config value. The returned value
is the one the server is operating with, no matter whether it comes from defaults
or from the user-supplied configuration.
This function only provides access to configs which are deemed safe to share
publicly (i.e.: not security-related configs). The list of configs which are
considered off-limit can itself be configured via '{@value #RESTRICTED_CONFIGS}'.
@param key config key for which to retrieve the value.
@return the value for the requested config key, in String format.
May return null if the key exists and its value is explicitly set to null.
@throws UndefinedPropertyException if the requested key does not exist in the config.
@throws ConfigurationException if the requested key is not publicly available. | [
"public String getPublicConfigValue(String key) throws ConfigurationException {\n if (!allProps.containsKey(key)) {\n throw new UndefinedPropertyException(\"The requested config key does not exist.\");\n }\n if (restrictedConfigs.contains(key)) {\n throw new ConfigurationException(\"The requested config key is not publicly available!\");\n }\n return allProps.get(key);\n }"
] | [
"private void configureCustomFields()\n {\n CustomFieldContainer customFields = m_projectFile.getCustomFields();\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityIDField == null)\n {\n m_activityIDField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Code\");\n if (m_activityIDField == null)\n {\n m_activityIDField = TaskField.WBS;\n }\n }\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityTypeField == null)\n {\n m_activityTypeField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Activity Type\");\n }\n }",
"private static Converter<List<String>, Object> createStringConstructorConverter(Class<?> resultClass) {\n try {\n final Constructor<?> constructor = resultClass.getConstructor(String.class);\n return new BasicConverter(defaultValue(resultClass)) {\n @Override\n protected Object convert(String value) throws Exception {\n return constructor.newInstance(value);\n }\n };\n } catch (Exception e) {\n return null;\n }\n }",
"@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n rendererBuilder.withParent(viewGroup);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext()));\n rendererBuilder.withViewType(viewType);\n RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder();\n if (viewHolder == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null viewHolder\");\n }\n return viewHolder;\n }",
"public static void printHelp(PrintStream stream) {\n stream.println();\n stream.println(\"Voldemort Admin Tool Async-Job Commands\");\n stream.println(\"---------------------------------------\");\n stream.println(\"list Get async job list from nodes.\");\n stream.println(\"stop Stop async jobs on one node.\");\n stream.println();\n stream.println(\"To get more information on each command,\");\n stream.println(\"please try \\'help async-job <command-name>\\'.\");\n stream.println();\n }",
"public PayloadBuilder sound(final String sound) {\n if (sound != null) {\n aps.put(\"sound\", sound);\n } else {\n aps.remove(\"sound\");\n }\n return this;\n }",
"public Where<T, ID> in(String columnName, Iterable<?> objects) throws SQLException {\n\t\taddClause(new In(columnName, findColumnFieldType(columnName), objects, true));\n\t\treturn this;\n\t}",
"public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{\n DFAgentDescription dfd = new DFAgentDescription();\n ServiceDescription sd = new ServiceDescription();\n \n sd.setType(serviceType);\n sd.setName(serviceName);\n \n //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. \n // He escogido crear nombres en clave en jade.common.Definitions para este campo. \n //NOTE El serviceName es el nombre efectivo del servicio. \n // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. \n // sd.setType(agentType);\n // sd.setName(agent.getLocalName());\n \n //Add services??\n \n // Sets the agent description\n dfd.setName(agent.getAID());\n dfd.addServices(sd);\n \n // Register the agent\n DFService.register(agent, dfd);\n }",
"@SuppressWarnings(\"unchecked\")\r\n public static <E> E[] filter(E[] elems, Filter<E> filter) {\r\n List<E> filtered = new ArrayList<E>();\r\n for (E elem: elems) {\r\n if (filter.accept(elem)) {\r\n filtered.add(elem);\r\n }\r\n }\r\n return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));\r\n }",
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }"
] |
Use this API to update inat resources. | [
"public static base_responses update(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat updateresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new inat();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].privateip = resources[i].privateip;\n\t\t\t\tupdateresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].tftp = resources[i].tftp;\n\t\t\t\tupdateresources[i].usip = resources[i].usip;\n\t\t\t\tupdateresources[i].usnip = resources[i].usnip;\n\t\t\t\tupdateresources[i].proxyip = resources[i].proxyip;\n\t\t\t\tupdateresources[i].mode = resources[i].mode;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public final Object copy(final Object toCopy, PersistenceBroker broker)\r\n\t{\r\n\t\treturn clone(toCopy, IdentityMapFactory.getIdentityMap(), new HashMap());\r\n\t}",
"@PreDestroy\n public final void dispose() {\n getConnectionPool().ifPresent(PoolResources::dispose);\n getThreadPool().dispose();\n\n try {\n ObjectName name = getByteBufAllocatorObjectName();\n\n if (ManagementFactory.getPlatformMBeanServer().isRegistered(name)) {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n }\n } catch (JMException e) {\n this.logger.error(\"Unable to register ByteBufAllocator MBean\", e);\n }\n }",
"public final void notifyFooterItemChanged(int position) {\n if (position < 0 || position >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount + contentItemCount);\n }",
"public static base_response unset(nitro_service client, snmpalarm resource, String[] args) throws Exception{\n\t\tsnmpalarm unsetresource = new snmpalarm();\n\t\tunsetresource.trapname = resource.trapname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static <T> T columnStringToObject(Class<?> objClass, String str, Pattern delimiterPattern, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException\r\n {\r\n String[] fields = delimiterPattern.split(str);\r\n T item = ErasureUtils.<T>uncheckedCast(objClass.newInstance());\r\n for (int i = 0; i < fields.length; i++) {\r\n try {\r\n Field field = objClass.getDeclaredField(fieldNames[i]);\r\n field.set(item, fields[i]);\r\n } catch (IllegalAccessException ex) {\r\n Method method = objClass.getDeclaredMethod(\"set\" + StringUtils.capitalize(fieldNames[i]), String.class);\r\n method.invoke(item, fields[i]);\r\n }\r\n }\r\n return item;\r\n }",
"public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public static void 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 }",
"private void readResources(Project ganttProject)\n {\n Resources resources = ganttProject.getResources();\n readResourceCustomPropertyDefinitions(resources);\n readRoleDefinitions(ganttProject);\n\n for (net.sf.mpxj.ganttproject.schema.Resource gpResource : resources.getResource())\n {\n readResource(gpResource);\n }\n }",
"void addValue(V value, Resource resource) {\n\t\tthis.valueQueue.add(value);\n\t\tthis.valueSubjectQueue.add(resource);\n\t}"
] |
Replaces the proxy url with the correct url from the tileMap.
@return correct url to TMS service | [
"public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}"
] | [
"synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }",
"private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }",
"private static void transposeBlock(DMatrixRBlock A , DMatrixRBlock A_tran,\n int indexA , int indexC ,\n int width , int height )\n {\n for( int i = 0; i < height; i++ ) {\n int rowIndexC = indexC + i;\n int rowIndexA = indexA + width*i;\n int end = rowIndexA + width;\n for( ; rowIndexA < end; rowIndexC += height, rowIndexA++ ) {\n A_tran.data[ rowIndexC ] = A.data[ rowIndexA ];\n }\n }\n }",
"public GVRAndroidResource openResource(String filePath) throws IOException {\n // Error tolerance: Remove initial '/' introduced by file::///filename\n // In this case, the path is interpreted as relative to defaultPath,\n // which is the root of the filesystem.\n if (filePath.startsWith(File.separator)) {\n filePath = filePath.substring(File.separator.length());\n }\n\n filePath = adaptFilePath(filePath);\n String path;\n int resourceId;\n\n GVRAndroidResource resourceKey;\n switch (volumeType) {\n case ANDROID_ASSETS:\n // Resolve '..' and '.'\n path = getFullPath(defaultPath, filePath);\n path = new File(path).getCanonicalPath();\n if (path.startsWith(File.separator)) {\n path = path.substring(1);\n }\n resourceKey = new GVRAndroidResource(gvrContext, path);\n break;\n\n case ANDROID_RESOURCE:\n path = FileNameUtils.getBaseName(filePath);\n resourceId = gvrContext.getContext().getResources().getIdentifier(path, \"raw\", gvrContext.getContext().getPackageName());\n if (resourceId == 0) {\n throw new FileNotFoundException(filePath + \" resource not found\");\n }\n resourceKey = new GVRAndroidResource(gvrContext, resourceId);\n break;\n\n case LINUX_FILESYSTEM:\n resourceKey = new GVRAndroidResource(\n getFullPath(defaultPath, filePath));\n break;\n\n case ANDROID_SDCARD:\n String linuxPath = Environment.getExternalStorageDirectory()\n .getAbsolutePath();\n resourceKey = new GVRAndroidResource(\n getFullPath(linuxPath, defaultPath, filePath));\n break;\n\n case INPUT_STREAM:\n resourceKey = new GVRAndroidResource(getFullPath(defaultPath, filePath), volumeInputStream);\n break;\n\n case NETWORK:\n resourceKey = new GVRAndroidResource(gvrContext,\n getFullURL(defaultPath, filePath), enableUrlLocalCache);\n break;\n\n default:\n throw new IOException(\n String.format(\"Unrecognized volumeType %s\", volumeType));\n }\n return addResource(resourceKey);\n }",
"public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\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 photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }",
"public static int[] getTileScreenSize(double[] worldSize, double scale) {\n\t\tint screenWidth = (int) Math.round(scale * worldSize[0]);\n\t\tint screenHeight = (int) Math.round(scale * worldSize[1]);\n\t\treturn new int[] { screenWidth, screenHeight };\n\t}",
"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}",
"ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }"
] |
Function to perform forward activation | [
"public static int cudnnActivationForward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnActivationForwardNative(handle, activationDesc, alpha, xDesc, x, beta, yDesc, y));\n }"
] | [
"public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }",
"public Integer getEnd() {\n if (mtasPositionType.equals(POSITION_RANGE)\n || mtasPositionType.equals(POSITION_SET)) {\n return mtasPositionEnd;\n } else if (mtasPositionType.equals(POSITION_SINGLE)) {\n return mtasPositionStart;\n } else {\n return null;\n }\n }",
"private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }",
"public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }",
"private Expression getExpression(String expressionString) throws ParseException {\n\t\tif (!expressionCache.containsKey(expressionString)) {\n\t\t\tExpression expression;\n\t\t\texpression = parser.parseExpression(expressionString);\n\t\t\texpressionCache.put(expressionString, expression);\n\t\t}\n\t\treturn expressionCache.get(expressionString);\n\n\t}",
"private void sortFields()\r\n {\r\n HashMap fields = new HashMap();\r\n ArrayList fieldsWithId = new ArrayList();\r\n ArrayList fieldsWithoutId = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext(); )\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n fields.put(fieldDef.getName(), fieldDef);\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_ID))\r\n {\r\n fieldsWithId.add(fieldDef.getName());\r\n }\r\n else\r\n {\r\n fieldsWithoutId.add(fieldDef.getName());\r\n }\r\n }\r\n\r\n Collections.sort(fieldsWithId, new FieldWithIdComparator(fields));\r\n\r\n ArrayList result = new ArrayList();\r\n\r\n for (Iterator it = fieldsWithId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n for (Iterator it = fieldsWithoutId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n\r\n _fields = result;\r\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 }",
"public static Object newInstance(String className, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(getClass(className), types, args);\r\n }",
"public static double getRadiusToBoundedness(double D, int N, double timelag, double B){\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble radius = Math.sqrt(cov_area/(4*B));\n\t\treturn radius;\n\t}"
] |
If there is a zero on the diagonal element, the off diagonal element needs pushed
off so that all the algorithms assumptions are two and so that it can split the matrix. | [
"private void pushRight( int row ) {\n if( isOffZero(row))\n return;\n\n// B = createB();\n// B.print();\n rotatorPushRight(row);\n int end = N-2-row;\n for( int i = 0; i < end && bulge != 0; i++ ) {\n rotatorPushRight2(row,i+2);\n }\n// }\n }"
] | [
"public static appfwlearningdata[] get(nitro_service service, appfwlearningdata_args args) throws Exception{\n\t\tappfwlearningdata obj = new appfwlearningdata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tappfwlearningdata[] response = (appfwlearningdata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public int consume(Map<String, String> initialVars) {\r\n int result = 0;\n\r\n for (int i = 0; i < repeatNumber; i++) {\r\n result += super.consume(initialVars);\r\n }\n\r\n return result;\r\n }",
"private void getWeeklyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDay = calendar.get(Calendar.DAY_OF_WEEK);\n\n while (moreDates(calendar, dates))\n {\n int offset = 0;\n for (int dayIndex = 0; dayIndex < 7; dayIndex++)\n {\n if (getWeeklyDay(Day.getInstance(currentDay)))\n {\n if (offset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n offset = 0;\n }\n if (!moreDates(calendar, dates))\n {\n break;\n }\n dates.add(calendar.getTime());\n }\n\n ++offset;\n ++currentDay;\n\n if (currentDay > 7)\n {\n currentDay = 1;\n }\n }\n\n if (frequency > 1)\n {\n offset += (7 * (frequency - 1));\n }\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n }\n }",
"public List<MapRow> readTable(TableReader reader) throws IOException\n {\n reader.read();\n return reader.getRows();\n }",
"@Override\r\n @SuppressWarnings(\"unchecked\")\r\n public V put(K key, V value) {\r\n if (value == null) {\r\n return put(key, (V)nullValue);\r\n }\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V result = deltaMap.put(key, value);\r\n if (result == null) {\r\n return originalMap.get(key);\r\n }\r\n if (result == nullValue) {\r\n return null;\r\n }\r\n if (result == removedValue) {\r\n return null;\r\n }\r\n return result;\r\n }",
"public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException {\n\t\tif(calibrationParameters == null) {\n\t\t\tcalibrationParameters = new HashMap<>();\n\t\t}\n\t\tInteger maxIterationsParameter\t= (Integer)calibrationParameters.get(\"maxIterations\");\n\t\tDouble\taccuracyParameter\t\t= (Double)calibrationParameters.get(\"accuracy\");\n\t\tDouble\tevaluationTimeParameter\t\t= (Double)calibrationParameters.get(\"evaluationTime\");\n\n\t\t// @TODO currently ignored, we use the setting form the OptimizerFactory\n\t\tint maxIterations\t\t= maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600;\n\t\tdouble accuracy\t\t\t= accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8;\n\t\tdouble evaluationTime\t= evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0;\n\n\t\tAnalyticModel model = calibrationModel.addVolatilitySurfaces(this);\n\t\tSolver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory);\n\n\t\tSet<ParameterObject> objectsToCalibrate = new HashSet<>();\n\t\tobjectsToCalibrate.add(this);\n\t\tAnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate);\n\n\t\t// Diagnostic output\n\t\tif (logger.isLoggable(Level.FINE)) {\n\t\t\tdouble lastAccuracy\t\t= solver.getAccuracy();\n\t\t\tint \tlastIterations\t= solver.getIterations();\n\n\t\t\tlogger.fine(\"The solver achieved an accuracy of \" + lastAccuracy + \" in \" + lastIterations + \".\");\n\t\t}\n\n\t\treturn (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName());\n\t}",
"public static void write(File file, String text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file);\n writeUTF16BomIfRequired(charset, out);\n writer = new OutputStreamWriter(out, charset);\n writer.write(text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }",
"@SuppressWarnings(\"unused\")\n\t@XmlID\n @XmlAttribute(name = \"id\")\n private String getXmlID(){\n return String.format(\"%s-%s\", this.getClass().getSimpleName(), Long.valueOf(id));\n }",
"public static long count(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}"
] |
Resolve all files from a given path and simplify its definition. | [
"private org.apache.tools.ant.types.Path resolveFiles(org.apache.tools.ant.types.Path path) {\n org.apache.tools.ant.types.Path cloned = new org.apache.tools.ant.types.Path(getProject());\n for (String location : path.list()) {\n cloned.createPathElement().setLocation(new File(location));\n }\n return cloned;\n }"
] | [
"public DateRange getRange(int index)\n {\n DateRange result;\n\n if (index >= 0 && index < m_ranges.size())\n {\n result = m_ranges.get(index);\n }\n else\n {\n result = DateRange.EMPTY_RANGE;\n }\n\n return (result);\n }",
"private String normalizePath(String scriptPath) {\n StringBuilder builder = new StringBuilder(scriptPath.length() + 1);\n if (scriptPath.startsWith(\"/\")) {\n builder.append(scriptPath.substring(1));\n } else {\n builder.append(scriptPath);\n }\n if (!scriptPath.endsWith(\"/\")) {\n builder.append(\"/\");\n }\n return builder.toString();\n }",
"public void ifHasName(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n\r\n if ((name != null) && (name.length() > 0))\r\n {\r\n generate(template);\r\n }\r\n }",
"public static <T> IteratorFromReaderFactory<T> getFactory(String delim, Function<String,T> op) {\r\n return new DelimitRegExIteratorFactory<T>(delim, op);\r\n }",
"public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }",
"private Envelope getMaxScreenEnvelope(InternalTile tile, Coordinate panOrigin) {\n\t\tint nrOfTilesX = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenWidth());\n\t\tint nrOfTilesY = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenHeight());\n\n\t\tdouble x1 = panOrigin.x - nrOfTilesX * tile.getTileWidth();\n\t\t// double x2 = x1 + (nrOfTilesX * tileWidth * 2);\n\t\tdouble x2 = panOrigin.x + nrOfTilesX * tile.getTileWidth();\n\t\tdouble y1 = panOrigin.y - nrOfTilesY * tile.getTileHeight();\n\t\t// double y2 = y1 + (nrOfTilesY * tileHeight * 2);\n\t\tdouble y2 = panOrigin.y + nrOfTilesY * tile.getTileHeight();\n\t\treturn new Envelope(x1, x2, y1, y2);\n\t}",
"public static Collection<String> getKnownPGPSecureRingLocations() {\n final LinkedHashSet<String> locations = new LinkedHashSet<String>();\n\n final String os = System.getProperty(\"os.name\");\n final boolean runOnWindows = os == null || os.toLowerCase().contains(\"win\");\n\n if (runOnWindows) {\n // The user's roaming profile on Windows, via environment\n final String windowsRoaming = System.getenv(\"APPDATA\");\n if (windowsRoaming != null) {\n locations.add(joinLocalPath(windowsRoaming, \"gnupg\", \"secring.gpg\"));\n }\n\n // The user's local profile on Windows, via environment\n final String windowsLocal = System.getenv(\"LOCALAPPDATA\");\n if (windowsLocal != null) {\n locations.add(joinLocalPath(windowsLocal, \"gnupg\", \"secring.gpg\"));\n }\n\n // The Windows installation directory\n final String windir = System.getProperty(\"WINDIR\");\n if (windir != null) {\n // Local Profile on Windows 98 and ME\n locations.add(joinLocalPath(windir, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n }\n\n final String home = System.getProperty(\"user.home\");\n\n if (home != null && runOnWindows) {\n // These are for various flavours of Windows\n // if the environment variables above have failed\n\n // Roaming profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Roaming\", \"gnupg\", \"secring.gpg\"));\n // Local profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Local\", \"gnupg\", \"secring.gpg\"));\n // Roaming profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n // Local profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Local Settings\", \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n\n // *nix, including OS X\n if (home != null) {\n locations.add(joinLocalPath(home, \".gnupg\", \"secring.gpg\"));\n }\n\n return locations;\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 static String readStringFromUrlGeneric(String url)\n throws IOException {\n InputStream is = null;\n URL urlObj = null;\n String responseString = PcConstants.NA;\n try {\n urlObj = new URL(url);\n URLConnection con = urlObj.openConnection();\n\n con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis);\n con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis);\n is = con.getInputStream();\n\n BufferedReader rd = new BufferedReader(new InputStreamReader(is,\n Charset.forName(\"UTF-8\")));\n responseString = PcFileNetworkIoUtils.readAll(rd);\n\n } finally {\n\n if (is != null) {\n is.close();\n }\n\n }\n\n return responseString;\n }"
] |
If this address section is equivalent to the mask for a CIDR prefix block, it returns that prefix length.
Otherwise, it returns null.
A CIDR network mask is an address with all 1s in the network section and then all 0s in the host section.
A CIDR host mask is an address with all 0s in the network section and then all 1s in the host section.
The prefix length is the length of the network section.
Also, keep in mind that the prefix length returned by this method is not equivalent to the prefix length used to construct this object.
The prefix length used to construct indicates the network and host section of this address.
The prefix length returned here indicates the whether the value of this address can be used as a mask for the network and host
section of any other address. Therefore the two values can be different values, or one can be null while the other is not.
This method applies only to the lower value of the range if this section represents multiple values.
@param network whether to check for a network mask or a host mask
@return the prefix length corresponding to this mask, or null if there is no such prefix length | [
"public Integer getBlockMaskPrefixLength(boolean network) {\n\t\tInteger prefixLen;\n\t\tif(network) {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.networkMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t} else {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.hostMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setHostMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t}\n\t\tif(prefixLen < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn prefixLen;\n\t}"
] | [
"public void setRotation(String rotation) {\r\n if (rotation != null) {\r\n try {\r\n setRotation(Integer.parseInt(rotation));\r\n } catch (NumberFormatException e) {\r\n setRotation(-1);\r\n }\r\n }\r\n }",
"public static MetadataTemplate getMetadataTemplateByID(BoxAPIConnection api, String templateID) {\n\n URL url = METADATA_TEMPLATE_BY_ID_URL_TEMPLATE.build(api.getBaseURL(), templateID);\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new MetadataTemplate(response.getJSON());\n }",
"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 SimpleFeatureSource getFeatureSource() throws LayerException {\n\t\ttry {\n\t\t\tif (dataStore instanceof WFSDataStore) {\n\t\t\t\treturn dataStore.getFeatureSource(featureSourceName.replace(\":\", \"_\"));\n\t\t\t} else {\n\t\t\t\treturn dataStore.getFeatureSource(featureSourceName);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new LayerException(e, ExceptionCode.FEATURE_MODEL_PROBLEM,\n\t\t\t\t\t\"Cannot find feature source \" + featureSourceName);\n\t\t} catch (NullPointerException e) {\n\t\t\tthrow new LayerException(e, ExceptionCode.FEATURE_MODEL_PROBLEM,\n\t\t\t\t\t\"Cannot find feature source \" + featureSourceName);\n\t\t}\n\t}",
"public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) {\n return getObjectFromJSONPath(record, path);\n }",
"public static boolean isConstructorCall(Expression expression, List<String> classNames) {\r\n return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName());\r\n }",
"private String FCMGetFreshToken(final String senderID) {\n String token = null;\n try {\n if(senderID != null){\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token with Sender Id - \"+senderID);\n token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);\n }else {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token\");\n token = FirebaseInstanceId.getInstance().getToken();\n }\n getConfigLogger().info(getAccountId(),\"FCM token: \"+token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Error requesting FCM token\", t);\n }\n return token;\n }",
"public static base_response unset(nitro_service client, responderpolicy resource, String[] args) throws Exception{\n\t\tresponderpolicy unsetresource = new responderpolicy();\n\t\tunsetresource.name = resource.name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate(\n String listStr, boolean removeDuplicate) {\n\n List<String> nodes = new ArrayList<String>();\n\n for (String token : listStr.split(\"[\\\\r?\\\\n| +]+\")) {\n\n // 20131025: fix if fqdn has space in the end.\n if (token != null && !token.trim().isEmpty()) {\n nodes.add(token.trim());\n\n }\n }\n\n if (removeDuplicate) {\n removeDuplicateNodeList(nodes);\n }\n logger.info(\"Target hosts size : \" + nodes.size());\n\n return nodes;\n\n }"
] |
This is a convenience method provided to allow a day to be set
as working or non-working, by using the day number to
identify the required day.
@param day required day
@param working flag indicating if the day is a working day | [
"public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }"
] | [
"public static void writeFully(ByteBuffer buffer, WritableByteChannel channel) throws IOException {\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\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 static Date getSentDate(MimeMessage msg, Date defaultVal) {\r\n if (msg == null) {\r\n return defaultVal;\r\n }\r\n try {\r\n Date sentDate = msg.getSentDate();\r\n if (sentDate == null) {\r\n return defaultVal;\r\n } else {\r\n return sentDate;\r\n }\r\n } catch (MessagingException me) {\r\n return new Date();\r\n }\r\n }",
"private void readRecord(Tokenizer tk, List<String> record) throws IOException\n {\n record.clear();\n while (tk.nextToken() == Tokenizer.TT_WORD)\n {\n record.add(tk.getToken());\n }\n }",
"public String registerHandler(GFXEventHandler handler) {\n String uuid = UUID.randomUUID().toString();\n handlers.put(uuid, handler);\n return uuid;\n }",
"public ServerGroup getServerGroup(int id, int profileId) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n if (id == 0) {\n return new ServerGroup(0, \"Default\", profileId);\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerGroup curGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.GENERIC_NAME),\n results.getInt(Constants.GENERIC_PROFILE_ID));\n return curGroup;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }",
"public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException {\n build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(),\n getSvnAuthenticationProvider(build), buildListener));\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 }",
"private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }"
] |
Gets the name for the getter for this property
@return The name of the property. The name is "get"+ the capitalized propertyName
or, in the case of boolean values, "is" + the capitalized propertyName | [
"public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }"
] | [
"public Resource addReference(Reference reference) {\n\t\tResource resource = this.rdfWriter.getUri(Vocabulary.getReferenceUri(reference));\n\n\t\tthis.referenceQueue.add(reference);\n\t\tthis.referenceSubjectQueue.add(resource);\n\n\t\treturn resource;\n\t}",
"public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\n }",
"private void attachMeta(final JSONObject o, final Context context) {\n // Memory consumption\n try {\n o.put(\"mc\", Utils.getMemoryConsumption());\n } catch (Throwable t) {\n // Ignore\n }\n\n // Attach the network type\n try {\n o.put(\"nt\", Utils.getCurrentNetworkType(context));\n } catch (Throwable t) {\n // Ignore\n }\n }",
"public static String readContent(InputStream is) {\n String ret = \"\";\n try {\n String line;\n BufferedReader in = new BufferedReader(new InputStreamReader(is));\n StringBuffer out = new StringBuffer();\n\n while ((line = in.readLine()) != null) {\n out.append(line).append(CARRIAGE_RETURN);\n }\n ret = out.toString();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return ret;\n }",
"private boolean isSecuredByPolicy(Server server) {\n boolean isSecured = false;\n\n EndpointInfo ei = server.getEndpoint().getEndpointInfo();\n\n PolicyEngine pe = bus.getExtension(PolicyEngine.class);\n if (null == pe) {\n LOG.finest(\"No Policy engine found\");\n return isSecured;\n }\n\n Destination destination = server.getDestination();\n EndpointPolicy ep = pe.getServerEndpointPolicy(ei, destination, null);\n Collection<Assertion> assertions = ep.getChosenAlternative();\n for (Assertion a : assertions) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n Policy policy = ep.getPolicy();\n List<PolicyComponent> pcList = policy.getPolicyComponents();\n for (PolicyComponent a : pcList) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n return isSecured;\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addBooleanFilter(String attribute, Boolean value) {\n booleanFilterMap.put(attribute, value);\n rebuildQueryFacetFilters();\n return this;\n }",
"private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }",
"public static byte[] storeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws IOException, OperationFailedException {\n if (!operation.hasDefined(CONTENT)) {\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final ModelNode content = operation.get(CONTENT).get(0);\n if (content.hasDefined(HASH)) {\n // This should be handled as part of the OSH\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final byte[] hash = storeDeploymentContent(context, operation, contentRepository);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }",
"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}"
] |
Decrements the client's use count, and makes it eligible for closing if it is no longer in use.
@param client the dbserver connection client which is no longer being used for a task | [
"private synchronized void freeClient(Client client) {\n int current = useCounts.get(client);\n if (current > 0) {\n timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now.\n useCounts.put(client, current - 1);\n if ((current == 1) && (idleLimit.get() == 0)) {\n closeClient(client); // This was the last use, and we are supposed to immediately close idle clients.\n }\n } else {\n logger.error(\"Ignoring attempt to free a client that is not allocated: {}\", client);\n }\n }"
] | [
"public static List<Versioned<byte[]>> resolveVersions(List<Versioned<byte[]>> values) {\n List<Versioned<byte[]>> resolvedVersions = new ArrayList<Versioned<byte[]>>(values.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<byte[]> value: values) {\n Iterator<Versioned<byte[]>> iter = resolvedVersions.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<byte[]> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(!obsolete) {\n // else update the set of accepted versions\n resolvedVersions.add(value);\n }\n }\n\n return resolvedVersions;\n }",
"public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }",
"private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }",
"public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }",
"@Override\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> deploymentConfig = entities.stream()\n .filter(hm -> hm instanceof DeploymentConfig)\n .map(hm -> (DeploymentConfig) hm)\n .map(dc -> dc.getMetadata().getName()).findFirst();\n\n deploymentConfig.ifPresent(name -> this.applicationName = name);\n }\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 onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case REQUEST_PERMISSIONS_CODE:\n if (listener != null) {\n boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;\n listener.onPermissionResult(granted);\n }\n break;\n default:\n // Ignored\n }\n }",
"public static Iterable<BoxGroup.Info> getAllGroupsByName(final BoxAPIConnection api, String name) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (name == null || name.trim().isEmpty()) {\n throw new BoxAPIException(\"Searching groups by name requires a non NULL or non empty name\");\n } else {\n builder.appendParam(\"name\", name);\n }\n\n return new Iterable<BoxGroup.Info>() {\n public Iterator<BoxGroup.Info> iterator() {\n URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxGroupIterator(api, url);\n }\n };\n }",
"public static Thumbor create(String host, String key) {\n if (key == null || key.length() == 0) {\n throw new IllegalArgumentException(\"Key must not be blank.\");\n }\n return new Thumbor(host, key);\n }"
] |
Recursively construct a LblTree from DOM tree
@param walker tree walker for DOM tree traversal
@return tree represented by DOM tree | [
"private static LblTree createTree(TreeWalker walker) {\n\t\tNode parent = walker.getCurrentNode();\n\t\tLblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1\n\t\tfor (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {\n\t\t\tnode.add(createTree(walker));\n\t\t}\n\t\twalker.setCurrentNode(parent);\n\t\treturn node;\n\t}"
] | [
"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 <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}",
"public static sslocspresponder get(nitro_service service, String name) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tobj.set_name(name);\n\t\tsslocspresponder response = (sslocspresponder) obj.get_resource(service);\n\t\treturn response;\n\t}",
"protected boolean prepareClose() {\n synchronized (lock) {\n final State state = this.state;\n if (state == State.OPEN) {\n this.state = State.CLOSING;\n lock.notifyAll();\n return true;\n }\n }\n return false;\n }",
"private QueueCursor updateCursorForDBObject(JSONObject dbObject, QueueCursor cursor) {\n\n if (dbObject == null) return cursor;\n\n Iterator<String> keys = dbObject.keys();\n if (keys.hasNext()) {\n String key = keys.next();\n cursor.setLastId(key);\n try {\n cursor.setData(dbObject.getJSONArray(key));\n } catch (JSONException e) {\n cursor.setLastId(null);\n cursor.setData(null);\n }\n }\n\n return cursor;\n }",
"public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }",
"@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}",
"protected void parseOperationsLR(Symbol ops[], TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n boolean hasLeft = false;\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.VARIABLE ) {\n if( hasLeft ) {\n if( isTargetOp(token.previous,ops)) {\n token = createOp(token.previous.previous,token.previous,token,tokens,sequence);\n }\n } else {\n hasLeft = true;\n }\n } else {\n if( token.previous.getType() == Type.SYMBOL ) {\n throw new ParseError(\"Two symbols next to each other. \"+token.previous+\" and \"+token);\n }\n }\n token = token.next;\n }\n }",
"public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }"
] |
Join to internal threads and wait millis time per thread or until all
threads are finished if millis is 0.
@param millis the time to wait in milliseconds for the threads to join; a timeout of 0 means to wait forever.
@throws InterruptedException if any thread has interrupted the current thread.
The interrupted status of the current thread is cleared when this exception is thrown. | [
"@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\n }\n }"
] | [
"public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }",
"@Override\n public void prettyPrint(StringBuffer sb, int indent)\n {\n sb.append(Log.getSpaces(indent));\n sb.append(GVRBone.class.getSimpleName());\n sb.append(\" [name=\" + getName() + \", boneId=\" + getBoneId()\n + \", offsetMatrix=\" + getOffsetMatrix()\n + \", finalTransformMatrix=\" + getFinalTransformMatrix() // crashes debugger\n + \"]\");\n sb.append(System.lineSeparator());\n }",
"public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }",
"public CmsJspInstanceDateBean getToInstanceDate() {\n\n if (m_instanceDate == null) {\n m_instanceDate = new CmsJspInstanceDateBean(getToDate(), m_cms.getRequestContext().getLocale());\n }\n return m_instanceDate;\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void enableDeviceNetworkInfoReporting(boolean value){\n enableNetworkInfoReporting = value;\n StorageHelper.putBoolean(context,storageKeyWithSuffix(Constants.NETWORK_INFO),enableNetworkInfoReporting);\n getConfigLogger().verbose(getAccountId(), \"Device Network Information reporting set to \" + enableNetworkInfoReporting);\n }",
"private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {\n\n int i, j;\n QrMode currentMode;\n int inputLength = inputModeUnoptimized.length;\n int count = 0;\n int alphaLength;\n int percent = 0;\n\n // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave\n // the original array alone so that subsequent binary length checks don't irrevocably\n // optimize the mode array for the wrong QR Code version\n QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);\n\n currentMode = QrMode.NULL;\n\n if (gs1) {\n count += 4;\n }\n\n if (eciMode != 3) {\n count += 12;\n }\n\n for (i = 0; i < inputLength; i++) {\n if (inputMode[i] != currentMode) {\n count += 4;\n switch (inputMode[i]) {\n case KANJI:\n count += tribus(version, 8, 10, 12);\n count += (blockLength(i, inputMode) * 13);\n break;\n case BINARY:\n count += tribus(version, 8, 16, 16);\n for (j = i; j < (i + blockLength(i, inputMode)); j++) {\n if (inputData[j] > 0xff) {\n count += 16;\n } else {\n count += 8;\n }\n }\n break;\n case ALPHANUM:\n count += tribus(version, 9, 11, 13);\n alphaLength = blockLength(i, inputMode);\n // In alphanumeric mode % becomes %%\n if (gs1) {\n for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b\n if (inputData[j] == '%') {\n percent++;\n }\n }\n }\n alphaLength += percent;\n switch (alphaLength % 2) {\n case 0:\n count += (alphaLength / 2) * 11;\n break;\n case 1:\n count += ((alphaLength - 1) / 2) * 11;\n count += 6;\n break;\n }\n break;\n case NUMERIC:\n count += tribus(version, 10, 12, 14);\n switch (blockLength(i, inputMode) % 3) {\n case 0:\n count += (blockLength(i, inputMode) / 3) * 10;\n break;\n case 1:\n count += ((blockLength(i, inputMode) - 1) / 3) * 10;\n count += 4;\n break;\n case 2:\n count += ((blockLength(i, inputMode) - 2) / 3) * 10;\n count += 7;\n break;\n }\n break;\n }\n currentMode = inputMode[i];\n }\n }\n\n return count;\n }",
"private void readZookeeperConfig() {\n\n try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {\n curator.start();\n\n accumuloInstance =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),\n StandardCharsets.UTF_8);\n accumuloInstanceID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),\n StandardCharsets.UTF_8);\n fluoApplicationID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),\n StandardCharsets.UTF_8);\n\n table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),\n StandardCharsets.UTF_8);\n\n observers = ObserverUtil.load(curator);\n\n config = FluoAdminImpl.mergeZookeeperConfig(config);\n\n // make sure not to include config passed to env, only want config from zookeeper\n appConfig = config.getAppConfiguration();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }",
"public T insert(T entity) {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to insert entity of type %s with null or zero primary key\",\n entity.getClass().getSimpleName()));\n }\n\n InsertCreator insert = new InsertCreator(table);\n\n insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n insert.setValue(versionColumn.getColumnName(), 0);\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n new JdbcTemplate(ormConfig.getDataSource()).update(insert);\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0);\n }\n\n return entity;\n }",
"@Override\n public AuthInterface getAuthInterface() {\n if (authInterface == null) {\n authInterface = new AuthInterface(apiKey, sharedSecret, transport);\n }\n return authInterface;\n }"
] |
Evaluates the body if current member has no tag with the specified name.
@param template The body of the block tag
@param attributes The attributes of the template tag
@exception XDocletException Description of Exception
@doc.tag type="block"
@doc.param name="tagName" optional="false" description="The tag name."
@doc.param name="paramName" description="The parameter name. If not specified, then the raw
content of the tag is returned."
@doc.param name="paramNum" description="The zero-based parameter number. It's used if the user
used the space-separated format for specifying parameters."
@doc.param name="error" description="Show this error message if no tag found." | [
"public void ifDoesntHaveMemberTag(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean result = false;\r\n\r\n if (getCurrentField() != null) {\r\n if (!hasTag(attributes, FOR_FIELD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (!hasTag(attributes, FOR_METHOD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n if (!result) {\r\n String error = attributes.getProperty(\"error\");\r\n\r\n if (error != null) {\r\n getEngine().print(error);\r\n }\r\n }\r\n }"
] | [
"private void emitSuiteEnd(AggregatedSuiteResultEvent e, int suitesCompleted) throws IOException {\n assert showSuiteSummary;\n\n final StringBuilder b = new StringBuilder();\n final int totalErrors = this.totalErrors.addAndGet(e.isSuccessful() ? 0 : 1);\n b.append(String.format(Locale.ROOT, \"%sCompleted [%d/%d%s]%s in %.2fs, \",\n shortTimestamp(e.getStartTimestamp() + e.getExecutionTime()),\n suitesCompleted,\n totalSuites,\n totalErrors == 0 ? \"\" : \" (\" + totalErrors + \"!)\",\n e.getSlave().slaves > 1 ? \" on J\" + e.getSlave().id : \"\",\n e.getExecutionTime() / 1000.0d));\n b.append(e.getTests().size()).append(Pluralize.pluralize(e.getTests().size(), \" test\"));\n\n int failures = e.getFailureCount();\n if (failures > 0) {\n b.append(\", \").append(failures).append(Pluralize.pluralize(failures, \" failure\"));\n }\n\n int errors = e.getErrorCount();\n if (errors > 0) {\n b.append(\", \").append(errors).append(Pluralize.pluralize(errors, \" error\"));\n }\n\n int ignored = e.getIgnoredCount();\n if (ignored > 0) {\n b.append(\", \").append(ignored).append(\" skipped\");\n }\n\n if (!e.isSuccessful()) {\n b.append(FAILURE_STRING);\n }\n\n b.append(\"\\n\");\n logShort(b, false);\n }",
"protected B fields(List<F> fields) {\n if (instance.def.fields == null) {\n instance.def.fields = new ArrayList<F>(fields.size());\n }\n instance.def.fields.addAll(fields);\n return returnThis();\n }",
"public static gslbservice_stats get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice_stats response = (gslbservice_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }",
"SimpleJsonEncoder appendToJSON(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n if (value instanceof Number) {\n sb.append(value.toString());\n } else {\n sb.append(QUOTE).append(escapeString(value.toString())).append(QUOTE);\n }\n }\n return this;\n }",
"public void setWorkDir(String dir) throws IOException\r\n {\r\n File workDir = new File(dir);\r\n\r\n if (!workDir.exists() || !workDir.canWrite() || !workDir.canRead())\r\n {\r\n throw new IOException(\"Cannot access directory \"+dir);\r\n }\r\n _workDir = workDir;\r\n }",
"@VisibleForTesting\n protected static double getNearestNiceValue(\n final double value, final DistanceUnit scaleUnit, final boolean lockUnits) {\n DistanceUnit bestUnit = bestUnit(scaleUnit, value, lockUnits);\n double factor = scaleUnit.convertTo(1.0, bestUnit);\n\n // nearest power of 10 lower than value\n int digits = (int) Math.floor((Math.log(value * factor) / Math.log(10)));\n double pow10 = Math.pow(10, digits);\n\n // ok, find first character\n double firstChar = value * factor / pow10;\n\n // right, put it into the correct bracket\n int barLen;\n if (firstChar >= 10.0) {\n barLen = 10;\n } else if (firstChar >= 5.0) {\n barLen = 5;\n } else if (firstChar >= 2.0) {\n barLen = 2;\n } else {\n barLen = 1;\n }\n\n // scale it up the correct power of 10\n return barLen * pow10 / factor;\n }",
"public float getBoundsWidth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.x - v.minCorner.x;\n }\n return 0f;\n }",
"@SuppressWarnings(\"unchecked\")\n @Nonnull\n public final java.util.Optional<Style> getStyle(final String styleName) {\n final String styleRef = this.styles.get(styleName);\n Optional<Style> style;\n if (styleRef != null) {\n style = (Optional<Style>) this.styleParser\n .loadStyle(getConfiguration(), this.httpRequestFactory, styleRef);\n } else {\n style = Optional.empty();\n }\n return or(style, this.configuration.getStyle(styleName));\n }"
] |
Use this API to add sslocspresponder. | [
"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}"
] | [
"public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\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 Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }",
"protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) {\n this.valid = false;\n for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) {\n if (annotatedAnnotation.isAnnotationPresent(annotationType)) {\n this.valid = true;\n }\n }\n }",
"private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }",
"private MapRow getRow(int index)\n {\n MapRow result;\n\n if (index == m_rows.size())\n {\n result = new MapRow(this, new HashMap<FastTrackField, Object>());\n m_rows.add(result);\n }\n else\n {\n result = m_rows.get(index);\n }\n\n return result;\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public UTMDetail getUTMDetails() {\n UTMDetail ud = new UTMDetail();\n ud.setSource(source);\n ud.setMedium(medium);\n ud.setCampaign(campaign);\n return ud;\n }",
"public void retrieveReference(Object pInstance, String pAttributeName) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n \tlogger.debug(\"Retrieving reference named [\"+pAttributeName+\"] on object of type [\"+\n \t pInstance.getClass().getName()+\"]\");\n }\n ClassDescriptor cld = getClassDescriptor(pInstance.getClass());\n CollectionDescriptor cod = cld.getCollectionDescriptorByName(pAttributeName);\n getInternalCache().enableMaterializationCache();\n // to avoid problems with circular references, locally cache the current object instance\n Identity oid = serviceIdentity().buildIdentity(pInstance);\n boolean needLocalRemove = false;\n if(getInternalCache().doLocalLookup(oid) == null)\n {\n getInternalCache().doInternalCache(oid, pInstance, MaterializationCache.TYPE_TEMP);\n needLocalRemove = true;\n }\n try\n {\n if (cod != null)\n {\n referencesBroker.retrieveCollection(pInstance, cld, cod, true);\n }\n else\n {\n ObjectReferenceDescriptor ord = cld.getObjectReferenceDescriptorByName(pAttributeName);\n if (ord != null)\n {\n referencesBroker.retrieveReference(pInstance, cld, ord, true);\n }\n else\n {\n throw new PersistenceBrokerException(\"did not find attribute \" + pAttributeName +\n \" for class \" + pInstance.getClass().getName());\n }\n }\n // do locally remove the object to avoid problems with object state detection (insert/update),\n // because objects found in the cache detected as 'old' means 'update'\n if(needLocalRemove) getInternalCache().doLocalRemove(oid);\n getInternalCache().disableMaterializationCache();\n }\n catch(RuntimeException e)\n {\n getInternalCache().doLocalClear();\n throw e;\n }\n }",
"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 }",
"protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"private Task readTask(ChildTaskContainer parent, Integer id)\n {\n Table a0 = getTable(\"A0TAB\");\n Table a1 = getTable(\"A1TAB\");\n Table a2 = getTable(\"A2TAB\");\n Table a3 = getTable(\"A3TAB\");\n Table a4 = getTable(\"A4TAB\");\n\n Task task = parent.addTask();\n MapRow a1Row = a1.find(id);\n MapRow a2Row = a2.find(id);\n\n setFields(A0TAB_FIELDS, a0.find(id), task);\n setFields(A1TAB_FIELDS, a1Row, task);\n setFields(A2TAB_FIELDS, a2Row, task);\n setFields(A3TAB_FIELDS, a3.find(id), task);\n setFields(A5TAB_FIELDS, a4.find(id), task);\n\n task.setStart(task.getEarlyStart());\n task.setFinish(task.getEarlyFinish());\n if (task.getName() == null)\n {\n task.setName(task.getText(1));\n }\n\n m_eventManager.fireTaskReadEvent(task);\n\n return task;\n }"
] |
Return the hostname of this address such as "MYCOMPUTER". | [
"public String getHostName() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostName();\n }\n return ((InetAddress)addr).getHostName();\n }"
] | [
"public final ZoomToFeatures copy() {\n ZoomToFeatures obj = new ZoomToFeatures();\n obj.zoomType = this.zoomType;\n obj.minScale = this.minScale;\n obj.minMargin = this.minMargin;\n return obj;\n }",
"public static double extractColumnAndMax( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU) {\n int indexU = (offsetU+row0)*2;\n\n // find the largest value in this column\n // this is used to normalize the column and mitigate overflow/underflow\n double max = 0;\n\n int indexA = A.getIndex(row0,col);\n double h[] = A.data;\n\n for( int i = row0; i < row1; i++, indexA += A.numCols*2 ) {\n // copy the householder vector to an array to reduce cache misses\n // big improvement on larger matrices and a relatively small performance hit on small matrices.\n double realVal = u[indexU++] = h[indexA];\n double imagVal = u[indexU++] = h[indexA+1];\n\n double magVal = realVal*realVal + imagVal*imagVal;\n if( max < magVal ) {\n max = magVal;\n }\n }\n return Math.sqrt(max);\n }",
"public ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {\n Objects.requireNonNull(rateTypes);\n if (rateTypes.isEmpty()) {\n throw new IllegalArgumentException(\"At least one RateType is required.\");\n }\n Set<RateType> rtSet = new HashSet<>(rateTypes);\n set(ProviderContext.KEY_RATE_TYPES, rtSet);\n return this;\n }",
"public static aaagroup_vpnsessionpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpnsessionpolicy_binding obj = new aaagroup_vpnsessionpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpnsessionpolicy_binding response[] = (aaagroup_vpnsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private Class<?> beanType(String name) {\n\t\tClass<?> type = context.getType(name);\n\t\tif (ClassUtils.isCglibProxyClass(type)) {\n\t\t\treturn AopProxyUtils.ultimateTargetClass(context.getBean(name));\n\t\t}\n\t\treturn type;\n\t}",
"public void execute() throws MojoExecutionException, MojoFailureException {\n try {\n Set<File> thriftFiles = findThriftFiles();\n\n final File outputDirectory = getOutputDirectory();\n ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());\n\n Set<String> compileRoots = new HashSet<String>();\n compileRoots.add(\"scrooge\");\n\n if (thriftFiles.isEmpty()) {\n getLog().info(\"No thrift files to compile.\");\n } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {\n getLog().info(\"Generated thrift files up to date, skipping compile.\");\n attachFiles(compileRoots);\n } else {\n outputDirectory.mkdirs();\n\n // Quick fix to fix issues with two mvn installs in a row (ie no clean)\n cleanDirectory(outputDirectory);\n\n getLog().info(format(\"compiling thrift files %s with Scrooge\", thriftFiles));\n synchronized(lock) {\n ScroogeRunner runner = new ScroogeRunner();\n Map<String, String> thriftNamespaceMap = new HashMap<String, String>();\n for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {\n thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());\n }\n\n // Include thrifts from resource as well.\n Set<File> includes = thriftIncludes;\n includes.add(getResourcesOutputDirectory());\n\n // Include thrift root\n final File thriftSourceRoot = getThriftSourceRoot();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n includes.add(thriftSourceRoot);\n }\n\n runner.compile(\n getLog(),\n includeOutputDirectoryNamespace ? new File(outputDirectory, \"scrooge\") : outputDirectory,\n thriftFiles,\n includes,\n thriftNamespaceMap,\n language,\n thriftOpts);\n }\n attachFiles(compileRoots);\n }\n } catch (IOException e) {\n throw new MojoExecutionException(\"An IO error occurred\", e);\n }\n }",
"public Swagger read(Set<Class<?>> classes) {\n Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {\n if (class1.equals(class2)) {\n return 0;\n } else if (class1.isAssignableFrom(class2)) {\n return -1;\n } else if (class2.isAssignableFrom(class1)) {\n return 1;\n }\n return class1.getName().compareTo(class2.getName());\n });\n sortedClasses.addAll(classes);\n\n Map<Class<?>, ReaderListener> listeners = new HashMap<Class<?>, ReaderListener>();\n\n for (Class<?> cls : sortedClasses) {\n if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {\n try {\n listeners.put(cls, (ReaderListener) cls.newInstance());\n } catch (Exception e) {\n LOGGER.error(\"Failed to create ReaderListener\", e);\n }\n }\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.beforeScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking beforeScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n // process SwaggerDefinitions first - so we get tags in desired order\n for (Class<?> cls : sortedClasses) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n }\n\n for (Class<?> cls : sortedClasses) {\n read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.afterScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking afterScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n return swagger;\n }",
"private String getInitials(String name)\n {\n String result = null;\n\n if (name != null && name.length() != 0)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(name.charAt(0));\n int index = 1;\n while (true)\n {\n index = name.indexOf(' ', index);\n if (index == -1)\n {\n break;\n }\n\n ++index;\n if (index < name.length() && name.charAt(index) != ' ')\n {\n sb.append(name.charAt(index));\n }\n\n ++index;\n }\n\n result = sb.toString();\n }\n\n return result;\n }",
"public void resizeKeys(int numKeys)\n {\n int n = numKeys * mFloatsPerKey;\n if (mKeys.length == n)\n {\n return;\n }\n float[] newKeys = new float[n];\n n = Math.min(n, mKeys.length);\n\n System.arraycopy(mKeys, 0, newKeys, 0, n);\n mKeys = newKeys;\n mFloatInterpolator.setKeyData(mKeys);\n }"
] |
Adds a metadata classification to the specified file.
@param classificationType the metadata classification type.
@return the metadata classification type added to the file. | [
"public String addClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY,\n \"enterprise\", metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }"
] | [
"private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // 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), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }",
"public void addFileSet(FileSet fs) {\n add(fs);\n if (fs.getProject() == null) {\n fs.setProject(getProject());\n }\n }",
"private void processStages() {\n\n // Locate the next step to execute.\n ModelNode primaryResponse = null;\n Step step;\n do {\n step = steps.get(currentStage).pollFirst();\n if (step == null) {\n\n if (currentStage == Stage.MODEL && addModelValidationSteps()) {\n continue;\n }\n // No steps remain in this stage; give subclasses a chance to check status\n // and approve moving to the next stage\n if (!tryStageCompleted(currentStage)) {\n // Can't continue\n resultAction = ResultAction.ROLLBACK;\n executeResultHandlerPhase(null);\n return;\n }\n // Proceed to the next stage\n if (currentStage.hasNext()) {\n currentStage = currentStage.next();\n if (currentStage == Stage.VERIFY) {\n // a change was made to the runtime. Thus, we must wait\n // for stability before resuming in to verify.\n try {\n awaitServiceContainerStability();\n } catch (InterruptedException e) {\n cancelled = true;\n handleContainerStabilityFailure(primaryResponse, e);\n executeResultHandlerPhase(null);\n return;\n } catch (TimeoutException te) {\n // The service container is in an unknown state; but we don't require restart\n // because rollback may allow the container to stabilize. We force require-restart\n // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)\n //processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback\n handleContainerStabilityFailure(primaryResponse, te);\n executeResultHandlerPhase(null);\n return;\n }\n }\n }\n } else {\n // The response to the first step is what goes to the outside caller\n if (primaryResponse == null) {\n primaryResponse = step.response;\n }\n // Execute the step, but make sure we always finalize any steps\n Throwable toThrow = null;\n // Whether to return after try/finally\n boolean exit = false;\n try {\n CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step);\n if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) {\n executeStep(step);\n } else {\n String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED\n ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD;\n step.response.get(RESPONSE_HEADERS, header).set(true);\n }\n } catch (RuntimeException | Error re) {\n resultAction = ResultAction.ROLLBACK;\n toThrow = re;\n } finally {\n // See if executeStep put us in a state where we shouldn't do any more\n if (toThrow != null || !canContinueProcessing()) {\n // We're done.\n executeResultHandlerPhase(toThrow);\n exit = true; // we're on the return path\n }\n }\n if (exit) {\n return;\n }\n }\n } while (currentStage != Stage.DONE);\n\n assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps\n\n // All steps ran and canContinueProcessing returned true for the last one, so...\n executeDoneStage(primaryResponse);\n }",
"public Optional<URL> getRoute() {\n Optional<Route> optionalRoute = getClient().routes().inNamespace(namespace)\n .list().getItems()\n .stream()\n .findFirst();\n\n return optionalRoute\n .map(OpenShiftRouteLocator::createUrlFromRoute);\n }",
"public void generateReport(List<XmlSuite> xmlSuites,\n List<ISuite> suites,\n String outputDirectoryName)\n {\n removeEmptyDirectories(new File(outputDirectoryName));\n \n boolean useFrames = System.getProperty(FRAMES_PROPERTY, \"true\").equals(\"true\");\n boolean onlyFailures = System.getProperty(ONLY_FAILURES_PROPERTY, \"false\").equals(\"true\");\n\n File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);\n outputDirectory.mkdirs();\n\n try\n {\n if (useFrames)\n {\n createFrameset(outputDirectory);\n }\n createOverview(suites, outputDirectory, !useFrames, onlyFailures);\n createSuiteList(suites, outputDirectory, onlyFailures);\n createGroups(suites, outputDirectory);\n createResults(suites, outputDirectory, onlyFailures);\n createLog(outputDirectory, onlyFailures);\n copyResources(outputDirectory);\n }\n catch (Exception ex)\n {\n throw new ReportNGException(\"Failed generating HTML report.\", ex);\n }\n }",
"public final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }",
"public 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 }",
"private static void updateBaseCalendarNames(List<Pair<ProjectCalendar, BigInteger>> baseCalendars, HashMap<BigInteger, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, BigInteger> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n BigInteger baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n\n }",
"public static void validateClusterPartitionState(final Cluster subsetCluster,\n final Cluster supersetCluster) {\n if(!supersetCluster.getNodeIds().containsAll(subsetCluster.getNodeIds())) {\n throw new VoldemortException(\"Superset cluster does not contain all nodes from subset cluster[ subset cluster node ids (\"\n + subsetCluster.getNodeIds()\n + \") are not a subset of superset cluster node ids (\"\n + supersetCluster.getNodeIds() + \") ]\");\n\n }\n for(int nodeId: subsetCluster.getNodeIds()) {\n Node supersetNode = supersetCluster.getNodeById(nodeId);\n Node subsetNode = subsetCluster.getNodeById(nodeId);\n if(!supersetNode.getPartitionIds().equals(subsetNode.getPartitionIds())) {\n throw new VoldemortRebalancingException(\"Partition IDs do not match between clusters for nodes with id \"\n + nodeId\n + \" : subset cluster has \"\n + subsetNode.getPartitionIds()\n + \" and superset cluster has \"\n + supersetNode.getPartitionIds());\n }\n }\n Set<Integer> nodeIds = supersetCluster.getNodeIds();\n nodeIds.removeAll(subsetCluster.getNodeIds());\n for(int nodeId: nodeIds) {\n Node supersetNode = supersetCluster.getNodeById(nodeId);\n if(!supersetNode.getPartitionIds().isEmpty()) {\n throw new VoldemortRebalancingException(\"New node \"\n + nodeId\n + \" in superset cluster already has partitions: \"\n + supersetNode.getPartitionIds());\n }\n }\n }"
] |
Use this API to add dnsaaaarec resources. | [
"public static base_responses add(nitro_service client, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec addresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsaaaarec();\n\t\t\t\taddresources[i].hostname = resources[i].hostname;\n\t\t\t\taddresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\n }",
"public static void columnMaxAbs( DMatrixSparseCSC A , double []values ) {\n if( values.length < A.numCols )\n throw new IllegalArgumentException(\"Array is too small. \"+values.length+\" < \"+A.numCols);\n\n for (int i = 0; i < A.numCols; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n double maxabs = 0;\n for (int j = idx0; j < idx1; j++) {\n double v = Math.abs(A.nz_values[j]);\n if( v > maxabs )\n maxabs = v;\n }\n values[i] = maxabs;\n }\n }",
"public void setShadow(float radius, float dx, float dy, int color) {\n\t\tshadowRadius = radius;\n\t\tshadowDx = dx;\n\t\tshadowDy = dy;\n\t\tshadowColor = color;\n\t\tupdateShadow();\n\t}",
"protected void removeInvalidChildren() {\n\n if (getLoadState() == LoadState.LOADED) {\n List<CmsSitemapTreeItem> toDelete = new ArrayList<CmsSitemapTreeItem>();\n for (int i = 0; i < getChildCount(); i++) {\n CmsSitemapTreeItem item = (CmsSitemapTreeItem)getChild(i);\n CmsUUID id = item.getEntryId();\n if ((id != null) && (CmsSitemapView.getInstance().getController().getEntryById(id) == null)) {\n toDelete.add(item);\n }\n }\n for (CmsSitemapTreeItem deleteItem : toDelete) {\n m_children.removeItem(deleteItem);\n }\n }\n }",
"public static vlan[] get(nitro_service service) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tvlan[] response = (vlan[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private ArrayList<String> getRemoveHeaders() throws Exception {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n\n for (EndpointOverride selectedPath : requestInformation.get().selectedResponsePaths) {\n // check to see if there is custom override data or if we have headers to remove\n List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();\n for (EnabledEndpoint endpoint : points) {\n // skip if repeat count is 0\n if (endpoint.getRepeatNumber() == 0) {\n continue;\n }\n\n if (endpoint.getOverrideId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n // add to remove headers array\n headersToRemove.add(endpoint.getArguments()[0].toString());\n endpoint.decrementRepeatNumber();\n }\n }\n }\n\n return headersToRemove;\n }",
"static PatchingTask createTask(final PatchingTasks.ContentTaskDefinition definition, final PatchContentProvider provider, final IdentityPatchContext.PatchEntry context) {\n final PatchContentLoader contentLoader = provider.getLoader(definition.getTarget().getPatchId());\n final PatchingTaskDescription description = PatchingTaskDescription.create(definition, contentLoader);\n return PatchingTask.Factory.create(description, context);\n }",
"public static Date getDateFromLong(long date)\n {\n TimeZone tz = TimeZone.getDefault();\n return (new Date(date - tz.getRawOffset()));\n }",
"@SuppressWarnings(\"unchecked\")\n private static void parseProperties(JSONObject modelJSON,\n Shape current,\n Boolean keepGlossaryLink) throws JSONException {\n if (modelJSON.has(\"properties\")) {\n JSONObject propsObject = modelJSON.getJSONObject(\"properties\");\n Iterator<String> keys = propsObject.keys();\n Pattern pattern = Pattern.compile(jsonPattern);\n\n while (keys.hasNext()) {\n StringBuilder result = new StringBuilder();\n int lastIndex = 0;\n String key = keys.next();\n String value = propsObject.getString(key);\n\n if (!keepGlossaryLink) {\n Matcher matcher = pattern.matcher(value);\n while (matcher.find()) {\n String id = matcher.group(1);\n current.addGlossaryIds(id);\n String text = matcher.group(2);\n result.append(text);\n lastIndex = matcher.end();\n }\n result.append(value.substring(lastIndex));\n value = result.toString();\n }\n\n current.putProperty(key,\n value);\n }\n }\n }"
] |
Update the project properties from the project summary task.
@param task project summary task | [
"private void updateProjectProperties(Task task)\n {\n ProjectProperties props = m_projectFile.getProjectProperties();\n props.setComments(task.getNotes());\n }"
] | [
"private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) {\n\t\treturn IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString())\n\t\t\t\t.shouldDeleteMessages(this.properties.isDelete())\n\t\t\t\t.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead()));\n\t}",
"public static Map<String, String> mapStringToMap(String map) {\r\n String[] m = map.split(\"[,;]\");\r\n Map<String, String> res = new HashMap<String, String>();\r\n for (String str : m) {\r\n int index = str.lastIndexOf('=');\r\n String key = str.substring(0, index);\r\n String val = str.substring(index + 1);\r\n res.put(key.trim(), val.trim());\r\n }\r\n return res;\r\n }",
"public static ComplexNumber Tan(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.tan(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n double real2 = 2 * z1.real;\r\n double imag2 = 2 * z1.imaginary;\r\n double denom = Math.cos(real2) + Math.cosh(real2);\r\n\r\n result.real = Math.sin(real2) / denom;\r\n result.imaginary = Math.sinh(imag2) / denom;\r\n }\r\n\r\n return result;\r\n }",
"public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\n }",
"private char getCachedCharValue(FieldType field, char defaultValue)\n {\n Character c = (Character) getCachedValue(field);\n return c == null ? defaultValue : c.charValue();\n }",
"public static ComplexNumber Pow(ComplexNumber z1, double n) {\r\n\r\n double norm = Math.pow(z1.getMagnitude(), n);\r\n double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real)));\r\n\r\n double common = n * angle;\r\n\r\n double r = norm * Math.cos(Math.toRadians(common));\r\n double i = norm * Math.sin(Math.toRadians(common));\r\n\r\n return new ComplexNumber(r, i);\r\n\r\n }",
"public void reset( int N ) {\n this.N = N;\n\n this.diag = null;\n this.off = null;\n\n if( splits.length < N ) {\n splits = new int[N];\n }\n\n numSplits = 0;\n\n x1 = 0;\n x2 = N-1;\n\n steps = numExceptional = lastExceptional = 0;\n\n this.Q = null;\n }",
"public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\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 }"
] |
Sets the alias. Empty String is regarded as null.
@param alias The alias to set | [
"public void setAlias(String alias)\r\n\t{\r\n\t\tif (alias == null || alias.trim().equals(\"\"))\r\n\t\t{\r\n\t\t\tm_alias = null;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tm_alias = alias;\r\n\t\t}\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(m_alias);\r\n\t\t\t}\r\n\t\t}\r\n\t}"
] | [
"@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }",
"public void setSlideDrawable(Drawable drawable) {\n mSlideDrawable = new SlideDrawable(drawable);\n mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL);\n\n if (mActionBarHelper != null) {\n mActionBarHelper.setDisplayShowHomeAsUpEnabled(true);\n\n if (mDrawerIndicatorEnabled) {\n mActionBarHelper.setActionBarUpIndicator(mSlideDrawable,\n isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc);\n }\n }\n }",
"private void readRecurringData(ProjectCalendarException bce, Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n RecurrenceType rt = getRecurrenceType(NumberHelper.getInt(exception.getType()));\n if (rt != null)\n {\n RecurringData rd = new RecurringData();\n rd.setStartDate(bce.getFromDate());\n rd.setFinishDate(bce.getToDate());\n rd.setRecurrenceType(rt);\n rd.setRelative(getRelative(NumberHelper.getInt(exception.getType())));\n rd.setOccurrences(NumberHelper.getInteger(exception.getOccurrences()));\n\n switch (rd.getRecurrenceType())\n {\n case DAILY:\n {\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case WEEKLY:\n {\n rd.setWeeklyDaysFromBitmap(NumberHelper.getInteger(exception.getDaysOfWeek()), DAY_MASKS);\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case MONTHLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case YEARLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setMonthNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonth()) + 1));\n break;\n }\n }\n\n if (rd.getRecurrenceType() != RecurrenceType.DAILY || rd.getDates().length > 1)\n {\n bce.setRecurring(rd);\n }\n }\n }",
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}",
"public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }",
"private void populateContainer(FieldType field, List<Pair<String, String>> items)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n for (Pair<String, String> pair : items)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setValue(pair.getFirst());\n item.setDescription(pair.getSecond());\n table.add(item);\n }\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 String getUnicodeString(Integer id, Integer type)\n {\n return (getUnicodeString(m_meta.getOffset(id, type)));\n }",
"@Override\n @Deprecated\n public List<CardWithActions> getBoardMemberActivity(String boardId, String memberId,\n String actionFilter, Argument... args) {\n if (actionFilter == null)\n actionFilter = \"all\";\n Argument[] argsAndFilter = Arrays.copyOf(args, args.length + 1);\n argsAndFilter[args.length] = new Argument(\"actions\", actionFilter);\n\n return asList(() -> get(createUrl(GET_BOARD_MEMBER_CARDS).params(argsAndFilter).asString(),\n CardWithActions[].class, boardId, memberId));\n }"
] |
Release all memory addresses taken by this allocator.
Be careful in using this method, since all of the memory addresses become invalid. | [
"public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }"
] | [
"private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException {\n if (shouldWriteDecoratorAndElements(model)) {\n writer.writeStartElement(decoratorElement);\n persistChildren(writer, model);\n writer.writeEndElement();\n }\n }",
"public void updateProvider(final String gavc, final String provider) {\n final DbArtifact artifact = getArtifact(gavc);\n repositoryHandler.updateProvider(artifact, provider);\n }",
"public void setIndexBuffer(GVRIndexBuffer ibuf)\n {\n mIndices = ibuf;\n NativeMesh.setIndexBuffer(getNative(), (ibuf != null) ? ibuf.getNative() : 0L);\n }",
"private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }",
"private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)\r\n throws java.sql.SQLException\r\n {\r\n Statement result;\r\n try\r\n {\r\n // if necessary use JDBC1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n result =\r\n con.createStatement(\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result = con.createStatement();\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // if a JDBC1.0 driver is used, the signature\r\n // createStatement(int, int) is not defined.\r\n // we then call the JDBC1.0 variant createStatement()\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n result = con.createStatement();\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql.getClass().getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n FORCEJDBC1_0 = true;\r\n result = con.createStatement();\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }",
"public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\n }",
"private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) {\n MenuDrawer drawer;\n\n if (type == Type.STATIC) {\n drawer = new StaticDrawer(activity);\n\n } else if (type == Type.OVERLAY) {\n drawer = new OverlayDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n\n } else {\n drawer = new SlidingDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n }\n\n drawer.mDragMode = dragMode;\n drawer.setPosition(position);\n\n return drawer;\n }",
"private boolean isNullOrEmpty(Object paramValue) {\n boolean isNullOrEmpty = false;\n if (paramValue == null) {\n isNullOrEmpty = true;\n }\n if (paramValue instanceof String) {\n if (((String) paramValue).trim().equalsIgnoreCase(\"\")) {\n isNullOrEmpty = true;\n }\n } else if (paramValue instanceof List) {\n return ((List) paramValue).isEmpty();\n }\n return isNullOrEmpty;\n }",
"public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}"
] |
Start watching the fluo app uuid. If it changes or goes away then halt the process. | [
"public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] | [
"public static 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 updateRemoveR() {\n for( int i = 1; i < n+1; i++ ) {\n for( int j = 0; j < n; j++ ) {\n double sum = 0;\n for( int k = i-1; k <= j; k++ ) {\n sum += U_tran.data[i*m+k] * R.data[k*n+j];\n }\n R.data[(i-1)*n+j] = sum;\n }\n }\n }",
"public static final ProjectFile setProjectNameAndRead(File directory) throws MPXJException\n {\n List<String> projects = listProjectNames(directory);\n\n if (!projects.isEmpty())\n {\n P3DatabaseReader reader = new P3DatabaseReader();\n reader.setProjectName(projects.get(0));\n return reader.read(directory);\n }\n\n return null;\n }",
"public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }",
"public String getController() {\n final StringBuilder controller = new StringBuilder();\n if (getProtocol() != null) {\n controller.append(getProtocol()).append(\"://\");\n }\n if (getHost() != null) {\n controller.append(getHost());\n } else {\n controller.append(\"localhost\");\n }\n if (getPort() > 0) {\n controller.append(':').append(getPort());\n }\n return controller.toString();\n }",
"private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }",
"private void handleSendDataRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Send Data Request\");\n\t\t\n\t\tint callbackId = incomingMessage.getMessagePayloadByte(0);\n\t\tTransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));\n\t\tSerialMessage originalMessage = this.lastSentMessage;\n\t\t\n\t\tif (status == null) {\n\t\t\tlogger.warn(\"Transmission state not found, ignoring.\");\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.debug(\"CallBack ID = {}\", callbackId);\n\t\tlogger.debug(String.format(\"Status = %s (0x%02x)\", status.getLabel(), status.getKey()));\n\t\t\n\t\tif (originalMessage == null || originalMessage.getCallbackId() != callbackId) {\n\t\t\tlogger.warn(\"Already processed another send data request for this callback Id, ignoring.\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tswitch (status) {\n\t\t\tcase COMPLETE_OK:\n\t\t\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\t// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.\n\t\t\t\tif (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {\n\t\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tif (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase COMPLETE_NO_ACK:\n\t\t\tcase COMPLETE_FAIL:\n\t\t\tcase COMPLETE_NOT_IDLE:\n\t\t\tcase COMPLETE_NOROUTE:\n\t\t\t\ttry {\n\t\t\t\t\thandleFailedSendDataRequest(originalMessage);\n\t\t\t\t} finally {\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\tdefault:\n\t\t}\n\t}",
"public boolean getCritical()\n {\n Boolean critical = (Boolean) getCachedValue(TaskField.CRITICAL);\n if (critical == null)\n {\n Duration totalSlack = getTotalSlack();\n ProjectProperties props = getParentFile().getProjectProperties();\n int criticalSlackLimit = NumberHelper.getInt(props.getCriticalSlackLimit());\n if (criticalSlackLimit != 0 && totalSlack.getDuration() != 0 && totalSlack.getUnits() != TimeUnit.DAYS)\n {\n totalSlack = totalSlack.convertUnits(TimeUnit.DAYS, props);\n }\n critical = Boolean.valueOf(totalSlack.getDuration() <= criticalSlackLimit && NumberHelper.getInt(getPercentageComplete()) != 100 && ((getTaskMode() == TaskMode.AUTO_SCHEDULED) || (getDurationText() == null && getStartText() == null && getFinishText() == null)));\n set(TaskField.CRITICAL, critical);\n }\n return (BooleanHelper.getBoolean(critical));\n }",
"public static Status from(Set<ServiceReference> serviceReferencesBound, Set<ServiceReference> serviceReferencesHandled) {\n if (serviceReferencesBound == null && serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\" +\n \"and serviceReferencesHandled == null\");\n } else if (serviceReferencesBound == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\");\n } else if (serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesHandled == null\");\n }\n return new Status(serviceReferencesBound, serviceReferencesHandled);\n }"
] |
Read string from url generic.
@param url
the url
@return the string
@throws IOException
Signals that an I/O exception has occurred. | [
"public static String readStringFromUrlGeneric(String url)\n throws IOException {\n InputStream is = null;\n URL urlObj = null;\n String responseString = PcConstants.NA;\n try {\n urlObj = new URL(url);\n URLConnection con = urlObj.openConnection();\n\n con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis);\n con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis);\n is = con.getInputStream();\n\n BufferedReader rd = new BufferedReader(new InputStreamReader(is,\n Charset.forName(\"UTF-8\")));\n responseString = PcFileNetworkIoUtils.readAll(rd);\n\n } finally {\n\n if (is != null) {\n is.close();\n }\n\n }\n\n return responseString;\n }"
] | [
"private void processHyperlinkData(Task task, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n task.setHyperlink(hyperlink);\n task.setHyperlinkAddress(address);\n task.setHyperlinkSubAddress(subaddress);\n }\n }",
"public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {\n synchronized (changeListenerList) {\n ArrayList<MetaClassRegistryChangeEventListener> ret =\n new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());\n ret.addAll(nonRemoveableChangeListenerList);\n ret.addAll(changeListenerList);\n return ret.toArray(new MetaClassRegistryChangeEventListener[ret.size()]);\n }\n }",
"protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {\n final String parameterString = servletContext.getInitParameter(parameterName);\n if(parameterString != null && parameterString.trim().length() > 0) {\n try {\n return Integer.parseInt(parameterString);\n }\n catch (NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return defaultValue;\n }",
"private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\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 JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\n }",
"private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)\n {\n Project.Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();\n for (Project.Calendars.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, map, baseCalendars);\n }\n updateBaseCalendarNames(baseCalendars, map);\n }\n\n try\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());\n ProjectCalendar calendar = map.get(calendarID);\n m_projectFile.setDefaultCalendar(calendar);\n }\n\n catch (Exception ex)\n {\n // Ignore exceptions\n }\n }",
"public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\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 }"
] |
Called to reset current sensor data.
@param timeStamp
current time stamp
@param rotationW
Quaternion rotation W
@param rotationX
Quaternion rotation X
@param rotationY
Quaternion rotation Y
@param rotationZ
Quaternion rotation Z
@param gyroX
Gyro rotation X
@param gyroY
Gyro rotation Y
@param gyroZ
Gyro rotation Z | [
"@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }"
] | [
"@UiHandler(\"m_seriesCheckBox\")\n void onSeriesChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setIsSeries(event.getValue());\n }\n }",
"public void build(Point3d[] points, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (points.length < nump) {\n throw new IllegalArgumentException(\"Point array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(points, nump);\n buildHull();\n }",
"public void handleEvent(Event event) {\n LOG.fine(\"ContentLengthHandler called\");\n\n //if maximum length is shorter then <cut><![CDATA[ ]]></cut> it's not possible to cut the content\n if(CUT_START_TAG.length() + CUT_END_TAG.length() > length) {\n LOG.warning(\"Trying to cut content. But length is shorter then needed for \"\n + CUT_START_TAG + CUT_END_TAG + \". So content is skipped.\");\n event.setContent(\"\");\n return;\n }\n\n int currentLength = length - CUT_START_TAG.length() - CUT_END_TAG.length();\n\n if (event.getContent() != null && event.getContent().length() > length) {\n LOG.fine(\"cutting content to \" + currentLength\n + \" characters. Original length was \"\n + event.getContent().length());\n LOG.fine(\"Content before cutting: \" + event.getContent());\n event.setContent(CUT_START_TAG\n + event.getContent().substring(0, currentLength) + CUT_END_TAG);\n LOG.fine(\"Content after cutting: \" + event.getContent());\n }\n }",
"public void forAllForeignkeyColumnPairs(String template, Properties attributes) throws XDocletException\r\n {\r\n for (int idx = 0; idx < _curForeignkeyDef.getNumColumnPairs(); idx++)\r\n {\r\n _curPairLeft = _curForeignkeyDef.getLocalColumn(idx);\r\n _curPairRight = _curForeignkeyDef.getRemoteColumn(idx);\r\n generate(template);\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }",
"private void writePredecessors(Task mpxjTask, net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Predecessors plannerPredecessors = m_factory.createPredecessors();\n plannerTask.setPredecessors(plannerPredecessors);\n List<Predecessor> predecessorList = plannerPredecessors.getPredecessor();\n int id = 0;\n\n List<Relation> predecessors = mpxjTask.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n Predecessor plannerPredecessor = m_factory.createPredecessor();\n plannerPredecessor.setId(getIntegerString(++id));\n plannerPredecessor.setPredecessorId(getIntegerString(taskUniqueID));\n plannerPredecessor.setLag(getDurationString(rel.getLag()));\n plannerPredecessor.setType(RELATIONSHIP_TYPES.get(rel.getType()));\n predecessorList.add(plannerPredecessor);\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }",
"List<CmsFavoriteEntry> getEntries() {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n for (I_CmsEditableGroupRow row : m_group.getRows()) {\n CmsFavoriteEntry entry = ((CmsFavInfo)row).getEntry();\n result.add(entry);\n }\n return result;\n }",
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }",
"public Task add()\n {\n Task task = new Task(m_projectFile, (Task) null);\n add(task);\n m_projectFile.getChildTasks().add(task);\n return task;\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}"
] |
GENERIC!!! HELPER FUNCION FOR REPLACEMENT
update the var: DYNAMIC REPLACEMENT of VAR.
Every task must have matching command data and task result
@param task
the task
@param replaceVarKey
the replace var key
@param replaceVarValue
the replace var value | [
"public void updateRequestByAddingReplaceVarPair(\n ParallelTask task, String replaceVarKey, String replaceVarValue) {\n\n Map<String, NodeReqResponse> taskResult = task.getParallelTaskResult();\n\n for (Entry<String, NodeReqResponse> entry : taskResult.entrySet()) {\n NodeReqResponse nodeReqResponse = entry.getValue();\n\n nodeReqResponse.getRequestParameters()\n .put(PcConstants.NODE_REQUEST_PREFIX_REPLACE_VAR\n + replaceVarKey, replaceVarValue);\n nodeReqResponse.getRequestParameters().put(\n PcConstants.NODE_REQUEST_WILL_EXECUTE,\n Boolean.toString(true));\n\n }// end for loop\n\n }"
] | [
"public void addControl(String name, JSONObject properties, Widget.OnTouchListener listener) {\n final JSONObject allowedProperties = new JSONObject();\n put(allowedProperties, Widget.Properties.name, optString(properties, Widget.Properties.name));\n put(allowedProperties, Widget.Properties.size, new PointF(mControlDimensions.x, mControlDimensions.y));\n put(allowedProperties, Widget.Properties.states, optJSONObject(properties, Widget.Properties.states));\n\n Widget control = new Widget(getGVRContext(), allowedProperties);\n setupControl(name, control, listener, -1);\n }",
"@SuppressWarnings(\"unchecked\")\n protected Class<? extends Annotation> annotationTypeForName(String name) {\n try {\n return (Class<? extends Annotation>) resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_ANNOTATION;\n }\n }",
"public EventBus emitAsync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }",
"public static List<String> getDefaultConversionProviderChain(){\n List<String> defaultChain = getMonetaryConversionsSpi()\n .getDefaultProviderChain();\n Objects.requireNonNull(defaultChain, \"No default provider chain provided by SPI: \" +\n getMonetaryConversionsSpi().getClass().getName());\n return defaultChain;\n }",
"public boolean isEmpty() {\n\t\tint snapshotSize = cleared ? 0 : snapshot.size();\n\t\t//nothing in both\n\t\tif ( snapshotSize == 0 && currentState.isEmpty() ) {\n\t\t\treturn true;\n\t\t}\n\t\t//snapshot bigger than changeset\n\t\tif ( snapshotSize > currentState.size() ) {\n\t\t\treturn false;\n\t\t}\n\t\treturn size() == 0;\n\t}",
"public synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }",
"@UiThread\n protected void expandView() {\n setExpanded(true);\n onExpansionToggled(false);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentExpanded(getAdapterPosition());\n }\n }",
"public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }",
"private void updateMax(MtasRBTreeNode n, MtasRBTreeNode c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n }\n }"
] |
Use this API to fetch vpnvserver_responderpolicy_binding resources of given name . | [
"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 static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }",
"public CmsScheduledJobInfo getJob(String id) {\n\n Iterator<CmsScheduledJobInfo> it = m_jobs.iterator();\n while (it.hasNext()) {\n CmsScheduledJobInfo job = it.next();\n if (job.getId().equals(id)) {\n return job;\n }\n }\n // not found\n return null;\n }",
"protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) {\n this.valid = false;\n for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) {\n if (annotatedAnnotation.isAnnotationPresent(annotationType)) {\n this.valid = true;\n }\n }\n }",
"public static String normalizeWS(String value) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n boolean prevws = false;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (ch != ' ' && ch != '\\t' && ch != '\\n' && ch != '\\r') {\n if (prevws && pos != 0)\n tmp[pos++] = ' ';\n\n tmp[pos++] = ch;\n prevws = false;\n } else\n prevws = true;\n }\n return new String(tmp, 0, pos);\n }",
"public static base_response add(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser addresource = new systemuser();\n\t\taddresource.username = resource.username;\n\t\taddresource.password = resource.password;\n\t\taddresource.externalauth = resource.externalauth;\n\t\taddresource.promptstring = resource.promptstring;\n\t\taddresource.timeout = resource.timeout;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void end(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n LOG.info(\"Called end with key: \" + key + \" without ever calling begin\");\n return;\n }\n data.end();\n }",
"@Override\n public Response toResponse(ErrorDto e)\n {\n // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType();\n return Response.status(e.httpStatus).entity(e).type(MediaType.APPLICATION_JSON).build();\n }",
"public static Timespan create(Timespan... timespans) {\n if (timespans == null) {\n return null;\n }\n\n if (timespans.length == 0) {\n return ZERO_MILLISECONDS;\n }\n\n Timespan res = timespans[0];\n\n for (int i = 1; i < timespans.length; i++) {\n Timespan timespan = timespans[i];\n res = res.add(timespan);\n }\n\n return res;\n }",
"private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) {\n if (!(flexiblePublisher instanceof FlexiblePublisher)) {\n throw new IllegalArgumentException(String.format(\"Publisher should be of type: '%s'. Found type: '%s'\",\n FlexiblePublisher.class, flexiblePublisher.getClass()));\n }\n\n List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers();\n for (ConditionalPublisher condition : conditions) {\n if (type.isInstance(condition.getPublisher())) {\n return type.cast(condition.getPublisher());\n }\n }\n\n return null;\n }"
] |
Arrange to become the tempo master. Starts a sequence of interactions with the other players that should end
up with us in charge of the group tempo and beat alignment.
@throws IllegalStateException if we are not sending status updates
@throws IOException if there is a problem sending the master yield request | [
"public synchronized void becomeTempoMaster() throws IOException {\n logger.debug(\"Trying to become master.\");\n if (!isSendingStatus()) {\n throw new IllegalStateException(\"Must be sending status updates to become the tempo master.\");\n }\n\n // Is there someone we need to ask to yield to us?\n final DeviceUpdate currentMaster = getTempoMaster();\n if (currentMaster != null) {\n // Send the yield request; we will become master when we get a successful response.\n byte[] payload = new byte[MASTER_HANDOFF_REQUEST_PAYLOAD.length];\n System.arraycopy(MASTER_HANDOFF_REQUEST_PAYLOAD, 0, payload, 0, MASTER_HANDOFF_REQUEST_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n if (logger.isDebugEnabled()) {\n logger.debug(\"Sending master yield request to player \" + currentMaster);\n }\n requestingMasterRoleFromPlayer.set(currentMaster.deviceNumber);\n assembleAndSendPacket(Util.PacketType.MASTER_HANDOFF_REQUEST, payload, currentMaster.address, BeatFinder.BEAT_PORT);\n } else if (!master.get()) {\n // There is no other master, we can just become it immediately.\n requestingMasterRoleFromPlayer.set(0);\n setMasterTempo(getTempo());\n master.set(true);\n }\n }"
] | [
"private String getIntegerString(Number value)\n {\n return (value == null ? null : Integer.toString(value.intValue()));\n }",
"private void expireDevices() {\n long now = System.currentTimeMillis();\n // Make a copy so we don't have to worry about concurrent modification.\n Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices);\n for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) {\n if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) {\n devices.remove(entry.getKey());\n deliverLostAnnouncement(entry.getValue());\n }\n }\n if (devices.isEmpty()) {\n firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device.\n }\n }",
"public static String getDatatypeIriFromJsonDatatype(String jsonDatatype) {\n\t\tswitch (jsonDatatype) {\n\t\tcase JSON_DT_ITEM:\n\t\t\treturn DT_ITEM;\n\t\tcase JSON_DT_PROPERTY:\n\t\t\treturn DT_PROPERTY;\n\t\tcase JSON_DT_GLOBE_COORDINATES:\n\t\t\treturn DT_GLOBE_COORDINATES;\n\t\tcase JSON_DT_URL:\n\t\t\treturn DT_URL;\n\t\tcase JSON_DT_COMMONS_MEDIA:\n\t\t\treturn DT_COMMONS_MEDIA;\n\t\tcase JSON_DT_TIME:\n\t\t\treturn DT_TIME;\n\t\tcase JSON_DT_QUANTITY:\n\t\t\treturn DT_QUANTITY;\n\t\tcase JSON_DT_STRING:\n\t\t\treturn DT_STRING;\n\t\tcase JSON_DT_MONOLINGUAL_TEXT:\n\t\t\treturn DT_MONOLINGUAL_TEXT;\n\t\tdefault:\n\t\t\tif(!JSON_DATATYPE_PATTERN.matcher(jsonDatatype).matches()) {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid JSON datatype \\\"\" + jsonDatatype + \"\\\"\");\n\t\t\t}\n\n\t\t\tString[] parts = jsonDatatype.split(\"-\");\n\t\t\tfor(int i = 0; i < parts.length; i++) {\n\t\t\t\tparts[i] = StringUtils.capitalize(parts[i]);\n\t\t\t}\n\t\t\treturn \"http://wikiba.se/ontology#\" + StringUtils.join(parts);\n\t\t}\n\t}",
"public MapBounds getRotatedBounds(final Rectangle2D.Double paintAreaPrecise, final Rectangle paintArea) {\n final MapBounds rotatedBounds = this.getRotatedBounds();\n\n if (rotatedBounds instanceof CenterScaleMapBounds) {\n return rotatedBounds;\n }\n\n final ReferencedEnvelope envelope = ((BBoxMapBounds) rotatedBounds).toReferencedEnvelope(null);\n // the paint area size and the map bounds are rotated independently. because\n // the paint area size is rounded to integers, the map bounds have to be adjusted\n // to these rounding changes.\n final double widthRatio = paintArea.getWidth() / paintAreaPrecise.getWidth();\n final double heightRatio = paintArea.getHeight() / paintAreaPrecise.getHeight();\n\n final double adaptedWidth = envelope.getWidth() * widthRatio;\n final double adaptedHeight = envelope.getHeight() * heightRatio;\n\n final double widthDiff = adaptedWidth - envelope.getWidth();\n final double heigthDiff = adaptedHeight - envelope.getHeight();\n envelope.expandBy(widthDiff / 2.0, heigthDiff / 2.0);\n\n return new BBoxMapBounds(envelope);\n }",
"public static void main(String args[]) throws Exception {\n final StringBuffer buffer = new StringBuffer(\"The lazy fox\");\n Thread t1 = new Thread() {\n public void run() {\n synchronized(buffer) {\n buffer.delete(0,4);\n buffer.append(\" in the middle\");\n System.err.println(\"Middle\");\n try { Thread.sleep(4000); } catch(Exception e) {}\n buffer.append(\" of fall\");\n System.err.println(\"Fall\");\n }\n }\n };\n Thread t2 = new Thread() {\n public void run() {\n try { Thread.sleep(1000); } catch(Exception e) {}\n buffer.append(\" jump over the fence\");\n System.err.println(\"Fence\");\n }\n };\n t1.start();\n t2.start();\n\n t1.join();\n t2.join();\n System.err.println(buffer);\n }",
"public static base_responses update(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile updateresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleprofile();\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].apikey = resources[i].apikey;\n\t\t\t\tupdateresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public String[][] getRequiredRuleNames(Param param) {\n\t\tif (isFiltered(param)) {\n\t\t\treturn EMPTY_ARRAY;\n\t\t}\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\tString ruleName = param.ruleName;\n\t\tif (ruleName == null) {\n\t\t\treturn getRequiredRuleNames(param, elementToParse);\n\t\t}\n\t\treturn getAdjustedRequiredRuleNames(param, elementToParse, ruleName);\n\t}",
"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 }",
"public static List<CompiledAutomaton> createAutomata(String prefix,\n String regexp, Map<String, Automaton> automatonMap) throws IOException {\n List<CompiledAutomaton> list = new ArrayList<>();\n Automaton automatonRegexp = null;\n if (regexp != null) {\n RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + \"\\u0000*\");\n automatonRegexp = re.toAutomaton();\n }\n int step = 500;\n List<String> keyList = new ArrayList<>(automatonMap.keySet());\n for (int i = 0; i < keyList.size(); i += step) {\n int localStep = step;\n boolean success = false;\n CompiledAutomaton compiledAutomaton = null;\n while (!success) {\n success = true;\n int next = Math.min(keyList.size(), i + localStep);\n List<Automaton> listAutomaton = new ArrayList<>();\n for (int j = i; j < next; j++) {\n listAutomaton.add(automatonMap.get(keyList.get(j)));\n }\n Automaton automatonList = Operations.union(listAutomaton);\n Automaton automaton;\n if (automatonRegexp != null) {\n automaton = Operations.intersection(automatonList, automatonRegexp);\n } else {\n automaton = automatonList;\n }\n try {\n compiledAutomaton = new CompiledAutomaton(automaton);\n } catch (TooComplexToDeterminizeException e) {\n log.debug(e);\n success = false;\n if (localStep > 1) {\n localStep /= 2;\n } else {\n throw new IOException(\"TooComplexToDeterminizeException\");\n }\n }\n }\n list.add(compiledAutomaton);\n }\n return list;\n }"
] |
Create the grid feature type.
@param mapContext the map context containing the information about the map the grid will be
added to.
@param geomClass the geometry type | [
"public static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }"
] | [
"public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\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 }",
"public static String[] tokenizeUnquoted(String s) {\r\n List tokens = new LinkedList();\r\n int first = 0;\r\n while (first < s.length()) {\r\n first = skipWhitespace(s, first);\r\n int last = scanToken(s, first);\r\n if (first < last) {\r\n tokens.add(s.substring(first, last));\r\n }\r\n first = last;\r\n }\r\n return (String[])tokens.toArray(new String[tokens.size()]);\r\n }",
"synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }",
"public PartitionInfo partitionInfo(String partitionKey) {\n if (partitionKey == null) {\n throw new UnsupportedOperationException(\"Cannot get partition information for null partition key.\");\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).build();\n return client.couchDbClient.get(uri, PartitionInfo.class);\n }",
"public synchronized void becomeTempoMaster() throws IOException {\n logger.debug(\"Trying to become master.\");\n if (!isSendingStatus()) {\n throw new IllegalStateException(\"Must be sending status updates to become the tempo master.\");\n }\n\n // Is there someone we need to ask to yield to us?\n final DeviceUpdate currentMaster = getTempoMaster();\n if (currentMaster != null) {\n // Send the yield request; we will become master when we get a successful response.\n byte[] payload = new byte[MASTER_HANDOFF_REQUEST_PAYLOAD.length];\n System.arraycopy(MASTER_HANDOFF_REQUEST_PAYLOAD, 0, payload, 0, MASTER_HANDOFF_REQUEST_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n if (logger.isDebugEnabled()) {\n logger.debug(\"Sending master yield request to player \" + currentMaster);\n }\n requestingMasterRoleFromPlayer.set(currentMaster.deviceNumber);\n assembleAndSendPacket(Util.PacketType.MASTER_HANDOFF_REQUEST, payload, currentMaster.address, BeatFinder.BEAT_PORT);\n } else if (!master.get()) {\n // There is no other master, we can just become it immediately.\n requestingMasterRoleFromPlayer.set(0);\n setMasterTempo(getTempo());\n master.set(true);\n }\n }",
"private void setNsid() throws FlickrException {\n\n if (username != null && !username.equals(\"\")) {\n Auth auth = null;\n if (authStore != null) {\n auth = authStore.retrieve(username); // assuming FileAuthStore is enhanced else need to\n // keep in user-level files.\n\n if (auth != null) {\n nsid = auth.getUser().getId();\n }\n }\n if (auth != null)\n return;\n\n Auth[] allAuths = authStore.retrieveAll();\n for (int i = 0; i < allAuths.length; i++) {\n if (username.equals(allAuths[i].getUser().getUsername())) {\n nsid = allAuths[i].getUser().getId();\n return;\n }\n }\n\n // For this to work: REST.java or PeopleInterface needs to change to pass apiKey\n // as the parameter to the call which is not authenticated.\n\n // Get nsid using flickr.people.findByUsername\n PeopleInterface peopleInterf = flickr.getPeopleInterface();\n User u = peopleInterf.findByUsername(username);\n if (u != null) {\n nsid = u.getId();\n }\n }\n }",
"public void removeOverride(int overrideId, int pathId, Integer ordinal, String clientUUID) {\n // TODO: reorder priorities after removal\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, enabledId);\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 }",
"@SuppressWarnings(\"deprecation\")\n public BUILDER setAllowedValues(String ... allowedValues) {\n assert allowedValues!= null;\n this.allowedValues = new ModelNode[allowedValues.length];\n for (int i = 0; i < allowedValues.length; i++) {\n this.allowedValues[i] = new ModelNode(allowedValues[i]);\n }\n return (BUILDER) this;\n }"
] |
Returns status help message.
@param user CmsUser
@param disabled boolean
@param newUser boolean
@return String | [
"String getStatusHelp(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_HELP_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_HELP_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_HELP_0);\n }\n long lastLogin = user.getLastlogin();\n return CmsVaadinUtils.getMessageText(\n Messages.GUI_USERMANAGEMENT_USER_ACTIVE_HELP_1,\n CmsDateUtil.getDateTime(new Date(lastLogin), DateFormat.SHORT, A_CmsUI.get().getLocale()));\n }"
] | [
"public boolean toggleProfile(Boolean enabled) {\n // TODO: make this return values properly\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"active\", enabled.toString())\n };\n try {\n String uri = BASE_PROFILE + uriEncode(this._profileName) + \"/\" + BASE_CLIENTS + \"/\";\n if (_clientId == null) {\n uri += \"-1\";\n } else {\n uri += _clientId;\n }\n JSONObject response = new JSONObject(doPost(uri, params));\n } catch (Exception e) {\n // some sort of error\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }",
"public static base_response unset(nitro_service client, snmpoption resource, String[] args) throws Exception{\n\t\tsnmpoption unsetresource = new snmpoption();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"protected static JSONObject getDefaultProfile() throws Exception {\n String uri = DEFAULT_BASE_URL + BASE_PROFILE;\n try {\n JSONObject response = new JSONObject(doGet(uri, 60000));\n JSONArray profiles = response.getJSONArray(\"profiles\");\n\n if (profiles.length() > 0) {\n return profiles.getJSONObject(0);\n }\n } catch (Exception e) {\n // some sort of error\n throw new Exception(\"Could not create a proxy client\");\n }\n\n return null;\n }",
"public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }",
"@Override\n\tpublic void add(String headerName, String headerValue) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\tif (headerValues == null) {\n\t\t\theaderValues = new LinkedList<String>();\n\t\t\tthis.headers.put(headerName, headerValues);\n\t\t}\n\t\theaderValues.add(headerValue);\n\t}",
"public static final String printExtendedAttribute(MSPDIWriter writer, Object value, DataType type)\n {\n String result;\n\n if (type == DataType.DATE)\n {\n result = printExtendedAttributeDate((Date) value);\n }\n else\n {\n if (value instanceof Boolean)\n {\n result = printExtendedAttributeBoolean((Boolean) value);\n }\n else\n {\n if (value instanceof Duration)\n {\n result = printDuration(writer, (Duration) value);\n }\n else\n {\n if (type == DataType.CURRENCY)\n {\n result = printExtendedAttributeCurrency((Number) value);\n }\n else\n {\n if (value instanceof Number)\n {\n result = printExtendedAttributeNumber((Number) value);\n }\n else\n {\n result = value.toString();\n }\n }\n }\n }\n }\n\n return (result);\n }",
"private File buildDirPath(final String serverConfigUserDirPropertyName, final String suppliedConfigDir,\n final String serverConfigDirPropertyName, final String serverBaseDirPropertyName, final String defaultBaseDir) {\n String propertyDir = System.getProperty(serverConfigUserDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n if (suppliedConfigDir != null) {\n return new File(suppliedConfigDir);\n }\n propertyDir = System.getProperty(serverConfigDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n\n propertyDir = System.getProperty(serverBaseDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n\n return new File(new File(stateValues.getOptions().getJBossHome(), defaultBaseDir), \"configuration\");\n }",
"public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}",
"Response put(URI uri, InputStream instream, String contentType) {\n HttpConnection connection = Http.PUT(uri, contentType);\n\n connection.setRequestBody(instream);\n\n return executeToResponse(connection);\n }"
] |
Returns the scene graph root.
This method is part of the wrapped API (see {@link AiWrapperProvider}
for details on wrappers).<p>
The built-in behavior is to return a {@link AiVector}.
@param wrapperProvider the wrapper provider (used for type inference)
@return the scene graph root | [
"@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n\n return (N) m_sceneRoot;\n }"
] | [
"List<List<Word>> getDifferentArguments( List<List<Word>> argumentWords ) {\n List<List<Word>> result = Lists.newArrayList();\n for( int i = 0; i < argumentWords.size(); i++ ) {\n result.add( Lists.<Word>newArrayList() );\n }\n\n int nWords = argumentWords.get( 0 ).size();\n\n for( int iWord = 0; iWord < nWords; iWord++ ) {\n Word wordOfFirstCase = argumentWords.get( 0 ).get( iWord );\n\n // data tables have equal here, otherwise\n // the cases would be structurally different\n if( wordOfFirstCase.isDataTable() ) {\n continue;\n }\n\n boolean different = false;\n for( int iCase = 1; iCase < argumentWords.size(); iCase++ ) {\n Word wordOfCase = argumentWords.get( iCase ).get( iWord );\n if( !wordOfCase.getFormattedValue().equals( wordOfFirstCase.getFormattedValue() ) ) {\n different = true;\n break;\n }\n\n }\n if( different ) {\n for( int iCase = 0; iCase < argumentWords.size(); iCase++ ) {\n result.get( iCase ).add( argumentWords.get( iCase ).get( iWord ) );\n }\n }\n }\n\n return result;\n }",
"public static appfwlearningsettings[] get(nitro_service service) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void readResources(Project plannerProject) throws MPXJException\n {\n Resources resources = plannerProject.getResources();\n if (resources != null)\n {\n for (net.sf.mpxj.planner.schema.Resource res : resources.getResource())\n {\n readResource(res);\n }\n }\n }",
"protected PersistenceBrokerInternal createNewBrokerInstance(PBKey key) throws PBFactoryException\r\n {\r\n if (key == null) throw new PBFactoryException(\"Could not create new broker with PBkey argument 'null'\");\r\n // check if the given key really exists\r\n if (MetadataManager.getInstance().connectionRepository().getDescriptor(key) == null)\r\n {\r\n throw new PBFactoryException(\"Given PBKey \" + key + \" does not match in metadata configuration\");\r\n }\r\n if (log.isEnabledFor(Logger.INFO))\r\n {\r\n // only count created instances when INFO-Log-Level\r\n log.info(\"Create new PB instance for PBKey \" + key +\r\n \", already created persistence broker instances: \" + instanceCount);\r\n // useful for testing\r\n ++this.instanceCount;\r\n }\r\n\r\n PersistenceBrokerInternal instance = null;\r\n Class[] types = {PBKey.class, PersistenceBrokerFactoryIF.class};\r\n Object[] args = {key, this};\r\n try\r\n {\r\n instance = (PersistenceBrokerInternal) ClassHelper.newInstance(implementationClass, types, args);\r\n OjbConfigurator.getInstance().configure(instance);\r\n instance = (PersistenceBrokerInternal) InterceptorFactory.getInstance().createInterceptorFor(instance);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Creation of a new PB instance failed\", e);\r\n throw new PBFactoryException(\"Creation of a new PB instance failed\", e);\r\n }\r\n return instance;\r\n }",
"private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }",
"protected static Map<Double, Double> doQuantization(double max,\n double min,\n double[] values)\n {\n double range = max - min;\n int noIntervals = 20;\n double intervalSize = range / noIntervals;\n int[] intervals = new int[noIntervals];\n for (double value : values)\n {\n int interval = Math.min(noIntervals - 1,\n (int) Math.floor((value - min) / intervalSize));\n assert interval >= 0 && interval < noIntervals : \"Invalid interval: \" + interval;\n ++intervals[interval];\n }\n Map<Double, Double> discretisedValues = new HashMap<Double, Double>();\n for (int i = 0; i < intervals.length; i++)\n {\n // Correct the value to take into account the size of the interval.\n double value = (1 / intervalSize) * (double) intervals[i];\n discretisedValues.put(min + ((i + 0.5) * intervalSize), value);\n }\n return discretisedValues;\n }",
"private void generateCopyingPart(WrappingHint.Builder builder) {\n ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder()\n .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS)\n .putAll(userDefinedCopyMethods)\n .build()\n .get(typeAssignedToField);\n \n if (copyMethods.isEmpty()) {\n throw new WrappingHintGenerationException();\n }\n \n CopyMethod firstSuitable = copyMethods.iterator().next();\n builder.setCopyMethodOwnerName(firstSuitable.owner.toString())\n .setCopyMethodName(firstSuitable.name);\n \n if (firstSuitable.isGeneric && typeSignature != null) {\n CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature)\n .transformGenericTree(GenericType::withoutWildcard);\n builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString()));\n }\n }",
"private Calendar cleanHistCalendar(Calendar cal) {\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.HOUR, 0);\n return cal;\n }",
"public CollectionRequest<User> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/users\", workspace);\n return new CollectionRequest<User>(this, User.class, path, \"GET\");\n }"
] |
Converts the given CharSequence into a List of Strings of one character.
@param self a CharSequence
@return a List of characters (a 1-character String)
@see #toSet(String)
@since 1.8.2 | [
"public static List<String> toList(CharSequence self) {\n String s = self.toString();\n int size = s.length();\n List<String> answer = new ArrayList<String>(size);\n for (int i = 0; i < size; i++) {\n answer.add(s.substring(i, i + 1));\n }\n return answer;\n }"
] | [
"public static base_response add(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup addresource = new cachecontentgroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\taddresource.heurexpiryparam = resource.heurexpiryparam;\n\t\taddresource.relexpiry = resource.relexpiry;\n\t\taddresource.relexpirymillisec = resource.relexpirymillisec;\n\t\taddresource.absexpiry = resource.absexpiry;\n\t\taddresource.absexpirygmt = resource.absexpirygmt;\n\t\taddresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\taddresource.hitparams = resource.hitparams;\n\t\taddresource.invalparams = resource.invalparams;\n\t\taddresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\taddresource.matchcookies = resource.matchcookies;\n\t\taddresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\taddresource.polleverytime = resource.polleverytime;\n\t\taddresource.ignorereloadreq = resource.ignorereloadreq;\n\t\taddresource.removecookies = resource.removecookies;\n\t\taddresource.prefetch = resource.prefetch;\n\t\taddresource.prefetchperiod = resource.prefetchperiod;\n\t\taddresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\taddresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\taddresource.flashcache = resource.flashcache;\n\t\taddresource.expireatlastbyte = resource.expireatlastbyte;\n\t\taddresource.insertvia = resource.insertvia;\n\t\taddresource.insertage = resource.insertage;\n\t\taddresource.insertetag = resource.insertetag;\n\t\taddresource.cachecontrol = resource.cachecontrol;\n\t\taddresource.quickabortsize = resource.quickabortsize;\n\t\taddresource.minressize = resource.minressize;\n\t\taddresource.maxressize = resource.maxressize;\n\t\taddresource.memlimit = resource.memlimit;\n\t\taddresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\taddresource.minhits = resource.minhits;\n\t\taddresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\taddresource.persist = resource.persist;\n\t\taddresource.pinned = resource.pinned;\n\t\taddresource.lazydnsresolve = resource.lazydnsresolve;\n\t\taddresource.hitselector = resource.hitselector;\n\t\taddresource.invalselector = resource.invalselector;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}",
"static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }",
"public static Class getClass(String className, boolean initialize) throws ClassNotFoundException\r\n {\r\n return Class.forName(className, initialize, getClassLoader());\r\n }",
"public static boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }",
"@SuppressWarnings(\"deprecation\")\n public boolean cancelOnTargetHosts(List<String> targetHosts) {\n\n boolean success = false;\n\n try {\n\n switch (state) {\n\n case IN_PROGRESS:\n if (executionManager != null\n && !executionManager.isTerminated()) {\n executionManager.tell(new CancelTaskOnHostRequest(\n targetHosts), executionManager);\n logger.info(\n \"asked task to stop from running on target hosts with count {}...\",\n targetHosts.size());\n } else {\n logger.info(\"manager already killed or not exist.. NO OP\");\n }\n success = true;\n break;\n case COMPLETED_WITHOUT_ERROR:\n case COMPLETED_WITH_ERROR:\n case WAITING:\n logger.info(\"will NO OP for cancelOnTargetHost as it is not in IN_PROGRESS state\");\n success = true;\n break;\n default:\n break;\n\n }\n\n } catch (Exception e) {\n logger.error(\n \"cancel task {} on hosts with count {} error with exception details \",\n this.getTaskId(), targetHosts.size(), e);\n }\n\n return success;\n }",
"public static NodeList evaluateXpathExpression(Document dom, String xpathExpr)\n\t\t\tthrows XPathExpressionException {\n\t\tXPathFactory factory = XPathFactory.newInstance();\n\t\tXPath xpath = factory.newXPath();\n\t\tXPathExpression expr = xpath.compile(xpathExpr);\n\t\tObject result = expr.evaluate(dom, XPathConstants.NODESET);\n\t\treturn (NodeList) result;\n\t}",
"private void setBelief(String bName, Object value) {\n introspector.setBeliefValue(this.getLocalName(), bName, value, null);\n }",
"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 }",
"public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) {\n\t\tfinal DbModule module = getModule(dbArtifact);\n\t\tif(module == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tfinal String jenkinsJobUrl = module.getBuildInfo().get(\"jenkins-job-url\");\n\t\t\n\t\tif(jenkinsJobUrl == null){\n\t\t\treturn \"\";\t\t\t\n\t\t}\n\n\t\treturn jenkinsJobUrl;\n\t}"
] |
ensures that the first invocation of a date seeking
rule is captured | [
"private void markDateInvocation() {\n\n _updatePreviousDates = !_dateGivenInGroup;\n _dateGivenInGroup = true;\n _dateGroup.setDateInferred(false);\n\n if(_firstDateInvocationInGroup) {\n // if a time has been given within the current date group, \n // we capture the current time before resetting the calendar\n if(_timeGivenInGroup) {\n int hours = _calendar.get(Calendar.HOUR_OF_DAY);\n int minutes = _calendar.get(Calendar.MINUTE);\n int seconds = _calendar.get(Calendar.SECOND);\n resetCalendar();\n _calendar.set(Calendar.HOUR_OF_DAY, hours);\n _calendar.set(Calendar.MINUTE, minutes);\n _calendar.set(Calendar.SECOND, seconds);\n }\n else {\n resetCalendar();\n }\n _firstDateInvocationInGroup = false;\n }\n }"
] | [
"public AssemblyResponse save(boolean isResumable)\n throws RequestException, LocalOperationException {\n Request request = new Request(getClient());\n options.put(\"steps\", steps.toMap());\n\n // only do tus uploads if files will be uploaded\n if (isResumable && getFilesCount() > 0) {\n Map<String, String> tusOptions = new HashMap<String, String>();\n tusOptions.put(\"tus_num_expected_upload_files\", Integer.toString(getFilesCount()));\n\n AssemblyResponse response = new AssemblyResponse(\n request.post(\"/assemblies\", options, tusOptions, null, null), true);\n\n // check if the assembly returned an error\n if (response.hasError()) {\n throw new RequestException(\"Request to Assembly failed: \" + response.json().getString(\"error\"));\n }\n\n try {\n handleTusUpload(response);\n } catch (IOException e) {\n throw new LocalOperationException(e);\n } catch (ProtocolException e) {\n throw new RequestException(e);\n }\n return response;\n } else {\n return new AssemblyResponse(request.post(\"/assemblies\", options, null, files, fileStreams));\n }\n }",
"public RasterLayerInfo asLayerInfo(TileMap tileMap) {\n\t\tRasterLayerInfo layerInfo = new RasterLayerInfo();\n\n\t\tlayerInfo.setCrs(tileMap.getSrs());\n\t\tlayerInfo.setDataSourceName(tileMap.getTitle());\n\t\tlayerInfo.setLayerType(LayerType.RASTER);\n\t\tlayerInfo.setMaxExtent(asBbox(tileMap.getBoundingBox()));\n\t\tlayerInfo.setTileHeight(tileMap.getTileFormat().getHeight());\n\t\tlayerInfo.setTileWidth(tileMap.getTileFormat().getWidth());\n\n\t\tList<ScaleInfo> zoomLevels = new ArrayList<ScaleInfo>(tileMap.getTileSets().getTileSets().size());\n\t\tfor (TileSet tileSet : tileMap.getTileSets().getTileSets()) {\n\t\t\tzoomLevels.add(asScaleInfo(tileSet));\n\t\t}\n\t\tlayerInfo.setZoomLevels(zoomLevels);\n\n\t\treturn layerInfo;\n\t}",
"public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }",
"public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException {\n // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation.\n // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client\n // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to\n // have this issue.\n\n // First shutdown the servers\n final ModelNode stopServersOp = Operations.createOperation(\"stop-servers\");\n stopServersOp.get(\"blocking\").set(true);\n stopServersOp.get(\"timeout\").set(timeout);\n ModelNode response = client.execute(stopServersOp);\n if (!Operations.isSuccessfulOutcome(response)) {\n throw new OperationExecutionException(\"Failed to stop servers.\", stopServersOp, response);\n }\n\n // Now shutdown the host\n final ModelNode address = determineHostAddress(client);\n final ModelNode shutdownOp = Operations.createOperation(\"shutdown\", address);\n response = client.execute(shutdownOp);\n if (Operations.isSuccessfulOutcome(response)) {\n // Wait until the process has died\n while (true) {\n if (isDomainRunning(client, true)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(\"Failed to shutdown host.\", shutdownOp, response);\n }\n }",
"@Pure\n\t@Inline(value = \"$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))\",\n\t\t\timported = { MapExtensions.class, Collections.class })\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn union(left, Collections.singletonMap(right.getKey(), right.getValue()));\n\t}",
"private void populateCalendar(Record record, ProjectCalendar calendar, boolean isBaseCalendar)\n {\n if (isBaseCalendar == true)\n {\n calendar.setName(record.getString(0));\n }\n else\n {\n calendar.setParent(m_projectFile.getCalendarByName(record.getString(0)));\n }\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.getInstance(record.getInteger(1)));\n calendar.setWorkingDay(Day.MONDAY, DayType.getInstance(record.getInteger(2)));\n calendar.setWorkingDay(Day.TUESDAY, DayType.getInstance(record.getInteger(3)));\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.getInstance(record.getInteger(4)));\n calendar.setWorkingDay(Day.THURSDAY, DayType.getInstance(record.getInteger(5)));\n calendar.setWorkingDay(Day.FRIDAY, DayType.getInstance(record.getInteger(6)));\n calendar.setWorkingDay(Day.SATURDAY, DayType.getInstance(record.getInteger(7)));\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }",
"private boolean canSuccessorProceed() {\n\n if (predecessor != null && !predecessor.canSuccessorProceed()) {\n return false;\n }\n\n synchronized (this) {\n while (responseCount < groups.size()) {\n try {\n wait();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n return !failed;\n }\n }",
"private void addHandlerInitializerMethod(ClassFile proxyClassType, ClassMethod staticConstructor) throws Exception {\n ClassMethod classMethod = proxyClassType.addMethod(AccessFlag.PRIVATE, INIT_MH_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT);\n final CodeAttribute b = classMethod.getCodeAttribute();\n b.aload(0);\n StaticMethodInformation methodInfo = new StaticMethodInformation(INIT_MH_METHOD_NAME, new Class[] { Object.class }, void.class,\n classMethod.getClassFile().getName());\n invokeMethodHandler(classMethod, methodInfo, false, DEFAULT_METHOD_RESOLVER, staticConstructor);\n b.checkcast(MethodHandler.class);\n b.putfield(classMethod.getClassFile().getName(), METHOD_HANDLER_FIELD_NAME, DescriptorUtils.makeDescriptor(MethodHandler.class));\n b.returnInstruction();\n BeanLogger.LOG.createdMethodHandlerInitializerForDecoratorProxy(getBeanType());\n\n }",
"public RedwoodConfiguration captureStdout(){\r\n tasks.add(new Runnable() { public void run() { Redwood.captureSystemStreams(true, false); } });\r\n return this;\r\n }"
] |
Creates a sorted list that contains the items of the given iterable. The resulting list is sorted according to
the order induced by the specified comparator.
@param iterable
the items to be sorted. May not be <code>null</code>.
@param comparator
the comparator to be used. May be <code>null</code> to indicate that the natural ordering of the
elements should be used.
@return a sorted list as a shallow copy of the given iterable.
@see Collections#sort(List, Comparator)
@see #sort(Iterable)
@see #sortBy(Iterable, org.eclipse.xtext.xbase.lib.Functions.Function1)
@see ListExtensions#sortInplace(List, Comparator)
@since 2.7 | [
"public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) {\n\t\treturn ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator);\n\t}"
] | [
"public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}",
"private static boolean isAssignableFrom(Type from, GenericArrayType to) {\n\t\tType toGenericComponentType = to.getGenericComponentType();\n\t\tif (toGenericComponentType instanceof ParameterizedType) {\n\t\t\tType t = from;\n\t\t\tif (from instanceof GenericArrayType) {\n\t\t\t\tt = ((GenericArrayType) from).getGenericComponentType();\n\t\t\t} else if (from instanceof Class) {\n\t\t\t\tClass<?> classType = (Class<?>) from;\n\t\t\t\twhile (classType.isArray()) {\n\t\t\t\t\tclassType = classType.getComponentType();\n\t\t\t\t}\n\t\t\t\tt = classType;\n\t\t\t}\n\t\t\treturn isAssignableFrom(t,\n\t\t\t\t\t(ParameterizedType) toGenericComponentType,\n\t\t\t\t\tnew HashMap<String, Type>());\n\t\t}\n\t\t// No generic defined on \"to\"; therefore, return true and let other\n\t\t// checks determine assignability\n\t\treturn true;\n\t}",
"public GroovyConstructorDoc[] constructors() {\n Collections.sort(constructors);\n return constructors.toArray(new GroovyConstructorDoc[constructors.size()]);\n }",
"public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }",
"private void processProjectID()\n {\n if (m_projectID == null)\n {\n List<Row> rows = getRows(\"project\", null, null);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_projectID = row.getInteger(\"proj_id\");\n }\n }\n }",
"public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }",
"public void process(InputStream is) throws Exception\n {\n readHeader(is);\n readVersion(is);\n readTableData(readTableHeaders(is), is);\n }",
"public void removeExpiration() {\n\n if (getFilterQueries() != null) {\n for (String fq : getFilterQueries()) {\n if (fq.startsWith(CmsSearchField.FIELD_DATE_EXPIRED + \":\")\n || fq.startsWith(CmsSearchField.FIELD_DATE_RELEASED + \":\")) {\n removeFilterQuery(fq);\n }\n }\n }\n m_ignoreExpiration = true;\n }"
] |
Use this API to fetch sslcipher resource of given name . | [
"public static sslcipher get(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher obj = new sslcipher();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\tsslcipher response = (sslcipher) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static boolean checkDuplicateElements(DMatrixSparseCSC A ) {\n A = A.copy(); // create a copy so that it doesn't modify A\n A.sortIndices(null);\n return !checkSortedFlag(A);\n }",
"public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void deleteEmailAlias(String emailAliasID) {\n URL url = EMAIL_ALIAS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), emailAliasID);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\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 readAvailabilityTable(Resource resource, AvailabilityPeriods periods)\n {\n if (periods != null)\n {\n AvailabilityTable table = resource.getAvailability();\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (AvailabilityPeriod period : list)\n {\n Date start = period.getAvailableFrom();\n Date end = period.getAvailableTo();\n Number units = DatatypeConverter.parseUnits(period.getAvailableUnits());\n Availability availability = new Availability(start, end, units);\n table.add(availability);\n }\n Collections.sort(table);\n }\n }",
"private void updateDates(Task parentTask)\n {\n if (parentTask.hasChildTasks())\n {\n Date plannedStartDate = null;\n Date plannedFinishDate = null;\n\n for (Task task : parentTask.getChildTasks())\n {\n updateDates(task);\n plannedStartDate = DateHelper.min(plannedStartDate, task.getStart());\n plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish());\n }\n\n parentTask.setStart(plannedStartDate);\n parentTask.setFinish(plannedFinishDate);\n }\n }",
"public void setLocale(String locale) {\n\n try {\n m_locale = LocaleUtils.toLocale(locale);\n } catch (IllegalArgumentException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_TAG_INVALID_LOCALE_1, \"cms:navigation\"), e);\n m_locale = null;\n }\n }",
"public void put(final K key, V value) {\n ManagedReference<V> ref = new ManagedReference<V>(bundle, value) {\n @Override\n public void finalizeReference() {\n super.finalizeReference();\n internalMap.remove(key, get());\n }\n };\n internalMap.put(key, ref);\n }"
] |
Create a new DateTime. To the last second. This will not create any
extra-millis-seconds, which may cause bugs when writing to stores such as
databases that round milli-seconds up and down. | [
"public static java.util.Date newDateTime() {\n return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);\n }"
] | [
"public static clusterinstance[] get(nitro_service service) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tclusterinstance[] response = (clusterinstance[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static HttpResponse getResponse(String urls, HttpRequest request,\n HttpMethod method, int connectTimeoutMillis, int readTimeoutMillis) throws IOException {\n OutputStream out = null;\n InputStream content = null;\n HttpResponse response = null;\n HttpURLConnection httpConn = request\n .getHttpConnection(urls, method.name());\n httpConn.setConnectTimeout(connectTimeoutMillis);\n httpConn.setReadTimeout(readTimeoutMillis);\n\n try {\n httpConn.connect();\n if (null != request.getPayload() && request.getPayload().length > 0) {\n out = httpConn.getOutputStream();\n out.write(request.getPayload());\n }\n content = httpConn.getInputStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } catch (SocketTimeoutException e) {\n throw e;\n } catch (IOException e) {\n content = httpConn.getErrorStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } finally {\n if (content != null) {\n content.close();\n }\n httpConn.disconnect();\n }\n }",
"public void addForeignKeyField(int newId)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(new Integer(newId));\r\n }",
"public void setAlias(String alias)\r\n\t{\r\n\t\tm_alias = alias;\r\n\t\tString attributePath = (String)getAttribute();\r\n\t\tboolean allPathsAliased = true;\r\n\t\tm_userAlias = new UserAlias(alias, attributePath, allPathsAliased);\r\n\t\t\r\n\t}",
"protected Boolean getSearchForEmptyQuery() {\n\n Boolean isSearchForEmptyQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_SEARCH_FOR_EMPTY_QUERY);\n return (isSearchForEmptyQuery == null) && (null != m_baseConfig)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getSearchForEmptyQueryParam())\n : isSearchForEmptyQuery;\n }",
"public static URI createRestURI(\n final String matrixId, final int row, final int col,\n final WMTSLayerParam layerParam) throws URISyntaxException {\n String path = layerParam.baseURL;\n if (layerParam.dimensions != null) {\n for (int i = 0; i < layerParam.dimensions.length; i++) {\n String dimension = layerParam.dimensions[i];\n String value = layerParam.dimensionParams.optString(dimension);\n if (value == null) {\n value = layerParam.dimensionParams.getString(dimension.toUpperCase());\n }\n path = path.replace(\"{\" + dimension + \"}\", value);\n }\n }\n path = path.replace(\"{TileMatrixSet}\", layerParam.matrixSet);\n path = path.replace(\"{TileMatrix}\", matrixId);\n path = path.replace(\"{TileRow}\", String.valueOf(row));\n path = path.replace(\"{TileCol}\", String.valueOf(col));\n path = path.replace(\"{style}\", layerParam.style);\n path = path.replace(\"{Layer}\", layerParam.layer);\n\n return new URI(path);\n }",
"public void updateDownLoadUrl(final String gavc, final String downLoadUrl) {\n final DbArtifact artifact = getArtifact(gavc);\n repositoryHandler.updateDownloadUrl(artifact, downLoadUrl);\n }",
"private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }",
"protected void onRemoveParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onRemoveOwnersParent(parent);\n }\n }"
] |
Exception handler if we are unable to parse a json value into a java representation
@param expectedType Name of the expected Type
@param type Type of the json node
@return SpinJsonDataFormatException | [
"public SpinJsonDataFormatException unableToParseValue(String expectedType, JsonNodeType type) {\n return new SpinJsonDataFormatException(exceptionMessage(\"002\", \"Expected '{}', got '{}'\", expectedType, type.toString()));\n }"
] | [
"@Override\n public void onDismiss(DialogInterface dialog) {\n if (mOldDialog != null && mOldDialog == dialog) {\n // This is the callback from the old progress dialog that was already dismissed before\n // the device orientation change, so just ignore it.\n return;\n }\n super.onDismiss(dialog);\n }",
"@Override\n protected void checkType() {\n if (!isDependent() && getEnhancedAnnotated().isParameterizedType()) {\n throw BeanLogger.LOG.managedBeanWithParameterizedBeanClassMustBeDependent(type);\n }\n boolean passivating = beanManager.isPassivatingScope(getScope());\n if (passivating && !isPassivationCapableBean()) {\n if (!getEnhancedAnnotated().isSerializable()) {\n throw BeanLogger.LOG.passivatingBeanNeedsSerializableImpl(this);\n } else if (hasDecorators() && !allDecoratorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableDecorator(this, getFirstNonPassivationCapableDecorator());\n } else if (hasInterceptors() && !allInterceptorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableInterceptor(this, getFirstNonPassivationCapableInterceptor());\n }\n }\n }",
"private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // 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), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }",
"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 static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }",
"public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }",
"private Priority getPriority(Integer gpPriority)\n {\n int result;\n if (gpPriority == null)\n {\n result = Priority.MEDIUM;\n }\n else\n {\n int index = gpPriority.intValue();\n if (index < 0 || index >= PRIORITY.length)\n {\n result = Priority.MEDIUM;\n }\n else\n {\n result = PRIORITY[index];\n }\n }\n return Priority.getInstance(result);\n }",
"protected void runStatements(Reader reader, PrintStream out)\n throws IOException {\n log.debug(\"runStatements()\");\n StringBuilder txt = new StringBuilder();\n String line = \"\";\n BufferedReader in = new BufferedReader(reader);\n\n while ((line = in.readLine()) != null) {\n line = getProject().replaceProperties(line);\n if (line.indexOf(\"--\") >= 0) {\n txt.append(\"\\n\");\n }\n }\n // Catch any statements not followed by ;\n if (!txt.toString().equals(\"\")) {\n execGroovy(txt.toString(), out);\n }\n }",
"private Send handle(SelectionKey key, Receive request) {\n final short requestTypeId = request.buffer().getShort();\n final RequestKeys requestType = RequestKeys.valueOf(requestTypeId);\n if (requestLogger.isTraceEnabled()) {\n if (requestType == null) {\n throw new InvalidRequestException(\"No mapping found for handler id \" + requestTypeId);\n }\n String logFormat = \"Handling %s request from %s\";\n requestLogger.trace(format(logFormat, requestType, channelFor(key).socket().getRemoteSocketAddress()));\n }\n RequestHandler handlerMapping = requesthandlerFactory.mapping(requestType, request);\n if (handlerMapping == null) {\n throw new InvalidRequestException(\"No handler found for request\");\n }\n long start = System.nanoTime();\n Send maybeSend = handlerMapping.handler(requestType, request);\n stats.recordRequest(requestType, System.nanoTime() - start);\n return maybeSend;\n }"
] |
This function uses a proxy which is capable of transforming typed invocations into proper HTTP calls
which will be understood by RESTful services. This works for subresources as well. Interfaces and
concrete classes can be proxified, in the latter case a CGLIB runtime dependency is needed. CXF JAX-RS
proxies can be configured the same way as HTTP-centric WebClients and response status and headers can
also be checked. HTTP response errors can be converted into typed exceptions. | [
"public void useSimpleProxy() {\n String webAppAddress = \"http://localhost:\" + port + \"/services/personservice\";\n PersonService proxy = JAXRSClientFactory.create(webAppAddress, PersonService.class);\n\n new PersonServiceProxyClient(proxy).useService();\n }"
] | [
"public ProjectFile read(POIFSFileSystem fs) throws MPXJException\n {\n try\n {\n ProjectFile projectFile = new ProjectFile();\n ProjectConfig config = projectFile.getProjectConfig();\n\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoOutlineLevel(false);\n config.setAutoOutlineNumber(false);\n config.setAutoWBS(false);\n config.setAutoCalendarUniqueID(false);\n config.setAutoAssignmentUniqueID(false);\n\n projectFile.getEventManager().addProjectListeners(m_projectListeners);\n\n //\n // Open the file system and retrieve the root directory\n //\n DirectoryEntry root = fs.getRoot();\n\n //\n // Retrieve the CompObj data, validate the file format and process\n //\n CompObj compObj = new CompObj(new DocumentInputStream((DocumentEntry) root.getEntry(\"\\1CompObj\")));\n ProjectProperties projectProperties = projectFile.getProjectProperties();\n projectProperties.setFullApplicationName(compObj.getApplicationName());\n projectProperties.setApplicationVersion(compObj.getApplicationVersion());\n String format = compObj.getFileFormat();\n Class<? extends MPPVariantReader> readerClass = FILE_CLASS_MAP.get(format);\n if (readerClass == null)\n {\n throw new MPXJException(MPXJException.INVALID_FILE + \": \" + format);\n }\n MPPVariantReader reader = readerClass.newInstance();\n reader.process(this, projectFile, root);\n\n //\n // Update the internal structure. We'll take this opportunity to\n // generate outline numbers for the tasks as they don't appear to\n // be present in the MPP file.\n //\n config.setAutoOutlineNumber(true);\n projectFile.updateStructure();\n config.setAutoOutlineNumber(false);\n\n //\n // Perform post-processing to set the summary flag and clean\n // up any instances where a task has an empty splits list.\n //\n for (Task task : projectFile.getTasks())\n {\n task.setSummary(task.hasChildTasks());\n List<DateRange> splits = task.getSplits();\n if (splits != null && splits.isEmpty())\n {\n task.setSplits(null);\n }\n validationRelations(task);\n }\n\n //\n // Ensure that the unique ID counters are correct\n //\n config.updateUniqueCounters();\n\n //\n // Add some analytics\n //\n String projectFilePath = projectFile.getProjectProperties().getProjectFilePath();\n if (projectFilePath != null && projectFilePath.startsWith(\"<>\\\\\"))\n {\n projectProperties.setFileApplication(\"Microsoft Project Server\");\n }\n else\n {\n projectProperties.setFileApplication(\"Microsoft\");\n }\n projectProperties.setFileType(\"MPP\");\n\n return (projectFile);\n }\n\n catch (IOException ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n\n catch (IllegalAccessException ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n\n catch (InstantiationException ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n }",
"public static Duration getDuration(ProjectProperties properties, Integer durationValue, Integer unitsValue)\n {\n Duration result;\n if (durationValue == null)\n {\n result = null;\n }\n else\n {\n result = Duration.getInstance(durationValue.intValue(), TimeUnit.MINUTES);\n TimeUnit units = getDurationUnits(unitsValue);\n if (result.getUnits() != units)\n {\n result = result.convertUnits(units, properties);\n }\n }\n return (result);\n }",
"private void wrongUsage() {\n\n String usage = \"Usage: java -cp $PATH_TO_OPENCMS_JAR org.opencms.rmi.CmsRemoteShellClient\\n\"\n + \" -script=[path to script] (optional) \\n\"\n + \" -registryPort=[port of RMI registry] (optional, default is \"\n + CmsRemoteShellConstants.DEFAULT_PORT\n + \")\\n\"\n + \" -additional=[additional commands class name] (optional)\";\n System.out.println(usage);\n System.exit(1);\n }",
"public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }",
"public static base_response delete(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 deleteresource = new nsacl6();\n\t\tdeleteresource.acl6name = acl6name;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private void processRequestHeaderOverrides(HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n for (EndpointOverride selectedPath : requestInfo.selectedRequestPaths) {\n List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();\n for (EnabledEndpoint endpoint : points) {\n if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD) {\n httpMethodProxyRequest.addRequestHeader(endpoint.getArguments()[0].toString(),\n endpoint.getArguments()[1].toString());\n requestInfo.modified = true;\n } else if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE) {\n httpMethodProxyRequest.removeRequestHeader(endpoint.getArguments()[0].toString());\n requestInfo.modified = true;\n }\n }\n }\n }",
"public static void outputString(final HttpServletResponse response, final Object obj) {\n try {\n response.setContentType(\"text/javascript\");\n response.setCharacterEncoding(\"utf-8\");\n disableCache(response);\n response.getWriter().write(obj.toString());\n response.getWriter().flush();\n response.getWriter().close();\n } catch (IOException e) {\n }\n }",
"public static WidgetLib init(GVRContext gvrContext, String customPropertiesAsset)\n throws InterruptedException, JSONException, NoSuchMethodException {\n if (mInstance == null) {\n // Constructor sets mInstance to ensure the initialization order\n new WidgetLib(gvrContext, customPropertiesAsset);\n }\n return mInstance.get();\n }",
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }"
] |
Generates the routing Java source code | [
"protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }"
] | [
"public FastReportBuilder addGroups(int numgroups) {\n\t\tgroupCount = numgroups;\n\t\tfor (int i = 0; i < groupCount; i++) {\n\t\t\tGroupBuilder gb = new GroupBuilder();\n\t\t\tPropertyColumn col = (PropertyColumn) report.getColumns().get(i);\n\t\t\tgb.setCriteriaColumn(col);\n\t\t\treport.getColumnsGroups().add(gb.build());\n\t\t}\n\t\treturn this;\n\t}",
"private static void checkPreconditions(final List<String> forbiddenSubStrings) {\n\t\tif( forbiddenSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"forbiddenSubStrings list should not be null\");\n\t\t} else if( forbiddenSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"forbiddenSubStrings list should not be empty\");\n\t\t}\n\t}",
"public static IndexableTaskItem create(final FunctionalTaskItem taskItem) {\n return new IndexableTaskItem() {\n @Override\n protected Observable<Indexable> invokeTaskAsync(TaskGroup.InvocationContext context) {\n FunctionalTaskItem.Context fContext = new FunctionalTaskItem.Context(this);\n fContext.setInnerContext(context);\n return taskItem.call(fContext);\n }\n };\n }",
"public void setGroupName(String name, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" SET \" + Constants.GENERIC_NAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\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 static void checkRequired(OptionSet options, String opt1, String opt2)\n throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt1);\n opts.add(opt2);\n checkRequired(options, opts);\n }",
"private SortedProperties getLocalization(Locale locale) throws IOException, CmsException {\n\n if (null == m_localizations.get(locale)) {\n switch (m_bundleType) {\n case PROPERTY:\n loadLocalizationFromPropertyBundle(locale);\n break;\n case XML:\n loadLocalizationFromXmlBundle(locale);\n break;\n case DESCRIPTOR:\n return null;\n default:\n break;\n }\n }\n return m_localizations.get(locale);\n }",
"public QueryBuilder useIndex(String designDocument, String indexName) {\n useIndex = new String[]{designDocument, indexName};\n return this;\n }",
"public static String getShortName(String className) {\n\t\tAssert.hasLength(className, \"Class name must not be empty\");\n\t\tint lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);\n\t\tint nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);\n\t\tif (nameEndIndex == -1) {\n\t\t\tnameEndIndex = className.length();\n\t\t}\n\t\tString shortName = className.substring(lastDotIndex + 1, nameEndIndex);\n\t\tshortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);\n\t\treturn shortName;\n\t}",
"private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }"
] |
Optimized version of the Wagner & Fischer algorithm that only
keeps a single column in the matrix in memory at a time. It
implements the simple cutoff, but otherwise computes the entire
matrix. It is roughly twice as fast as the original function. | [
"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 }"
] | [
"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 Enumeration getPKEnumerationByQuery(Class primaryKeyClass, Query query) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getPKEnumerationByQuery \" + query);\n\n query.setFetchSize(1);\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return new PkEnumeration(query, cld, primaryKeyClass, this);\n }",
"public static base_response delete(nitro_service client, String ipv6address) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"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 }",
"public double dot(Vector3d v1) {\n return x * v1.x + y * v1.y + z * v1.z;\n }",
"public StitchEvent<T> nextEvent() throws IOException {\n final Event nextEvent = eventStream.nextEvent();\n if (nextEvent == null) {\n return null;\n }\n\n return StitchEvent.fromEvent(nextEvent, this.decoder);\n }",
"public QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't orderBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddOrderBy(new OrderBy(columnName, ascending));\n\t\treturn this;\n\t}",
"private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns)\n {\n Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>();\n for (ColumnDefinition def : columns)\n {\n map.put(def.getName(), def);\n }\n return map;\n }",
"private void updatePreview(TrackMetadataUpdate update, WaveformPreview preview) {\n previewHotCache.put(DeckReference.getDeckReference(update.player, 0), preview); // 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 previewHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), preview);\n }\n }\n }\n deliverWaveformPreviewUpdate(update.player, preview);\n }"
] |
Perform the given work with a Jedis connection from the given pool.
@param pool the resource pool
@param work the work to perform
@param <V> the result type
@return the result of the given work
@throws Exception if something went wrong | [
"public static <V> V doWorkInPool(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) throws Exception {\n if (pool == null) {\n throw new IllegalArgumentException(\"pool must not be null\");\n }\n if (work == null) {\n throw new IllegalArgumentException(\"work must not be null\");\n }\n final V result;\n final Jedis poolResource = pool.getResource();\n try {\n result = work.doWork(poolResource);\n } finally {\n poolResource.close();\n }\n return result;\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 int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }",
"private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }",
"public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }",
"final public void setRealOffset(Integer start, Integer end) {\n if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\n \"Start real offset after end real offset\");\n } else {\n tokenRealOffset = new MtasOffset(start, end);\n }\n }",
"protected void parseRoutingCodeHeader() {\n\n String rtCode = this.request.getHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE);\n if(rtCode != null) {\n try {\n int routingTypeCode = Integer.parseInt(rtCode);\n this.parsedRoutingType = RequestRoutingType.getRequestRoutingType(routingTypeCode);\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect routing type parameter. Cannot parse this to long: \"\n + rtCode,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect routing type parameter. Cannot parse this to long: \"\n + rtCode);\n } catch(VoldemortException ve) {\n logger.error(\"Exception when validating request. Incorrect routing type code: \"\n + rtCode, ve);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect routing type code: \" + rtCode);\n }\n }\n }",
"private ProjectFile handleDirectory(File directory) throws Exception\n {\n ProjectFile result = handleDatabaseInDirectory(directory);\n if (result == null)\n {\n result = handleFileInDirectory(directory);\n }\n return result;\n }",
"protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\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}"
] |
Generate the body of a toString method that uses plain concatenation.
<p>Conventionally, we join properties with comma separators. If all of the properties are
always present, this can be done with a long block of unconditional code. We could use a
StringBuilder for this, but in fact the Java compiler will do this for us under the hood
if we use simple string concatenation, so we use the more readable approach. | [
"private static void bodyWithConcatenation(\n SourceBuilder code,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n code.add(\" return \\\"%s{\", typename);\n String prefix = \"\";\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n code.add(\"%s%s=\\\" + %s + \\\"\",\n prefix, property.getName(), (Excerpt) generator::addToStringValue);\n prefix = \", \";\n }\n code.add(\"}\\\";%n\");\n }"
] | [
"public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\n }",
"public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }",
"public static base_response delete(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"@NotNull\n static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree,\n @NotNull final EnvironmentImpl env,\n @NotNull final ExpiredLoggableCollection expired) {\n final long newMetaTreeAddress = metaTree.save();\n final Log log = env.getLog();\n final int lastStructureId = env.getLastStructureId();\n final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,\n DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId));\n expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress));\n return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress);\n }",
"public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }",
"private void readProjectProperties(Settings phoenixSettings, Storepoint storepoint)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(phoenixSettings.getTitle());\n mpxjProperties.setDefaultDurationUnits(phoenixSettings.getBaseunit());\n mpxjProperties.setStatusDate(storepoint.getDataDate());\n }",
"public static base_response delete(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey deleteresource = new sslcertkey();\n\t\tdeleteresource.certkey = resource.certkey;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static String getOffsetCodeFromCurveName(String curveName) {\r\n\t\tif(curveName == null || curveName.length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tString[] splits = curveName.split(\"(?<=\\\\D)(?=\\\\d)\");\r\n\t\tString offsetCode = splits[splits.length-1];\r\n\t\tif(!Character.isDigit(offsetCode.charAt(0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\toffsetCode = offsetCode.split(\"(?<=[A-Za-z])(?=.)\", 2)[0];\r\n\t\toffsetCode = offsetCode.replaceAll( \"[\\\\W_]\", \"\" );\r\n\t\treturn offsetCode;\r\n\t}",
"public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster,\n final int randomSwapAttempts,\n final int randomSwapSuccesses,\n final List<Integer> randomSwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(randomSwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(randomSwapZoneIds);\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 int successes = 0;\n for(int i = 0; i < randomSwapAttempts; 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\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 = swapRandomPartitionsAmongNodes(returnCluster, nodeIds);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n if(nextUtility < currentUtility) {\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (improvement \" + successes\n + \" on swap attempt \" + i + \")\");\n successes++;\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n if(successes >= randomSwapSuccesses) {\n // Enough successes, move on.\n break;\n }\n }\n return returnCluster;\n }"
] |
Might not fill all of dst. | [
"@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 }"
] | [
"void applyFreshParticleOffScreen(\n @NonNull final Scene scene,\n final int position) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n float x = random.nextInt(w);\n float y = random.nextInt(h);\n\n // The offset to make when creating point of out bounds\n final short offset = (short) (scene.getParticleRadiusMin() + scene.getLineLength());\n\n // Point angle range\n final float startAngle;\n float endAngle;\n\n // Make random offset and calulate angles so that the direction of travel will always be\n // towards our View\n switch (random.nextInt(4)) {\n case 0:\n // offset to left\n x = (short) -offset;\n startAngle = angleDeg(pcc, pcc, x, y);\n endAngle = angleDeg(pcc, h - pcc, x, y);\n break;\n\n case 1:\n // offset to top\n y = (short) -offset;\n startAngle = angleDeg(w - pcc, pcc, x, y);\n endAngle = angleDeg(pcc, pcc, x, y);\n break;\n\n case 2:\n // offset to right\n x = (short) (w + offset);\n startAngle = angleDeg(w - pcc, h - pcc, x, y);\n endAngle = angleDeg(w - pcc, pcc, x, y);\n break;\n\n case 3:\n // offset to bottom\n y = (short) (h + offset);\n startAngle = angleDeg(pcc, h - pcc, x, y);\n endAngle = angleDeg(w - pcc, h - pcc, x, y);\n break;\n\n default:\n throw new IllegalArgumentException(\"Supplied value out of range\");\n }\n\n if (endAngle < startAngle) {\n endAngle += 360;\n }\n\n // Get random angle from angle range\n final float randomAngleInRange = startAngle + (random\n .nextInt((int) Math.abs(endAngle - startAngle)));\n final double direction = Math.toRadians(randomAngleInRange);\n\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }",
"public String addPostRunDependent(FunctionalTaskItem dependentTaskItem) {\n IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem);\n this.addPostRunDependent(taskItem);\n return taskItem.key();\n }",
"public T removeBundle(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createBundleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }",
"private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }",
"private void checkReadonlyAccessForNativePKs(FieldDescriptorDef fieldDef, String checkLevel)\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 String autoInc = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT);\r\n\r\n if (\"database\".equals(autoInc) && !\"readonly\".equals(access))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"checkAccess\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is set to database auto-increment. Therefore the field's access is set to 'readonly'.\");\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"readonly\");\r\n }\r\n }",
"protected void addArguments(FieldDescriptor field[])\r\n {\r\n for (int i = 0; i < field.length; i++)\r\n {\r\n ArgumentDescriptor arg = new ArgumentDescriptor(this);\r\n arg.setValue(field[i].getAttributeName(), false);\r\n this.addArgument(arg);\r\n }\r\n }",
"private static String getFileName(@Nullable final MapPrinter mapPrinter, final PJsonObject spec) {\n String fileName = spec.optString(Constants.OUTPUT_FILENAME_KEY);\n if (fileName != null) {\n return fileName;\n }\n\n if (mapPrinter != null) {\n final Configuration config = mapPrinter.getConfiguration();\n final String templateName = spec.getString(Constants.JSON_LAYOUT_KEY);\n\n final Template template = config.getTemplate(templateName);\n\n if (template.getOutputFilename() != null) {\n return template.getOutputFilename();\n }\n\n if (config.getOutputFilename() != null) {\n return config.getOutputFilename();\n }\n }\n return \"mapfish-print-report\";\n }",
"public boolean getBoolean(FastTrackField type)\n {\n boolean result = false;\n Object value = getObject(type);\n if (value != null)\n {\n result = BooleanHelper.getBoolean((Boolean) value);\n }\n return result;\n }",
"public AT_Row setPaddingRightChar(Character paddingRightChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] |
Read data from the table. Return a reference to the current
instance to allow method chaining.
@return reader instance | [
"public TableReader read() throws IOException\n {\n int tableHeader = m_stream.readInt();\n if (tableHeader != 0x39AF547A)\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n int recordCount = m_stream.readInt();\n for (int loop = 0; loop < recordCount; loop++)\n {\n int rowMagicNumber = m_stream.readInt();\n if (rowMagicNumber != rowMagicNumber())\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n // We use a LinkedHashMap to preserve insertion order in iteration\n // Useful when debugging the file format.\n Map<String, Object> map = new LinkedHashMap<String, Object>();\n\n if (hasUUID())\n {\n readUUID(m_stream, map);\n }\n\n readRow(m_stream, map);\n\n SynchroLogger.log(\"READER\", getClass(), map);\n\n m_rows.add(new MapRow(map));\n }\n\n int tableTrailer = m_stream.readInt();\n if (tableTrailer != 0x6F99E416)\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n postTrailer(m_stream);\n\n return this;\n }"
] | [
"private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }",
"protected int readShort(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"public URL buildWithQuery(String base, String queryString, Object... values) {\n String urlString = String.format(base + this.template, values) + queryString;\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n assert false : \"An invalid URL template indicates a bug in the SDK.\";\n }\n\n return url;\n }",
"public static void main(String[] args) {\n if (args.length < 2) { // NOSONAR\n LOGGER.error(\"There must be at least two arguments\");\n return;\n }\n int lastIndex = args.length - 1;\n AllureReportGenerator reportGenerator = new AllureReportGenerator(\n getFiles(Arrays.copyOf(args, lastIndex))\n );\n reportGenerator.generate(new File(args[lastIndex]));\n }",
"public void useXopAttachmentServiceWithWebClient() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments/xop\";\n \n JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean();\n factoryBean.setAddress(serviceURI);\n factoryBean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, \n (Object)\"true\"));\n WebClient client = factoryBean.createWebClient();\n WebClient.getConfig(client).getRequestContext().put(\"support.type.as.multipart\", \n \"true\"); \n client.type(\"multipart/related\").accept(\"multipart/related\");\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a WebClient\");\n \n XopBean xopResponse = client.post(xop, XopBean.class);\n \n verifyXopResponse(xop, xopResponse);\n }",
"public void setSessionTimeout(int timeout) {\n ((ZKBackend) getBackend()).setSessionTimeout(timeout);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Locator session timeout set to: \" + timeout);\n }\n }",
"public Object getProperty(Object object) {\n return java.lang.reflect.Array.getLength(object);\n }",
"public static void Forward(double[] data) {\n double[] result = new double[data.length];\n\n for (int k = 0; k < result.length; k++) {\n double sum = 0;\n for (int n = 0; n < data.length; n++) {\n double theta = ((2.0 * Math.PI) / data.length) * k * n;\n sum += data[n] * cas(theta);\n }\n result[k] = (1.0 / Math.sqrt(data.length)) * sum;\n }\n\n for (int i = 0; i < result.length; i++) {\n data[i] = result[i];\n }\n\n }",
"private void writeTask(Task task) throws IOException\n {\n writeFields(null, task, TaskField.values());\n for (Task child : task.getChildTasks())\n {\n writeTask(child);\n }\n }"
] |
Use this API to fetch all the rnatparam resources that are configured on netscaler. | [
"public static rnatparam get(nitro_service service) throws Exception{\n\t\trnatparam obj = new rnatparam();\n\t\trnatparam[] response = (rnatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"void release() {\n\t\tif (mCurrentRequests != null) {\n\t\t\tsynchronized (mCurrentRequests) {\n\t\t\t\tmCurrentRequests.clear();\n\t\t\t\tmCurrentRequests = null;\n\t\t\t}\n\t\t}\n\n\t\tif (mDownloadQueue != null) {\n\t\t\tmDownloadQueue = null;\n\t\t}\n\n\t\tif (mDownloadDispatchers != null) {\n\t\t\tstop();\n\n\t\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\t\tmDownloadDispatchers[i] = null;\n\t\t\t}\n\t\t\tmDownloadDispatchers = null;\n\t\t}\n\n\t}",
"public static gslbservice get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice response = (gslbservice) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) {\n Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones());\n Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones());\n if(!lhsSet.equals(rhsSet))\n throw new VoldemortException(\"Zones are not the same [ lhs cluster zones (\"\n + lhs.getZones() + \") not equal to rhs cluster zones (\"\n + rhs.getZones() + \") ]\");\n }",
"public static base_responses unset(nitro_service client, String sitename[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite unsetresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tunsetresources[i] = new gslbsite();\n\t\t\t\tunsetresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"private boolean checkTagAndParam(XDoc doc, String tagName, String paramName, String paramValue)\r\n {\r\n if (tagName == null) {\r\n return true;\r\n }\r\n if (!doc.hasTag(tagName)) {\r\n return false;\r\n }\r\n if (paramName == null) {\r\n return true;\r\n }\r\n if (!doc.getTag(tagName).getAttributeNames().contains(paramName)) {\r\n return false;\r\n }\r\n return (paramValue == null) || paramValue.equals(doc.getTagAttributeValue(tagName, paramName));\r\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public UTMDetail getUTMDetails() {\n UTMDetail ud = new UTMDetail();\n ud.setSource(source);\n ud.setMedium(medium);\n ud.setCampaign(campaign);\n return ud;\n }",
"private void writeExceptions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions)\n {\n Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions();\n calendar.setExceptions(ce);\n List<Exceptions.Exception> el = ce.getException();\n\n for (ProjectCalendarException exception : exceptions)\n {\n Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException();\n el.add(ex);\n\n ex.setName(exception.getName());\n boolean working = exception.getWorking();\n ex.setDayWorking(Boolean.valueOf(working));\n\n if (exception.getRecurring() == null)\n {\n ex.setEnteredByOccurrences(Boolean.FALSE);\n ex.setOccurrences(BigInteger.ONE);\n ex.setType(BigInteger.ONE);\n }\n else\n {\n populateRecurringException(exception, ex);\n }\n\n Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod();\n ex.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes();\n ex.setWorkingTimes(times);\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }",
"public GroovyMethodDoc[] methods() {\n Collections.sort(methods);\n return methods.toArray(new GroovyMethodDoc[methods.size()]);\n }",
"public Where<T, ID> not() {\n\t\t/*\n\t\t * Special circumstance here when we have a needs future with a not. Something like and().not().like(...). In\n\t\t * this case we satisfy the and()'s future as the not() but the not() becomes the new needs-future.\n\t\t */\n\t\tNot not = new Not();\n\t\taddClause(not);\n\t\taddNeedsFuture(not);\n\t\treturn this;\n\t}"
] |
Synthesize and forward a KeyEvent to the library.
This call is made from the native layer.
@param code id of the button
@param action integer representing the action taken on the button | [
"public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }"
] | [
"private void init()\n {\n style = new BoxStyle(UNIT);\n textLine = new StringBuilder();\n textMetrics = null;\n graphicsPath = new Vector<PathSegment>();\n startPage = 0;\n endPage = Integer.MAX_VALUE;\n fontTable = new FontTable();\n }",
"public boolean setVisibility(final Visibility visibility) {\n if (visibility != mVisibility) {\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"setVisibility(%s) for %s\", visibility, getName());\n updateVisibility(visibility);\n mVisibility = visibility;\n return true;\n }\n return false;\n }",
"protected Container findContainer(ContainerContext ctx, StringBuilder dump) {\n Container container = null;\n // 1. Custom container class\n String containerClassName = ctx.getServletContext().getInitParameter(Container.CONTEXT_PARAM_CONTAINER_CLASS);\n if (containerClassName != null) {\n try {\n Class<Container> containerClass = Reflections.classForName(resourceLoader, containerClassName);\n container = SecurityActions.newInstance(containerClass);\n WeldServletLogger.LOG.containerDetectionSkipped(containerClassName);\n } catch (Exception e) {\n WeldServletLogger.LOG.unableToInstantiateCustomContainerClass(containerClassName);\n WeldServletLogger.LOG.catchingDebug(e);\n }\n }\n if (container == null) {\n // 2. Service providers\n Iterable<Container> extContainers = ServiceLoader.load(Container.class, getClass().getClassLoader());\n container = checkContainers(ctx, dump, extContainers);\n if (container == null) {\n // 3. Built-in containers in predefined order\n container = checkContainers(ctx, dump,\n Arrays.asList(TomcatContainer.INSTANCE, JettyContainer.INSTANCE, UndertowContainer.INSTANCE, GwtDevHostedModeContainer.INSTANCE));\n }\n }\n return container;\n }",
"public Set<Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n for (ProcessorGraphNode<?, ?> root: this.roots) {\n for (Processor p: root.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }",
"public static final Date parseDate(String value)\n {\n Date result = null;\n\n try\n {\n if (value != null && !value.isEmpty())\n {\n result = DATE_FORMAT.get().parse(value);\n }\n }\n catch (ParseException ex)\n {\n // Ignore\n }\n\n return result;\n }",
"public static tunneltrafficpolicy get(nitro_service service, String name) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\tobj.set_name(name);\n\t\ttunneltrafficpolicy response = (tunneltrafficpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }",
"private void checkOrderby(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String orderbySpec = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ORDERBY);\r\n\r\n if ((orderbySpec == null) || (orderbySpec.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.');\r\n ClassDescriptorDef elementClass = ((ModelDef)ownerClass.getOwner()).getClass(elementClassName);\r\n FieldDescriptorDef fieldDef;\r\n String token;\r\n String fieldName;\r\n String ordering;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(orderbySpec); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos == -1)\r\n {\r\n fieldName = token;\r\n ordering = null;\r\n }\r\n else\r\n {\r\n fieldName = token.substring(0, pos);\r\n ordering = token.substring(pos + 1);\r\n }\r\n fieldDef = elementClass.getField(fieldName);\r\n if (fieldDef == null)\r\n {\r\n throw new ConstraintException(\"The field \"+fieldName+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" hasn't been found in the element class \"+elementClass.getName());\r\n }\r\n if ((ordering != null) && (ordering.length() > 0) &&\r\n !\"ASC\".equals(ordering) && !\"DESC\".equals(ordering))\r\n {\r\n throw new ConstraintException(\"The ordering \"+ordering+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" is invalid\");\r\n }\r\n }\r\n }",
"public void cache(Identity oid, Object obj)\r\n {\r\n try\r\n {\r\n jcsCache.put(oid.toString(), obj);\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e);\r\n }\r\n }"
] |
Retrieves the monthly or yearly relative day of the week.
@return day of the week | [
"public Day getDayOfWeek()\n {\n Day result = null;\n if (!m_days.isEmpty())\n {\n result = m_days.iterator().next();\n }\n return result;\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}",
"private ProctorContext getProctorContext(final HttpServletRequest request) throws IllegalAccessException, InstantiationException {\n final ProctorContext proctorContext = contextClass.newInstance();\n final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext);\n for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) {\n final String propertyName = descriptor.getName();\n if (!\"class\".equals(propertyName)) { // ignore class property which every object has\n final String parameterValue = request.getParameter(propertyName);\n if (parameterValue != null) {\n beanWrapper.setPropertyValue(propertyName, parameterValue);\n }\n }\n }\n return proctorContext;\n }",
"public static base_response flush(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl flushresource = new nssimpleacl();\n\t\tflushresource.estsessions = resource.estsessions;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}",
"public static JqmEngineOperations startEngine(String name, JqmEngineHandler handler)\n {\n JqmEngine e = new JqmEngine();\n e.start(name, handler);\n return e;\n }",
"public void setProductModules(final String name, final List<String> moduleNames) {\n final DbProduct dbProduct = getProduct(name);\n dbProduct.setModules(moduleNames);\n repositoryHandler.store(dbProduct);\n }",
"public 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 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 }",
"public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {\n\t\tCheck.notNull(code, \"code\");\n\t\tfinal ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, \"settings\"));\n\n\t\tfinal InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);\n\t\tfinal Clazz clazz = scaffoldClazz(analysis, settings);\n\n\t\t// immutable settings\n\t\tsettingsBuilder.fields(clazz.getFields());\n\t\tsettingsBuilder.immutableName(clazz.getName());\n\t\tsettingsBuilder.imports(clazz.getImports());\n\t\tfinal Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));\n\t\tsettingsBuilder.mainInterface(definition);\n\t\tsettingsBuilder.interfaces(clazz.getInterfaces());\n\t\tsettingsBuilder.packageDeclaration(clazz.getPackage());\n\n\t\tfinal String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));\n\t\tfinal String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));\n\t\treturn new Result(implementationCode, testCode);\n\t}",
"public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {\n return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );\n }"
] |
Parses an RgbaColor from a hexadecimal, rgb, rgba, hsl, or hsla
value.
@return returns the parsed color | [
"public static RgbaColor from(String color) {\n if (color.startsWith(\"#\")) {\n return fromHex(color);\n }\n else if (color.startsWith(\"rgba\")) {\n return fromRgba(color);\n }\n else if (color.startsWith(\"rgb\")) {\n return fromRgb(color);\n }\n else if (color.startsWith(\"hsla\")) {\n return fromHsla(color);\n }\n else if (color.startsWith(\"hsl\")) {\n return fromHsl(color);\n }\n else {\n return getDefaultColor();\n }\n }"
] | [
"public <X> X invokeOnInstance(Object instance, Object... parameters) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n final Map<Class<?>, Method> methods = this.methods;\n Method method = methods.get(instance.getClass());\n if (method == null) {\n // the same method may be written to the map twice, but that is ok\n // lookupMethod is very slow\n Method delegate = annotatedMethod.getJavaMember();\n method = SecurityActions.lookupMethod(instance.getClass(), delegate.getName(), delegate.getParameterTypes());\n SecurityActions.ensureAccessible(method);\n synchronized (this) {\n final Map<Class<?>, Method> newMethods = new HashMap<Class<?>, Method>(methods);\n newMethods.put(instance.getClass(), method);\n this.methods = WeldCollections.immutableMapView(newMethods);\n }\n }\n return cast(method.invoke(instance, parameters));\n }",
"public void addNotIn(String attribute, Query subQuery)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }",
"public JSONObject toJson() throws JSONException {\n\n JSONObject result = new JSONObject();\n if (m_detailId != null) {\n result.put(JSON_DETAIL, \"\" + m_detailId);\n }\n if (m_siteRoot != null) {\n result.put(JSON_SITEROOT, m_siteRoot);\n }\n if (m_structureId != null) {\n result.put(JSON_STRUCTUREID, \"\" + m_structureId);\n }\n if (m_projectId != null) {\n result.put(JSON_PROJECT, \"\" + m_projectId);\n }\n if (m_type != null) {\n result.put(JSON_TYPE, \"\" + m_type.getJsonId());\n }\n return result;\n }",
"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}",
"@Deprecated\n public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) {\n Utils.notNull(nodes);\n this.nodes = new HashSet<Node>(nodes);\n return this;\n }",
"protected void boot(final BootContext context) throws ConfigurationPersistenceException {\n List<ModelNode> bootOps = configurationPersister.load();\n ModelNode op = registerModelControllerServiceInitializationBootStep(context);\n if (op != null) {\n bootOps.add(op);\n }\n boot(bootOps, false);\n finishBoot();\n }",
"public AiTextureInfo getTextureInfo(AiTextureType type, int index) {\n return new AiTextureInfo(type, index, getTextureFile(type, index), \n getTextureUVIndex(type, index), getBlendFactor(type, index), \n getTextureOp(type, index), getTextureMapModeW(type, index), \n getTextureMapModeW(type, index), \n getTextureMapModeW(type, index));\n }",
"@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }",
"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 }"
] |
Convert the Primavera string representation of a UUID into a Java UUID instance.
@param value Primavera UUID
@return Java UUID instance | [
"public static final UUID parseUUID(String value)\n {\n UUID result = null;\n if (value != null && !value.isEmpty())\n {\n if (value.charAt(0) == '{')\n {\n // PMXML representation: <GUID>{0AB9133E-A09A-9648-B98A-B2384894AC44}</GUID>\n result = UUID.fromString(value.substring(1, value.length() - 1));\n }\n else\n {\n // XER representation: CrkTPqCalki5irI4SJSsRA\n byte[] data = javax.xml.bind.DatatypeConverter.parseBase64Binary(value + \"==\");\n long msb = 0;\n long lsb = 0;\n\n for (int i = 0; i < 8; i++)\n {\n msb = (msb << 8) | (data[i] & 0xff);\n }\n\n for (int i = 8; i < 16; i++)\n {\n lsb = (lsb << 8) | (data[i] & 0xff);\n }\n\n result = new UUID(msb, lsb);\n }\n }\n return result;\n }"
] | [
"private Integer highlanderMode(JobDef jd, DbConn cnx)\n {\n if (!jd.isHighlander())\n {\n return null;\n }\n\n try\n {\n Integer existing = cnx.runSelectSingle(\"ji_select_existing_highlander\", Integer.class, jd.getId());\n return existing;\n }\n catch (NoResultException ex)\n {\n // Just continue, this means no existing waiting JI in queue.\n }\n\n // Now we need to actually synchronize through the database to avoid double posting\n // TODO: use a dedicated table, not the JobDef one. Will avoid locking the configuration.\n ResultSet rs = cnx.runSelect(true, \"jd_select_by_id\", jd.getId());\n\n // Now we have a lock, just retry - some other client may have created a job instance recently.\n try\n {\n Integer existing = cnx.runSelectSingle(\"ji_select_existing_highlander\", Integer.class, jd.getId());\n rs.close();\n cnx.commit(); // Do not keep the lock!\n return existing;\n }\n catch (NoResultException ex)\n {\n // Just continue, this means no existing waiting JI in queue. We keep the lock!\n }\n catch (SQLException e)\n {\n // Who cares.\n jqmlogger.warn(\"Issue when closing a ResultSet. Transaction or session leak is possible.\", e);\n }\n\n jqmlogger.trace(\"Highlander mode analysis is done: nor existing JO, must create a new one. Lock is hold.\");\n return null;\n }",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n ValueContainer[] result = new ValueContainer[pkFields.length];\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n\r\n try\r\n {\r\n for(int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fd = pkFields[i];\r\n Object cv = pkValues[i];\r\n if(convertToSql)\r\n {\r\n // BRJ : apply type and value mapping\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n throw new PersistenceBrokerException(\"Can't generate primary key values for given Identity \" + oid, e);\r\n }\r\n return result;\r\n }",
"void notifyMwRevisionProcessors(MwRevision mwRevision, boolean isCurrent) {\n\t\tif (mwRevision == null || mwRevision.getPageId() <= 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (MwRevisionProcessorBroker.RevisionSubscription rs : this.revisionSubscriptions) {\n\t\t\tif (rs.onlyCurrentRevisions == isCurrent\n\t\t\t\t\t&& (rs.model == null || mwRevision.getModel().equals(\n\t\t\t\t\t\t\trs.model))) {\n\t\t\t\trs.mwRevisionProcessor.processRevision(mwRevision);\n\t\t\t}\n\t\t}\n\t}",
"protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }",
"private Cluster expandCluster(final Cluster cluster,\n final Point2D point,\n final List<Point2D> neighbors,\n final KDTree<Point2D> points,\n final Map<Point2D, PointStatus> visited) {\n cluster.addPoint(point);\n visited.put(point, PointStatus.PART_OF_CLUSTER);\n\n List<Point2D> seeds = new ArrayList<Point2D>(neighbors);\n int index = 0;\n while (index < seeds.size()) {\n Point2D current = seeds.get(index);\n PointStatus pStatus = visited.get(current);\n // only check non-visited points\n if (pStatus == null) {\n final List<Point2D> currentNeighbors = getNeighbors(current, points);\n if (currentNeighbors.size() >= minPoints) {\n seeds = merge(seeds, currentNeighbors);\n }\n }\n\n if (pStatus != PointStatus.PART_OF_CLUSTER) {\n visited.put(current, PointStatus.PART_OF_CLUSTER);\n cluster.addPoint(current);\n }\n\n index++;\n }\n return cluster;\n }",
"public final void notifyFooterItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount + contentItemCount, itemCount);\n }",
"public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) {\n\t\treturn CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason });\n\t}",
"private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }",
"public static Artifact getIdlArtifact(Artifact artifact, ArtifactFactory artifactFactory,\n ArtifactResolver artifactResolver,\n ArtifactRepository localRepository,\n List<ArtifactRepository> remoteRepos,\n String classifier)\n throws MojoExecutionException {\n Artifact idlArtifact = artifactFactory.createArtifactWithClassifier(\n artifact.getGroupId(),\n artifact.getArtifactId(),\n artifact.getVersion(),\n \"jar\",\n classifier);\n try {\n artifactResolver.resolve(idlArtifact, remoteRepos, localRepository);\n return idlArtifact;\n } catch (final ArtifactResolutionException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n } catch (final ArtifactNotFoundException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n }\n }"
] |
Translate the string to bytes using the given encoding
@param string The string to translate
@param encoding The encoding to use
@return The bytes that make up the string | [
"public static byte[] getBytes(String string, String encoding) {\n try {\n return string.getBytes(encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }"
] | [
"private FieldDescriptor[] getExtentFieldDescriptors(TableAlias extAlias, FieldDescriptor[] fds)\r\n {\r\n FieldDescriptor[] result = new FieldDescriptor[fds.length];\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n result[i] = extAlias.cld.getFieldDescriptorByName(fds[i].getAttributeName());\r\n }\r\n\r\n return result;\r\n }",
"@Override\n public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"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 static Span exact(Bytes row) {\n Objects.requireNonNull(row);\n return new Span(row, true, row, true);\n }",
"public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createRemoveOperation(address);\n op.get(RECURSIVE).set(recursive);\n return op;\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 ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }",
"public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {\n\t\tfor (Map.Entry<String, List<String>> entry : headers.entrySet()) {\n\t\t\tString headerName = entry.getKey();\n\t\t\tif (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265\n\t\t\t\tString headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), \"; \");\n\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t}\n\t\t\telse if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) &&\n\t\t\t\t\t!HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {\n\t\t\t\tfor (String headerValue : entry.getValue()) {\n\t\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] |
Creates a project shared with the given team.
Returns the full record of the newly created project.
@param team The team to create the project in.
@return Request object | [
"public ItemRequest<Project> createInTeam(String team) {\n \n String path = String.format(\"/teams/%s/projects\", team);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }"
] | [
"boolean callbackUnregistered(final TransactionalProtocolClient old, final boolean shuttingDown) {\n // Disconnect the remote connection.\n // WFCORE-196 Do this out of the sync block to avoid deadlocks where in-flight requests can't\n // be informed that the channel has closed\n protocolClient.disconnected(old);\n\n synchronized (this) {\n // If the connection dropped without us stopping the process ask for reconnection\n if (!shuttingDown && requiredState == InternalState.SERVER_STARTED) {\n final InternalState state = internalState;\n if (state == InternalState.PROCESS_STOPPED\n || state == InternalState.PROCESS_STOPPING\n || state == InternalState.STOPPED) {\n // In case it stopped we don't reconnect\n return true;\n }\n // In case we are reloading, it will reconnect automatically\n if (state == InternalState.RELOADING) {\n return true;\n }\n try {\n ROOT_LOGGER.logf(DEBUG_LEVEL, \"trying to reconnect to %s current-state (%s) required-state (%s)\", serverName, state, requiredState);\n internalSetState(new ReconnectTask(), state, InternalState.SEND_STDIN);\n } catch (Exception e) {\n ROOT_LOGGER.logf(DEBUG_LEVEL, e, \"failed to send reconnect task\");\n }\n return false;\n } else {\n return true;\n }\n }\n }",
"protected static PatchElement createRollbackElement(final PatchEntry entry) {\n final PatchElement patchElement = entry.element;\n final String patchId;\n final Patch.PatchType patchType = patchElement.getProvider().getPatchType();\n if (patchType == Patch.PatchType.CUMULATIVE) {\n patchId = entry.getCumulativePatchID();\n } else {\n patchId = patchElement.getId();\n }\n return createPatchElement(entry, patchId, entry.rollbackActions);\n }",
"public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) {\n\t\tClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature\n\t\t\t\t.getTypeSignature(clazz);\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length];\n\t\tfor (int i = 0; i < typeArgs.length; i++) {\n\t\t\ttypeArgSignatures[i] = new TypeArgSignature(\n\t\t\t\t\tTypeArgSignature.NO_WILDCARD,\n\t\t\t\t\t(FieldTypeSignature) javaTypeToTypeSignature\n\t\t\t\t\t\t\t.getTypeSignature(typeArgs[i]));\n\t\t}\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\n\t\t\t\trawClassTypeSignature.getBinaryName(), typeArgSignatures,\n\t\t\t\trawClassTypeSignature.getOwnerTypeSignature());\n\n\t\treturn classTypeSignature;\n\t}",
"public void init(ServletContext context) {\n if (profiles != null) {\n for (IDiagramProfile profile : profiles) {\n profile.init(context);\n _registry.put(profile.getName(),\n profile);\n }\n }\n }",
"public static ModelNode createListDeploymentsOperation() {\n final ModelNode op = createOperation(READ_CHILDREN_NAMES);\n op.get(CHILD_TYPE).set(DEPLOYMENT);\n return op;\n }",
"private Project.Tasks.Task.PredecessorLink writePredecessor(Integer taskID, RelationType type, Duration lag)\n {\n Project.Tasks.Task.PredecessorLink link = m_factory.createProjectTasksTaskPredecessorLink();\n\n link.setPredecessorUID(NumberHelper.getBigInteger(taskID));\n link.setType(BigInteger.valueOf(type.getValue()));\n link.setCrossProject(Boolean.FALSE); // SF-300: required to keep P6 happy when importing MSPDI files\n\n if (lag != null && lag.getDuration() != 0)\n {\n double linkLag = lag.getDuration();\n if (lag.getUnits() != TimeUnit.PERCENT && lag.getUnits() != TimeUnit.ELAPSED_PERCENT)\n {\n linkLag = 10.0 * Duration.convertUnits(linkLag, lag.getUnits(), TimeUnit.MINUTES, m_projectFile.getProjectProperties()).getDuration();\n }\n link.setLinkLag(BigInteger.valueOf((long) linkLag));\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(lag.getUnits(), false));\n }\n else\n {\n // SF-329: default required to keep Powerproject happy when importing MSPDI files\n link.setLinkLag(BIGINTEGER_ZERO);\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(m_projectFile.getProjectProperties().getDefaultDurationUnits(), false));\n }\n\n return (link);\n }",
"public static URI setPath(final URI initialUri, final String path) {\n String finalPath = path;\n if (!finalPath.startsWith(\"/\")) {\n finalPath = '/' + path;\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,\n initialUri.getQuery(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n finalPath, initialUri.getQuery(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }",
"@Deprecated\n\tpublic void setResolutions(List<Double> resolutions) {\n\t\tgetZoomLevels().clear();\n\t\tfor (Double resolution : resolutions) {\n\t\t\tgetZoomLevels().add(new ScaleInfo(1. / resolution));\n\t\t}\n\t}",
"public static cacheobject[] get(nitro_service service, cacheobject_args args) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] |
Set a callback to handle any exceptions in the chain of execution.
@param callback
Instance of {@link ErrorCallback}.
@return Reference to the {@code ExecutionChain}
@throws IllegalStateException
if the chain of execution has already been {@link #execute()
started}. | [
"public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }"
] | [
"@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\n }",
"public ConfigurableMessages getConfigurableMessages(CmsMessages defaultMessages, Locale locale) {\n\n return new ConfigurableMessages(defaultMessages, locale, m_configuredBundle);\n\n }",
"public CollectionRequest<Project> tasks(String project) {\n \n String path = String.format(\"/projects/%s/tasks\", project);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }",
"public static base_responses update(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\tupdateresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n public boolean decompose(DMatrixRBlock A) {\n if( A.numCols != A.numRows )\n throw new IllegalArgumentException(\"A must be square\");\n\n this.T = A;\n\n if( lower )\n return decomposeLower();\n else\n return decomposeUpper();\n }",
"private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {\n if (bean.getInjectionPoints().isEmpty()) {\n // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)\n return;\n }\n reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());\n }",
"public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) {\n\t\tType propertyType = mainSidePersister.getPropertyTypes()[propertyIndex];\n\t\tSessionFactoryImplementor factory = mainSidePersister.getFactory();\n\n\t\t// property represents no association, so no inverse meta-data can exist\n\t\tif ( !propertyType.isAssociationType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tJoinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory );\n\t\tOgmEntityPersister inverseSidePersister = null;\n\n\t\t// to-many association\n\t\tif ( mainSideJoinable.isCollection() ) {\n\t\t\tinverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister();\n\t\t}\n\t\t// to-one\n\t\telse {\n\t\t\tinverseSidePersister = (OgmEntityPersister) mainSideJoinable;\n\t\t\tmainSideJoinable = mainSidePersister;\n\t\t}\n\n\t\tString mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex];\n\n\t\t// property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data\n\t\t// straight from the main-side persister\n\t\tAssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty );\n\t\tif ( inverseOneToOneMetadata != null ) {\n\t\t\treturn inverseOneToOneMetadata;\n\t\t}\n\n\t\t// process properties of inverse side and try to find association back to main side\n\t\tfor ( String candidateProperty : inverseSidePersister.getPropertyNames() ) {\n\t\t\tType type = inverseSidePersister.getPropertyType( candidateProperty );\n\n\t\t\t// candidate is a *-to-many association\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type );\n\t\t\t\tString mappedByProperty = inverseCollectionPersister.getMappedByProperty();\n\t\t\t\tif ( mainSideProperty.equals( mappedByProperty ) ) {\n\t\t\t\t\tif ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) {\n\t\t\t\t\t\treturn inverseCollectionPersister.getAssociationKeyMetadata();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"public void updateInfo(Info info) {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"PUT\");\n request.setBody(info.getPendingChanges());\n BoxAPIResponse boxAPIResponse = request.send();\n\n if (boxAPIResponse instanceof BoxJSONResponse) {\n BoxJSONResponse response = (BoxJSONResponse) boxAPIResponse;\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }\n }",
"public Slice newSlice(long address, int size, Object reference)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (reference == null) {\n throw new NullPointerException(\"Object reference is null\");\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, size, reference);\n }"
] |
Retrieves the text value for the baseline duration.
@return baseline duration text | [
"public String getBaselineDurationText()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }"
] | [
"public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }",
"public static base_responses disable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm disableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tdisableresources[i] = new snmpalarm();\n\t\t\t\tdisableresources[i].trapname = trapname[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}",
"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 Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\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 Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }",
"public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}",
"protected void swapColumns( int j ) {\n\n // find the column with the largest norm\n int largestIndex = j;\n double largestNorm = normsCol[j];\n for( int col = j+1; col < numCols; col++ ) {\n double n = normsCol[col];\n if( n > largestNorm ) {\n largestNorm = n;\n largestIndex = col;\n }\n }\n // swap the columns\n double []tempC = dataQR[j];\n dataQR[j] = dataQR[largestIndex];\n dataQR[largestIndex] = tempC;\n double tempN = normsCol[j];\n normsCol[j] = normsCol[largestIndex];\n normsCol[largestIndex] = tempN;\n int tempP = pivots[j];\n pivots[j] = pivots[largestIndex];\n pivots[largestIndex] = tempP;\n }",
"public void loadClassifier(String loadPath, Properties props) throws ClassCastException, IOException, ClassNotFoundException {\r\n InputStream is;\r\n // ms, 10-04-2010: check first is this path exists in our CLASSPATH. This\r\n // takes priority over the file system.\r\n if ((is = loadStreamFromClasspath(loadPath)) != null) {\r\n Timing.startDoing(\"Loading classifier from \" + loadPath);\r\n loadClassifier(is);\r\n is.close();\r\n Timing.endDoing();\r\n } else {\r\n loadClassifier(new File(loadPath), props);\r\n }\r\n }",
"public static cmppolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tobj.set_name(name);\n\t\tcmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static base_response disable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance disableresource = new clusterinstance();\n\t\tdisableresource.clid = clid;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}"
] |
Creates new row in table
@param broker
@param field
@param sequenceName
@param maxKey
@throws Exception | [
"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 static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\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 <A extends Annotation> AnnotationConverter<A> getConverter(Annotation annotation) {\n\t\tMappingOption mappingOption = annotation.annotationType().getAnnotation( MappingOption.class );\n\t\tif ( mappingOption == null ) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// wrong type would be a programming error of the annotation developer\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tClass<? extends AnnotationConverter<A>> converterClass = (Class<? extends AnnotationConverter<A>>) mappingOption.value();\n\n\t\ttry {\n\t\t\treturn converterClass.newInstance();\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow log.cannotConvertAnnotation( converterClass, e );\n\t\t}\n\t}",
"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 boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }",
"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 static base_response clear(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig clearresource = new nsconfig();\n\t\tclearresource.force = resource.force;\n\t\tclearresource.level = resource.level;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }"
] |
A smoothed pulse function. A cubic function is used to smooth the step between two thresholds.
@param a1 the lower threshold position for the start of the pulse
@param a2 the upper threshold position for the start of the pulse
@param b1 the lower threshold position for the end of the pulse
@param b2 the upper threshold position for the end of the pulse
@param x the input parameter
@return the output value | [
"public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {\n\t\tif (x < a1 || x >= b2)\n\t\t\treturn 0;\n\t\tif (x >= a2) {\n\t\t\tif (x < b1)\n\t\t\t\treturn 1.0f;\n\t\t\tx = (x - b1) / (b2 - b1);\n\t\t\treturn 1.0f - (x*x * (3.0f - 2.0f*x));\n\t\t}\n\t\tx = (x - a1) / (a2 - a1);\n\t\treturn x*x * (3.0f - 2.0f*x);\n\t}"
] | [
"@Override\r\n public String remove(Object key) {\r\n\r\n String result = m_configurationStrings.remove(key);\r\n m_configurationObjects.remove(key);\r\n return result;\r\n }",
"void start(String monitoredDirectory, Long pollingTime) {\n this.monitoredDirectory = monitoredDirectory;\n String deployerKlassName;\n if (klass.equals(ImportDeclaration.class)) {\n deployerKlassName = ImporterDeployer.class.getName();\n } else if (klass.equals(ExportDeclaration.class)) {\n deployerKlassName = ExporterDeployer.class.getName();\n } else {\n throw new IllegalStateException(\"\");\n }\n\n this.dm = new DirectoryMonitor(monitoredDirectory, pollingTime, deployerKlassName);\n try {\n dm.start(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to start \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory + \" and polling time \" + pollingTime.toString(), e);\n }\n }",
"@Override\n public HandlerRegistration addSearchFinishHandler(final SearchFinishEvent.SearchFinishHandler handler) {\n return addHandler(handler, SearchFinishEvent.TYPE);\n }",
"public String name(Properties attributes) throws XDocletException\r\n {\r\n return getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n }",
"public void removeTag(String tagId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REMOVE_TAG);\r\n\r\n parameters.put(\"tag_id\", tagId);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private CmsCheckBox generateCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = new CmsCheckBox();\n cb.setText(m_dateFormat.format(date));\n cb.setChecked(checkState);\n cb.getElement().setPropertyObject(\"date\", date);\n return cb;\n\n }",
"private Number calculateDurationPercentComplete(Row row)\n {\n double result = 0;\n double targetDuration = row.getDuration(\"target_drtn_hr_cnt\").getDuration();\n double remainingDuration = row.getDuration(\"remain_drtn_hr_cnt\").getDuration();\n\n if (targetDuration == 0)\n {\n if (remainingDuration == 0)\n {\n if (\"TK_Complete\".equals(row.getString(\"status_code\")))\n {\n result = 100;\n }\n }\n }\n else\n {\n if (remainingDuration < targetDuration)\n {\n result = ((targetDuration - remainingDuration) * 100) / targetDuration;\n }\n }\n\n return NumberHelper.getDouble(result);\n }",
"protected String colorString(PDColor pdcolor)\n {\n String color = null;\n try\n {\n float[] rgb = pdcolor.getColorSpace().toRGB(pdcolor.getComponents());\n color = colorString(rgb[0], rgb[1], rgb[2]);\n } catch (IOException e) {\n log.error(\"colorString: IOException: {}\", e.getMessage());\n } catch (UnsupportedOperationException e) {\n log.error(\"colorString: UnsupportedOperationException: {}\", e.getMessage());\n }\n return color;\n }",
"@VisibleForTesting\n protected static String createLabelText(\n final DistanceUnit scaleUnit, final double value, final DistanceUnit intervalUnit) {\n double scaledValue = scaleUnit.convertTo(value, intervalUnit);\n\n // assume that there is no interval smaller then 0.0001\n scaledValue = Math.round(scaledValue * 10000) / 10000;\n String decimals = Double.toString(scaledValue).split(\"\\\\.\")[1];\n\n if (Double.valueOf(decimals) == 0) {\n return Long.toString(Math.round(scaledValue));\n } else {\n return Double.toString(scaledValue);\n }\n }"
] |
Returns string content of blob identified by specified blob handle. String contents cache is used.
@param blobHandle blob handle
@param txn {@linkplain Transaction} instance
@return string content of blob identified by specified blob handle
@throws IOException if something went wrong | [
"@Nullable\n public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException {\n String result;\n result = stringContentCache.tryKey(this, blobHandle);\n if (result == null) {\n final InputStream content = getContent(blobHandle, txn);\n if (content == null) {\n logger.error(\"Blob string not found: \" + getBlobLocation(blobHandle), new FileNotFoundException());\n }\n result = content == null ? null : UTFUtil.readUTF(content);\n if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) {\n if (stringContentCache.getObject(this, blobHandle) == null) {\n stringContentCache.cacheObject(this, blobHandle, result);\n }\n }\n }\n return result;\n }"
] | [
"public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }",
"public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"public static Artifact withGroupId(String groupId)\n {\n\n Artifact artifact = new Artifact();\n artifact.groupId = new RegexParameterizedPatternParser(groupId);\n return artifact;\n }",
"private void initPatternControllers() {\r\n\r\n m_patternControllers.put(PatternType.NONE, new CmsPatternPanelNoneController());\r\n m_patternControllers.put(PatternType.DAILY, new CmsPatternPanelDailyController(m_model, this));\r\n m_patternControllers.put(PatternType.WEEKLY, new CmsPatternPanelWeeklyController(m_model, this));\r\n m_patternControllers.put(PatternType.MONTHLY, new CmsPatternPanelMonthlyController(m_model, this));\r\n m_patternControllers.put(PatternType.YEARLY, new CmsPatternPanelYearlyController(m_model, this));\r\n // m_patternControllers.put(PatternType.INDIVIDUAL, new CmsPatternPanelIndividualController(m_model, this));\r\n }",
"@VisibleForTesting\n protected static int getBarSize(final ScaleBarRenderSettings settings) {\n if (settings.getParams().barSize != null) {\n return settings.getParams().barSize;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().height / 4;\n } else {\n return settings.getMaxSize().width / 4;\n }\n }\n }",
"public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }",
"public void invalidate() {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate all [%d]\", mMeasuredChildren.size());\n mMeasuredChildren.clear();\n }\n }",
"public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.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) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public void setT(int t) {\r\n this.t = Math.min((radius * 2 + 1) * (radius * 2 + 1) / 2, Math.max(0, t));\r\n }"
] |
Whether this association contains no rows.
@return {@code true} if this association contains no rows, {@code false} otherwise | [
"public boolean isEmpty() {\n\t\tint snapshotSize = cleared ? 0 : snapshot.size();\n\t\t//nothing in both\n\t\tif ( snapshotSize == 0 && currentState.isEmpty() ) {\n\t\t\treturn true;\n\t\t}\n\t\t//snapshot bigger than changeset\n\t\tif ( snapshotSize > currentState.size() ) {\n\t\t\treturn false;\n\t\t}\n\t\treturn size() == 0;\n\t}"
] | [
"public void setValue(FieldContainer container, byte[] data)\n {\n if (data != null)\n {\n container.set(m_type, ((MPPUtility.getInt(data, m_offset) & m_mask) == 0) ? m_zeroValue : m_nonZeroValue);\n }\n }",
"public final void fatal(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.FATAL, pObject, null);\r\n\t}",
"public void removeDescriptor(Object validKey)\r\n {\r\n PBKey pbKey;\r\n if (validKey instanceof PBKey)\r\n {\r\n pbKey = (PBKey) validKey;\r\n }\r\n else if (validKey instanceof JdbcConnectionDescriptor)\r\n {\r\n pbKey = ((JdbcConnectionDescriptor) validKey).getPBKey();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Could not remove descriptor, given object was no vaild key: \" +\r\n validKey);\r\n }\r\n Object removed = null;\r\n synchronized (jcdMap)\r\n {\r\n removed = jcdMap.remove(pbKey);\r\n jcdAliasToPBKeyMap.remove(pbKey.getAlias());\r\n }\r\n log.info(\"Remove descriptor: \" + removed);\r\n }",
"public List<String> getMultiSelect(String path) {\n List<String> values = new ArrayList<String>();\n for (JsonValue val : this.getValue(path).asArray()) {\n values.add(val.asString());\n }\n\n return values;\n }",
"public static String retrieveVendorId() {\n if (MapboxTelemetry.applicationContext == null) {\n return updateVendorId();\n }\n\n SharedPreferences sharedPreferences = obtainSharedPreferences(MapboxTelemetry.applicationContext);\n String mapboxVendorId = sharedPreferences.getString(MAPBOX_SHARED_PREFERENCE_KEY_VENDOR_ID, \"\");\n if (TelemetryUtils.isEmpty(mapboxVendorId)) {\n mapboxVendorId = TelemetryUtils.updateVendorId();\n }\n return mapboxVendorId;\n }",
"public static List<TestSuiteResult> unmarshalSuites(File... directories) throws IOException {\n List<TestSuiteResult> results = new ArrayList<>();\n\n List<File> files = listTestSuiteFiles(directories);\n\n for (File file : files) {\n results.add(unmarshal(file));\n }\n return results;\n }",
"protected void setProperty(String propertyName, JavascriptEnum propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getEnumValue());\n }",
"private void processClassMethods(XMLStreamWriter writer, Class<?> aClass, Set<Method> methodSet) throws XMLStreamException\n {\n Method[] methods = aClass.getDeclaredMethods();\n for (Method method : methods)\n {\n if (!methodSet.contains(method) && Modifier.isPublic(method.getModifiers()) && !Modifier.isInterface(method.getModifiers()))\n {\n if (Modifier.isStatic(method.getModifiers()))\n {\n // TODO Handle static methods here\n }\n else\n {\n String name = method.getName();\n String methodSignature = createMethodSignature(method);\n String fullJavaName = aClass.getCanonicalName() + \".\" + name + methodSignature;\n\n if (!ignoreMethod(fullJavaName))\n {\n //\n // Hide the original method\n //\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n\n writer.writeStartElement(\"attribute\");\n writer.writeAttribute(\"type\", \"System.ComponentModel.EditorBrowsableAttribute\");\n writer.writeAttribute(\"sig\", \"(Lcli.System.ComponentModel.EditorBrowsableState;)V\");\n writer.writeStartElement(\"parameter\");\n writer.writeCharacters(\"Never\");\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n\n //\n // Create a wrapper method\n //\n name = name.toUpperCase().charAt(0) + name.substring(1);\n\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeAttribute(\"modifiers\", \"public\");\n\n writer.writeStartElement(\"body\");\n\n for (int index = 0; index <= method.getParameterTypes().length; index++)\n {\n if (index < 4)\n {\n writer.writeEmptyElement(\"ldarg_\" + index);\n }\n else\n {\n writer.writeStartElement(\"ldarg_s\");\n writer.writeAttribute(\"argNum\", Integer.toString(index));\n writer.writeEndElement();\n }\n }\n\n writer.writeStartElement(\"callvirt\");\n writer.writeAttribute(\"class\", aClass.getName());\n writer.writeAttribute(\"name\", method.getName());\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeEndElement();\n\n if (!method.getReturnType().getName().equals(\"void\"))\n {\n writer.writeEmptyElement(\"ldnull\");\n writer.writeEmptyElement(\"pop\");\n }\n writer.writeEmptyElement(\"ret\");\n writer.writeEndElement();\n writer.writeEndElement();\n\n /*\n * The private method approach doesn't work... so\n * 3. Add EditorBrowsableAttribute (Never) to original methods\n * 4. Generate C Sharp and VB variants of the DLL to avid case-sensitivity issues\n * 5. Implement static method support?\n <attribute type=\"System.ComponentModel.EditorBrowsableAttribute\" sig=\"(Lcli.System.ComponentModel.EditorBrowsableState;)V\">\n 914 <parameter>Never</parameter>\n 915 </attribute>\n */\n\n m_responseList.add(fullJavaName);\n }\n }\n }\n }\n }",
"private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }"
] |
Add a new Corporate GroupId to an organization.
@param credential DbCredential
@param organizationId String Organization name
@param corporateGroupId String
@return Response | [
"@POST\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response addCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an add a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to add!\");\n throw new WebApplicationException(Response.serverError().status(HttpStatus.BAD_REQUEST_400)\n .entity(\"CorporateGroupId to add should be in the query content.\").build());\n }\n\n getOrganizationHandler().addCorporateGroupId(organizationId, corporateGroupId);\n return Response.ok().status(HttpStatus.CREATED_201).build();\n }"
] | [
"public static Stack getStack() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n stack = new Stack(interceptionContexts);\n interceptionContexts.set(stack);\n }\n return stack;\n }",
"public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }",
"public static base_response rename(nitro_service client, nsacl6 resource, String new_acl6name) throws Exception {\n\t\tnsacl6 renameresource = new nsacl6();\n\t\trenameresource.acl6name = resource.acl6name;\n\t\treturn renameresource.rename_resource(client,new_acl6name);\n\t}",
"public static Set<String> listLinks(OperationContext context, PathAddress overlayAddress) {\n Resource overlayResource = context.readResourceFromRoot(overlayAddress);\n if (overlayResource.hasChildren(DEPLOYMENT)) {\n return overlayResource.getChildrenNames(DEPLOYMENT);\n }\n return Collections.emptySet();\n }",
"static GVRPerspectiveCamera makePerspShadowCamera(GVRPerspectiveCamera centerCam, float coneAngle)\n {\n GVRPerspectiveCamera camera = new GVRPerspectiveCamera(centerCam.getGVRContext());\n float near = centerCam.getNearClippingDistance();\n float far = centerCam.getFarClippingDistance();\n\n camera.setNearClippingDistance(near);\n camera.setFarClippingDistance(far);\n camera.setFovY((float) Math.toDegrees(coneAngle));\n camera.setAspectRatio(1.0f);\n return camera;\n }",
"private boolean isPacketLongEnough(DatagramPacket packet, int expectedLength, String name) {\n final int length = packet.getLength();\n if (length < expectedLength) {\n logger.warn(\"Ignoring too-short \" + name + \" packet; expecting \" + expectedLength + \" bytes and got \" +\n length + \".\");\n return false;\n }\n\n if (length > expectedLength) {\n logger.warn(\"Processing too-long \" + name + \" packet; expecting \" + expectedLength +\n \" bytes and got \" + length + \".\");\n }\n\n return true;\n }",
"public static URL codeLocationFromURL(String url) {\n try {\n return new URL(url);\n } catch (Exception e) {\n throw new InvalidCodeLocation(url);\n }\n }",
"public static URL codeLocationFromPath(String filePath) {\n try {\n return new File(filePath).toURI().toURL();\n } catch (Exception e) {\n throw new InvalidCodeLocation(filePath);\n }\n }",
"private void cullDisabledPaths() throws Exception {\n\n ArrayList<EndpointOverride> removePaths = new ArrayList<EndpointOverride>();\n RequestInformation requestInfo = requestInformation.get();\n for (EndpointOverride selectedPath : requestInfo.selectedResponsePaths) {\n\n // check repeat count on selectedPath\n // -1 is unlimited\n if (selectedPath != null && selectedPath.getRepeatNumber() == 0) {\n // skip\n removePaths.add(selectedPath);\n } else if (selectedPath != null && selectedPath.getRepeatNumber() != -1) {\n // need to decrement the #\n selectedPath.updateRepeatNumber(selectedPath.getRepeatNumber() - 1);\n }\n }\n\n // remove paths if we need to\n for (EndpointOverride removePath : removePaths) {\n requestInfo.selectedResponsePaths.remove(removePath);\n }\n }"
] |
This method can be used by child classes to apply the configuration that is stored in config. | [
"protected void doConfigure() {\n if (config != null) {\n for (UserBean user : config.getUsersToCreate()) {\n setUser(user.getEmail(), user.getLogin(), user.getPassword());\n }\n getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled());\n }\n }"
] | [
"public String addDependency(FunctionalTaskItem dependencyTaskItem) {\n IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem);\n this.addDependency(dependency);\n return dependency.key();\n }",
"public GVRAnimation setDuration(float start, float end)\n {\n if(start>end || start<0 || end>mDuration){\n throw new IllegalArgumentException(\"start and end values are wrong\");\n }\n animationOffset = start;\n mDuration = end-start;\n return this;\n }",
"private void writeInterfaceCriteria(final XMLExtendedStreamWriter writer, final ModelNode subModel, final boolean nested) throws XMLStreamException {\n for (final Property property : subModel.asPropertyList()) {\n if (property.getValue().isDefined()) {\n writeInterfaceCriteria(writer, property, nested);\n }\n }\n }",
"public static <T> int createTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn doCreateTable(dao, false);\n\t}",
"public static int[] insertArray(int[] original, int index, int[] inserted) {\n int[] modified = new int[original.length + inserted.length];\n System.arraycopy(original, 0, modified, 0, index);\n System.arraycopy(inserted, 0, modified, index, inserted.length);\n System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);\n return modified;\n }",
"public double[] getTenors(double moneyness, double maturity) {\r\n\t\tint maturityInMonths\t= (int) Math.round(maturity * 12);\r\n\t\tint[] tenorsInMonths\t= getTenors(convertMoneyness(moneyness), maturityInMonths);\r\n\t\tdouble[] tenors\t\t\t= new double[tenorsInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < tenors.length; index++) {\r\n\t\t\ttenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]);\r\n\t\t}\r\n\t\treturn tenors;\r\n\t}",
"public void linkOneToOne(Object obj, ClassDescriptor cld, ObjectReferenceDescriptor rds, boolean insert)\n {\n storeAndLinkOneToOne(true, obj, cld, rds, true);\n }",
"public static base_response export(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey exportresource = new sslfipskey();\n\t\texportresource.fipskeyname = resource.fipskeyname;\n\t\texportresource.key = resource.key;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}",
"public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }"
] |
Removes the duplicate node list.
@param list
the list
@return the int | [
"public static int removeDuplicateNodeList(List<String> list) {\n\n int originCount = list.size();\n // add elements to all, including duplicates\n HashSet<String> hs = new LinkedHashSet<String>();\n hs.addAll(list);\n list.clear();\n list.addAll(hs);\n\n return originCount - list.size();\n }"
] | [
"static ProcessedLayers process(final InstalledConfiguration conf, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n final ProcessedLayers layers = new ProcessedLayers(conf);\n // Process module roots\n final LayerPathSetter moduleSetter = new LayerPathSetter() {\n @Override\n public boolean setPath(final LayerPathConfig pending, final File root) {\n if (pending.modulePath == null) {\n pending.modulePath = root;\n return true;\n }\n return false;\n }\n };\n for (final File moduleRoot : moduleRoots) {\n processRoot(moduleRoot, layers, moduleSetter);\n }\n // Process bundle root\n final LayerPathSetter bundleSetter = new LayerPathSetter() {\n @Override\n public boolean setPath(LayerPathConfig pending, File root) {\n if (pending.bundlePath == null) {\n pending.bundlePath = root;\n return true;\n }\n return false;\n }\n };\n for (final File bundleRoot : bundleRoots) {\n processRoot(bundleRoot, layers, bundleSetter);\n }\n// if (conf.getInstalledLayers().size() != layers.getLayers().size()) {\n// throw processingError(\"processed layers don't match expected %s, but was %s\", conf.getInstalledLayers(), layers.getLayers().keySet());\n// }\n// if (conf.getInstalledAddOns().size() != layers.getAddOns().size()) {\n// throw processingError(\"processed add-ons don't match expected %s, but was %s\", conf.getInstalledAddOns(), layers.getAddOns().keySet());\n// }\n return layers;\n }",
"public boolean removeKey(long key) {\r\n\tint i = indexOfKey(key);\r\n\tif (i<0) return false; // key not contained\r\n\r\n\tthis.state[i]=REMOVED;\r\n\tthis.values[i]=0; // delta\r\n\tthis.distinct--;\r\n\r\n\tif (this.distinct < this.lowWaterMark) {\r\n\t\tint newCapacity = chooseShrinkCapacity(this.distinct,this.minLoadFactor, this.maxLoadFactor);\r\n\t\trehash(newCapacity);\r\n\t}\r\n\t\r\n\treturn true;\t\r\n}",
"private void add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }",
"public AT_Context setFrameTopBottomMargin(int frameTop, int frameBottom){\r\n\t\tif(frameTop>-1 && frameBottom>-1){\r\n\t\t\tthis.frameTopMargin = frameTop;\r\n\t\t\tthis.frameBottomMargin = frameBottom;\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static XMLGregorianCalendar convertDate(Date date) {\n if (date == null) {\n return null;\n }\n\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTimeInMillis(date.getTime());\n\n try {\n return getDatatypeFactory().newXMLGregorianCalendar(gc);\r\n } catch (DatatypeConfigurationException ex) {\n return null;\n }\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period,\n KeepRunning callback) {\n validateDelay(delay);\n validatePeriod(period);\n return new Event(task, delay, period, callback);\n }",
"private float max(float x, float y, float z) {\n if (x > y) {\n // not y\n if (x > z) {\n return x;\n }\n else {\n return z;\n }\n }\n else {\n // not x\n if (y > z) {\n return y;\n }\n else {\n return z;\n }\n }\n }",
"public void copy(ProjectCalendar cal)\n {\n setName(cal.getName());\n setParent(cal.getParent());\n System.arraycopy(cal.getDays(), 0, getDays(), 0, getDays().length);\n for (ProjectCalendarException ex : cal.m_exceptions)\n {\n addCalendarException(ex.getFromDate(), ex.getToDate());\n for (DateRange range : ex)\n {\n ex.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n\n for (ProjectCalendarHours hours : getHours())\n {\n if (hours != null)\n {\n ProjectCalendarHours copyHours = cal.addCalendarHours(hours.getDay());\n for (DateRange range : hours)\n {\n copyHours.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n }\n }"
] |
Helper method for formatting connection termination messages.
@param connectionName
The name of the connection
@param host
The remote host
@param connectionReason
The reason for establishing the connection
@param terminationReason
The reason for terminating the connection
@return A formatted message in the format:
"[<connectionName>] remote host[<host>] <connectionReason> - <terminationReason>"
<br/>
e.g. [con1] remote host[123.123.123.123] connection to ECMG -
terminated by remote host. | [
"public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) {\n\t\treturn CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason });\n\t}"
] | [
"public static boolean containsUid(IdRange[] idRanges, long uid) {\r\n if (null != idRanges && idRanges.length > 0) {\r\n for (IdRange range : idRanges) {\r\n if (range.includes(uid)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"public boolean doSyncPass() {\n if (!this.isConfigured || !syncLock.tryLock()) {\n return false;\n }\n try {\n if (logicalT == Long.MAX_VALUE) {\n if (logger.isInfoEnabled()) {\n logger.info(\"reached max logical time; resetting back to 0\");\n }\n logicalT = 0;\n }\n logicalT++;\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass START\",\n logicalT));\n }\n if (networkMonitor == null || !networkMonitor.isConnected()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Network disconnected\",\n logicalT));\n }\n return false;\n }\n if (authMonitor == null || !authMonitor.tryIsLoggedIn()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Logged out\",\n logicalT));\n }\n return false;\n }\n\n syncRemoteToLocal();\n syncLocalToRemote();\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END\",\n logicalT));\n }\n } catch (InterruptedException e) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass INTERRUPTED\",\n logicalT));\n }\n return false;\n } finally {\n syncLock.unlock();\n }\n return true;\n }",
"private void emitSuiteStart(Description description, long startTimestamp) throws IOException {\n String suiteName = description.getDisplayName();\n if (useSimpleNames) {\n if (suiteName.lastIndexOf('.') >= 0) {\n suiteName = suiteName.substring(suiteName.lastIndexOf('.') + 1);\n }\n }\n logShort(shortTimestamp(startTimestamp) +\n \"Suite: \" +\n FormattingUtils.padTo(maxClassNameColumns, suiteName, \"[...]\"));\n }",
"public static boolean oracleExists(CuratorFramework curator) {\n boolean exists = false;\n try {\n exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null\n && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty();\n } catch (Exception nne) {\n if (nne instanceof KeeperException.NoNodeException) {\n // you'll do nothing\n } else {\n throw new RuntimeException(nne);\n }\n }\n return exists;\n }",
"public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }",
"public static boolean isTodoItem(final Document todoItemDoc) {\n return todoItemDoc.containsKey(ID_KEY)\n && todoItemDoc.containsKey(TASK_KEY)\n && todoItemDoc.containsKey(CHECKED_KEY);\n }",
"void setRightChild(final byte b, @NotNull final MutableNode child) {\n final ChildReference right = children.getRight();\n if (right == null || (right.firstByte & 0xff) != (b & 0xff)) {\n throw new IllegalArgumentException();\n }\n children.setAt(children.size() - 1, new ChildReferenceMutable(b, child));\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 }",
"private void populateRelation(TaskField field, Task sourceTask, String relationship) throws MPXJException\n {\n int index = 0;\n int length = relationship.length();\n\n //\n // Extract the identifier\n //\n while ((index < length) && (Character.isDigit(relationship.charAt(index)) == true))\n {\n ++index;\n }\n\n Integer taskID;\n try\n {\n taskID = Integer.valueOf(relationship.substring(0, index));\n }\n\n catch (NumberFormatException ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n //\n // Now find the task, so we can extract the unique ID\n //\n Task targetTask;\n if (field == TaskField.PREDECESSORS)\n {\n targetTask = m_projectFile.getTaskByID(taskID);\n }\n else\n {\n targetTask = m_projectFile.getTaskByUniqueID(taskID);\n }\n\n //\n // If we haven't reached the end, we next expect to find\n // SF, SS, FS, FF\n //\n RelationType type = null;\n Duration lag = null;\n\n if (index == length)\n {\n type = RelationType.FINISH_START;\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if ((index + 1) == length)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n type = RelationTypeUtility.getInstance(m_locale, relationship.substring(index, index + 2));\n\n index += 2;\n\n if (index == length)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if (relationship.charAt(index) == '+')\n {\n ++index;\n }\n\n lag = DurationUtility.getInstance(relationship.substring(index), m_formats.getDurationDecimalFormat(), m_locale);\n }\n }\n\n if (type == null)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n // We have seen at least one example MPX file where an invalid task ID\n // is present. We'll ignore this as the schedule is otherwise valid.\n if (targetTask != null)\n {\n Relation relation = sourceTask.addPredecessor(targetTask, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }"
] |
Copies all elements from input into output which are > tol.
@param input (Input) input matrix. Not modified.
@param output (Output) Output matrix. Modified and shaped to match input.
@param tol Tolerance for defining zero | [
"public static void removeZeros( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) {\n ImplCommonOps_DSCC.removeZeros(input,output,tol);\n }"
] | [
"public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }",
"public void setScriptText(String scriptText, String language)\n {\n GVRScriptFile newScript = new GVRJavascriptScriptFile(getGVRContext(), scriptText);\n mLanguage = GVRScriptManager.LANG_JAVASCRIPT;\n setScriptFile(newScript);\n }",
"public static DataPersister lookupForField(Field field) {\n\n\t\t// see if the any of the registered persisters are valid first\n\t\tif (registeredPersisters != null) {\n\t\t\tfor (DataPersister persister : registeredPersisters) {\n\t\t\t\tif (persister.isValidForField(field)) {\n\t\t\t\t\treturn persister;\n\t\t\t\t}\n\t\t\t\t// check the classes instead\n\t\t\t\tfor (Class<?> clazz : persister.getAssociatedClasses()) {\n\t\t\t\t\tif (field.getType() == clazz) {\n\t\t\t\t\t\treturn persister;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// look it up in our built-in map by class\n\t\tDataPersister dataPersister = builtInMap.get(field.getType().getName());\n\t\tif (dataPersister != null) {\n\t\t\treturn dataPersister;\n\t\t}\n\n\t\t/*\n\t\t * Special case for enum types. We can't put this in the registered persisters because we want people to be able\n\t\t * to override it.\n\t\t */\n\t\tif (field.getType().isEnum()) {\n\t\t\treturn DEFAULT_ENUM_PERSISTER;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Serializable classes return null here because we don't want them to be automatically configured for\n\t\t\t * forwards compatibility with future field types that happen to be Serializable.\n\t\t\t */\n\t\t\treturn null;\n\t\t}\n\t}",
"public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }",
"public static boolean isQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return false;\n }\n return (str.startsWith(\"\\\"\") && str.endsWith(\"\\\"\"));\n }",
"public static <T> void checkAbstractMethods(Set<Type> decoratedTypes, EnhancedAnnotatedType<T> type, BeanManagerImpl beanManager) {\n\n if (decoratedTypes == null) {\n decoratedTypes = new HashSet<Type>(type.getInterfaceClosure());\n decoratedTypes.remove(Serializable.class);\n }\n\n Set<MethodSignature> signatures = new HashSet<MethodSignature>();\n\n for (Type decoratedType : decoratedTypes) {\n for (EnhancedAnnotatedMethod<?, ?> method : ClassTransformer.instance(beanManager)\n .getEnhancedAnnotatedType(Reflections.getRawType(decoratedType), beanManager.getId()).getEnhancedMethods()) {\n signatures.add(method.getSignature());\n }\n }\n\n for (EnhancedAnnotatedMethod<?, ?> method : type.getEnhancedMethods()) {\n if (Reflections.isAbstract(((AnnotatedMethod<?>) method).getJavaMember())) {\n MethodSignature methodSignature = method.getSignature();\n if (!signatures.contains(methodSignature)) {\n throw BeanLogger.LOG.abstractMethodMustMatchDecoratedType(method, Formats.formatAsStackTraceElement(method.getJavaMember()));\n }\n }\n }\n }",
"private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }",
"private void logBinaryStringInfo(StringBuilder binaryString) {\n\n encodeInfo += \"Binary Length: \" + binaryString.length() + \"\\n\";\n encodeInfo += \"Binary String: \";\n\n int nibble = 0;\n for (int i = 0; i < binaryString.length(); i++) {\n switch (i % 4) {\n case 0:\n if (binaryString.charAt(i) == '1') {\n nibble += 8;\n }\n break;\n case 1:\n if (binaryString.charAt(i) == '1') {\n nibble += 4;\n }\n break;\n case 2:\n if (binaryString.charAt(i) == '1') {\n nibble += 2;\n }\n break;\n case 3:\n if (binaryString.charAt(i) == '1') {\n nibble += 1;\n }\n encodeInfo += Integer.toHexString(nibble);\n nibble = 0;\n break;\n }\n }\n\n if ((binaryString.length() % 4) != 0) {\n encodeInfo += Integer.toHexString(nibble);\n }\n\n encodeInfo += \"\\n\";\n }",
"private void addToInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.addNavigationalInformationForInverseSide();\n\t}"
] |
Creates a simple, annotation defined Web Bean
@param <T> The type
@param clazz The class
@param beanManager the current manager
@return A Web Bean | [
"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 }"
] | [
"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 }",
"public T mapRow(ResultSet rs) throws SQLException {\n Map<String, Object> map = new HashMap<String, Object>();\n ResultSetMetaData metadata = rs.getMetaData();\n\n for (int i = 1; i <= metadata.getColumnCount(); ++i) {\n String label = metadata.getColumnLabel(i);\n\n final Object value;\n // calling getObject on a BLOB/CLOB produces weird results\n switch (metadata.getColumnType(i)) {\n case Types.BLOB:\n value = rs.getBytes(i);\n break;\n case Types.CLOB:\n value = rs.getString(i);\n break;\n default:\n value = rs.getObject(i);\n }\n\n // don't use table name extractor because we don't want aliased table name\n boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));\n String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);\n if (tableName != null && !tableName.isEmpty()) {\n String qualifiedName = tableName + \".\" + metadata.getColumnName(i);\n add(map, qualifiedName, value, overwrite);\n }\n\n add(map, label, value, overwrite);\n }\n\n return objectMapper.convertValue(map, type);\n }",
"public 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}",
"private Pair<Double, String>\n summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\n\" + title + \"\\n\");\n\n Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>();\n for(Integer zoneId: cluster.getZoneIds()) {\n zoneToBalanceStats.put(zoneId, new ZoneBalanceStats());\n }\n\n for(Node node: cluster.getNodes()) {\n int curCount = nodeIdToPartitionCount.get(node.getId());\n builder.append(\"\\tNode ID: \" + node.getId() + \" : \" + curCount + \" (\" + node.getHost()\n + \")\\n\");\n zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount);\n }\n\n // double utilityToBeMinimized = Double.MIN_VALUE;\n double utilityToBeMinimized = 0;\n for(Integer zoneId: cluster.getZoneIds()) {\n builder.append(\"Zone \" + zoneId + \"\\n\");\n builder.append(zoneToBalanceStats.get(zoneId).dumpStats());\n utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility();\n /*- \n * Another utility function to consider \n if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) {\n utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility();\n }\n */\n }\n\n return Pair.create(utilityToBeMinimized, builder.toString());\n }",
"public boolean isEmbeddedProperty(String targetTypeName, List<String> namesWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\t// Embedded\n\t\t\treturn true;\n\t\t}\n\t\telse if ( propertyType.isAssociationType() ) {\n\t\t\tJoinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );\n\t\t\tif ( associatedJoinable.isCollection() ) {\n\t\t\t\tOgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;\n\t\t\t\treturn collectionPersister.getType().isComponentType();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static <T> String extractTableName(DatabaseType databaseType, Class<T> clazz) {\n\t\tDatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class);\n\t\tString name = null;\n\t\tif (databaseTable != null && databaseTable.tableName() != null && databaseTable.tableName().length() > 0) {\n\t\t\tname = databaseTable.tableName();\n\t\t}\n\t\tif (name == null && javaxPersistenceConfigurer != null) {\n\t\t\tname = javaxPersistenceConfigurer.getEntityName(clazz);\n\t\t}\n\t\tif (name == null) {\n\t\t\t// if the name isn't specified, it is the class name lowercased\n\t\t\tif (databaseType == null) {\n\t\t\t\t// database-type is optional so if it is not specified we just use english\n\t\t\t\tname = clazz.getSimpleName().toLowerCase(Locale.ENGLISH);\n\t\t\t} else {\n\t\t\t\tname = databaseType.downCaseString(clazz.getSimpleName(), true);\n\t\t\t}\n\t\t}\n\t\treturn name;\n\t}",
"public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }",
"protected void addNeighbor(Queue<ColorPoint> queue, int px, int py, int color, Feature component) {\n if (!inBoundary(px, py, component)) {\n return;\n }\n\n if (!mask.isTouched(px, py)) {\n queue.add(new ColorPoint(px, py, color));\n }\n }",
"public void addFkToItemClass(String column)\r\n {\r\n if (fksToItemClass == null)\r\n {\r\n fksToItemClass = new Vector();\r\n }\r\n fksToItemClass.add(column);\r\n fksToItemClassAry = null;\r\n }"
] |
Sets the publish queue shutdown time.
@param publishQueueShutdowntime the shutdown time to set, parsed as <code>int</code> | [
"public void setPublishQueueShutdowntime(String publishQueueShutdowntime) {\n\n if (m_frozen) {\n throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0));\n }\n m_publishQueueShutdowntime = Integer.parseInt(publishQueueShutdowntime);\n }"
] | [
"private void initExceptionsPanel() {\n\n m_exceptionsPanel.setLegend(Messages.get().key(Messages.GUI_SERIALDATE_PANEL_EXCEPTIONS_0));\n m_exceptionsPanel.addCloseHandler(this);\n m_exceptionsPanel.setVisible(false);\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 ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }",
"private void emitSuiteStart(Description description, long startTimestamp) throws IOException {\n String suiteName = description.getDisplayName();\n if (useSimpleNames) {\n if (suiteName.lastIndexOf('.') >= 0) {\n suiteName = suiteName.substring(suiteName.lastIndexOf('.') + 1);\n }\n }\n logShort(shortTimestamp(startTimestamp) +\n \"Suite: \" +\n FormattingUtils.padTo(maxClassNameColumns, suiteName, \"[...]\"));\n }",
"@Override\n\tprotected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\t// nothing to do\n\t}",
"public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static aaauser_vpntrafficpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_vpntrafficpolicy_binding obj = new aaauser_vpntrafficpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_vpntrafficpolicy_binding response[] = (aaauser_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception {\n Integer overrideId = -1;\n\n try {\n // there is an issue with parseInt where it does not parse negative values correctly\n boolean isNegative = false;\n if (overrideIdentifier.startsWith(\"-\")) {\n isNegative = true;\n overrideIdentifier = overrideIdentifier.substring(1);\n }\n overrideId = Integer.parseInt(overrideIdentifier);\n\n if (isNegative) {\n overrideId = 0 - overrideId;\n }\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n\n // split into two parts\n String className = null;\n String methodName = null;\n int lastDot = overrideIdentifier.lastIndexOf(\".\");\n className = overrideIdentifier.substring(0, lastDot);\n methodName = overrideIdentifier.substring(lastDot + 1);\n\n overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName);\n }\n\n return overrideId;\n }",
"public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {\n\t\tinit(t1, t2);\n\t\tSTR = new int[size1][size2];\n\t\tcomputeOptimalStrategy();\n\t\treturn computeDistUsingStrArray(it1, it2);\n\t}"
] |
Add calendars to the tree.
@param parentNode parent tree node
@param file calendar container | [
"private void addCalendars(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ProjectCalendar calendar : file.getCalendars())\n {\n addCalendar(parentNode, calendar);\n }\n }"
] | [
"@PostConstruct\n\tprotected void buildCopyrightMap() {\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\t\t// go over all plug-ins, adding copyright info, avoiding duplicates (on object key)\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tfor (CopyrightInfo copyright : plugin.getCopyrightInfo()) {\n\t\t\t\tString key = copyright.getKey();\n\t\t\t\tString msg = copyright.getKey() + \": \" + copyright.getCopyright() + \" : licensed as \" +\n\t\t\t\t\t\tcopyright.getLicenseName() + \", see \" + copyright.getLicenseUrl();\n\t\t\t\tif (null != copyright.getSourceUrl()) {\n\t\t\t\t\tmsg += \" source \" + copyright.getSourceUrl();\n\t\t\t\t}\n\t\t\t\tif (!copyrightMap.containsKey(key)) {\n\t\t\t\t\tlog.info(msg);\n\t\t\t\t\tcopyrightMap.put(key, copyright);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static double computeTauAndDivide(final int j, final int numRows ,\n final double[] u , final double max) {\n double tau = 0;\n// double div_max = 1.0/max;\n// if( Double.isInfinite(div_max)) {\n for( int i = j; i < numRows; i++ ) {\n double d = u[i] /= max;\n tau += d*d;\n }\n// } else {\n// for( int i = j; i < numRows; i++ ) {\n// double d = u[i] *= div_max;\n// tau += d*d;\n// }\n// }\n tau = Math.sqrt(tau);\n\n if( u[j] < 0 )\n tau = -tau;\n\n return tau;\n }",
"public void createNewFile() throws SmbException {\n if( getUncPath0().length() == 1 ) {\n throw new SmbException( \"Invalid operation for workgroups, servers, or shares\" );\n }\n close( open0( O_RDWR | O_CREAT | O_EXCL, 0, ATTR_NORMAL, 0 ), 0L );\n }",
"public static double computeTauAndDivide(final int j, final int numRows ,\n final double[] u , final double max) {\n double tau = 0;\n// double div_max = 1.0/max;\n// if( Double.isInfinite(div_max)) {\n for( int i = j; i < numRows; i++ ) {\n double d = u[i] /= max;\n tau += d*d;\n }\n// } else {\n// for( int i = j; i < numRows; i++ ) {\n// double d = u[i] *= div_max;\n// tau += d*d;\n// }\n// }\n tau = Math.sqrt(tau);\n\n if( u[j] < 0 )\n tau = -tau;\n\n return tau;\n }",
"public void useNewRESTServiceWithOldClient() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/new-rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n \n // The outgoing old Customer data needs to be transformed for \n // the new service to understand it and the response from the new service\n // needs to be transformed for this old client to understand it.\n ClientConfiguration config = WebClient.getConfig(customerService);\n addTransformInterceptors(config.getInInterceptors(),\n config.getOutInterceptors(),\n false);\n \n \n System.out.println(\"Using new RESTful CustomerService with old Client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old to New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old to New REST\");\n printOldCustomerDetails(customer);\n }",
"private Field getFieldRecursive(Class c, String name) throws NoSuchFieldException\r\n {\r\n try\r\n {\r\n return c.getDeclaredField(name);\r\n }\r\n catch (NoSuchFieldException e)\r\n {\r\n // if field could not be found in the inheritance hierarchy, signal error\r\n if ((c == Object.class) || (c.getSuperclass() == null) || c.isInterface())\r\n {\r\n throw e;\r\n }\r\n // if field could not be found in class c try in superclass\r\n else\r\n {\r\n return getFieldRecursive(c.getSuperclass(), name);\r\n }\r\n }\r\n }",
"public double[][] getPositionsAsArray(){\n\t\tdouble[][] posAsArr = new double[size()][3];\n\t\tfor(int i = 0; i < size(); i++){\n\t\t\tif(get(i)!=null){\n\t\t\t\tposAsArr[i][0] = get(i).x;\n\t\t\t\tposAsArr[i][1] = get(i).y;\n\t\t\t\tposAsArr[i][2] = get(i).z;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tposAsArr[i] = null;\n\t\t\t}\n\t\t}\n\t\treturn posAsArr;\n\t}",
"public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }",
"public static appfwpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_stats response = (appfwpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Parses chroot section of Zookeeper connection string
@param zookeepers Zookeeper connection string
@return Returns root path or "/" if none found | [
"public static String parseRoot(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(slashIndex).trim();\n }\n return \"/\";\n }"
] | [
"protected Path createTempDirectory(String prefix) {\n try {\n return Files.createTempDirectory(tempDirectory, prefix);\n } catch (IOException e) {\n throw new AllureCommandException(e);\n }\n }",
"public List<DbMigration> getMigrationsSinceVersion(int version) {\n List<DbMigration> dbMigrations = new ArrayList<>();\n migrationScripts.stream().filter(script -> script.getVersion() > version).forEach(script -> {\n String content = loadScriptContent(script);\n dbMigrations.add(new DbMigration(script.getScriptName(), script.getVersion(), content));\n });\n return dbMigrations;\n }",
"private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,\r\n\t\t\tDayCountConvention daycountConvention) {\r\n\r\n\t\tboolean isFixed = leg.getElementsByTagName(\"interestType\").item(0).getTextContent().equalsIgnoreCase(\"FIX\");\r\n\r\n\t\tArrayList<Period> periods \t\t= new ArrayList<>();\r\n\t\tArrayList<Double> notionalsList\t= new ArrayList<>();\r\n\t\tArrayList<Double> rates\t\t\t= new ArrayList<>();\r\n\r\n\t\t//extracting data for each period\r\n\t\tNodeList periodsXML = leg.getElementsByTagName(\"incomePayment\");\r\n\t\tfor(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {\r\n\r\n\t\t\tElement periodXML = (Element) periodsXML.item(periodIndex);\r\n\r\n\t\t\tLocalDate startDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"startDate\").item(0).getTextContent());\r\n\t\t\tLocalDate endDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"endDate\").item(0).getTextContent());\r\n\r\n\t\t\tLocalDate fixingDate\t= startDate;\r\n\t\t\tLocalDate paymentDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"payDate\").item(0).getTextContent());\r\n\r\n\t\t\tif(! isFixed) {\r\n\t\t\t\tfixingDate = LocalDate.parse(periodXML.getElementsByTagName(\"fixingDate\").item(0).getTextContent());\r\n\t\t\t}\r\n\r\n\t\t\tperiods.add(new Period(fixingDate, paymentDate, startDate, endDate));\r\n\r\n\t\t\tdouble notional\t\t= Double.parseDouble(periodXML.getElementsByTagName(\"nominal\").item(0).getTextContent());\r\n\t\t\tnotionalsList.add(new Double(notional));\r\n\r\n\t\t\tif(isFixed) {\r\n\t\t\t\tdouble fixedRate\t= Double.parseDouble(periodXML.getElementsByTagName(\"fixedRate\").item(0).getTextContent());\r\n\t\t\t\trates.add(new Double(fixedRate));\r\n\t\t\t} else {\r\n\t\t\t\trates.add(new Double(0));\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);\r\n\t\tdouble[] notionals\t= notionalsList.stream().mapToDouble(Double::doubleValue).toArray();\r\n\t\tdouble[] spreads\t= rates.stream().mapToDouble(Double::doubleValue).toArray();\r\n\r\n\t\treturn new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);\r\n\t}",
"synchronized boolean reload(int permit, boolean suspend) {\n return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);\n }",
"public static void shutdownStandalone(final ModelControllerClient client, final int timeout) throws IOException {\n final ModelNode op = Operations.createOperation(\"shutdown\");\n op.get(\"timeout\").set(timeout);\n final ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n while (true) {\n if (isStandaloneRunning(client)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(op, response);\n }\n }",
"public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}",
"public final B accessToken(String accessToken) {\n requireNonNull(accessToken, \"accessToken\");\n checkArgument(!accessToken.isEmpty(), \"accessToken is empty.\");\n this.accessToken = accessToken;\n return self();\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 float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }"
] |
a useless object at the top level of the response JSON for no reason at all. | [
"private List<EnrollmentTerm> parseEnrollmentTermList(final List<Response> responses) {\n return responses.stream().\n map(this::parseEnrollmentTermList).\n flatMap(Collection::stream).\n collect(Collectors.toList());\n }"
] | [
"public static aaagroup_aaauser_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_aaauser_binding obj = new aaagroup_aaauser_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_aaauser_binding response[] = (aaagroup_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static void attachToContent(Activity activity, MenuDrawer menuDrawer) {\n /**\n * Do not call mActivity#setContentView.\n * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to\n * MenuDrawer#setContentView, which then again would call Activity#setContentView.\n */\n ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);\n content.removeAllViews();\n content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }",
"private void disableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(false);\n\n }\n }",
"public static nsspparams get(nitro_service service) throws Exception{\n\t\tnsspparams obj = new nsspparams();\n\t\tnsspparams[] response = (nsspparams[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"protected NodeData createRectangleStyle(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformLength((float) getGraphicsState().getLineWidth());\n float lw = (lineWidth < 1f) ? 1f : lineWidth;\n float wcor = stroke ? lw : 0.0f;\n \n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"absolute\")));\n ret.push(createDeclaration(\"left\", tf.createLength(x, unit)));\n ret.push(createDeclaration(\"top\", tf.createLength(y, unit)));\n ret.push(createDeclaration(\"width\", tf.createLength(width - wcor, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(height - wcor, unit)));\n \n if (stroke)\n {\n ret.push(createDeclaration(\"border-width\", tf.createLength(lw, unit)));\n ret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n String color = colorString(getGraphicsState().getStrokingColor());\n ret.push(createDeclaration(\"border-color\", tf.createColor(color)));\n }\n \n if (fill)\n {\n String color = colorString(getGraphicsState().getNonStrokingColor());\n if (color != null)\n ret.push(createDeclaration(\"background-color\", tf.createColor(color)));\n }\n\n return ret;\n }",
"public DynamicReportBuilder setProperty(String name, String value) {\n this.report.setProperty(name, value);\n return this;\n }",
"public static base_response add(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction addresource = new vpnsessionaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.httpport = resource.httpport;\n\t\taddresource.winsip = resource.winsip;\n\t\taddresource.dnsvservername = resource.dnsvservername;\n\t\taddresource.splitdns = resource.splitdns;\n\t\taddresource.sesstimeout = resource.sesstimeout;\n\t\taddresource.clientsecurity = resource.clientsecurity;\n\t\taddresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\taddresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\taddresource.clientsecuritylog = resource.clientsecuritylog;\n\t\taddresource.splittunnel = resource.splittunnel;\n\t\taddresource.locallanaccess = resource.locallanaccess;\n\t\taddresource.rfc1918 = resource.rfc1918;\n\t\taddresource.spoofiip = resource.spoofiip;\n\t\taddresource.killconnections = resource.killconnections;\n\t\taddresource.transparentinterception = resource.transparentinterception;\n\t\taddresource.windowsclienttype = resource.windowsclienttype;\n\t\taddresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\taddresource.authorizationgroup = resource.authorizationgroup;\n\t\taddresource.clientidletimeout = resource.clientidletimeout;\n\t\taddresource.proxy = resource.proxy;\n\t\taddresource.allprotocolproxy = resource.allprotocolproxy;\n\t\taddresource.httpproxy = resource.httpproxy;\n\t\taddresource.ftpproxy = resource.ftpproxy;\n\t\taddresource.socksproxy = resource.socksproxy;\n\t\taddresource.gopherproxy = resource.gopherproxy;\n\t\taddresource.sslproxy = resource.sslproxy;\n\t\taddresource.proxyexception = resource.proxyexception;\n\t\taddresource.proxylocalbypass = resource.proxylocalbypass;\n\t\taddresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\taddresource.forcecleanup = resource.forcecleanup;\n\t\taddresource.clientoptions = resource.clientoptions;\n\t\taddresource.clientconfiguration = resource.clientconfiguration;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.ssocredential = resource.ssocredential;\n\t\taddresource.windowsautologon = resource.windowsautologon;\n\t\taddresource.usemip = resource.usemip;\n\t\taddresource.useiip = resource.useiip;\n\t\taddresource.clientdebug = resource.clientdebug;\n\t\taddresource.loginscript = resource.loginscript;\n\t\taddresource.logoutscript = resource.logoutscript;\n\t\taddresource.homepage = resource.homepage;\n\t\taddresource.icaproxy = resource.icaproxy;\n\t\taddresource.wihome = resource.wihome;\n\t\taddresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\taddresource.wiportalmode = resource.wiportalmode;\n\t\taddresource.clientchoices = resource.clientchoices;\n\t\taddresource.epaclienttype = resource.epaclienttype;\n\t\taddresource.iipdnssuffix = resource.iipdnssuffix;\n\t\taddresource.forcedtimeout = resource.forcedtimeout;\n\t\taddresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\taddresource.ntdomain = resource.ntdomain;\n\t\taddresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\taddresource.emailhome = resource.emailhome;\n\t\taddresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\taddresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\taddresource.allowedlogingroups = resource.allowedlogingroups;\n\t\taddresource.securebrowse = resource.securebrowse;\n\t\taddresource.storefronturl = resource.storefronturl;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\treturn addresource.add_resource(client);\n\t}",
"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 JSONObject toJson() throws JSONException {\n\n JSONObject result = new JSONObject();\n if (m_detailId != null) {\n result.put(JSON_DETAIL, \"\" + m_detailId);\n }\n if (m_siteRoot != null) {\n result.put(JSON_SITEROOT, m_siteRoot);\n }\n if (m_structureId != null) {\n result.put(JSON_STRUCTUREID, \"\" + m_structureId);\n }\n if (m_projectId != null) {\n result.put(JSON_PROJECT, \"\" + m_projectId);\n }\n if (m_type != null) {\n result.put(JSON_TYPE, \"\" + m_type.getJsonId());\n }\n return result;\n }"
] |
Entry point for recursive resolution of an expression and all of its
nested expressions.
@todo Ensure unresolvable expressions don't trigger infinite recursion. | [
"public String interpolate( String input, RecursionInterceptor recursionInterceptor )\n\t throws InterpolationException\n\t {\n\t try\n\t {\n\t return interpolate( input, recursionInterceptor, new HashSet<String>() );\n\t }\n\t finally\n\t {\n\t if ( !cacheAnswers )\n\t {\n\t existingAnswers.clear();\n\t }\n\t }\n\t }"
] | [
"public static String readTextFile(File file) {\n try {\n return readTextFile(new FileReader(file));\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }",
"@Override\n public PaxDate date(int prolepticYear, int month, int dayOfMonth) {\n return PaxDate.of(prolepticYear, month, dayOfMonth);\n }",
"public ProjectCalendar addDefaultBaseCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n calendar.setWorkingDay(Day.SUNDAY, false);\n calendar.setWorkingDay(Day.MONDAY, true);\n calendar.setWorkingDay(Day.TUESDAY, true);\n calendar.setWorkingDay(Day.WEDNESDAY, true);\n calendar.setWorkingDay(Day.THURSDAY, true);\n calendar.setWorkingDay(Day.FRIDAY, true);\n calendar.setWorkingDay(Day.SATURDAY, false);\n\n calendar.addDefaultCalendarHours();\n\n return (calendar);\n }",
"public static String load(LoadConfiguration config, String prefix) {\n\t\tif (config.getMode() == Mode.INSERT) {\n\t\t\treturn loadInsert(config, prefix);\n\t\t}\n\t\telse if (config.getMode() == Mode.UPDATE) {\n\t\t\treturn loadUpdate(config, prefix);\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unsupported mode \" + config.getMode());\n\t}",
"public void editMeta(String photosetId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_META);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"title\", title);\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }",
"protected void handleExceptions(MessageEvent messageEvent, Exception exception) {\n logger.error(\"Unknown exception. Internal Server Error.\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Internal Server Error\");\n }",
"public com.cloudant.client.api.model.ReplicationResult trigger() {\r\n ReplicationResult couchDbReplicationResult = replication.trigger();\r\n com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant\r\n .client.api.model.ReplicationResult(couchDbReplicationResult);\r\n return replicationResult;\r\n }",
"private void removeTimedOutLocks(long timeout)\r\n {\r\n int count = 0;\r\n long maxAge = System.currentTimeMillis() - timeout;\r\n boolean breakFromLoop = false;\r\n ObjectLocks temp = null;\r\n \tsynchronized (locktable)\r\n \t{\r\n\t Iterator it = locktable.values().iterator();\r\n\t /**\r\n\t * run this loop while:\r\n\t * - we have more in the iterator\r\n\t * - the breakFromLoop flag hasn't been set\r\n\t * - we haven't removed more than the limit for this cleaning iteration.\r\n\t */\r\n\t while (it.hasNext() && !breakFromLoop && (count <= MAX_LOCKS_TO_CLEAN))\r\n\t {\r\n\t \ttemp = (ObjectLocks) it.next();\r\n\t \tif (temp.getWriter() != null)\r\n\t \t{\r\n\t\t \tif (temp.getWriter().getTimestamp() < maxAge)\r\n\t\t \t{\r\n\t\t \t\t// writer has timed out, set it to null\r\n\t\t \t\ttemp.setWriter(null);\r\n\t\t \t}\r\n\t \t}\r\n\t \tif (temp.getYoungestReader() < maxAge)\r\n\t \t{\r\n\t \t\t// all readers are older than timeout.\r\n\t \t\ttemp.getReaders().clear();\r\n\t \t\tif (temp.getWriter() == null)\r\n\t \t\t{\r\n\t \t\t\t// all readers and writer are older than timeout,\r\n\t \t\t\t// remove the objectLock from the iterator (which\r\n\t \t\t\t// is backed by the map, so it will be removed.\r\n\t \t\t\tit.remove();\r\n\t \t\t}\r\n\t \t}\r\n\t \telse\r\n\t \t{\r\n\t \t\t// we need to walk each reader.\r\n\t \t\tIterator readerIt = temp.getReaders().values().iterator();\r\n\t \t\tLockEntry readerLock = null;\r\n\t \t\twhile (readerIt.hasNext())\r\n\t \t\t{\r\n\t \t\t\treaderLock = (LockEntry) readerIt.next();\r\n\t \t\t\tif (readerLock.getTimestamp() < maxAge)\r\n\t \t\t\t{\r\n\t \t\t\t\t// this read lock is old, remove it.\r\n\t \t\t\t\treaderIt.remove();\r\n\t \t\t\t}\r\n\t \t\t}\r\n\t \t}\r\n\t \tcount++;\r\n\t }\r\n \t}\r\n }"
] |
Combines adjacent blocks of the same type. | [
"private static void mergeBlocks(List< Block > blocks) {\r\n for (int i = 1; i < blocks.size(); i++) {\r\n Block b1 = blocks.get(i - 1);\r\n Block b2 = blocks.get(i);\r\n if ((b1.mode == b2.mode) &&\r\n (b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n b1.length += b2.length;\r\n blocks.remove(i);\r\n i--;\r\n }\r\n }\r\n }"
] | [
"private void notifyIfStopped() {\n if (isAcceptingNewJobs() || !this.runningTasksFutures.isEmpty()) {\n return;\n }\n final File stoppedFile = new File(this.workingDirectories.getWorking(), \"stopped\");\n try {\n LOGGER.info(\"The print has finished processing jobs and can now stop\");\n stoppedFile.createNewFile();\n } catch (IOException e) {\n LOGGER.warn(\"Cannot create the {} file\", stoppedFile, e);\n }\n }",
"public static I_CmsMacroResolver newWorkplaceLocaleResolver(final CmsObject cms) {\n\n // Resolve macros in the property configuration\n CmsMacroResolver resolver = new CmsMacroResolver();\n resolver.setCmsObject(cms);\n CmsUserSettings userSettings = new CmsUserSettings(cms.getRequestContext().getCurrentUser());\n CmsMultiMessages multimessages = new CmsMultiMessages(userSettings.getLocale());\n multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(userSettings.getLocale()));\n resolver.setMessages(multimessages);\n resolver.setKeepEmptyMacros(true);\n\n return resolver;\n }",
"private void getMonthlyRelativeDates(Calendar calendar, int frequency, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }",
"public Axis getOrientationAxis() {\n final Axis axis;\n switch(getOrientation()) {\n case HORIZONTAL:\n axis = Axis.X;\n break;\n case VERTICAL:\n axis = Axis.Y;\n break;\n case STACK:\n axis = Axis.Z;\n break;\n default:\n Log.w(TAG, \"Unsupported orientation %s\", mOrientation);\n axis = Axis.X;\n break;\n }\n return axis;\n }",
"public void forAllIndexDescriptorDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getIndexDescriptors(); it.hasNext(); )\r\n {\r\n _curIndexDescriptorDef = (IndexDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curIndexDescriptorDef = null;\r\n }",
"public static ComplexNumber Add(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real + scalar, z1.imaginary);\r\n }",
"private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds)\r\n {\r\n Query fkQuery;\r\n QueryByCriteria fkQueryCrit;\r\n\r\n if (cds.isMtoNRelation())\r\n {\r\n fkQueryCrit = getFKQueryMtoN(obj, cld, cds);\r\n }\r\n else\r\n {\r\n fkQueryCrit = getFKQuery1toN(obj, cld, cds);\r\n }\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n fkQueryCrit.addOrderBy((FieldHelper)iter.next());\r\n }\r\n }\r\n\r\n // BRJ: customize the query\r\n if (cds.getQueryCustomizer() != null)\r\n {\r\n fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit);\r\n }\r\n else\r\n {\r\n fkQuery = fkQueryCrit;\r\n }\r\n\r\n return fkQuery;\r\n }",
"protected void setProperty(String propertyName, JavascriptObject propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getJSObject());\n }",
"@SuppressWarnings(\"unchecked\")\n\tprivate void addParameters(Model model, HttpServletRequest request) {\n\t\tfor (Object objectEntry : request.getParameterMap().entrySet()) {\n\t\t\tMap.Entry<String, String[]> entry = (Map.Entry<String, String[]>) objectEntry;\n\t\t\tString key = entry.getKey();\n\t\t\tString[] values = entry.getValue();\n\t\t\tif (null != values && values.length > 0) {\n\t\t\t\tString value = values[0];\n\t\t\t\ttry {\n\t\t\t\t\tmodel.addAttribute(key, getParameter(key, value));\n\t\t\t\t} catch (ParseException pe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t} catch (NumberFormatException nfe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] |
Waits for the current outstanding request retrying it with exponential backoff if it fails.
@throws ClosedByInterruptException if request was interrupted
@throws IOException In the event of FileNotFoundException, MalformedURLException
@throws RetriesExhaustedException if exceeding the number of retries | [
"private void waitForOutstandingRequest() throws IOException {\n if (outstandingRequest == null) {\n return;\n }\n try {\n RetryHelper.runWithRetries(new Callable<Void>() {\n @Override\n public Void call() throws IOException, InterruptedException {\n if (RetryHelper.getContext().getAttemptNumber() > 1) {\n outstandingRequest.retry();\n }\n token = outstandingRequest.waitForNextToken();\n outstandingRequest = null;\n return null;\n }\n }, retryParams, GcsServiceImpl.exceptionHandler);\n } catch (RetryInterruptedException ex) {\n token = null;\n throw new ClosedByInterruptException();\n } catch (NonRetriableException e) {\n Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);\n throw e;\n }\n }"
] | [
"public ModelNode translateOperationForProxy(final ModelNode op) {\n return translateOperationForProxy(op, PathAddress.pathAddress(op.get(OP_ADDR)));\n }",
"okhttp3.Response delete(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(getFullUrl(url))\n .delete(getBody(toPayload(params), null))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }",
"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 ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }",
"public ListenableFuture<Connection> getAsyncConnection(){\r\n\r\n\t\treturn this.asyncExecutor.submit(new Callable<Connection>() {\r\n\r\n\t\t\tpublic Connection call() throws Exception {\r\n\t\t\t\treturn getConnection();\r\n\t\t\t}});\r\n\t}",
"public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }",
"private int getReplicaTypeForPartition(int partitionId) {\n List<Integer> routingPartitionList = routingStrategy.getReplicatingPartitionList(partitionId);\n\n // Determine if we should host this partition, and if so, whether we are a primary,\n // secondary or n-ary replica for it\n int correctReplicaType = -1;\n for (int replica = 0; replica < routingPartitionList.size(); replica++) {\n if(nodePartitionIds.contains(routingPartitionList.get(replica))) {\n // This means the partitionId currently being iterated on should be hosted\n // by this node. Let's remember its replica type in order to make sure the\n // files we have are properly named.\n correctReplicaType = replica;\n break;\n }\n }\n\n return correctReplicaType;\n }",
"private Client getClientFromResultSet(ResultSet result) throws Exception {\n Client client = new Client();\n client.setId(result.getInt(Constants.GENERIC_ID));\n client.setUUID(result.getString(Constants.CLIENT_CLIENT_UUID));\n client.setFriendlyName(result.getString(Constants.CLIENT_FRIENDLY_NAME));\n client.setProfile(ProfileService.getInstance().findProfile(result.getInt(Constants.GENERIC_PROFILE_ID)));\n client.setIsActive(result.getBoolean(Constants.CLIENT_IS_ACTIVE));\n client.setActiveServerGroup(result.getInt(Constants.CLIENT_ACTIVESERVERGROUP));\n return client;\n }",
"@JmxGetter(name = \"avgFetchEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgFetchEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }"
] |
Get the current attribute type.
@param key the entry's key, not null
@return the current attribute type, or null, if no such attribute exists. | [
"public Class<?> getType(String key) {\n Object val = this.data.get(key);\n return val == null ? null : val.getClass();\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 Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\n }",
"public void updateProvider(final String gavc, final String provider) {\n final DbArtifact artifact = getArtifact(gavc);\n repositoryHandler.updateProvider(artifact, provider);\n }",
"protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException {\n Class c = this.findLoadedClass(name);\n if (c != null) return c;\n c = (Class) customClasses.get(name);\n if (c != null) return c;\n\n try {\n c = oldFindClass(name);\n } catch (ClassNotFoundException cnfe) {\n // IGNORE\n }\n if (c == null) c = super.loadClass(name, resolve);\n\n if (resolve) resolveClass(c);\n\n return c;\n }",
"public static base_response clear(nitro_service client, route6 resource) throws Exception {\n\t\troute6 clearresource = new route6();\n\t\tclearresource.routetype = resource.routetype;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"private Date readOptionalDate(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return new Date(Long.parseLong(str.stringValue()));\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // do nothing - return the default value\n }\n }\n return null;\n }",
"public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }",
"public DateTimeZone getZone(String id) {\n if (id == null) {\n return null;\n }\n\n Object obj = iZoneInfoMap.get(id);\n if (obj == null) {\n return null;\n }\n\n if (id.equals(obj)) {\n // Load zone data for the first time.\n return loadZoneData(id);\n }\n\n if (obj instanceof SoftReference<?>) {\n @SuppressWarnings(\"unchecked\")\n SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;\n DateTimeZone tz = ref.get();\n if (tz != null) {\n return tz;\n }\n // Reference cleared; load data again.\n return loadZoneData(id);\n }\n\n // If this point is reached, mapping must link to another.\n return getZone((String) obj);\n }",
"public void findMatch(ArrayList<String> speechResult) {\n\n loadCadidateString();\n\n for (String matchCandidate : speechResult) {\n\n Locale localeDefault = mGvrContext.getActivity().getResources().getConfiguration().locale;\n if (volumeUp.equals(matchCandidate)) {\n startVolumeUp();\n break;\n } else if (volumeDown.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startVolumeDown();\n break;\n } else if (zoomIn.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startZoomIn();\n break;\n } else if (zoomOut.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startZoomOut();\n break;\n } else if (invertedColors.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n startInvertedColors();\n break;\n } else if (talkBack.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n enableTalkBack();\n } else if (disableTalkBack.toLowerCase(localeDefault).equals(matchCandidate.toLowerCase(localeDefault))) {\n disableTalkBack();\n }\n }\n }"
] |
Given a Task instance, this task determines if it should be written to the
PM XML file as an activity or as a WBS item, and calls the appropriate
method.
@param task Task instance | [
"private void writeTask(Task task)\n {\n if (!task.getNull())\n {\n if (extractAndConvertTaskType(task) == null || task.getSummary())\n {\n writeWBS(task);\n }\n else\n {\n writeActivity(task);\n }\n }\n }"
] | [
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }",
"private List<CmsResource> getDetailContainerResources(CmsObject cms, CmsResource res) throws CmsException {\n\n CmsRelationFilter filter = CmsRelationFilter.relationsFromStructureId(res.getStructureId()).filterType(\n CmsRelationType.DETAIL_ONLY);\n List<CmsResource> result = Lists.newArrayList();\n List<CmsRelation> relations = cms.readRelations(filter);\n for (CmsRelation relation : relations) {\n try {\n result.add(relation.getTarget(cms, CmsResourceFilter.ALL));\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return result;\n }",
"public void set1Value(int index, String newValue) {\n try {\n value.set( index, newValue );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) exception \" + e);\n }\n }",
"protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{\r\n\t\t// fetch any configured setup sql.\r\n\t\tif (initSQL != null){\r\n\t\t\tStatement stmt = null;\r\n\t\t\ttry{\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(initSQL);\r\n\t\t\t\tif (testSupport){ // only to aid code coverage, normally set to false\r\n\t\t\t\t\tstmt = null;\r\n\t\t\t\t}\r\n\t\t\t} finally{\r\n\t\t\t\tif (stmt != null){\r\n\t\t\t\t\tstmt.close();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\n }",
"private void cleanUpAction() {\n\n try {\n m_model.deleteDescriptorIfNecessary();\n } catch (CmsException e) {\n LOG.error(m_messages.key(Messages.ERR_DELETING_DESCRIPTOR_0), e);\n }\n // unlock resource\n m_model.unlock();\n }",
"protected void addLoadError(PdfContext context, ImageException e) {\n\t\tBbox imageBounds = e.getRasterImage().getBounds();\n\t\tfloat scaleFactor = (float) (72 / getMap().getRasterResolution());\n\t\tfloat width = (float) imageBounds.getWidth() * scaleFactor;\n\t\tfloat height = (float) imageBounds.getHeight() * scaleFactor;\n\t\t// subtract screen position of lower-left corner\n\t\tfloat x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;\n\t\t// shift y to lower left corner, flip y to user space and subtract\n\t\t// screen position of lower-left\n\t\t// corner\n\t\tfloat y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;\n\t\tif (log.isDebugEnabled()) {\n\t\t\tlog.debug(\"adding failed message=\" + width + \",height=\" + height + \",x=\" + x + \",y=\" + y);\n\t\t}\n\t\tfloat textHeight = context.getTextSize(\"failed\", ERROR_FONT).getHeight() * 3f;\n\t\tRectangle rec = new Rectangle(x, y, x + width, y + height);\n\t\tcontext.strokeRectangle(rec, Color.RED, 0.5f);\n\t\tcontext.drawText(getNlsString(\"RasterLayerComponent.loaderror.line1\"), ERROR_FONT, new Rectangle(x, y\n\t\t\t\t+ textHeight, x + width, y + height), Color.RED);\n\t\tcontext.drawText(getNlsString(\"RasterLayerComponent.loaderror.line2\"), ERROR_FONT, rec, Color.RED);\n\t\tcontext.drawText(getNlsString(\"RasterLayerComponent.loaderror.line3\"), ERROR_FONT, new Rectangle(x, y\n\t\t\t\t- textHeight, x + width, y + height), Color.RED);\n\t}",
"void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }"
] |
Sets left and right padding for all cells in the table.
@param padding new padding for left and right, ignored if smaller than 0
@return this to allow chaining | [
"public AsciiTable setPaddingLeftRight(int padding){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] | [
"public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}",
"private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateImagePath = DockerUtils.getImagePath(imageTag);\n String manifestPath;\n\n // Try to get manifest, assuming reverse proxy\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Try to get manifest, assuming proxy-less\n candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf(\"/\") + 1);\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Couldn't find correct manifest\n listener.getLogger().println(\"Could not find corresponding manifest.json file in Artifactory.\");\n return false;\n }",
"public static void updatePathTable(String columnName, Object newData, int path_id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + columnName + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setObject(1, newData);\n statement.setInt(2, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}",
"private JSONArray getApplicablePathNames (String requestUrl, Integer requestType) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n List<EndpointOverride> applicablePaths;\n JSONArray pathNames = new JSONArray();\n // Get all paths that match the request\n applicablePaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, requestInfo.client,\n requestInfo.profile,\n requestUrl + \"?\" + requestInfo.originalRequestInfo.getQueryString(),\n requestType, true);\n // Extract just the path name from each path\n for (EndpointOverride path : applicablePaths) {\n JSONObject pathName = new JSONObject();\n pathName.put(\"name\", path.getPathName());\n pathNames.put(pathName);\n }\n\n return pathNames;\n }",
"protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }",
"private File makeDestFile(URL src) {\n if (dest == null) {\n throw new IllegalArgumentException(\"Please provide a download destination\");\n }\n\n File destFile = dest;\n if (destFile.isDirectory()) {\n //guess name from URL\n String name = src.toString();\n if (name.endsWith(\"/\")) {\n name = name.substring(0, name.length() - 1);\n }\n name = name.substring(name.lastIndexOf('/') + 1);\n destFile = new File(dest, name);\n } else {\n //create destination directory\n File parent = destFile.getParentFile();\n if (parent != null) {\n parent.mkdirs();\n }\n }\n return destFile;\n }",
"public List<Ticket> checkTickets(Set<String> tickets) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CHECK_TICKETS);\r\n\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = tickets.iterator();\r\n while (it.hasNext()) {\r\n if (sb.length() > 0) {\r\n sb.append(\",\");\r\n }\r\n Object obj = it.next();\r\n if (obj instanceof Ticket) {\r\n sb.append(((Ticket) obj).getTicketId());\r\n } else {\r\n sb.append(obj);\r\n }\r\n }\r\n parameters.put(\"tickets\", sb.toString());\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n // <uploader>\r\n // <ticket id=\"128\" complete=\"1\" photoid=\"2995\" />\r\n // <ticket id=\"129\" complete=\"0\" />\r\n // <ticket id=\"130\" complete=\"2\" />\r\n // <ticket id=\"131\" invalid=\"1\" />\r\n // </uploader>\r\n\r\n List<Ticket> list = new ArrayList<Ticket>();\r\n Element uploaderElement = response.getPayload();\r\n NodeList ticketNodes = uploaderElement.getElementsByTagName(\"ticket\");\r\n int n = ticketNodes.getLength();\r\n for (int i = 0; i < n; i++) {\r\n Element ticketElement = (Element) ticketNodes.item(i);\r\n String id = ticketElement.getAttribute(\"id\");\r\n String complete = ticketElement.getAttribute(\"complete\");\r\n boolean invalid = \"1\".equals(ticketElement.getAttribute(\"invalid\"));\r\n String photoId = ticketElement.getAttribute(\"photoid\");\r\n Ticket info = new Ticket();\r\n info.setTicketId(id);\r\n info.setInvalid(invalid);\r\n info.setStatus(Integer.parseInt(complete));\r\n info.setPhotoId(photoId);\r\n list.add(info);\r\n }\r\n return list;\r\n }",
"public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,\r\n boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)\r\n throws PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);\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 }"
] |
Log the data for a single column.
@param startIndex offset into buffer
@param length length | [
"private void logColumnData(int startIndex, int length)\n {\n if (m_log != null)\n {\n m_log.println();\n m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, length, true, 16, \"\"));\n m_log.println();\n m_log.flush();\n }\n }"
] | [
"private void readExceptions(Project.Calendars.Calendar calendar, ProjectCalendar bc)\n {\n Project.Calendars.Calendar.Exceptions exceptions = calendar.getExceptions();\n if (exceptions != null)\n {\n for (Project.Calendars.Calendar.Exceptions.Exception exception : exceptions.getException())\n {\n readException(bc, exception);\n }\n }\n }",
"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 final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }",
"public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"public CoordinatorConfig setBootstrapURLs(List<String> bootstrapUrls) {\n this.bootstrapURLs = Utils.notNull(bootstrapUrls);\n if(this.bootstrapURLs.size() <= 0)\n throw new IllegalArgumentException(\"Must provide at least one bootstrap URL.\");\n return this;\n }",
"public void hideKeyboard() {\n InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0);\n }",
"public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\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 }",
"protected B fields(List<F> fields) {\n if (instance.def.fields == null) {\n instance.def.fields = new ArrayList<F>(fields.size());\n }\n instance.def.fields.addAll(fields);\n return returnThis();\n }"
] |
List the indexes in the database. The returned object allows for listing indexes by type.
@return indexes object with methods for getting indexes of a particular type | [
"public Indexes listIndexes() {\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").build();\n return client.couchDbClient.get(uri, Indexes.class);\n }"
] | [
"public static <T> void finish(T query, long correlationId, EventBus bus, String... types) {\n for (String type : types) {\n RemoveQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }",
"private static int getColumnWidth(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n if (Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) {\n return 70;\n } else if (type == Boolean.class) {\n return 10;\n } else if (Number.class.isAssignableFrom(type)) {\n return 60;\n } else if (type == String.class) {\n return 100;\n } else if (Date.class.isAssignableFrom(type)) {\n return 50;\n } else {\n return 50;\n }\n }",
"public ItemRequest<CustomField> update(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }",
"@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }",
"public static filterhtmlinjectionparameter get(nitro_service service, options option) throws Exception{\n\t\tfilterhtmlinjectionparameter obj = new filterhtmlinjectionparameter();\n\t\tfilterhtmlinjectionparameter[] response = (filterhtmlinjectionparameter[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}",
"String buildSelect(String htmlAttributes, SelectOptions options) {\n\n return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());\n }",
"boolean advance() {\n if (header.frameCount <= 0) {\n return false;\n }\n\n if(framePointer == getFrameCount() - 1) {\n loopIndex++;\n }\n\n if(header.loopCount != LOOP_FOREVER && loopIndex > header.loopCount) {\n return false;\n }\n\n framePointer = (framePointer + 1) % header.frameCount;\n return true;\n }",
"public static base_responses clear(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface clearresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new Interface();\n\t\t\t\tclearresources[i].id = resources[i].id;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute)\n\t{\n\t\t_mappedPublicKeys.put(original, substitute);\n\t\tif(persistImmediately) { persistPublicKeyMap(); }\n\t}"
] |
This method is called to alert project listeners to the fact that
a resource assignment has been read from a project file.
@param resourceAssignment resourceAssignment instance | [
"public void fireAssignmentReadEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentRead(resourceAssignment);\n }\n }\n }"
] | [
"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 }",
"@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 }",
"@NonNull\n public static File[] listAllFiles(File directory) {\n if (directory == null) {\n return new File[0];\n }\n File[] files = directory.listFiles();\n return files != null ? files : new File[0];\n }",
"public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }",
"public static Variable deserialize(String s,\n VariableType variableType) {\n return deserialize(s,\n variableType,\n null);\n }",
"public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }",
"public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}",
"protected final void verify() {\n collectInitialisers();\n verifyCandidates();\n verifyInitialisers();\n collectPossibleInitialValues();\n verifyPossibleInitialValues();\n collectEffectiveAssignmentInstructions();\n verifyEffectiveAssignmentInstructions();\n collectAssignmentGuards();\n verifyAssignmentGuards();\n end();\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 }"
] |
Unchecks 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 unchecked; {@code false} otherwise. | [
"public <T extends Widget & Checkable> boolean uncheck(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, false);\n }"
] | [
"public ParallelTaskBuilder preparePing() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.PING);\n return cb;\n }",
"public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}",
"public void setLoop(boolean doLoop, GVRContext gvrContext) {\n if (this.loop != doLoop ) {\n // a change in the loop\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n if (doLoop) gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.REPEATED);\n else gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.ONCE);\n }\n // be sure to start the animations if loop is true\n if ( doLoop ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n gvrKeyFrameAnimation.start(gvrContext.getAnimationEngine() );\n }\n }\n this.loop = doLoop;\n }\n }",
"public Class<? extends com.vividsolutions.jts.geom.Geometry> toInternal(LayerType layerType) {\n\t\tswitch (layerType) {\n\t\t\tcase GEOMETRY:\n\t\t\t\treturn com.vividsolutions.jts.geom.Geometry.class;\n\t\t\tcase LINESTRING:\n\t\t\t\treturn LineString.class;\n\t\t\tcase MULTILINESTRING:\n\t\t\t\treturn MultiLineString.class;\n\t\t\tcase POINT:\n\t\t\t\treturn Point.class;\n\t\t\tcase MULTIPOINT:\n\t\t\t\treturn MultiPoint.class;\n\t\t\tcase POLYGON:\n\t\t\t\treturn Polygon.class;\n\t\t\tcase MULTIPOLYGON:\n\t\t\t\treturn MultiPolygon.class;\n\t\t\tcase RASTER:\n\t\t\t\treturn null;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalStateException(\"Don't know how to handle layer type \" + layerType);\n\t\t}\n\t}",
"final protected void putChar(char c) {\n final int clen = _internalBuffer.length;\n if (clen == _bufferPosition) {\n final char[] next = new char[2 * clen + 1];\n\n System.arraycopy(_internalBuffer, 0, next, 0, _bufferPosition);\n _internalBuffer = next;\n }\n\n _internalBuffer[_bufferPosition++] = c;\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 }",
"private String getContentFromPath(String sourcePath,\n HostsSourceType sourceType) throws IOException {\n\n String res = \"\";\n\n if (sourceType == HostsSourceType.LOCAL_FILE) {\n res = PcFileNetworkIoUtils.readFileContentToString(sourcePath);\n } else if (sourceType == HostsSourceType.URL) {\n res = PcFileNetworkIoUtils.readStringFromUrlGeneric(sourcePath);\n }\n return res;\n\n }",
"public static boolean isLong(CharSequence self) {\n try {\n Long.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"private long getTotalUploadSize() throws IOException {\n long size = 0;\n for (Map.Entry<String, File> entry : files.entrySet()) {\n size += entry.getValue().length();\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n size += entry.getValue().available();\n }\n return size;\n }"
] |
Inspects the object and all superclasses for public, non-final, accessible methods and returns a
collection containing all the attributes found.
@param classToInspect the class under inspection. | [
"public static Collection<Field> getAllAttributes(final Class<?> classToInspect) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), field -> true);\n return allFields;\n }"
] | [
"public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {\n if( numRows == numCols )\n return linear(numRows);\n else\n return leastSquares(numRows,numCols);\n }",
"public static long count(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"public final void addRule(TableRowStyle style){\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN, \"cannot add a rule of unknown style\");\r\n\t\tthis.rows.add(AT_Row.createRule(TableRowType.RULE, style));\r\n\t}",
"public ManagementModelNode findNode(String address) {\n ManagementModelNode root = (ManagementModelNode)tree.getModel().getRoot();\n Enumeration<javax.swing.tree.TreeNode> allNodes = root.depthFirstEnumeration();\n while (allNodes.hasMoreElements()) {\n ManagementModelNode node = (ManagementModelNode)allNodes.nextElement();\n if (node.addressPath().equals(address)) return node;\n }\n\n return null;\n }",
"@Override\n public Object put(List<Map.Entry> batch) throws InterruptedException {\n if (initializeClusterSource()) {\n return clusterSource.put(batch);\n }\n return null;\n }",
"public ProducerPoolData<V> getProducerPoolData(String topic, Partition bidPid, List<V> data) {\n return new ProducerPoolData<V>(topic, bidPid, data);\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 }",
"private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }",
"protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {\n Message inMsg = exchange.getInMessage();\n\n EventProducerInterceptor epi = null;\n FlowIdHelper.setFlowId(inMsg, reqFid);\n\n ListIterator<Interceptor<? extends Message>> interceptors = inMsg\n .getInterceptorChain().getIterator();\n\n while (interceptors.hasNext() && epi == null) {\n Interceptor<? extends Message> interceptor = interceptors.next();\n\n if (interceptor instanceof EventProducerInterceptor) {\n epi = (EventProducerInterceptor) interceptor;\n epi.handleMessage(inMsg);\n }\n }\n }"
] |
Pops the top of the stack of active elements if the current position in the call stack corresponds to the one
that pushed the active elements.
<p>This method does not do any type checks, so take care to retrieve the elements with the same types used to push
to them onto the stack.
@param <T> the type of the elements
@return the active elements or null if the current call stack did not push any active elements onto the stack | [
"@Nullable\n @SuppressWarnings(\"unchecked\")\n protected <T extends JavaElement> ActiveElements<T> popIfActive() {\n return (ActiveElements<T>) (!activations.isEmpty() && activations.peek().depth == depth ? activations.pop() :\n null);\n }"
] | [
"public void editComment(String commentId, String commentText) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COMMENT);\r\n\r\n parameters.put(\"comment_id\", commentId);\r\n parameters.put(\"comment_text\", commentText);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }",
"public static void acceptsDir(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_D, OPT_DIR), \"directory path for input/output\")\n .withRequiredArg()\n .describedAs(\"dir-path\")\n .ofType(String.class);\n }",
"private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\n }",
"public void cache(String key, Object obj, int expiration) {\n H.Session session = this.session;\n if (null != session) {\n session.cache(key, obj, expiration);\n } else {\n app().cache().put(key, obj, expiration);\n }\n }",
"public void initSize(Rectangle rectangle) {\n\t\ttemplate = writer.getDirectContent().createTemplate(rectangle.getWidth(), rectangle.getHeight());\n\t}",
"public static Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {\n if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {\n throw new VoldemortException(\"Node ids are not the same [ lhs cluster node ids (\"\n + lhs.getNodeIds()\n + \") not equal to rhs cluster node ids (\"\n + rhs.getNodeIds() + \") ]\");\n }\n }",
"public void setValue(float value) {\n\t\tmBarPointerPosition = Math.round((mSVToPosFactor * (1 - value))\n\t\t\t\t+ mBarPointerHaloRadius + (mBarLength / 2));\n\t\tcalculateColor(mBarPointerPosition);\n\t\tmBarPointerPaint.setColor(mColor);\n\t\t// Check whether the Saturation/Value bar is added to the ColorPicker\n\t\t// wheel\n\t\tif (mPicker != null) {\n\t\t\tmPicker.setNewCenterColor(mColor);\n\t\t\tmPicker.changeOpacityBarColor(mColor);\n\t\t}\n\t\tinvalidate();\n\t}"
] |
Checks whether table name and key column names of the given joinable and inverse collection persister match. | [
"private static boolean isCollectionMatching(Joinable mainSideJoinable, OgmCollectionPersister inverseSidePersister) {\n\t\tboolean isSameTable = mainSideJoinable.getTableName().equals( inverseSidePersister.getTableName() );\n\n\t\tif ( !isSameTable ) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn Arrays.equals( mainSideJoinable.getKeyColumnNames(), inverseSidePersister.getElementColumnNames() );\n\t}"
] | [
"public static synchronized FormInputValueHelper getInstance(\n\t\t\tInputSpecification inputSpecification, FormFillMode formFillMode) {\n\t\tif (instance == null)\n\t\t\tinstance = new FormInputValueHelper(inputSpecification,\n\t\t\t\t\tformFillMode);\n\t\treturn instance;\n\t}",
"public App named(String name) {\n App newApp = copy();\n newApp.name = name;\n return newApp;\n }",
"private void destroySession() {\n currentSessionId = 0;\n setAppLaunchPushed(false);\n getConfigLogger().verbose(getAccountId(),\"Session destroyed; Session ID is now 0\");\n clearSource();\n clearMedium();\n clearCampaign();\n clearWzrkParams();\n }",
"public NamespacesList<Namespace> getNamespaces(String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Namespace> nsList = new NamespacesList<Namespace>();\r\n parameters.put(\"method\", METHOD_GET_NAMESPACES);\r\n\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"namespace\");\r\n nsList.setPage(\"1\");\r\n nsList.setPages(\"1\");\r\n nsList.setPerPage(\"\" + nsNodes.getLength());\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parseNamespace(element));\r\n }\r\n return nsList;\r\n }",
"private String getCachedETag(HttpHost host, String file) {\n Map<String, Object> cachedETags = readCachedETags();\n\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> hostMap =\n (Map<String, Object>)cachedETags.get(host.toURI());\n if (hostMap == null) {\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n Map<String, String> etagMap = (Map<String, String>)hostMap.get(file);\n if (etagMap == null) {\n return null;\n }\n\n return etagMap.get(\"ETag\");\n }",
"boolean awaitState(final InternalState expected) {\n synchronized (this) {\n final InternalState initialRequired = this.requiredState;\n for(;;) {\n final InternalState required = this.requiredState;\n // Stop in case the server failed to reach the state\n if(required == InternalState.FAILED) {\n return false;\n // Stop in case the required state changed\n } else if (initialRequired != required) {\n return false;\n }\n final InternalState current = this.internalState;\n if(expected == current) {\n return true;\n }\n try {\n wait();\n } catch(InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n }\n }",
"public void addControllerType(GVRControllerType controllerType)\n {\n if (cursorControllerTypes == null)\n {\n cursorControllerTypes = new ArrayList<GVRControllerType>();\n }\n else if (cursorControllerTypes.contains(controllerType))\n {\n return;\n }\n cursorControllerTypes.add(controllerType);\n }",
"@Override\n public String printHelp() {\n List<CommandLineParser<CI>> parsers = getChildParsers();\n if (parsers != null && parsers.size() > 0) {\n StringBuilder sb = new StringBuilder();\n sb.append(processedCommand.printHelp(helpNames()))\n .append(Config.getLineSeparator())\n .append(processedCommand.name())\n .append(\" commands:\")\n .append(Config.getLineSeparator());\n\n int maxLength = 0;\n\n for (CommandLineParser child : parsers) {\n int length = child.getProcessedCommand().name().length();\n if (length > maxLength) {\n maxLength = length;\n }\n }\n\n for (CommandLineParser child : parsers) {\n sb.append(child.getFormattedCommand(4, maxLength + 2))\n .append(Config.getLineSeparator());\n }\n\n return sb.toString();\n }\n else\n return processedCommand.printHelp(helpNames());\n }",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteProfile(Model model, int id) throws Exception {\n profileService.remove(id);\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }"
] |
True if a CharSequence only contains whitespace characters.
@param self The CharSequence to check the characters in
@return true If all characters are whitespace characters
@see #isAllWhitespace(String)
@since 1.8.2 | [
"public static boolean isAllWhitespace(CharSequence self) {\n String s = self.toString();\n for (int i = 0; i < s.length(); i++) {\n if (!Character.isWhitespace(s.charAt(i)))\n return false;\n }\n return true;\n }"
] | [
"public static void applyMultiIconTo(Drawable icon, int iconColor, Drawable selectedIcon, int selectedIconColor, boolean tinted, ImageView imageView) {\n //if we have an icon then we want to set it\n if (icon != null) {\n //if we got a different color for the selectedIcon we need a StateList\n if (selectedIcon != null) {\n if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, selectedIcon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(UIUtils.getIconStateList(icon, selectedIcon));\n }\n } else if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(icon);\n }\n //make sure we display the icon\n imageView.setVisibility(View.VISIBLE);\n } else {\n //hide the icon\n imageView.setVisibility(View.GONE);\n }\n }",
"public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}",
"private static boolean containsObject(Object searchFor, Object[] searchIn)\r\n {\r\n for (int i = 0; i < searchIn.length; i++)\r\n {\r\n if (searchFor == searchIn[i])\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }",
"public void deleteEmailAlias(String emailAliasID) {\n URL url = EMAIL_ALIAS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), emailAliasID);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"protected void updateForNewConfiguration(CmsGitConfiguration gitConfig) {\n\n if (!m_checkinBean.setCurrentConfiguration(gitConfig)) {\n Notification.show(\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_0),\n CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CONFIGURATION_SWITCH_FAILED_DESC_0),\n Type.ERROR_MESSAGE);\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n return;\n }\n\n resetSelectableModules();\n for (final String moduleName : gitConfig.getConfiguredModules()) {\n addSelectableModule(moduleName);\n }\n updateNewModuleSelector();\n m_pullFirst.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullBefore()));\n m_pullAfterCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPullAfter()));\n m_addAndCommit.setValue(Boolean.valueOf(gitConfig.getDefaultAutoCommit()));\n m_pushAutomatically.setValue(Boolean.valueOf(gitConfig.getDefaultAutoPush()));\n m_commitMessage.setValue(Strings.nullToEmpty(gitConfig.getDefaultCommitMessage()));\n m_copyAndUnzip.setValue(Boolean.valueOf(gitConfig.getDefaultCopyAndUnzip()));\n m_excludeLib.setValue(Boolean.valueOf(gitConfig.getDefaultExcludeLibs()));\n m_ignoreUnclean.setValue(Boolean.valueOf(gitConfig.getDefaultIngoreUnclean()));\n m_userField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserName()));\n m_emailField.setValue(Strings.nullToEmpty(gitConfig.getDefaultGitUserEmail()));\n\n }",
"public static <T> JacksonParser<T> json(Class<T> contentType) {\n return new JacksonParser<>(null, contentType);\n }",
"public void emitEvent(\n final NamespaceSynchronizationConfig nsConfig,\n final ChangeEvent<BsonDocument> event) {\n listenersLock.lock();\n try {\n if (nsConfig.getNamespaceListenerConfig() == null) {\n return;\n }\n final NamespaceListenerConfig namespaceListener =\n nsConfig.getNamespaceListenerConfig();\n eventDispatcher.dispatch(() -> {\n try {\n if (namespaceListener.getEventListener() != null) {\n namespaceListener.getEventListener().onEvent(\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ChangeEvents.transformChangeEventForUser(\n event, namespaceListener.getDocumentCodec()));\n }\n } catch (final Exception ex) {\n logger.error(String.format(\n Locale.US,\n \"emitEvent ns=%s documentId=%s emit exception: %s\",\n event.getNamespace(),\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ex), ex);\n }\n return null;\n });\n } finally {\n listenersLock.unlock();\n }\n }",
"public static void checkDelegateType(Decorator<?> decorator) {\n\n Set<Type> types = new HierarchyDiscovery(decorator.getDelegateType()).getTypeClosure();\n\n for (Type decoratedType : decorator.getDecoratedTypes()) {\n if(!types.contains(decoratedType)) {\n throw BeanLogger.LOG.delegateMustSupportEveryDecoratedType(decoratedType, decorator);\n }\n }\n }"
] |
Maps a transportId to its corresponding TransportType.
@param transportId
@return | [
"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 }"
] | [
"public List<String> getModuleVersions(final String name, final FiltersHolder filters) {\n final List<String> versions = repositoryHandler.getModuleVersions(name, filters);\n\n if (versions.isEmpty()) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Module \" + name + \" does not exist.\").build());\n }\n\n return versions;\n }",
"private List<Job> getJobs(final Jedis jedis, final String queueName, final long jobOffset, final long jobCount) throws Exception {\n final String key = key(QUEUE, queueName);\n final List<Job> jobs = new ArrayList<>();\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZRANGEWITHSCORES\n final Set<Tuple> elements = jedis.zrangeWithScores(key, jobOffset, jobOffset + jobCount - 1);\n for (final Tuple elementWithScore : elements) {\n final Job job = ObjectMapperFactory.get().readValue(elementWithScore.getElement(), Job.class);\n job.setRunAt(elementWithScore.getScore());\n jobs.add(job);\n }\n } else { // Else, use LRANGE\n final List<String> elements = jedis.lrange(key, jobOffset, jobOffset + jobCount - 1);\n for (final String element : elements) {\n jobs.add(ObjectMapperFactory.get().readValue(element, Job.class));\n }\n }\n return jobs;\n }",
"public ByteBuffer payload() {\n ByteBuffer payload = buffer.duplicate();\n payload.position(headerSize(magic()));\n payload = payload.slice();\n payload.limit(payloadSize());\n payload.rewind();\n return payload;\n }",
"public void append(float[] newValue) {\n if ( (newValue.length % 2) == 0) {\n for (int i = 0; i < (newValue.length/2); i++) {\n value.add( new SFVec2f(newValue[i*2], newValue[i*2+1]) );\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec3f append set with array length not divisible by 2\");\n }\n }",
"public static BoxUser.Info createAppUser(BoxAPIConnection api, String name,\n CreateUserParams params) {\n\n params.setIsPlatformAccessOnly(true);\n return createEnterpriseUser(api, null, name, params);\n }",
"private EditorState getDefaultState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.TRANSLATION);\n\n return new EditorState(cols, false);\n }",
"public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }",
"private boolean loadCustomErrorPage(\n CmsObject cms,\n HttpServletRequest req,\n HttpServletResponse res,\n String rootPath) {\n\n try {\n\n // get the site of the error page resource\n CmsSite errorSite = OpenCms.getSiteManager().getSiteForRootPath(rootPath);\n cms.getRequestContext().setSiteRoot(errorSite.getSiteRoot());\n String relPath = cms.getRequestContext().removeSiteRoot(rootPath);\n if (cms.existsResource(relPath)) {\n cms.getRequestContext().setUri(relPath);\n OpenCms.getResourceManager().loadResource(cms, cms.readResource(relPath), req, res);\n return true;\n } else {\n return false;\n }\n } catch (Throwable e) {\n // something went wrong log the exception and return false\n LOG.error(e.getMessage(), e);\n return false;\n }\n }",
"public static authenticationvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_stats response = (authenticationvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Queries a Search Index and returns grouped results in a map where key
of the map is the groupName. In case the query didnt use grouping,
an empty map is returned
@param <T> Object type T
@param query the Lucene query to be passed to the Search index
@param classOfT The class of type T
@return The result of the grouped search query as a ordered {@code Map<String,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 boolean isInBounds(int row, int col) {\n return row >= 0 && col >= 0 && row < mat.getNumRows() && col < mat.getNumCols();\n }",
"public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) {\n MVCArray res = buildArcPoints(center, start, end);\n if (ArcType.ROUND.equals(arcType)) {\n res.push(center);\n }\n return new PolygonOptions().paths(res);\n }",
"public static int getLineCount(String str) {\r\n if (null == str || str.isEmpty()) {\r\n return 0;\r\n }\r\n int count = 1;\r\n for (char c : str.toCharArray()) {\r\n if ('\\n' == c) {\r\n count++;\r\n }\r\n }\r\n return count;\r\n }",
"private void unregisterAllServlets() {\n\n for (String endpoint : registeredServlets) {\n registeredServlets.remove(endpoint);\n web.unregister(endpoint);\n LOG.info(\"endpoint {} unregistered\", endpoint);\n }\n\n }",
"public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)\n {\n if (cleanBaseFileName)\n {\n baseFileName = PathUtil.cleanFileName(baseFileName);\n }\n\n if (ancestorFolders != null)\n {\n Path pathToFile = Paths.get(\"\", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);\n baseFileName = pathToFile.toString();\n }\n String filename = baseFileName + \".\" + extension;\n\n // FIXME this looks nasty\n while (usedFilenames.contains(filename))\n {\n filename = baseFileName + \".\" + index.getAndIncrement() + \".\" + extension;\n }\n usedFilenames.add(filename);\n\n return filename;\n }",
"public void addWatcher(final MongoNamespace namespace,\n final Callback<ChangeEvent<BsonDocument>, Object> watcher) {\n instanceChangeStreamListener.addWatcher(namespace, watcher);\n }",
"public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);\n } catch (IncompatibleTestMatrixException e) {\n LOGGER.info(String.format(\"Unable to load test matrix for %s\", testName), e);\n resultBuilder.recordError(testName, e);\n }\n }\n return resultBuilder.build();\n }",
"public Map<InetSocketAddress, ServerPort> activePorts() {\n final Server server = this.server;\n if (server != null) {\n return server.activePorts();\n } else {\n return Collections.emptyMap();\n }\n }",
"public static base_response add(nitro_service client, dnstxtrec resource) throws Exception {\n\t\tdnstxtrec addresource = new dnstxtrec();\n\t\taddresource.domain = resource.domain;\n\t\taddresource.String = resource.String;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Add tasks to the tree.
@param parentNode parent tree node
@param parent parent task container | [
"private void addTasks(MpxjTreeNode parentNode, ChildTaskContainer parent)\n {\n for (Task task : parent.getChildTasks())\n {\n final Task t = task;\n MpxjTreeNode childNode = new MpxjTreeNode(task, TASK_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n addTasks(childNode, task);\n }\n }"
] | [
"public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }",
"public static double getRadiusToBoundedness(double D, int N, double timelag, double B){\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble radius = Math.sqrt(cov_area/(4*B));\n\t\treturn radius;\n\t}",
"@Override\r\n public String upload(byte[] data, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(data);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"public boolean removeCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n return false;\n }\n String pathId = path.getString(\"pathId\");\n return resetResponseOverride(pathId);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public static void normalizeF( DMatrixRMaj A ) {\n double val = normF(A);\n\n if( val == 0 )\n return;\n\n int size = A.getNumElements();\n\n for( int i = 0; i < size; i++) {\n A.div(i , val);\n }\n }",
"public ClientBootstrap bootStrapTcpClient()\n throws HttpRequestCreateException {\n\n ClientBootstrap tcpClient = null;\n try {\n\n // Configure the client.\n tcpClient = new ClientBootstrap(tcpMeta.getChannelFactory());\n\n // Configure the pipeline factory.\n tcpClient.setPipelineFactory(new MyPipelineFactory(TcpUdpSshPingResourceStore.getInstance().getTimer(),\n this, tcpMeta.getTcpIdleTimeoutSec())\n );\n\n tcpClient.setOption(\"connectTimeoutMillis\",\n tcpMeta.getTcpConnectTimeoutMillis());\n tcpClient.setOption(\"tcpNoDelay\", true);\n // tcpClient.setOption(\"keepAlive\", true);\n\n } catch (Exception t) {\n throw new TcpUdpRequestCreateException(\n \"Error in creating request in Tcpworker. \"\n + \" If tcpClient is null. Then fail to create.\", t);\n }\n\n return tcpClient;\n\n }",
"public ActivityCodeValue addValue(Integer uniqueID, String name, String description)\n {\n ActivityCodeValue value = new ActivityCodeValue(this, uniqueID, name, description);\n m_values.add(value);\n return value;\n }",
"@Override\n public synchronized void start() {\n if (!started.getAndSet(true)) {\n finished.set(false);\n thread.start();\n }\n }",
"public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }"
] |
Read an optional string value form a JSON value.
@param val the JSON value that should represent the string.
@return the string from the JSON or null if reading the string fails. | [
"private String readOptionalString(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n return str.stringValue();\n }\n return null;\n }"
] | [
"public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}",
"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 float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }",
"public void stop(int waitMillis) throws InterruptedException {\n try {\n if (!isDone()) {\n setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format(\"Stopped by user: waiting for %d ms\", waitMillis)));\n }\n if (!waitForFinish(waitMillis)) {\n logger.warn(\"{} Client thread failed to finish in {} millis\", name, waitMillis);\n }\n } finally {\n rateTracker.shutdown();\n }\n }",
"public SqlStatement getPreparedDeleteStatement(Query query, ClassDescriptor cld)\r\n {\r\n return new SqlDeleteByQuery(m_platform, cld, query, logger);\r\n }",
"public String getSQL92LikePattern() throws IllegalArgumentException {\n\t\tif (escape.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> escape char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardSingle.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardSingle char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardMulti.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardMulti char should be of length exactly 1\");\n\t\t}\n\t\treturn LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),\n\t\t\t\tisMatchingCase(), pattern);\n\t}",
"public GroovyMethodDoc[] methods() {\n Collections.sort(methods);\n return methods.toArray(new GroovyMethodDoc[methods.size()]);\n }",
"public Response remove(String id) {\r\n assertNotEmpty(id, \"id\");\r\n id = ensureDesignPrefix(id);\r\n String revision = null;\r\n // Get the revision ID from ETag, removing leading and trailing \"\r\n revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri()\r\n ).documentUri(id))).getConnection().getHeaderField(\"ETag\");\r\n if (revision != null) {\r\n revision = revision.substring(1, revision.length() - 1);\r\n return db.remove(id, revision);\r\n } else {\r\n throw new CouchDbException(\"No ETag header found for design document with id \" + id);\r\n }\r\n }",
"public void cleanup() {\n managers.clear();\n for (BeanManagerImpl beanManager : beanDeploymentArchives.values()) {\n beanManager.cleanup();\n }\n beanDeploymentArchives.clear();\n deploymentServices.cleanup();\n deploymentManager.cleanup();\n instance.clear(contextId);\n }"
] |
Returns all the Artifacts of the module
@param module Module
@return List<Artifact> | [
"public static List<Artifact> getAllArtifacts(final Module module){\n final List<Artifact> artifacts = new ArrayList<Artifact>();\n\n for(final Module subModule: module.getSubmodules()){\n artifacts.addAll(getAllArtifacts(subModule));\n }\n\n artifacts.addAll(module.getArtifacts());\n\n return artifacts;\n }"
] | [
"public void setBaselineStartText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_STARTS, baselineNumber), value);\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 }",
"boolean attachmentsAreStructurallyDifferent( List<AttachmentModel> firstAttachments, List<AttachmentModel> otherAttachments ) {\n if( firstAttachments.size() != otherAttachments.size() ) {\n return true;\n }\n\n for( int i = 0; i < firstAttachments.size(); i++ ) {\n if( attachmentIsStructurallyDifferent( firstAttachments.get( i ), otherAttachments.get( i ) ) ) {\n return true;\n }\n }\n return false;\n }",
"public List<BoxAPIResponse> execute(List<BoxAPIRequest> requests) {\n this.prepareRequest(requests);\n BoxJSONResponse batchResponse = (BoxJSONResponse) send();\n return this.parseResponse(batchResponse);\n }",
"public static base_responses delete(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance deleteresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new clusterinstance();\n\t\t\t\tdeleteresources[i].clid = resources[i].clid;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"protected void _format(EObject obj, IFormattableDocument document) {\n\t\tfor (EObject child : obj.eContents())\n\t\t\tdocument.format(child);\n\t}",
"private static Object getParam(final Object param) {\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tif(param instanceof String){\n\t\t\tsb.append(\"'\");\n\t\t\tsb.append((String)param);\n\t\t\tsb.append(\"'\");\n\t\t}\n\t\telse if(param instanceof Boolean){\n\t\t\tsb.append(String.valueOf((Boolean)param));\t\t\t\n\t\t}\n else if(param instanceof Integer){\n sb.append(String.valueOf((Integer)param));\n }\n else if(param instanceof DBRegExp){\n sb.append('/');\n sb.append(((DBRegExp) param).toString());\n sb.append('/');\n }\n\t\t\n\t\treturn sb.toString();\n\t}",
"private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap)\n {\n Project.Resources resources = project.getResources();\n if (resources != null)\n {\n for (Project.Resources.Resource resource : resources.getResource())\n {\n readResource(resource, calendarMap);\n }\n }\n }",
"public static base_responses add(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 addresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dbdbprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\taddresources[i].stickiness = resources[i].stickiness;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Gets a SerialMessage with the SENSOR_ALARM_GET command
@return the serial message | [
"public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.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) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\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 }",
"protected Query buildMtoNImplementorQuery(Collection ids)\r\n {\r\n String[] indFkCols = getFksToThisClass();\r\n String[] indItemFkCols = getFksToItemClass();\r\n FieldDescriptor[] pkFields = getOwnerClassDescriptor().getPkFields();\r\n FieldDescriptor[] itemPkFields = getItemClassDescriptor().getPkFields();\r\n String[] cols = new String[indFkCols.length + indItemFkCols.length];\r\n int[] jdbcTypes = new int[indFkCols.length + indItemFkCols.length];\r\n\r\n // concatenate the columns[]\r\n System.arraycopy(indFkCols, 0, cols, 0, indFkCols.length);\r\n System.arraycopy(indItemFkCols, 0, cols, indFkCols.length, indItemFkCols.length);\r\n\r\n Criteria crit = buildPrefetchCriteria(ids, indFkCols, indItemFkCols, itemPkFields);\r\n\r\n // determine the jdbcTypes of the pks\r\n for (int i = 0; i < pkFields.length; i++)\r\n {\r\n jdbcTypes[i] = pkFields[i].getJdbcType().getType();\r\n }\r\n for (int i = 0; i < itemPkFields.length; i++)\r\n {\r\n jdbcTypes[pkFields.length + i] = itemPkFields[i].getJdbcType().getType();\r\n }\r\n\r\n ReportQueryByMtoNCriteria q = new ReportQueryByMtoNCriteria(getItemClassDescriptor().getClassOfObject(), cols,\r\n crit, false);\r\n q.setIndirectionTable(getCollectionDescriptor().getIndirectionTable());\r\n q.setJdbcTypes(jdbcTypes);\r\n\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n //check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n q.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n \r\n return q;\r\n }",
"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 }",
"public static base_response add(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 addresource = new nspbr6();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\taddresource.action = resource.action;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.nexthop = resource.nexthop;\n\t\taddresource.nexthopval = resource.nexthopval;\n\t\taddresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {\n return getSharedItem(api, sharedLink, null);\n }",
"@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }",
"public static systemcore[] get(nitro_service service, systemcore_args args) throws Exception{\n\t\tsystemcore obj = new systemcore();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystemcore[] response = (systemcore[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private static List<Class<?>> getClassHierarchy(Class<?> clazz) {\n\t\tList<Class<?>> hierarchy = new ArrayList<Class<?>>( 4 );\n\n\t\tfor ( Class<?> current = clazz; current != null; current = current.getSuperclass() ) {\n\t\t\thierarchy.add( current );\n\t\t}\n\n\t\treturn hierarchy;\n\t}",
"public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\n }"
] |
Given a filesystem, path and buffer-size, read the file contents and
presents it as a string
@param fs Underlying filesystem
@param path The file to read
@param bufferSize The buffer size to use for reading
@return The contents of the file as a string
@throws IOException | [
"public static String readFileContents(FileSystem fs, Path path, int bufferSize)\n throws IOException {\n if(bufferSize <= 0)\n return new String();\n\n FSDataInputStream input = fs.open(path);\n byte[] buffer = new byte[bufferSize];\n\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n\n while(true) {\n int read = input.read(buffer);\n if(read < 0) {\n break;\n } else {\n buffer = ByteUtils.copy(buffer, 0, read);\n }\n stream.write(buffer);\n }\n\n return new String(stream.toByteArray());\n }"
] | [
"@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 static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) {\n // since indy does not give us the runtime types\n // we produce first a dummy call site, which then changes the target to one,\n // that does the method selection including the the direct call to the \n // real method.\n MutableCallSite mc = new MutableCallSite(type);\n MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall);\n mc.setTarget(mh);\n return mc;\n }",
"public static String retrieveVendorId() {\n if (MapboxTelemetry.applicationContext == null) {\n return updateVendorId();\n }\n\n SharedPreferences sharedPreferences = obtainSharedPreferences(MapboxTelemetry.applicationContext);\n String mapboxVendorId = sharedPreferences.getString(MAPBOX_SHARED_PREFERENCE_KEY_VENDOR_ID, \"\");\n if (TelemetryUtils.isEmpty(mapboxVendorId)) {\n mapboxVendorId = TelemetryUtils.updateVendorId();\n }\n return mapboxVendorId;\n }",
"private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }",
"public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }",
"private void readExceptionDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay day)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod timePeriod = day.getTimePeriod();\n Date fromDate = timePeriod.getFromDate();\n Date toDate = timePeriod.getToDate();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = day.getWorkingTimes();\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n\n if (times != null)\n {\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n exception.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"public void setContentType(String photoId, String contentType) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_CONTENTTYPE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"content_type\", contentType);\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 }",
"String encodePath(String in) {\n try {\n String encodedString = HierarchicalUriComponents.encodeUriComponent(in, \"UTF-8\",\n HierarchicalUriComponents.Type.PATH_SEGMENT);\n if (encodedString.startsWith(_design_prefix_encoded) ||\n encodedString.startsWith(_local_prefix_encoded)) {\n // we replaced the first slash in the design or local doc URL, which we shouldn't\n // so let's put it back\n return encodedString.replaceFirst(\"%2F\", \"/\");\n } else {\n return encodedString;\n }\n } catch (UnsupportedEncodingException uee) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(\n \"Couldn't encode ID \" + in,\n uee);\n }\n }",
"public static base_response delete(nitro_service client, String ipv6prefix) throws Exception {\n\t\tonlinkipv6prefix deleteresource = new onlinkipv6prefix();\n\t\tdeleteresource.ipv6prefix = ipv6prefix;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] |
Returns whether this address section represents a subnet block of addresses associated its prefix length.
Returns false if it has no prefix length, if it is a single address with a prefix length (ie not a subnet), or if it is a range of addresses that does not include
the entire subnet block for its prefix length.
If {@link AddressNetwork#getPrefixConfiguration} is set to consider all prefixes as subnets, this returns true for any grouping with prefix length.
@return | [
"@Override\n\tpublic boolean isPrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif(getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn containsPrefixBlock(networkPrefixLength);\n\t}"
] | [
"public static void main(final String[] args) {\n if (System.getProperty(\"db.name\") == null) {\n System.out.println(\"Not running in multi-instance mode: no DB to connect to\");\n System.exit(1);\n }\n while (true) {\n try {\n Class.forName(\"org.postgresql.Driver\");\n DriverManager.getConnection(\"jdbc:postgresql://\" + System.getProperty(\"db.host\") + \":5432/\" +\n System.getProperty(\"db.name\"),\n System.getProperty(\"db.username\"),\n System.getProperty(\"db.password\"));\n System.out.println(\"Opened database successfully. Running in multi-instance mode\");\n System.exit(0);\n return;\n } catch (Exception e) {\n System.out.println(\"Failed to connect to the DB: \" + e.toString());\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e1) {\n //ignored\n }\n }\n }\n }",
"public static String[] tokenizeUnquoted(String s) {\r\n List tokens = new LinkedList();\r\n int first = 0;\r\n while (first < s.length()) {\r\n first = skipWhitespace(s, first);\r\n int last = scanToken(s, first);\r\n if (first < last) {\r\n tokens.add(s.substring(first, last));\r\n }\r\n first = last;\r\n }\r\n return (String[])tokens.toArray(new String[tokens.size()]);\r\n }",
"public String getToken() {\n String id = null == answer ? text : answer;\n return Act.app().crypto().generateToken(id);\n }",
"public Class getPersistentFieldClass()\r\n {\r\n if (m_persistenceClass == null)\r\n {\r\n Properties properties = new Properties();\r\n try\r\n {\r\n this.logWarning(\"Loading properties file: \" + getPropertiesFile());\r\n properties.load(new FileInputStream(getPropertiesFile()));\r\n }\r\n catch (IOException e)\r\n {\r\n this.logWarning(\"Could not load properties file '\" + getPropertiesFile()\r\n + \"'. Using PersistentFieldDefaultImpl.\");\r\n e.printStackTrace();\r\n }\r\n try\r\n {\r\n String className = properties.getProperty(\"PersistentFieldClass\");\r\n\r\n m_persistenceClass = loadClass(className);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n e.printStackTrace();\r\n m_persistenceClass = PersistentFieldPrivilegedImpl.class;\r\n }\r\n logWarning(\"PersistentFieldClass: \" + m_persistenceClass.toString());\r\n }\r\n return m_persistenceClass;\r\n }",
"public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }",
"public static appfwjsoncontenttype[] get(nitro_service service, options option) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tappfwjsoncontenttype[] response = (appfwjsoncontenttype[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"private List<T> computePagedList(List<T> result, HeaderAndBody httpResponse, JSONObject where, Pipe<T> requestingPipe) {\n ReadFilter previousRead = null;\n ReadFilter nextRead = null;\n\n if (PageConfig.MetadataLocations.WEB_LINKING.equals(pageConfig.getMetadataLocation())) {\n String webLinksRaw = \"\";\n final String relHeader = \"rel\";\n final String nextIdentifier = pageConfig.getNextIdentifier();\n final String prevIdentifier = pageConfig.getPreviousIdentifier();\n try {\n webLinksRaw = getWebLinkHeader(httpResponse);\n if (webLinksRaw == null) { // no paging, return result\n return result;\n }\n List<WebLink> webLinksParsed = WebLinkParser.parse(webLinksRaw);\n for (WebLink link : webLinksParsed) {\n if (nextIdentifier.equals(link.getParameters().get(relHeader))) {\n nextRead = new ReadFilter();\n nextRead.setLinkUri(new URI(link.getUri()));\n } else if (prevIdentifier.equals(link.getParameters().get(relHeader))) {\n previousRead = new ReadFilter();\n previousRead.setLinkUri(new URI(link.getUri()));\n }\n\n }\n } catch (URISyntaxException ex) {\n Log.e(TAG, webLinksRaw + \" did not contain a valid context URI\", ex);\n throw new RuntimeException(ex);\n } catch (ParseException ex) {\n Log.e(TAG, webLinksRaw + \" could not be parsed as a web link header\", ex);\n throw new RuntimeException(ex);\n }\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.HEADERS)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.BODY)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else {\n throw new IllegalStateException(\"Not supported\");\n }\n if (nextRead != null) {\n nextRead.setWhere(where);\n }\n\n if (previousRead != null) {\n previousRead.setWhere(where);\n }\n\n return new WrappingPagedList<T>(requestingPipe, result, nextRead, previousRead);\n }",
"public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }",
"void pumpEvents(InputStream eventStream) {\n try {\n Deserializer deserializer = new Deserializer(eventStream, refLoader);\n\n IEvent event = null;\n while ((event = deserializer.deserialize()) != null) {\n switch (event.getType()) {\n case APPEND_STDERR:\n case APPEND_STDOUT:\n // Ignore these two on activity heartbeats. GH-117\n break;\n default:\n lastActivity = System.currentTimeMillis();\n break;\n }\n\n try {\n switch (event.getType()) {\n case QUIT:\n eventBus.post(event);\n return;\n\n case IDLE:\n eventBus.post(new SlaveIdle(stdinWriter));\n break;\n\n case BOOTSTRAP:\n clientCharset = Charset.forName(((BootstrapEvent) event).getDefaultCharsetName());\n stdinWriter = new OutputStreamWriter(stdin, clientCharset);\n eventBus.post(event);\n break;\n\n case APPEND_STDERR:\n case APPEND_STDOUT:\n assert streamsBuffer.getFilePointer() == streamsBuffer.length();\n final long bufferStart = streamsBuffer.getFilePointer();\n IStreamEvent streamEvent = (IStreamEvent) event;\n streamEvent.copyTo(streamsBufferWrapper);\n final long bufferEnd = streamsBuffer.getFilePointer();\n\n event = new OnDiskStreamEvent(event.getType(), streamsBuffer, bufferStart, bufferEnd);\n eventBus.post(event);\n break;\n \n default:\n eventBus.post(event);\n }\n } catch (Throwable t) {\n warnStream.println(\"Event bus dispatch error: \" + t.toString());\n t.printStackTrace(warnStream);\n }\n }\n lastActivity = null;\n } catch (Throwable e) {\n if (!stopping) {\n warnStream.println(\"Event stream error: \" + e.toString());\n e.printStackTrace(warnStream);\n }\n }\n }"
] |
Registers Jersey HeaderDelegateProviders for the specified TinyTypes.
@param head a TinyType
@param tail other TinyTypes
@throws IllegalArgumentException when a non-TinyType is given | [
"public static void registerTinyTypes(Class<?> head, Class<?>... tail) {\n final Set<HeaderDelegateProvider> systemRegisteredHeaderProviders = stealAcquireRefToHeaderDelegateProviders();\n register(head, systemRegisteredHeaderProviders);\n for (Class<?> tt : tail) {\n register(tt, systemRegisteredHeaderProviders);\n }\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 }",
"private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }",
"public ArrayList<String> getCarouselImages(){\n ArrayList<String> carouselImages = new ArrayList<>();\n for(CTInboxMessageContent ctInboxMessageContent: getInboxMessageContents()){\n carouselImages.add(ctInboxMessageContent.getMedia());\n }\n return carouselImages;\n }",
"protected String addDependency(FunctionalTaskItem dependency) {\n Objects.requireNonNull(dependency);\n return this.taskGroup().addDependency(dependency);\n }",
"private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds)\r\n {\r\n Query fkQuery;\r\n QueryByCriteria fkQueryCrit;\r\n\r\n if (cds.isMtoNRelation())\r\n {\r\n fkQueryCrit = getFKQueryMtoN(obj, cld, cds);\r\n }\r\n else\r\n {\r\n fkQueryCrit = getFKQuery1toN(obj, cld, cds);\r\n }\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n fkQueryCrit.addOrderBy((FieldHelper)iter.next());\r\n }\r\n }\r\n\r\n // BRJ: customize the query\r\n if (cds.getQueryCustomizer() != null)\r\n {\r\n fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit);\r\n }\r\n else\r\n {\r\n fkQuery = fkQueryCrit;\r\n }\r\n\r\n return fkQuery;\r\n }",
"public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }",
"private void performScriptedStep() {\n double scale = computeBulgeScale();\n if( steps > giveUpOnKnown ) {\n // give up on the script\n followScript = false;\n } else {\n // use previous singular value to step\n double s = values[x2]/scale;\n performImplicitSingleStep(scale,s*s,false);\n }\n }",
"private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException {\n\n final PrintWriter pw = res.getWriter();\n final JSONObject response = getJsonFormattedSpellcheckResult(request);\n pw.println(response.toString());\n pw.close();\n }",
"public AccessAssertion unmarshal(final JSONObject encodedAssertion) {\n final String className;\n try {\n className = encodedAssertion.getString(JSON_CLASS_NAME);\n final Class<?> assertionClass =\n Thread.currentThread().getContextClassLoader().loadClass(className);\n final AccessAssertion assertion =\n (AccessAssertion) this.applicationContext.getBean(assertionClass);\n assertion.unmarshal(encodedAssertion);\n\n return assertion;\n } catch (JSONException | ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }"
] |
Reads OAuth 2.0 with JWT app configurations from the reader. The file should be in JSON format.
@param reader a reader object which points to a JSON formatted configuration file
@return a new Instance of BoxConfig
@throws IOException when unable to access the mapping file's content of the reader | [
"public static BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }"
] | [
"private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }",
"public void fire(StepEvent event) {\n Step step = stepStorage.getLast();\n event.process(step);\n\n notifier.fire(event);\n }",
"private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public static int getMpxField(int value)\n {\n int result = 0;\n\n if (value >= 0 && value < MPXJ_MPX_ARRAY.length)\n {\n result = MPXJ_MPX_ARRAY[value];\n }\n return (result);\n }",
"@Override\n public int add(DownloadRequest request) throws IllegalArgumentException {\n checkReleased(\"add(...) called on a released ThinDownloadManager.\");\n if (request == null) {\n throw new IllegalArgumentException(\"DownloadRequest cannot be null\");\n }\n return mRequestQueue.add(request);\n }",
"public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {\n\t\tDayCountConventionInterface daycountConvention = getDayCountConvention(convention);\n\t\treturn daycountConvention.getDaycount(startDate, endDate);\n\t}",
"public Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\n }",
"@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 }",
"public static ipset_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip6_binding obj = new ipset_nsip6_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip6_binding response[] = (ipset_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Processes an object cache tag.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException If an error occurs
@doc.tag type="content"
@doc.param name="attributes" optional="true" description="Attributes of the object-cache as name-value pairs 'name=value',
@doc.param name="class" optional="false" description="The object cache implementation"
@doc.param name="documentation" optional="true" description="Documentation on the object cache" | [
"public String processObjectCache(Properties attributes) throws XDocletException\r\n {\r\n ObjectCacheDef objCacheDef = _curClassDef.setObjectCache(attributes.getProperty(ATTRIBUTE_CLASS));\r\n String attrName;\r\n\r\n attributes.remove(ATTRIBUTE_CLASS);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n objCacheDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }"
] | [
"public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }",
"private int getDaysInRange(Date startDate, Date endDate)\n {\n int result;\n Calendar cal = DateHelper.popCalendar(endDate);\n int endDateYear = cal.get(Calendar.YEAR);\n int endDateDayOfYear = cal.get(Calendar.DAY_OF_YEAR);\n\n cal.setTime(startDate);\n\n if (endDateYear == cal.get(Calendar.YEAR))\n {\n result = (endDateDayOfYear - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n }\n else\n {\n result = 0;\n do\n {\n result += (cal.getActualMaximum(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n cal.roll(Calendar.YEAR, 1);\n cal.set(Calendar.DAY_OF_YEAR, 1);\n }\n while (cal.get(Calendar.YEAR) < endDateYear);\n result += endDateDayOfYear;\n }\n DateHelper.pushCalendar(cal);\n \n return result;\n }",
"protected float getViewPortSize(final Axis axis) {\n float size = mViewPort == null ? 0 : mViewPort.get(axis);\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getViewPortSize for %s %f mViewPort = %s\", axis, size, mViewPort);\n return size;\n }",
"public AiTextureInfo getTextureInfo(AiTextureType type, int index) {\n return new AiTextureInfo(type, index, getTextureFile(type, index), \n getTextureUVIndex(type, index), getBlendFactor(type, index), \n getTextureOp(type, index), getTextureMapModeW(type, index), \n getTextureMapModeW(type, index), \n getTextureMapModeW(type, index));\n }",
"public boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }",
"public ItemRequest<Project> removeMembers(String project) {\n \n String path = String.format(\"/projects/%s/removeMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }",
"public void merge(final ResourceRoot additionalResourceRoot) {\n if(!additionalResourceRoot.getRoot().equals(root)) {\n throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot());\n }\n usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource;\n if(additionalResourceRoot.getExportFilters().isEmpty()) {\n //new root has no filters, so we don't want our existing filters to break anything\n //see WFLY-1527\n this.exportFilters.clear();\n } else {\n this.exportFilters.addAll(additionalResourceRoot.getExportFilters());\n }\n }",
"private Object getLiteralValue(Expression expression) {\n\t\tif (!(expression instanceof Literal)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a Literal.\");\n\t\t}\n\t\treturn ((Literal) expression).getValue();\n\t}",
"public void processCalendar(Row calendarRow, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> workPatternAssignmentMap, Map<Integer, List<Row>> exceptionAssignmentMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n //\n // Create the calendar and add the default working hours\n //\n ProjectCalendar calendar = m_project.addCalendar();\n Integer dominantWorkPatternID = calendarRow.getInteger(\"DOMINANT_WORK_PATTERN\");\n calendar.setUniqueID(calendarRow.getInteger(\"CALENDARID\"));\n processWorkPattern(calendar, dominantWorkPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n calendar.setName(calendarRow.getString(\"NAMK\"));\n\n //\n // Add any additional working weeks\n //\n List<Row> rows = workPatternAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"WORK_PATTERN\");\n if (!workPatternID.equals(dominantWorkPatternID))\n {\n ProjectCalendarWeek week = calendar.addWorkWeek();\n week.setDateRange(new DateRange(row.getDate(\"START_DATE\"), row.getDate(\"END_DATE\")));\n processWorkPattern(week, workPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n }\n }\n }\n\n //\n // Add exceptions - not sure how exceptions which turn non-working days into working days are handled by Asta - if at all?\n //\n rows = exceptionAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Date startDate = row.getDate(\"STARU_DATE\");\n Date endDate = row.getDate(\"ENE_DATE\");\n calendar.addCalendarException(startDate, endDate);\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }"
] |
Process UDFs for a specific object.
@param mpxj field container
@param udfs UDF values | [
"private void readUDFTypes(FieldContainer mpxj, List<UDFAssignmentType> udfs)\n {\n for (UDFAssignmentType udf : udfs)\n {\n FieldType fieldType = m_fieldTypeMap.get(Integer.valueOf(udf.getTypeObjectId()));\n if (fieldType != null)\n {\n mpxj.set(fieldType, getUdfValue(udf));\n }\n }\n }"
] | [
"public void loadAnimation(GVRAndroidResource animResource, String boneMap)\n {\n String filePath = animResource.getResourcePath();\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, animResource);\n\n if (filePath.endsWith(\".bvh\"))\n {\n GVRAnimator animator = new GVRAnimator(ctx);\n animator.setName(filePath);\n try\n {\n BVHImporter importer = new BVHImporter(ctx);\n GVRSkeletonAnimation skelAnim;\n\n if (boneMap != null)\n {\n GVRSkeleton skel = importer.importSkeleton(animResource);\n skelAnim = importer.readMotion(skel);\n animator.addAnimation(skelAnim);\n\n GVRPoseMapper retargeter = new GVRPoseMapper(mSkeleton, skel, skelAnim.getDuration());\n retargeter.setBoneMap(boneMap);\n animator.addAnimation(retargeter);\n }\n else\n {\n skelAnim = importer.importAnimation(animResource, mSkeleton);\n animator.addAnimation(skelAnim);\n }\n addAnimation(animator);\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n animator,\n filePath,\n null);\n }\n catch (IOException ex)\n {\n ctx.getEventManager().sendEvent(this,\n IAvatarEvents.class,\n \"onAnimationLoaded\",\n GVRAvatar.this,\n null,\n filePath,\n ex.getMessage());\n }\n }\n else\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_TEXTURING));\n\n GVRSceneObject animRoot = new GVRSceneObject(ctx);\n ctx.getAssetLoader().loadModel(volume, animRoot, settings, false, mLoadAnimHandler);\n }\n }",
"public static <T> List<T> copyOf(Collection<T> source) {\n Preconditions.checkNotNull(source);\n if (source instanceof ImmutableList<?>) {\n return (ImmutableList<T>) source;\n }\n if (source.isEmpty()) {\n return Collections.emptyList();\n }\n return ofInternal(source.toArray());\n }",
"public ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}",
"public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }",
"@Override\n public boolean deleteObject(GcsFilename filename, long timeoutMillis) throws IOException {\n HTTPRequest req = makeRequest(filename, null, DELETE, timeoutMillis);\n HTTPResponse resp;\n try {\n resp = urlfetch.fetch(req);\n } catch (IOException e) {\n throw createIOException(new HTTPRequestInfo(req), e);\n }\n switch (resp.getResponseCode()) {\n case 204:\n return true;\n case 404:\n return false;\n default:\n throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);\n }\n }",
"public void eol() throws ProtocolException {\r\n char next = nextChar();\r\n\r\n // Ignore trailing spaces.\r\n while (next == ' ') {\r\n consume();\r\n next = nextChar();\r\n }\r\n\r\n // handle DOS and unix end-of-lines\r\n if (next == '\\r') {\r\n consume();\r\n next = nextChar();\r\n }\r\n\r\n // Check if we found extra characters.\r\n if (next != '\\n') {\r\n throw new ProtocolException(\"Expected end-of-line, found more character(s): \"+next);\r\n }\r\n dumpLine();\r\n }",
"public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }",
"public IOrientationState getOrientationStateFromParam(int orientation) {\n switch (orientation) {\n case Orientation.ORIENTATION_HORIZONTAL_BOTTOM:\n return new OrientationStateHorizontalBottom();\n case Orientation.ORIENTATION_HORIZONTAL_TOP:\n return new OrientationStateHorizontalTop();\n case Orientation.ORIENTATION_VERTICAL_LEFT:\n return new OrientationStateVerticalLeft();\n case Orientation.ORIENTATION_VERTICAL_RIGHT:\n return new OrientationStateVerticalRight();\n default:\n return new OrientationStateHorizontalBottom();\n }\n }",
"private void parseJSON(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n JsonValue value = member.getValue();\n if (value.isNull()) {\n continue;\n }\n\n try {\n String memberName = member.getName();\n if (memberName.equals(\"id\")) {\n this.versionID = value.asString();\n } else if (memberName.equals(\"sha1\")) {\n this.sha1 = value.asString();\n } else if (memberName.equals(\"name\")) {\n this.name = value.asString();\n } else if (memberName.equals(\"size\")) {\n this.size = Double.valueOf(value.toString()).longValue();\n } else if (memberName.equals(\"created_at\")) {\n this.createdAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_at\")) {\n this.modifiedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"trashed_at\")) {\n this.trashedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_by\")) {\n JsonObject userJSON = value.asObject();\n String userID = userJSON.get(\"id\").asString();\n BoxUser user = new BoxUser(getAPI(), userID);\n this.modifiedBy = user.new Info(userJSON);\n }\n } catch (ParseException e) {\n assert false : \"A ParseException indicates a bug in the SDK.\";\n }\n }\n }"
] |
Returns a site record for the site of the given name, creating a new one
if it does not exist yet.
@param siteKey
the key of the site
@return the suitable site record | [
"private SiteRecord getSiteRecord(String siteKey) {\n\t\tSiteRecord siteRecord = this.siteRecords.get(siteKey);\n\t\tif (siteRecord == null) {\n\t\t\tsiteRecord = new SiteRecord(siteKey);\n\t\t\tthis.siteRecords.put(siteKey, siteRecord);\n\t\t}\n\t\treturn siteRecord;\n\t}"
] | [
"public void credentialsMigration(T overrider, Class overriderClass) {\n try {\n deployerMigration(overrider, overriderClass);\n resolverMigration(overrider, overriderClass);\n } catch (NoSuchFieldException | IllegalAccessException | IOException e) {\n converterErrors.add(getConversionErrorMessage(overrider, e));\n }\n }",
"private void populateCalendar(Record record, ProjectCalendar calendar, boolean isBaseCalendar)\n {\n if (isBaseCalendar == true)\n {\n calendar.setName(record.getString(0));\n }\n else\n {\n calendar.setParent(m_projectFile.getCalendarByName(record.getString(0)));\n }\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.getInstance(record.getInteger(1)));\n calendar.setWorkingDay(Day.MONDAY, DayType.getInstance(record.getInteger(2)));\n calendar.setWorkingDay(Day.TUESDAY, DayType.getInstance(record.getInteger(3)));\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.getInstance(record.getInteger(4)));\n calendar.setWorkingDay(Day.THURSDAY, DayType.getInstance(record.getInteger(5)));\n calendar.setWorkingDay(Day.FRIDAY, DayType.getInstance(record.getInteger(6)));\n calendar.setWorkingDay(Day.SATURDAY, DayType.getInstance(record.getInteger(7)));\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }",
"public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"public static 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 List<EndpointOverride> getSelectedPaths(int overrideType, Client client, Profile profile, String uri,\n Integer requestType, boolean pathTest) throws Exception {\n List<EndpointOverride> selectPaths = new ArrayList<EndpointOverride>();\n\n // get the paths for the current active client profile\n // this returns paths in priority order\n List<EndpointOverride> paths = new ArrayList<EndpointOverride>();\n\n if (client.getIsActive()) {\n paths = getPaths(\n profile.getId(),\n client.getUUID(), null);\n }\n\n boolean foundRealPath = false;\n logger.info(\"Checking uri: {}\", uri);\n\n // it should now be ordered by priority, i updated tableOverrides to\n // return the paths in priority order\n for (EndpointOverride path : paths) {\n // first see if the request types match..\n // and if the path request type is not ALL\n // if they do not then skip this path\n // If requestType is -1 we evaluate all(probably called by the path tester)\n if (requestType != -1 && path.getRequestType() != requestType && path.getRequestType() != Constants.REQUEST_TYPE_ALL) {\n continue;\n }\n\n // first see if we get a match\n try {\n Pattern pattern = Pattern.compile(path.getPath());\n Matcher matcher = pattern.matcher(uri);\n\n // we won't select the path if there aren't any enabled endpoints in it\n // this works since the paths are returned in priority order\n if (matcher.find()) {\n // now see if this path has anything enabled in it\n // Only go into the if:\n // 1. There are enabled items in this path\n // 2. Caller was looking for ResponseOverride and Response is enabled OR looking for RequestOverride\n // 3. If pathTest is true then the rest of the conditions are not evaluated. The path tester ignores enabled states so everything is returned.\n // and request is enabled\n if (pathTest ||\n (path.getEnabledEndpoints().size() > 0 &&\n ((overrideType == Constants.OVERRIDE_TYPE_RESPONSE && path.getResponseEnabled()) ||\n (overrideType == Constants.OVERRIDE_TYPE_REQUEST && path.getRequestEnabled())))) {\n // if we haven't already seen a non global path\n // or if this is a global path\n // then add it to the list\n if (!foundRealPath || path.getGlobal()) {\n selectPaths.add(path);\n }\n }\n\n // we set this no matter what if a path matched and it was not the global path\n // this stops us from adding further non global matches to the list\n if (!path.getGlobal()) {\n foundRealPath = true;\n }\n }\n } catch (PatternSyntaxException pse) {\n // nothing to do but keep iterating over the list\n // this indicates an invalid regex\n }\n }\n\n return selectPaths;\n }",
"public IPlan[] getAgentPlans(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n plans = bia.getPlanbase().getPlans();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return plans;\n }",
"private int getItemViewType(Class prototypeClass) {\n int itemViewType = -1;\n for (Renderer renderer : prototypes) {\n if (renderer.getClass().equals(prototypeClass)) {\n itemViewType = getPrototypeIndex(renderer);\n break;\n }\n }\n if (itemViewType == -1) {\n throw new PrototypeNotFoundException(\n \"Review your RendererBuilder implementation, you are returning one\"\n + \" prototype class not found in prototypes collection\");\n }\n return itemViewType;\n }",
"private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}",
"public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }"
] |
Writes image files for all data that was collected and the statistics
file for all sites. | [
"private void writeImages() {\n\t\tfor (ValueMap gv : this.valueMaps) {\n\t\t\tgv.writeImage();\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"map-site-count.csv\"))) {\n\t\t\tout.println(\"Site key,Number of geo items\");\n\t\t\tout.println(\"wikidata total,\" + this.count);\n\t\t\tfor (Entry<String, Integer> entry : this.siteCounts.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\t}"
] | [
"private void populateResourceAssignmentWorkgroupFields(Record record, ResourceAssignmentWorkgroupFields workgroup) throws MPXJException\n {\n workgroup.setMessageUniqueID(record.getString(0));\n workgroup.setConfirmed(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setResponsePending(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setUpdateStart(record.getDateTime(3));\n workgroup.setUpdateFinish(record.getDateTime(4));\n workgroup.setScheduleID(record.getString(5));\n }",
"private int getBeliefCount() {\n Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT);\n if (count == null) count = 0; // Just in case, not really sure if this is necessary.\n return count;\n }",
"protected void setResults(GraphRewrite event, String variable, Iterable<? extends WindupVertexFrame> results)\n {\n Variables variables = Variables.instance(event);\n Iterable<? extends WindupVertexFrame> existingVariables = variables.findVariable(variable, 1);\n if (existingVariables != null)\n {\n variables.setVariable(variable, Iterables.concat(existingVariables, results));\n }\n else\n {\n variables.setVariable(variable, results);\n }\n }",
"private void handleIncomingRequestMessage(SerialMessage incomingMessage) {\n\t\tlogger.debug(\"Message type = REQUEST\");\n\t\tswitch (incomingMessage.getMessageClass()) {\n\t\t\tcase ApplicationCommandHandler:\n\t\t\t\thandleApplicationCommandRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase SendData:\n\t\t\t\thandleSendDataRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase ApplicationUpdate:\n\t\t\t\thandleApplicationUpdateRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tlogger.warn(String.format(\"TODO: Implement processing of Request Message = %s (0x%02X)\",\n\t\t\t\t\tincomingMessage.getMessageClass().getLabel(),\n\t\t\t\t\tincomingMessage.getMessageClass().getKey()));\n\t\t\tbreak;\t\n\t\t}\n\t}",
"public static final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }",
"public Entry<T>[] entries() {\n @SuppressWarnings(\"unchecked\")\n Entry<T>[] entries = new Entry[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n entries[idx++] = entry;\n entry = entry.next;\n }\n }\n return entries;\n }",
"public static lbvserver_rewritepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_rewritepolicy_binding obj = new lbvserver_rewritepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_rewritepolicy_binding response[] = (lbvserver_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static protocoludp_stats get(nitro_service service) throws Exception{\n\t\tprotocoludp_stats obj = new protocoludp_stats();\n\t\tprotocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"private File getDisabledMarkerFile(long version) throws PersistenceFailureException {\n File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (versionDirArray.length == 0) {\n throw new PersistenceFailureException(\"getDisabledMarkerFile did not find the requested version directory\" +\n \" on disk. Version: \" + version + \", rootDir: \" + rootDir);\n }\n File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME);\n return disabledMarkerFile;\n }"
] |
Add assignments to the tree.
@param parentNode parent tree node
@param file assignments container | [
"private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n final ResourceAssignment a = assignment;\n MpxjTreeNode childNode = new MpxjTreeNode(a)\n {\n @Override public String toString()\n {\n Resource resource = a.getResource();\n String resourceName = resource == null ? \"(unknown resource)\" : resource.getName();\n Task task = a.getTask();\n String taskName = task == null ? \"(unknown task)\" : task.getName();\n return resourceName + \"->\" + taskName;\n }\n };\n parentNode.add(childNode);\n }\n }"
] | [
"public String getString(int field)\n {\n String result;\n\n if (field < m_fields.length)\n {\n result = m_fields[field];\n\n if (result != null)\n {\n result = result.replace(MPXConstants.EOL_PLACEHOLDER, '\\n');\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public static void validateObserverMethod(ObserverMethod<?> observerMethod, BeanManager beanManager, ObserverMethod<?> originalObserverMethod) {\n Set<Annotation> qualifiers = observerMethod.getObservedQualifiers();\n if (observerMethod.getBeanClass() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getBeanClass\", observerMethod);\n }\n if (observerMethod.getObservedType() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getObservedType\", observerMethod);\n }\n Bindings.validateQualifiers(qualifiers, beanManager, observerMethod, \"ObserverMethod.getObservedQualifiers\");\n if (observerMethod.getReception() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getReception\", observerMethod);\n }\n if (observerMethod.getTransactionPhase() == null) {\n throw EventLogger.LOG.observerMethodsMethodReturnsNull(\"getTransactionPhase\", observerMethod);\n }\n if (originalObserverMethod != null && (!observerMethod.getBeanClass().equals(originalObserverMethod.getBeanClass()))) {\n throw EventLogger.LOG.beanClassMismatch(originalObserverMethod, observerMethod);\n }\n if (!(observerMethod instanceof SyntheticObserverMethod) && !hasNotifyOverriden(observerMethod.getClass(), observerMethod)) {\n throw EventLogger.LOG.notifyMethodNotImplemented(observerMethod);\n }\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 static FreeMarkerOperation create(Furnace furnace, String templatePath, String outputFilename,\n String... varNames)\n {\n return new FreeMarkerOperation(furnace, templatePath, outputFilename, varNames);\n }",
"public void assertGLThread() {\n if (Thread.currentThread().getId() != mGLThreadID) {\n RuntimeException e = new RuntimeException(\n \"Should not run GL functions from a non-GL thread!\");\n e.printStackTrace();\n throw e;\n }\n }",
"private List<Versioned<byte[]>> disassembleValues(byte[] values) throws IOException {\n\n if(values == null)\n return new ArrayList<Versioned<byte[]>>(0);\n\n List<Versioned<byte[]>> returnList = new ArrayList<Versioned<byte[]>>();\n ByteArrayInputStream stream = new ByteArrayInputStream(values);\n DataInputStream dataStream = new DataInputStream(stream);\n\n while(dataStream.available() > 0) {\n byte[] object = new byte[dataStream.readInt()];\n dataStream.read(object);\n\n byte[] clockBytes = new byte[dataStream.readInt()];\n dataStream.read(clockBytes);\n VectorClock clock = new VectorClock(clockBytes);\n\n returnList.add(new Versioned<byte[]>(object, clock));\n }\n\n return returnList;\n }",
"public static ModelNode getAccessControl(ModelControllerClient client, OperationRequestAddress address, boolean operations) {\n return getAccessControl(client, null, address, operations);\n }",
"public ActivityCodeValue addValue(Integer uniqueID, String name, String description)\n {\n ActivityCodeValue value = new ActivityCodeValue(this, uniqueID, name, description);\n m_values.add(value);\n return value;\n }",
"@SuppressWarnings(\"unchecked\")\n public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException {\n return mapperFor(parameterizedType).serialize(object);\n }"
] |
Sleeps if necessary to slow down the caller.
@param eventsSeen Number of events seen since last invocation. Basis for
determining whether its necessary to sleep. | [
"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 }"
] | [
"public void putBeanDeployments(BeanDeploymentArchiveMapping bdaMapping) {\n for (Entry<BeanDeploymentArchive, BeanManagerImpl> entry : bdaMapping.getBdaToBeanManagerMap().entrySet()) {\n beanDeploymentArchives.put(entry.getKey(), entry.getValue());\n addBeanManager(entry.getValue());\n }\n }",
"public static dbdbprofile[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tdbdbprofile[] response = (dbdbprofile[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) {\n \tMap<String, TermImpl> updatedValues = new HashMap<>();\n \tfor(NameWithUpdate update : updates.values()) {\n if (!update.write) {\n continue;\n }\n updatedValues.put(update.value.getLanguageCode(), monolingualToJackson(update.value));\n \t}\n \treturn updatedValues;\n }",
"public static transformpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\ttransformpolicylabel response = (transformpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private char getCachedCharValue(FieldType field, char defaultValue)\n {\n Character c = (Character) getCachedValue(field);\n return c == null ? defaultValue : c.charValue();\n }",
"private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) {\n final List<File> processed = new ArrayList<File>();\n List<File> reenabled = Collections.emptyList();\n List<File> disabled = Collections.emptyList();\n try {\n try {\n // Update the state to invalidate and process module resources\n if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n // Only invalidate modules when applying patches; on rollback files are immediately restored\n for (final File invalidation : moduleInvalidations) {\n processed.add(invalidation);\n PatchModuleInvalidationUtils.processFile(this, invalidation, mode);\n }\n if (!modulesToReenable.isEmpty()) {\n reenabled = new ArrayList<File>(modulesToReenable.size());\n for (final File path : modulesToReenable) {\n reenabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK);\n }\n }\n } else if(mode == PatchingTaskContext.Mode.ROLLBACK) {\n if (!modulesToDisable.isEmpty()) {\n disabled = new ArrayList<File>(modulesToDisable.size());\n for (final File path : modulesToDisable) {\n disabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY);\n }\n }\n }\n\n }\n modification.complete();\n callback.completed(this);\n state = State.COMPLETED;\n } catch (Exception e) {\n this.moduleInvalidations.clear();\n this.moduleInvalidations.addAll(processed);\n this.modulesToReenable.clear();\n this.modulesToReenable.addAll(reenabled);\n this.modulesToDisable.clear();\n this.moduleInvalidations.addAll(disabled);\n throw new RuntimeException(e);\n }\n } finally {\n if (state != State.COMPLETED) {\n try {\n modification.cancel();\n } finally {\n try {\n undoChanges();\n } finally {\n callback.operationCancelled(this);\n }\n }\n } else {\n try {\n if (checkForGarbageOnRestart) {\n final File cleanupMarker = new File(installedImage.getInstallationMetadata(), \"cleanup-patching-dirs\");\n cleanupMarker.createNewFile();\n }\n storeFailedRenaming();\n } catch (IOException e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to create cleanup marker\");\n }\n }\n }\n }",
"public static int findVerticalOffset(JRDesignBand band) {\n\t\tint finalHeight = 0;\n\t\tif (band != null) {\n\t\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\t\tJRDesignElement element = (JRDesignElement) jrChild;\n\t\t\t\tint currentHeight = element.getY() + element.getHeight();\n\t\t\t\tif (currentHeight > finalHeight) finalHeight = currentHeight;\n\t\t\t}\n\t\t\treturn finalHeight;\n\t\t}\n\t\treturn finalHeight;\n\t}",
"public static base_responses update(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable updateresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new bridgetable();\n\t\t\t\tupdateresources[i].bridgeage = resources[i].bridgeage;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private String quoteFormatCharacters(String literal)\n {\n StringBuilder sb = new StringBuilder();\n int length = literal.length();\n char c;\n\n for (int loop = 0; loop < length; loop++)\n {\n c = literal.charAt(loop);\n switch (c)\n {\n case '0':\n case '#':\n case '.':\n case '-':\n case ',':\n case 'E':\n case ';':\n case '%':\n {\n sb.append(\"'\");\n sb.append(c);\n sb.append(\"'\");\n break;\n }\n\n default:\n {\n sb.append(c);\n break;\n }\n }\n }\n\n return (sb.toString());\n }"
] |
Use this API to unset the properties of snmpmanager resource.
Properties that need to be unset are specified in args array. | [
"public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] | [
"public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }",
"@RequestMapping(value = \"/api/scripts\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getScripts(Model model,\n @RequestParam(required = false) Integer type) throws Exception {\n Script[] scripts = ScriptService.getInstance().getScripts(type);\n return Utils.getJQGridJSON(scripts, \"scripts\");\n }",
"public ItemRequest<Task> addTag(String task) {\n \n String path = String.format(\"/tasks/%s/addTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public Set<DeviceAnnouncement> findUnreachablePlayers() {\n ensureRunning();\n Set<DeviceAnnouncement> result = new HashSet<DeviceAnnouncement>();\n for (DeviceAnnouncement candidate: DeviceFinder.getInstance().getCurrentDevices()) {\n if (!Util.sameNetwork(matchedAddress.getNetworkPrefixLength(), matchedAddress.getAddress(), candidate.getAddress())) {\n result.add(candidate);\n }\n }\n return Collections.unmodifiableSet(result);\n }",
"public void writeTo(WritableByteChannel channel) throws IOException {\n for (ByteBuffer buffer : toDirectByteBuffers()) {\n channel.write(buffer);\n }\n }",
"public ItemRequest<Project> addCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/addCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }",
"public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }",
"public static InstalledIdentity load(final InstalledImage installedImage, final ProductConfig productConfig, List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n return LayersFactory.load(installedImage, productConfig, moduleRoots, bundleRoots);\n }",
"public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,\n ArtifactoryServer pipelineServer) {\n\n if (artifactoryServerID == null && pipelineServer == null) {\n return null;\n }\n if (artifactoryServerID != null && pipelineServer != null) {\n return null;\n }\n if (pipelineServer != null) {\n CredentialsConfig credentials = pipelineServer.createCredentialsConfig();\n\n return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,\n credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads());\n }\n org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());\n if (server == null) {\n return null;\n }\n return server;\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.