query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Checks to see if the rows of the provided matrix are linearly independent.
@param A Matrix whose rows are being tested for linear independence.
@return true if linearly independent and false otherwise. | [
"public static boolean isRowsLinearIndependent( DMatrixRMaj A )\n {\n // LU decomposition\n LUDecomposition<DMatrixRMaj> lu = DecompositionFactory_DDRM.lu(A.numRows,A.numCols);\n if( lu.inputModified() )\n A = A.copy();\n\n if( !lu.decompose(A))\n throw new RuntimeException(\"Decompositon failed?\");\n\n // if they are linearly independent it should not be singular\n return !lu.isSingular();\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 }",
"private String getSymbolName(char c)\n {\n String result = null;\n\n switch (c)\n {\n case ',':\n {\n result = \"Comma\";\n break;\n }\n\n case '.':\n {\n result = \"Period\";\n break;\n }\n }\n\n return result;\n }",
"public Class<E> getEventClass() {\n if (cachedClazz != null) {\n return cachedClazz;\n }\n Class<?> clazz = this.getClass();\n while (clazz != Object.class) {\n try {\n Type mySuperclass = clazz.getGenericSuperclass();\n Type tType = ((ParameterizedType) mySuperclass).getActualTypeArguments()[0];\n cachedClazz = (Class<E>) Class.forName(tType.getTypeName());\n return cachedClazz;\n } catch (Exception e) {\n }\n clazz = clazz.getSuperclass();\n }\n throw new IllegalStateException(\"Failed to load event class - \" + this.getClass().getCanonicalName());\n }",
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"attributes\");\n json.array();\n for (Map.Entry<String, Attribute> entry: this.attributes.entrySet()) {\n Attribute attribute = entry.getValue();\n if (attribute.getClass().getAnnotation(InternalAttribute.class) == null) {\n json.object();\n attribute.printClientConfig(json, this);\n json.endObject();\n }\n }\n json.endArray();\n }",
"public static void clear() {\n JobContext ctx = current_.get();\n if (null != ctx) {\n ctx.bag_.clear();\n JobContext parent = ctx.parent;\n if (null != parent) {\n current_.set(parent);\n ctx.parent = null;\n } else {\n current_.remove();\n Act.eventBus().trigger(new JobContextDestroyed(ctx));\n }\n }\n }",
"public List<Module> getModules(final Map<String, String> filters) throws GrapesCommunicationException {\n final Client client = getClient();\n WebResource resource = client.resource(serverURL).path(RequestUtils.getAllModulesPath());\n for(final Map.Entry<String,String> queryParam: filters.entrySet()){\n resource = resource.queryParam(queryParam.getKey(), queryParam.getValue());\n }\n\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get filtered modules.\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Module>>(){});\n }",
"public void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }",
"public static double SymmetricKullbackLeibler(double[] p, double[] q) {\n double dist = 0;\n for (int i = 0; i < p.length; i++) {\n dist += (p[i] - q[i]) * (Math.log(p[i]) - Math.log(q[i]));\n }\n\n return dist;\n }",
"public double[] 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}"
] |
Read an element which contains only a single list attribute of a given
type.
@param reader the reader
@param attributeName the attribute name, usually "value"
@param type the value type class
@param <T> the value type
@return the value list
@throws javax.xml.stream.XMLStreamException if an error occurs or if the
element does not contain the specified attribute, contains other
attributes, or contains child elements. | [
"@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }"
] | [
"protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }",
"protected void AddLODSceneObject(GVRSceneObject currentSceneObject) {\n if (this.transformLODSceneObject != null) {\n GVRSceneObject levelOfDetailSceneObject = null;\n if ( currentSceneObject.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = currentSceneObject;\n }\n else {\n GVRSceneObject lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_TRANSLATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_ROTATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_SCALE_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n\n }\n if ( levelOfDetailSceneObject != null) {\n final GVRLODGroup lodGroup = (GVRLODGroup) this.transformLODSceneObject.getComponent(GVRLODGroup.getComponentType());\n lodGroup.addRange(this.getMinRange(), levelOfDetailSceneObject);\n this.increment();\n }\n }\n }",
"private String readOptionalString(JSONObject json, String key, String defaultValue) {\n\n try {\n String str = json.getString(key);\n if (str != null) {\n return str;\n }\n\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON string failed. Default to provided default value.\", e);\n }\n return defaultValue;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal);\n }",
"static String findNonProgressingOp(Resource resource, boolean forServer, long timeout) throws OperationFailedException {\n\n Resource.ResourceEntry nonProgressing = null;\n for (Resource.ResourceEntry child : resource.getChildren(ACTIVE_OPERATION)) {\n ModelNode model = child.getModel();\n if (model.get(EXCLUSIVE_RUNNING_TIME).asLong() > timeout) {\n nonProgressing = child;\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"non-progressing op: %s\", nonProgressing.getModel());\n break;\n }\n }\n if (nonProgressing != null && !forServer) {\n // WFCORE-263\n // See if the op is non-progressing because it's the HC op waiting for commit\n // from the DC while other ops (i.e. ops proxied to our servers) associated\n // with the same domain-uuid are not completing\n ModelNode model = nonProgressing.getModel();\n if (model.get(DOMAIN_ROLLOUT).asBoolean()\n && OperationContext.ExecutionStatus.COMPLETING.toString().equals(model.get(EXECUTION_STATUS).asString())\n && model.hasDefined(DOMAIN_UUID)) {\n ControllerLogger.MGMT_OP_LOGGER.trace(\"Potential domain rollout issue\");\n String domainUUID = model.get(DOMAIN_UUID).asString();\n\n Set<String> relatedIds = null;\n List<Resource.ResourceEntry> relatedExecutingOps = null;\n for (Resource.ResourceEntry activeOp : resource.getChildren(ACTIVE_OPERATION)) {\n if (nonProgressing.getName().equals(activeOp.getName())) {\n continue; // ignore self\n }\n ModelNode opModel = activeOp.getModel();\n if (opModel.hasDefined(DOMAIN_UUID) && domainUUID.equals(opModel.get(DOMAIN_UUID).asString())\n && opModel.get(RUNNING_TIME).asLong() > timeout) {\n if (relatedIds == null) {\n relatedIds = new TreeSet<String>(); // order these as an aid to unit testing\n }\n relatedIds.add(activeOp.getName());\n\n // If the op is ExecutionStatus.EXECUTING that means it's still EXECUTING on the\n // server or a prepare message got lost. It would be COMPLETING if the server\n // had sent a prepare message, as that would result in ProxyStepHandler calling completeStep\n if (OperationContext.ExecutionStatus.EXECUTING.toString().equals(opModel.get(EXECUTION_STATUS).asString())) {\n if (relatedExecutingOps == null) {\n relatedExecutingOps = new ArrayList<Resource.ResourceEntry>();\n }\n relatedExecutingOps.add(activeOp);\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related non-executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"unrelated: %s\", opModel);\n }\n\n if (relatedIds != null) {\n // There are other ops associated with this domain-uuid that are also not completing\n // in the desired time, so we can't treat the one holding the lock as the problem.\n if (relatedExecutingOps != null && relatedExecutingOps.size() == 1) {\n // There's a single related op that's executing for too long. So we can report that one.\n // Note that it's possible that the same problem exists on other hosts as well\n // and that this cancellation will not resolve the overall problem. But, we only\n // get here on a slave HC and if the user is invoking this on a slave and not the\n // master, we'll assume they have a reason for doing that and want us to treat this\n // as a problem on this particular host.\n nonProgressing = relatedExecutingOps.get(0);\n } else {\n // Fail and provide a useful failure message.\n throw DomainManagementLogger.ROOT_LOGGER.domainRolloutNotProgressing(nonProgressing.getName(),\n timeout, domainUUID, relatedIds);\n }\n }\n }\n }\n\n return nonProgressing == null ? null : nonProgressing.getName();\n }",
"private Component createConvertToPropertyBundleButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.SETTINGS,\n m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n try {\n m_model.saveAsPropertyBundle();\n Notification.show(\"Conversion successful.\");\n } catch (CmsException | IOException e) {\n CmsVaadinUtils.showAlert(\"Conversion failed\", e.getLocalizedMessage(), null);\n }\n }\n });\n addDescriptorButton.setDisableOnClick(true);\n return addDescriptorButton;\n }",
"public PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {\n return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);\n }",
"public void removeCustomOverride(int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"custom_response\", \"\", getProfileIdFromPathID(path_id), client_uuid, path_id);\n }",
"public List<MapRow> readBlocks(Class<? extends BlockReader> readerClass) throws IOException\n {\n BlockReader reader;\n\n try\n {\n reader = readerClass.getConstructor(StreamReader.class).newInstance(this);\n }\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n return reader.read();\n }"
] |
Use this API to fetch all the lbvserver resources that are configured on netscaler. | [
"public static lbvserver[] get(nitro_service service) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\tlbvserver[] response = (lbvserver[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>\n getDonorsAndStealersForBalance(final Cluster nextCandidateCluster,\n Map<Integer, List<Integer>> numPartitionsPerNodePerZone) {\n HashMap<Node, Integer> donorNodes = Maps.newHashMap();\n HashMap<Node, Integer> stealerNodes = Maps.newHashMap();\n\n HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n numNodesAssignedInZone.put(zoneId, 0);\n }\n for(Node node: nextCandidateCluster.getNodes()) {\n int zoneId = node.getZoneId();\n\n int offset = numNodesAssignedInZone.get(zoneId);\n numNodesAssignedInZone.put(zoneId, offset + 1);\n\n int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset);\n\n if(numPartitions < node.getNumberOfPartitions()) {\n donorNodes.put(node, numPartitions);\n } else if(numPartitions > node.getNumberOfPartitions()) {\n stealerNodes.put(node, numPartitions);\n }\n }\n\n // Print out donor/stealer information\n for(Node node: donorNodes.keySet()) {\n System.out.println(\"Donor Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + donorNodes.get(node));\n }\n for(Node node: stealerNodes.keySet()) {\n System.out.println(\"Stealer Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + stealerNodes.get(node));\n }\n\n return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes);\n }",
"@Nullable\n public ResultT first() {\n final CoreRemoteMongoCursor<ResultT> cursor = iterator();\n if (!cursor.hasNext()) {\n return null;\n }\n return cursor.next();\n }",
"public void addRebalancingState(final RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n // Move into rebalancing state\n if(ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), \"UTF-8\")\n .compareTo(VoldemortState.NORMAL_SERVER.toString()) == 0) {\n put(SERVER_STATE_KEY, VoldemortState.REBALANCING_MASTER_SERVER);\n initCache(SERVER_STATE_KEY);\n }\n\n // Add the steal information\n RebalancerState rebalancerState = getRebalancerState();\n if(!rebalancerState.update(stealInfo)) {\n throw new VoldemortException(\"Could not add steal information \" + stealInfo\n + \" since a plan for the same donor node \"\n + stealInfo.getDonorId() + \" ( \"\n + rebalancerState.find(stealInfo.getDonorId())\n + \" ) already exists\");\n }\n put(MetadataStore.REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n } finally {\n writeLock.unlock();\n }\n }",
"private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }",
"public void setFieldByAlias(String alias, Object value)\n {\n set(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias), value);\n }",
"public Pixel[] pixels() {\n Pixel[] pixels = new Pixel[count()];\n Point[] points = points();\n for (int k = 0; k < points.length; k++) {\n pixels[k] = pixel(points[k]);\n }\n return pixels;\n }",
"public DbModule getModule(final String moduleId) {\n final DbModule dbModule = repositoryHandler.getModule(moduleId);\n\n if (dbModule == null) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Module \" + moduleId + \" does not exist.\").build());\n }\n\n return dbModule;\n }",
"public void stopServer() throws Exception {\n if (!externalDatabaseHost) {\n try (Connection sqlConnection = getConnection()) {\n sqlConnection.prepareStatement(\"SHUTDOWN\").execute();\n } catch (Exception e) {\n }\n\n try {\n server.stop();\n } catch (Exception e) {\n }\n }\n }",
"public static base_responses unset(nitro_service client, String name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (name != null && name.length > 0) {\n\t\t\tclusternodegroup unsetresources[] = new clusternodegroup[name.length];\n\t\t\tfor (int i=0;i<name.length;i++){\n\t\t\t\tunsetresources[i] = new clusternodegroup();\n\t\t\t\tunsetresources[i].name = name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] |
Quits server by closing server socket and closing client socket handlers. | [
"protected synchronized void quit() {\n log.debug(\"Stopping {}\", getName());\n closeServerSocket();\n\n // Close all handlers. Handler threads terminate if run loop exits\n synchronized (handlers) {\n for (ProtocolHandler handler : handlers) {\n handler.close();\n }\n handlers.clear();\n }\n log.debug(\"Stopped {}\", getName());\n }"
] | [
"private boolean isDebug(CmsObject cms, CmsSolrQuery query) {\r\n\r\n String[] debugSecretValues = query.remove(REQUEST_PARAM_DEBUG_SECRET);\r\n String debugSecret = (debugSecretValues == null) || (debugSecretValues.length < 1)\r\n ? null\r\n : debugSecretValues[0];\r\n if ((null != debugSecret) && !debugSecret.trim().isEmpty() && (null != m_handlerDebugSecretFile)) {\r\n try {\r\n CmsFile secretFile = cms.readFile(m_handlerDebugSecretFile);\r\n String secret = new String(secretFile.getContents(), CmsFileUtil.getEncoding(cms, secretFile));\r\n return secret.trim().equals(debugSecret.trim());\r\n } catch (Exception e) {\r\n LOG.info(\r\n \"Failed to read secret file for index \\\"\"\r\n + getName()\r\n + \"\\\" at path \\\"\"\r\n + m_handlerDebugSecretFile\r\n + \"\\\".\");\r\n }\r\n }\r\n return false;\r\n }",
"public void setFinalTransformMatrix(Matrix4f finalTransform)\n {\n float[] mat = new float[16];\n finalTransform.get(mat);\n NativeBone.setFinalTransformMatrix(getNative(), mat);\n }",
"public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}",
"public static <V> Map<V, V> convertListToMap(List<V> list) {\n Map<V, V> map = new HashMap<V, V>();\n if(list.size() % 2 != 0)\n throw new VoldemortException(\"Failed to convert list to map.\");\n for(int i = 0; i < list.size(); i += 2) {\n map.put(list.get(i), list.get(i + 1));\n }\n return map;\n }",
"private int getDaysToNextMatch(WeekDay weekDay) {\n\n for (WeekDay wd : m_weekDays) {\n if (wd.compareTo(weekDay) > 0) {\n return wd.toInt() - weekDay.toInt();\n }\n }\n return (m_weekDays.iterator().next().toInt() + (m_interval * I_CmsSerialDateValue.NUM_OF_WEEKDAYS))\n - weekDay.toInt();\n }",
"void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }",
"public void pauseUpload() throws LocalOperationException {\n if (state == State.UPLOADING) {\n setState(State.PAUSED);\n executor.hardStop();\n } else {\n throw new LocalOperationException(\"Attempt to pause upload while assembly is not uploading\");\n }\n }",
"public static Command newInsert(Object object,\n String outIdentifier,\n boolean returnObject,\n String entryPoint ) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier,\n returnObject,\n entryPoint );\n }",
"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}"
] |
Saves the current translations from the container to the respective localization. | [
"private void saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }"
] | [
"public static double huntKennedyCMSOptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble valueUnadjusted\t= blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t\tdouble valueAdjusted\t= blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);\n\n\t\treturn a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;\n\t}",
"public static void main(String[] args) {\r\n try {\r\n TreeFactory tf = new LabeledScoredTreeFactory();\r\n Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), \"UTF-8\"));\r\n TreeReader tr = new PennTreeReader(r, tf);\r\n Tree t = tr.readTree();\r\n while (t != null) {\r\n System.out.println(t);\r\n System.out.println();\r\n t = tr.readTree();\r\n }\r\n r.close();\r\n } catch (IOException ioe) {\r\n ioe.printStackTrace();\r\n }\r\n }",
"public Iterator select(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return this.query(predicate).iterator();\r\n }",
"public ItemRequest<Team> removeUser(String team) {\n \n String path = String.format(\"/teams/%s/removeUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }",
"public static void hideChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }",
"private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomTaskProperty property : gpTask.getCustomproperty())\n {\n Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_dateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjTask.set(item.getKey(), item.getValue());\n }\n }\n }",
"public static int cudnnGetCTCLossWorkspaceSize(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the\n timing steps, N is the mini batch size, A is the alphabet size) */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the\n dimensions are T,N,A. To compute costs\n only, set it to NULL */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n long[] sizeInBytes)/** pointer to the returned workspace size */\n {\n return checkResult(cudnnGetCTCLossWorkspaceSizeNative(handle, probsDesc, gradientsDesc, labels, labelLengths, inputLengths, algo, ctcLossDesc, sizeInBytes));\n }",
"public static Date max(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) > 0) ? d1 : d2;\n }\n return result;\n }",
"public boolean removePredecessor(Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = getPredecessors();\n if (!predecessorList.isEmpty())\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Ensure that there is a predecessor relationship between\n // these two tasks, and remove it.\n //\n matchFound = removeRelation(predecessorList, targetTask, type, lag);\n\n //\n // If we have removed a predecessor, then we must remove the\n // corresponding successor entry from the target task list\n //\n if (matchFound)\n {\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = targetTask.getSuccessors();\n if (!successorList.isEmpty())\n {\n //\n // Ensure that there is a successor relationship between\n // these two tasks, and remove it.\n //\n removeRelation(successorList, this, type, lag);\n }\n }\n }\n\n return matchFound;\n }"
] |
private multi-value handlers and helpers | [
"private void _handleMultiValues(ArrayList<String> values, String key, String command) {\n if (key == null) return;\n\n if (values == null || values.isEmpty()) {\n _generateEmptyMultiValueError(key);\n return;\n }\n\n ValidationResult vr;\n\n // validate the key\n vr = validator.cleanMultiValuePropertyKey(key);\n\n // Check for an error\n if (vr.getErrorCode() != 0) {\n pushValidationResult(vr);\n }\n\n // reset the key\n Object _key = vr.getObject();\n String cleanKey = (_key != null) ? vr.getObject().toString() : null;\n\n // if key is empty generate an error and return\n if (cleanKey == null || cleanKey.isEmpty()) {\n _generateInvalidMultiValueKeyError(key);\n return;\n }\n\n key = cleanKey;\n\n try {\n JSONArray currentValues = _constructExistingMultiValue(key, command);\n JSONArray newValues = _cleanMultiValues(values, key);\n _validateAndPushMultiValue(currentValues, newValues, values, key, command);\n\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Error handling multi value operation for key \" + key, t);\n }\n }"
] | [
"private void processHyperlinkData(ResourceAssignment assignment, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n\n offset += 12;\n String hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n String address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n String subaddress = MPPUtility.getUnicodeString(data, offset);\n offset += ((subaddress.length() + 1) * 2);\n\n offset += 12;\n String screentip = MPPUtility.getUnicodeString(data, offset);\n\n assignment.setHyperlink(hyperlink);\n assignment.setHyperlinkAddress(address);\n assignment.setHyperlinkSubAddress(subaddress);\n assignment.setHyperlinkScreenTip(screentip);\n }\n }",
"public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }",
"public static String eachMatch(String self, String regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n return eachMatch(self, Pattern.compile(regex), closure);\n }",
"public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }",
"private boolean fireEvent(Eventable eventable) {\n\t\tEventable eventToFire = eventable;\n\t\tif (eventable.getIdentification().getHow().toString().equals(\"xpath\")\n\t\t\t\t&& eventable.getRelatedFrame().equals(\"\")) {\n\t\t\teventToFire = resolveByXpath(eventable, eventToFire);\n\t\t}\n\t\tboolean isFired = false;\n\t\ttry {\n\t\t\tisFired = browser.fireEventAndWait(eventToFire);\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tif (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null\n\t\t\t\t\t&& \"A\".equals(eventToFire.getElement().getTag())) {\n\t\t\t\tisFired = visitAnchorHrefIfPossible(eventToFire);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Ignoring invisible element {}\", eventToFire.getElement());\n\t\t\t}\n\t\t} catch (InterruptedException e) {\n\t\t\tLOG.debug(\"Interrupted during fire event\");\n\t\t\tinterruptThread();\n\t\t\treturn false;\n\t\t}\n\n\t\tLOG.debug(\"Event fired={} for eventable {}\", isFired, eventable);\n\n\t\tif (isFired) {\n\t\t\t// Let the controller execute its specified wait operation on the browser thread safe.\n\t\t\twaitConditionChecker.wait(browser);\n\t\t\tbrowser.closeOtherWindows();\n\t\t\treturn true;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath\n\t\t\t * removed 1 state to represent the path TO here.\n\t\t\t */\n\t\t\tplugins.runOnFireEventFailedPlugins(context, eventable,\n\t\t\t\t\tcrawlpath.immutableCopyWithoutLast());\n\t\t\treturn false; // no event fired\n\t\t}\n\t}",
"public static nspbr6[] get(nitro_service service) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\tnspbr6[] response = (nspbr6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String marshal(Object object) {\n if (object == null) {\n return null;\n }\n\n try {\n JAXBContext jaxbCtx = JAXBContext.newInstance(object.getClass());\n\n Marshaller marshaller = jaxbCtx.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n\n StringWriter sw = new StringWriter();\n marshaller.marshal(object, sw);\n\n return sw.toString();\n } catch (Exception e) {\n }\n\n return null;\n }",
"protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) {\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n\n final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState();\n final String name = installedIdentity.getIdentity().getName();\n final IdentityImpl identity = new IdentityImpl(name, modification.getVersion());\n if (patchType == Patch.PatchType.CUMULATIVE) {\n identity.setPatchType(Patch.PatchType.CUMULATIVE);\n identity.setResultingVersion(installedIdentity.getIdentity().getVersion());\n } else if (patchType == Patch.PatchType.ONE_OFF) {\n identity.setPatchType(Patch.PatchType.ONE_OFF);\n }\n final List<ContentModification> modifications = identityEntry.rollbackActions;\n final Patch delegate = new PatchImpl(patchId, \"rollback patch\", identity, elements, modifications);\n return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity);\n }",
"public synchronized final void closeStream() {\n try {\n if ((stream != null) && (streamState == StreamStates.OPEN)) {\n stream.close();\n stream = null;\n }\n streamState = StreamStates.CLOSED;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }"
] |
Returns the association row with the given key.
@param key the key of the row to return.
@return the association row with the given key or {@code null} if no row with that key is contained in this
association | [
"public Tuple get(RowKey key) {\n\t\tAssociationOperation result = currentState.get( key );\n\t\tif ( result == null ) {\n\t\t\treturn cleared ? null : snapshot.get( key );\n\t\t}\n\t\telse if ( result.getType() == REMOVE ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn result.getValue();\n\t}"
] | [
"private ProjectFile handleSQLiteFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".sqlite\");\n\n try\n {\n Class.forName(\"org.sqlite.JDBC\");\n String url = \"jdbc:sqlite:\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseFileReader(), file);\n }\n\n if (tableNames.contains(\"PROJWBS\"))\n {\n Connection connection = null;\n try\n {\n Properties props = new Properties();\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n connection = DriverManager.getConnection(url, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(connection);\n addListeners(reader);\n return reader.read();\n }\n finally\n {\n if (connection != null)\n {\n connection.close();\n }\n }\n }\n\n if (tableNames.contains(\"ZSCHEDULEITEM\"))\n {\n return readProjectFile(new MerlinReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }",
"public CollectionRequest<Section> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new CollectionRequest<Section>(this, Section.class, path, \"GET\");\n }",
"public float getPositionZ(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"public static String formatAsStackTraceElement(InjectionPoint ij) {\n Member member;\n if (ij.getAnnotated() instanceof AnnotatedField) {\n AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated();\n member = annotatedField.getJavaMember();\n } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) {\n AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();\n member = annotatedParameter.getDeclaringCallable().getJavaMember();\n } else {\n // Not throwing an exception, because this method is invoked when an exception is already being thrown.\n // Throwing an exception here would hide the original exception.\n return \"-\";\n }\n return formatAsStackTraceElement(member);\n }",
"private void setExpressionForPrecalculatedTotalValue(\n\t\t\tDJCrosstabColumn[] auxCols, DJCrosstabRow[] auxRows, JRDesignExpression measureExp, DJCrosstabMeasure djmeasure,\n\t\t\tDJCrosstabColumn crosstabColumn, DJCrosstabRow crosstabRow, String meausrePrefix) {\n\n\t\tString rowValuesExp = \"new Object[]{\";\n\t\tString rowPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxRows.length; i++) {\n\t\t\tif (auxRows[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\trowValuesExp += \"$V{\" + auxRows[i].getProperty().getProperty() +\"}\";\n\t\t\trowPropsExp += \"\\\"\" + auxRows[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxRows.length && auxRows[i+1].getProperty()!= null){\n\t\t\t\trowValuesExp += \", \";\n\t\t\t\trowPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\trowValuesExp += \"}\";\n\t\trowPropsExp += \"}\";\n\n\t\tString colValuesExp = \"new Object[]{\";\n\t\tString colPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxCols.length; i++) {\n\t\t\tif (auxCols[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\tcolValuesExp += \"$V{\" + auxCols[i].getProperty().getProperty() +\"}\";\n\t\t\tcolPropsExp += \"\\\"\" + auxCols[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxCols.length && auxCols[i+1].getProperty()!= null){\n\t\t\t\tcolValuesExp += \", \";\n\t\t\t\tcolPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\tcolValuesExp += \"}\";\n\t\tcolPropsExp += \"}\";\n\n\t\tString measureProperty = meausrePrefix + djmeasure.getProperty().getProperty();\n\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_totalProvider}).getValueFor( \"\n\t\t+ colPropsExp +\", \"\n\t\t+ colValuesExp +\", \"\n\t\t+ rowPropsExp\n\t\t+ \", \"\n\t\t+ rowValuesExp\n\t\t+\" ))\";\n\n\t\tif (djmeasure.getValueFormatter() != null){\n\n\t\t\tString fieldsMap = ExpressionUtils.getTextForFieldsFromScriptlet();\n\t\t\tString parametersMap = ExpressionUtils.getTextForParametersFromScriptlet();\n\t\t\tString variablesMap = ExpressionUtils.getTextForVariablesFromScriptlet();\n\n\t\t\tString stringExpression = \"(((\"+DJValueFormatter.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_vf}).evaluate( \"\n\t\t\t\t+ \"(\"+expText+\"), \" + fieldsMap +\", \" + variablesMap + \", \" + parametersMap +\" ))\";\n\n\t\t\tmeasureExp.setText(stringExpression);\n\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t} else {\n\n//\t\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+djmeasure.getProperty().getProperty()+\"_totalProvider}).getValueFor( \"\n//\t\t\t+ colPropsExp +\", \"\n//\t\t\t+ colValuesExp +\", \"\n//\t\t\t+ rowPropsExp\n//\t\t\t+ \", \"\n//\t\t\t+ rowValuesExp\n//\t\t\t+\" ))\";\n//\n\t\t\tlog.debug(\"text for crosstab total provider is: \" + expText);\n\n\t\t\tmeasureExp.setText(expText);\n//\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t\tString valueClassNameForOperation = ExpressionUtils.getValueClassNameForOperation(djmeasure.getOperation(),djmeasure.getProperty());\n\t\t\tmeasureExp.setValueClassName(valueClassNameForOperation);\n\t\t}\n\n\t}",
"private PersistenceBrokerException createException(final Exception ex, String message, final Object objectToIdentify, Class topLevelClass, Class realClass, Object[] pks)\r\n {\r\n final String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer msg = new StringBuffer();\r\n if(message == null)\r\n {\r\n msg.append(\"Unexpected error: \");\r\n }\r\n else\r\n {\r\n msg.append(message).append(\" :\");\r\n }\r\n if(topLevelClass != null) msg.append(eol).append(\"objectTopLevelClass=\").append(topLevelClass.getName());\r\n if(realClass != null) msg.append(eol).append(\"objectRealClass=\").append(realClass.getName());\r\n if(pks != null) msg.append(eol).append(\"pkValues=\").append(ArrayUtils.toString(pks));\r\n if(objectToIdentify != null) msg.append(eol).append(\"object to identify: \").append(objectToIdentify);\r\n if(ex != null)\r\n {\r\n // add causing stack trace\r\n Throwable rootCause = ExceptionUtils.getRootCause(ex);\r\n if(rootCause != null)\r\n {\r\n msg.append(eol).append(\"The root stack trace is --> \");\r\n String rootStack = ExceptionUtils.getStackTrace(rootCause);\r\n msg.append(eol).append(rootStack);\r\n }\r\n\r\n return new PersistenceBrokerException(msg.toString(), ex);\r\n }\r\n else\r\n {\r\n return new PersistenceBrokerException(msg.toString());\r\n }\r\n }",
"private void beginInternTransaction()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"beginInternTransaction was called\");\r\n J2EETransactionImpl tx = (J2EETransactionImpl) super.currentTransaction();\r\n if (tx == null) tx = newInternTransaction();\r\n if (!tx.isOpen())\r\n {\r\n // start the transaction\r\n tx.begin();\r\n tx.setInExternTransaction(true);\r\n }\r\n }",
"@Override\n public AuthInterface getAuthInterface() {\n if (authInterface == null) {\n authInterface = new AuthInterface(apiKey, sharedSecret, transport);\n }\n return authInterface;\n }",
"public LayerType toDto(Class<? extends com.vividsolutions.jts.geom.Geometry> geometryClass) {\n\t\tif (geometryClass == LineString.class) {\n\t\t\treturn LayerType.LINESTRING;\n\t\t} else if (geometryClass == MultiLineString.class) {\n\t\t\treturn LayerType.MULTILINESTRING;\n\t\t} else if (geometryClass == Point.class) {\n\t\t\treturn LayerType.POINT;\n\t\t} else if (geometryClass == MultiPoint.class) {\n\t\t\treturn LayerType.MULTIPOINT;\n\t\t} else if (geometryClass == Polygon.class) {\n\t\t\treturn LayerType.POLYGON;\n\t\t} else if (geometryClass == MultiPolygon.class) {\n\t\t\treturn LayerType.MULTIPOLYGON;\n\t\t} else {\n\t\t\treturn LayerType.GEOMETRY;\n\t\t}\n\t}"
] |
Write correlation id to message.
@param message the message
@param correlationId the correlation id | [
"public static void writeCorrelationId(Message message, String correlationId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage) message;\n Header hdCorrelationId = soapMessage.getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n if ((soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) != null)\n && (soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) instanceof SAAJStreamWriter)\n && (((SAAJStreamWriter) soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class))\n .getDocument()\n .getElementsByTagNameNS(\"http://www.talend.com/esb/sam/correlationId/v1\",\n \"correlationId\").getLength() > 0)) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(CORRELATION_ID_QNAME, correlationId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored correlationId '\" + correlationId + \"' in soap header: \"\n + CORRELATION_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create correlationId header.\", e);\n }\n\n }"
] | [
"public static <T> int indexOf(T[] array, T element) {\n\t\tfor ( int i = 0; i < array.length; i++ ) {\n\t\t\tif ( array[i].equals( element ) ) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}",
"public static cmppolicy_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tcmppolicy_stats[] response = (cmppolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static base_response unset(nitro_service client, onlinkipv6prefix resource, String[] args) throws Exception{\n\t\tonlinkipv6prefix unsetresource = new onlinkipv6prefix();\n\t\tunsetresource.ipv6prefix = resource.ipv6prefix;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"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 }",
"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 void setAmbientIntensity(float r, float g, float b, float a) {\n setVec4(\"ambient_intensity\", r, g, b, a);\n }",
"private List<Entry> getChildNodes(DirectoryEntry parent)\n {\n List<Entry> result = new ArrayList<Entry>();\n Iterator<Entry> entries = parent.getEntries();\n while (entries.hasNext())\n {\n result.add(entries.next());\n }\n return result;\n }",
"private static int blockLength(int start, QrMode[] inputMode) {\n\n QrMode mode = inputMode[start];\n int count = 0;\n int i = start;\n\n do {\n count++;\n } while (((i + count) < inputMode.length) && (inputMode[i + count] == mode));\n\n return count;\n }",
"public static String next(CharSequence self) {\n StringBuilder buffer = new StringBuilder(self);\n if (buffer.length() == 0) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char last = buffer.charAt(buffer.length() - 1);\n if (last == Character.MAX_VALUE) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char next = last;\n next++;\n buffer.setCharAt(buffer.length() - 1, next);\n }\n }\n return buffer.toString();\n }"
] |
With the QR algorithm it is possible for the found singular values to be native. This
makes them all positive by multiplying it by a diagonal matrix that has | [
"private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = singularValues[i];\n\n if( val < 0 ) {\n singularValues[i] = -val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.data[j] = -Ut.data[j];\n }\n }\n }\n }\n }"
] | [
"public void inverse(GVRPose src)\n {\n if (getSkeleton() != src.getSkeleton())\n throw new IllegalArgumentException(\"GVRPose.copy: input pose is incompatible with this pose\");\n src.sync();\n int numbones = getNumBones();\n Bone srcBone = src.mBones[0];\n Bone dstBone = mBones[0];\n\n mNeedSync = true;\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n srcBone.LocalMatrix.set(dstBone.WorldMatrix);\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(0), dstBone.toString());\n\n }\n for (int i = 1; i < numbones; ++i)\n {\n srcBone = src.mBones[i];\n dstBone = mBones[i];\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n dstBone.Changed = WORLD_ROT | WORLD_POS;\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(i), dstBone.toString());\n }\n }\n sync();\n }",
"public String format(final LoggingEvent event) {\n\t\tfinal StringBuffer buf = new StringBuffer();\n\t\tfor (PatternConverter c = head; c != null; c = c.next) {\n\t\t\tc.format(buf, event);\n\t\t}\n\t\treturn buf.toString();\n\t}",
"private void removeAllBroadcasts(Set<String> sessionIds) {\n\n if (sessionIds == null) {\n for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos()) {\n OpenCms.getSessionManager().getBroadcastQueue(info.getSessionId().getStringValue()).clear();\n }\n return;\n }\n for (String sessionId : sessionIds) {\n OpenCms.getSessionManager().getBroadcastQueue(sessionId).clear();\n }\n }",
"private final boolean parseBoolean(String value)\n {\n return value != null && (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"y\") || value.equalsIgnoreCase(\"yes\"));\n }",
"public static base_response update(nitro_service client, nd6ravariables resource) throws Exception {\n\t\tnd6ravariables updateresource = new nd6ravariables();\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.ceaserouteradv = resource.ceaserouteradv;\n\t\tupdateresource.sendrouteradv = resource.sendrouteradv;\n\t\tupdateresource.srclinklayeraddroption = resource.srclinklayeraddroption;\n\t\tupdateresource.onlyunicastrtadvresponse = resource.onlyunicastrtadvresponse;\n\t\tupdateresource.managedaddrconfig = resource.managedaddrconfig;\n\t\tupdateresource.otheraddrconfig = resource.otheraddrconfig;\n\t\tupdateresource.currhoplimit = resource.currhoplimit;\n\t\tupdateresource.maxrtadvinterval = resource.maxrtadvinterval;\n\t\tupdateresource.minrtadvinterval = resource.minrtadvinterval;\n\t\tupdateresource.linkmtu = resource.linkmtu;\n\t\tupdateresource.reachabletime = resource.reachabletime;\n\t\tupdateresource.retranstime = resource.retranstime;\n\t\tupdateresource.defaultlifetime = resource.defaultlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}",
"protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException {\n // verify that the resource exist before removing it\n context.readResource(PathAddress.EMPTY_ADDRESS, false);\n Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS);\n recordCapabilitiesAndRequirements(context, operation, resource);\n }",
"private String storageOverhead(Map<Integer, Integer> finalNodeToOverhead) {\n double maxOverhead = Double.MIN_VALUE;\n PartitionBalance pb = new PartitionBalance(currentCluster, currentStoreDefs);\n StringBuilder sb = new StringBuilder();\n sb.append(\"Per-node store-overhead:\").append(Utils.NEWLINE);\n DecimalFormat doubleDf = new DecimalFormat(\"####.##\");\n for(int nodeId: finalCluster.getNodeIds()) {\n Node node = finalCluster.getNodeById(nodeId);\n String nodeTag = \"Node \" + String.format(\"%4d\", nodeId) + \" (\" + node.getHost() + \")\";\n int initialLoad = 0;\n if(currentCluster.getNodeIds().contains(nodeId)) {\n initialLoad = pb.getNaryPartitionCount(nodeId);\n }\n int toLoad = 0;\n if(finalNodeToOverhead.containsKey(nodeId)) {\n toLoad = finalNodeToOverhead.get(nodeId);\n }\n double overhead = (initialLoad + toLoad) / (double) initialLoad;\n if(initialLoad > 0 && maxOverhead < overhead) {\n maxOverhead = overhead;\n }\n\n String loadTag = String.format(\"%6d\", initialLoad) + \" + \"\n + String.format(\"%6d\", toLoad) + \" -> \"\n + String.format(\"%6d\", initialLoad + toLoad) + \" (\"\n + doubleDf.format(overhead) + \" X)\";\n sb.append(nodeTag + \" : \" + loadTag).append(Utils.NEWLINE);\n }\n sb.append(Utils.NEWLINE)\n .append(\"**** Max per-node storage overhead: \" + doubleDf.format(maxOverhead) + \" X.\")\n .append(Utils.NEWLINE);\n return (sb.toString());\n }",
"final void dispatchToAppender(final LoggingEvent customLoggingEvent) {\n // wrap the LoggingEvent in a FileRollEvent to prevent recursion bug\n final FoundationFileRollingAppender appender = this.getSource();\n if (appender != null) {\n appender.append(new FileRollEvent(customLoggingEvent, this));\n }\n }",
"private void checkAndAddLengths(final int... requiredLengths) {\n\t\tfor( final int length : requiredLengths ) {\n\t\t\tif( length < 0 ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\"required length cannot be negative but was %d\",\n\t\t\t\t\tlength));\n\t\t\t}\n\t\t\tthis.requiredLengths.add(length);\n\t\t}\n\t}"
] |
Use this API to fetch a dnsglobal_binding resource . | [
"public static dnsglobal_binding get(nitro_service service) throws Exception{\n\t\tdnsglobal_binding obj = new dnsglobal_binding();\n\t\tdnsglobal_binding response = (dnsglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"protected void layoutGroupFooterLabels(DJGroup djgroup, JRDesignGroup jgroup, int x, int y, int width, int height) {\n\t\t//List footerVariables = djgroup.getFooterVariables();\n\t\tDJGroupLabel label = djgroup.getFooterLabel();\n\n\t\t//if (label == null || footerVariables.isEmpty())\n\t\t\t//return;\n\n\t\t//PropertyColumn col = djgroup.getColumnToGroupBy();\n\t\tJRDesignBand band = LayoutUtils.getBandFromSection((JRDesignSection) jgroup.getGroupFooterSection());\n\n//\t\tlog.debug(\"Adding footer group label for group \" + djgroup);\n\n\t\t/*DJGroupVariable lmvar = findLeftMostColumn(footerVariables);\n\t\tAbstractColumn lmColumn = lmvar.getColumnToApplyOperation();\n\t\tint width = lmColumn.getPosX().intValue() - col.getPosX().intValue();\n\n\t\tint yOffset = findYOffsetForGroupLabel(band);*/\n\n\t\tJRDesignExpression labelExp;\n\t\tif (label.isJasperExpression()) //a text with things like \"$F{myField}\"\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(label.getText());\n\t\telse if (label.getLabelExpression() != null){\n\t\t\tlabelExp = ExpressionUtils.createExpression(jgroup.getName() + \"_labelExpression\", label.getLabelExpression(), true);\n\t\t} else //a simple text\n\t\t\t//labelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ Utils.escapeTextForExpression(label.getText())+ \"\\\"\");\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ label.getText() + \"\\\"\");\n\t\tJRDesignTextField labelTf = new JRDesignTextField();\n\t\tlabelTf.setExpression(labelExp);\n\t\tlabelTf.setWidth(width);\n\t\tlabelTf.setHeight(height);\n\t\tlabelTf.setX(x);\n\t\tlabelTf.setY(y);\n\t\t//int yOffsetGlabel = labelTf.getHeight();\n\t\tlabelTf.setPositionType( PositionTypeEnum.FIX_RELATIVE_TO_TOP );\n\t\tapplyStyleToElement(label.getStyle(), labelTf);\n\t\tband.addElement(labelTf);\n\t}",
"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 static void main(String[] args) throws LoginFailedException,\n\t\t\tIOException, MediaWikiApiErrorException {\n\t\tExampleHelpers.configureLogging();\n\t\tprintDocumentation();\n\n\t\tSetLabelsForNumbersBot bot = new SetLabelsForNumbersBot();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(bot);\n\t\tbot.finish();\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}",
"@Pure\n\tpublic static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure1<P2>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p) {\n\t\t\t\tprocedure.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}",
"public List<MapRow> read() throws IOException\n {\n List<MapRow> result = new ArrayList<MapRow>();\n int fileCount = m_stream.readInt();\n if (fileCount != 0)\n {\n for (int index = 0; index < fileCount; index++)\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 readBlock(map);\n result.add(new MapRow(map));\n }\n }\n return result;\n }",
"@JsonProperty(\"aliases\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, List<TermImpl>> getAliasUpdates() {\n \t\n \tMap<String, List<TermImpl>> updatedValues = new HashMap<>();\n \tfor(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) {\n \t\tAliasesWithUpdate update = entry.getValue();\n \t\tif (!update.write) {\n \t\t\tcontinue;\n \t\t}\n \t\tList<TermImpl> convertedAliases = new ArrayList<>();\n \t\tfor(MonolingualTextValue alias : update.aliases) {\n \t\t\tconvertedAliases.add(monolingualToJackson(alias));\n \t\t}\n \t\tupdatedValues.put(entry.getKey(), convertedAliases);\n \t}\n \treturn updatedValues;\n }",
"private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {\n /* bring together same type blocks */\n if (index_point > 1) {\n for (int i = 1; i < index_point; i++) {\n if (mode_type[i - 1] == mode_type[i]) {\n /* bring together */\n mode_length[i - 1] = mode_length[i - 1] + mode_length[i];\n /* decrease the list */\n for (int j = i + 1; j < index_point; j++) {\n mode_length[j - 1] = mode_length[j];\n mode_type[j - 1] = mode_type[j];\n }\n index_point--;\n i--;\n }\n }\n }\n return index_point;\n }",
"public static String[] addStringToArray(String[] array, String str) {\n if (isEmpty(array)) {\n return new String[]{str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }",
"private void initPixelsArray(BufferedImage image) {\n int width = image.getWidth();\n int height = image.getHeight();\n pixels = new int[width * height];\n image.getRGB(0, 0, width, height, pixels, 0, width);\n\n }"
] |
Loads the properties file using the classloader provided. Creating a string from the properties
"user.agent.name" and "user.agent.version".
@param loader The class loader to use to load the resource.
@param filename The name of the file to load.
@return A string that represents the first part of the UA string eg java-cloudant/2.6.1 | [
"private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }"
] | [
"public static boolean invert(final DMatrixRMaj cov , final DMatrixRMaj cov_inv ) {\n if( cov.numCols <= 4 ) {\n if( cov.numCols != cov.numRows ) {\n throw new IllegalArgumentException(\"Must be a square matrix.\");\n }\n\n if( cov.numCols >= 2 )\n UnrolledInverseFromMinor_DDRM.inv(cov,cov_inv);\n else\n cov_inv.data[0] = 1.0/cov.data[0];\n\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.symmPosDef(cov.numRows);\n // wrap it to make sure the covariance is not modified.\n solver = new LinearSolverSafe<DMatrixRMaj>(solver);\n if( !solver.setA(cov) )\n return false;\n solver.invert(cov_inv);\n }\n return true;\n }",
"public static final String getString(byte[] data, int offset)\n {\n return getString(data, offset, data.length - offset);\n }",
"@JmxOperation(description = \"swapFiles changes this store to use the new data directory\")\n public void swapFiles(String newStoreDirectory) {\n logger.info(\"Swapping files for store '\" + getName() + \"' to \" + newStoreDirectory);\n File newVersionDir = new File(newStoreDirectory);\n\n if(!newVersionDir.exists())\n throw new VoldemortException(\"File \" + newVersionDir.getAbsolutePath()\n + \" does not exist.\");\n\n if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))\n throw new VoldemortException(\"Invalid version folder name '\"\n + newVersionDir\n + \"'. Either parent directory is incorrect or format(version-n) is incorrect\");\n\n // retrieve previous version for (a) check if last write is winning\n // (b) if failure, rollback use\n File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n if(previousVersionDir == null)\n throw new VoldemortException(\"Could not find any latest directory to swap with in store '\"\n + getName() + \"'\");\n\n long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);\n long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);\n if(newVersionId == -1 || previousVersionId == -1)\n throw new VoldemortException(\"Unable to parse folder names (\" + newVersionDir.getName()\n + \",\" + previousVersionDir.getName()\n + \") since format(version-n) is incorrect\");\n\n // check if we're greater than latest since we want last write to win\n if(previousVersionId > newVersionId) {\n logger.info(\"No swap required since current latest version \" + previousVersionId\n + \" is greater than swap version \" + newVersionId);\n deleteBackups();\n return;\n }\n\n logger.info(\"Acquiring write lock on '\" + getName() + \"':\");\n fileModificationLock.writeLock().lock();\n boolean success = false;\n try {\n close();\n logger.info(\"Opening primary files for store '\" + getName() + \"' at \"\n + newStoreDirectory);\n\n // open the latest store\n open(newVersionDir);\n success = true;\n } finally {\n try {\n // we failed to do the swap, attempt a rollback to last version\n if(!success)\n rollback(previousVersionDir);\n\n } finally {\n fileModificationLock.writeLock().unlock();\n if(success)\n logger.info(\"Swap operation completed successfully on store \" + getName()\n + \", releasing lock.\");\n else\n logger.error(\"Swap operation failed.\");\n }\n }\n\n // okay we have released the lock and the store is now open again, it is\n // safe to do a potentially slow delete if we have one too many backups\n deleteBackups();\n }",
"public void updateLinks(ServiceReference<S> serviceReference) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);\n boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);\n if (isAlreadyLinked && !canBeLinked) {\n linkerManagement.unlink(declaration, serviceReference);\n } else if (!isAlreadyLinked && canBeLinked) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }",
"protected void layoutGroupFooterLabels(DJGroup djgroup, JRDesignGroup jgroup, int x, int y, int width, int height) {\n\t\t//List footerVariables = djgroup.getFooterVariables();\n\t\tDJGroupLabel label = djgroup.getFooterLabel();\n\n\t\t//if (label == null || footerVariables.isEmpty())\n\t\t\t//return;\n\n\t\t//PropertyColumn col = djgroup.getColumnToGroupBy();\n\t\tJRDesignBand band = LayoutUtils.getBandFromSection((JRDesignSection) jgroup.getGroupFooterSection());\n\n//\t\tlog.debug(\"Adding footer group label for group \" + djgroup);\n\n\t\t/*DJGroupVariable lmvar = findLeftMostColumn(footerVariables);\n\t\tAbstractColumn lmColumn = lmvar.getColumnToApplyOperation();\n\t\tint width = lmColumn.getPosX().intValue() - col.getPosX().intValue();\n\n\t\tint yOffset = findYOffsetForGroupLabel(band);*/\n\n\t\tJRDesignExpression labelExp;\n\t\tif (label.isJasperExpression()) //a text with things like \"$F{myField}\"\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(label.getText());\n\t\telse if (label.getLabelExpression() != null){\n\t\t\tlabelExp = ExpressionUtils.createExpression(jgroup.getName() + \"_labelExpression\", label.getLabelExpression(), true);\n\t\t} else //a simple text\n\t\t\t//labelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ Utils.escapeTextForExpression(label.getText())+ \"\\\"\");\n\t\t\tlabelExp = ExpressionUtils.createStringExpression(\"\\\"\"+ label.getText() + \"\\\"\");\n\t\tJRDesignTextField labelTf = new JRDesignTextField();\n\t\tlabelTf.setExpression(labelExp);\n\t\tlabelTf.setWidth(width);\n\t\tlabelTf.setHeight(height);\n\t\tlabelTf.setX(x);\n\t\tlabelTf.setY(y);\n\t\t//int yOffsetGlabel = labelTf.getHeight();\n\t\tlabelTf.setPositionType( PositionTypeEnum.FIX_RELATIVE_TO_TOP );\n\t\tapplyStyleToElement(label.getStyle(), labelTf);\n\t\tband.addElement(labelTf);\n\t}",
"public void close() {\n logger.info(\"Closing all sync producers\");\n if (sync) {\n for (SyncProducer p : syncProducers.values()) {\n p.close();\n }\n } else {\n for (AsyncProducer<V> p : asyncProducers.values()) {\n p.close();\n }\n }\n\n }",
"public static void checkStringNotNullOrEmpty(String parameterName,\n String value) {\n if (TextUtils.isEmpty(value)) {\n throw Exceptions.IllegalArgument(\"Current input string %s is %s.\",\n parameterName, value == null ? \"null\" : \"empty\");\n }\n }",
"protected void endDragging(MouseUpEvent event) {\n\n m_dragging = false;\n DOM.releaseCapture(getElement());\n removeStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging());\n }",
"public static String getTitleGalleryKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(GUI_TITLE_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }"
] |
Invokes the method on the class of the passed instance, not the declaring
class. Useful with proxies
@param instance The instance to invoke
@param manager The Bean manager
@return A reference to the instance | [
"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 Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }",
"public Duration getTotalSlack()\n {\n Duration totalSlack = (Duration) getCachedValue(TaskField.TOTAL_SLACK);\n if (totalSlack == null)\n {\n Duration duration = getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n TimeUnit units = duration.getUnits();\n\n Duration startSlack = getStartSlack();\n if (startSlack == null)\n {\n startSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (startSlack.getUnits() != units)\n {\n startSlack = startSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n Duration finishSlack = getFinishSlack();\n if (finishSlack == null)\n {\n finishSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (finishSlack.getUnits() != units)\n {\n finishSlack = finishSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n double startSlackDuration = startSlack.getDuration();\n double finishSlackDuration = finishSlack.getDuration();\n\n if (startSlackDuration == 0 || finishSlackDuration == 0)\n {\n if (startSlackDuration != 0)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n else\n {\n if (startSlackDuration < finishSlackDuration)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n\n set(TaskField.TOTAL_SLACK, totalSlack);\n }\n\n return (totalSlack);\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 static int[] convertBytesToInts(byte[] bytes)\n {\n if (bytes.length % 4 != 0)\n {\n throw new IllegalArgumentException(\"Number of input bytes must be a multiple of 4.\");\n }\n int[] ints = new int[bytes.length / 4];\n for (int i = 0; i < ints.length; i++)\n {\n ints[i] = convertBytesToInt(bytes, i * 4);\n }\n return ints;\n }",
"public String makeReport(String name, String report) {\n long increment = Long.valueOf(report);\n long currentLineCount = globalLineCounter.addAndGet(increment);\n\n if (currentLineCount >= maxScenarios) {\n return \"exit\";\n } else {\n return \"ok\";\n }\n }",
"static String[] tokenize(String str) {\n char sep = '.';\n int start = 0;\n int len = str.length();\n int count = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n count++;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n count++;\n }\n String[] l = new String[count];\n\n count = 0;\n start = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n String tok = str.substring(start, pos);\n l[count++] = tok;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n String tok = str.substring(start);\n l[count/* ++ */] = tok;\n }\n return l;\n }",
"private void injectAdditionalStyles() {\n\n try {\n Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();\n for (String stylesheet : stylesheets) {\n A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }",
"protected void mergeVerticalBlocks() {\n for(int i = 0; i < rectangles.size() - 1; i++) {\n for(int j = i + 1; j < rectangles.size(); j++) {\n Rectangle2D.Double firstRect = rectangles.get(i);\n Rectangle2D.Double secondRect = rectangles.get(j);\n if (roughlyEqual(firstRect.x, secondRect.x) && roughlyEqual(firstRect.width, secondRect.width)) {\n if (roughlyEqual(firstRect.y + firstRect.height, secondRect.y)) {\n firstRect.height += secondRect.height;\n rectangles.set(i, firstRect);\n rectangles.remove(j);\n }\n }\n }\n }\n }",
"final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }"
] |
Fetches the current online data for the given item, and adds numerical
labels if necessary.
@param itemIdValue
the id of the document to inspect | [
"protected void addLabelForNumbers(ItemIdValue itemIdValue) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if we still have exactly one numeric value:\n\t\t\tQuantityValue number = currentItemDocument\n\t\t\t\t\t.findStatementQuantityValue(\"P1181\");\n\t\t\tif (number == null) {\n\t\t\t\tSystem.out.println(\"*** No unique numeric value for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the item is in a known numeric class:\n\t\t\tif (!currentItemDocument.hasStatementValue(\"P31\", numberClasses)) {\n\t\t\t\tSystem.out\n\t\t\t\t\t\t.println(\"*** \"\n\t\t\t\t\t\t\t\t+ qid\n\t\t\t\t\t\t\t\t+ \" is not in a known class of integer numbers. Skipping.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the value is integer and build label string:\n\t\t\tString numberString;\n\t\t\ttry {\n\t\t\t\tBigInteger intValue = number.getNumericValue()\n\t\t\t\t\t\t.toBigIntegerExact();\n\t\t\t\tnumberString = intValue.toString();\n\t\t\t} catch (ArithmeticException e) {\n\t\t\t\tSystem.out.println(\"*** Numeric value for \" + qid\n\t\t\t\t\t\t+ \" is not an integer: \" + number.getNumericValue());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Construct data to write:\n\t\t\tItemDocumentBuilder itemDocumentBuilder = ItemDocumentBuilder\n\t\t\t\t\t.forItemId(itemIdValue).withRevisionId(\n\t\t\t\t\t\t\tcurrentItemDocument.getRevisionId());\n\t\t\tArrayList<String> languages = new ArrayList<>(\n\t\t\t\t\tarabicNumeralLanguages.length);\n\t\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\t\tif (!currentItemDocument.getLabels().containsKey(\n\t\t\t\t\t\tarabicNumeralLanguages[i])) {\n\t\t\t\t\titemDocumentBuilder.withLabel(numberString,\n\t\t\t\t\t\t\tarabicNumeralLanguages[i]);\n\t\t\t\t\tlanguages.add(arabicNumeralLanguages[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (languages.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** Labels already complete for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tnumberString, languages);\n\n\t\t\tdataEditor.editItemDocument(itemDocumentBuilder.build(), false,\n\t\t\t\t\t\"Set labels to numeric value (Task MB1)\");\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}"
] | [
"private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }",
"public Set<Action.ActionEffect> getActionEffects() {\n switch(getImpact()) {\n case CLASSLOADING:\n case WRITE:\n return WRITES;\n case READ_ONLY:\n return READS;\n default:\n throw new IllegalStateException();\n }\n\n }",
"public URL getDownloadURL() {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n request.setFollowRedirects(false);\n\n BoxRedirectResponse response = (BoxRedirectResponse) request.send();\n\n return response.getRedirectURL();\n }",
"public static long count(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_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 static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags)\n );\n }",
"protected Boolean getIgnoreReleaseDate() {\n\n Boolean isIgnoreReleaseDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_RELEASE_DATE);\n return (null == isIgnoreReleaseDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreReleaseDate())\n : isIgnoreReleaseDate;\n }",
"static void cleanup(final Resource resource) {\n synchronized (resource) {\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBSYSTEM)) {\n resource.removeChild(entry.getPathElement());\n }\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBDEPLOYMENT)) {\n resource.removeChild(entry.getPathElement());\n }\n }\n }",
"public long getLong(Integer type)\n {\n long result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getLong6(item, 0);\n }\n\n return (result);\n }",
"private CmsVfsEntryBean buildVfsEntryBeanForQuickSearch(\n CmsResource resource,\n Multimap<CmsResource, CmsResource> childMap,\n Set<CmsResource> filterMatches,\n Set<String> parentPaths,\n boolean isRoot)\n throws CmsException {\n\n CmsObject cms = getCmsObject();\n String title = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();\n boolean isMatch = filterMatches.contains(resource);\n List<CmsVfsEntryBean> childBeans = Lists.newArrayList();\n\n Collection<CmsResource> children = childMap.get(resource);\n if (!children.isEmpty()) {\n for (CmsResource child : children) {\n CmsVfsEntryBean childBean = buildVfsEntryBeanForQuickSearch(\n child,\n childMap,\n filterMatches,\n parentPaths,\n false);\n childBeans.add(childBean);\n }\n } else if (filterMatches.contains(resource)) {\n if (parentPaths.contains(resource.getRootPath())) {\n childBeans = null;\n }\n // otherwise childBeans remains an empty list\n }\n\n String rootPath = resource.getRootPath();\n CmsVfsEntryBean result = new CmsVfsEntryBean(\n rootPath,\n resource.getStructureId(),\n title,\n CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), true),\n isRoot,\n isEditable(cms, resource),\n childBeans,\n isMatch);\n String siteRoot = null;\n if (OpenCms.getSiteManager().startsWithShared(rootPath)) {\n siteRoot = OpenCms.getSiteManager().getSharedFolder();\n } else {\n String tempSiteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);\n if (tempSiteRoot != null) {\n siteRoot = tempSiteRoot;\n } else {\n siteRoot = \"\";\n }\n }\n result.setSiteRoot(siteRoot);\n return result;\n }"
] |
Method used to instantiate the appropriate input stream reader,
a standard one, or one which can deal with "encrypted" data.
@param directory directory entry
@param name file name
@return new input stream
@throws IOException | [
"public InputStream getInstance(DirectoryEntry directory, String name) throws IOException\n {\n DocumentEntry entry = (DocumentEntry) directory.getEntry(name);\n InputStream stream;\n if (m_encrypted)\n {\n stream = new EncryptedDocumentInputStream(entry, m_encryptionCode);\n }\n else\n {\n stream = new DocumentInputStream(entry);\n }\n\n return stream;\n }"
] | [
"public double getAccruedInterest(LocalDate date, AnalyticModel model) {\n\t\tint periodIndex=schedule.getPeriodIndex(date);\n\t\tPeriod period=schedule.getPeriod(periodIndex);\n\t\tDayCountConvention dcc= schedule.getDaycountconvention();\n\t\tdouble accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);\n\t\treturn accruedInterest;\n\t}",
"protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) {\n\n if (CmsXmlUtils.isDeepXpath(xmlPath)) {\n String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath);\n if (null == xmlContent.getValue(parentPath, l)) {\n createParentXmlElements(xmlContent, parentPath, l);\n xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1);\n }\n }\n\n }",
"@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }",
"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 }",
"private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null && baseCal.getName() != null)\n {\n cal.setParent(baseCal);\n }\n else\n {\n // Remove invalid calendar to avoid serious problems later.\n m_file.removeCalendar(cal);\n }\n }\n }",
"public void migrate() {\n if (databaseIsUpToDate()) {\n LOGGER.info(format(\"Keyspace %s is already up to date at version %d\", database.getKeyspaceName(),\n database.getVersion()));\n return;\n }\n\n List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());\n migrations.forEach(database::execute);\n LOGGER.info(format(\"Migrated keyspace %s to version %d\", database.getKeyspaceName(), database.getVersion()));\n database.close();\n }",
"public static HashMap<StoreDefinition, Integer> getUniqueStoreDefinitionsWithCounts(List<StoreDefinition> storeDefs) {\n\n HashMap<StoreDefinition, Integer> uniqueStoreDefs = Maps.newHashMap();\n for(StoreDefinition storeDef: storeDefs) {\n if(uniqueStoreDefs.isEmpty()) {\n uniqueStoreDefs.put(storeDef, 1);\n } else {\n StoreDefinition sameStore = null;\n\n // Go over all the other stores to find if this is unique\n for(StoreDefinition uniqueStoreDef: uniqueStoreDefs.keySet()) {\n if(uniqueStoreDef.getReplicationFactor() == storeDef.getReplicationFactor()\n && uniqueStoreDef.getRoutingStrategyType()\n .compareTo(storeDef.getRoutingStrategyType()) == 0) {\n\n // Further check for the zone routing case\n if(uniqueStoreDef.getRoutingStrategyType()\n .compareTo(RoutingStrategyType.ZONE_STRATEGY) == 0) {\n boolean zonesSame = true;\n for(int zoneId: uniqueStoreDef.getZoneReplicationFactor().keySet()) {\n if(storeDef.getZoneReplicationFactor().get(zoneId) == null\n || storeDef.getZoneReplicationFactor().get(zoneId) != uniqueStoreDef.getZoneReplicationFactor()\n .get(zoneId)) {\n zonesSame = false;\n break;\n }\n }\n if(zonesSame) {\n sameStore = uniqueStoreDef;\n }\n } else {\n sameStore = uniqueStoreDef;\n }\n\n if(sameStore != null) {\n // Bump up the count\n int currentCount = uniqueStoreDefs.get(sameStore);\n uniqueStoreDefs.put(sameStore, currentCount + 1);\n break;\n }\n }\n }\n\n if(sameStore == null) {\n // New store\n uniqueStoreDefs.put(storeDef, 1);\n }\n }\n }\n\n return uniqueStoreDefs;\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 final BigInteger printPriority(Priority priority)\n {\n int result = Priority.MEDIUM;\n\n if (priority != null)\n {\n result = priority.getValue();\n }\n\n return (BigInteger.valueOf(result));\n }"
] |
Locate a child block by byte pattern and validate by
checking the length of the string we are expecting
to follow the pattern.
@param bufferIndex start index
@return true if a child block starts at this point | [
"private final boolean matchChildBlock(int bufferIndex)\n {\n //\n // Match the pattern we see at the start of the child block\n //\n int index = 0;\n for (byte b : CHILD_BLOCK_PATTERN)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n return false;\n }\n ++index;\n }\n\n //\n // The first step will produce false positives. To handle this, we should find\n // the name of the block next, and check to ensure that the length\n // of the name makes sense.\n //\n int nameLength = FastTrackUtility.getInt(m_buffer, bufferIndex + index);\n\n// System.out.println(\"Name length: \" + nameLength);\n// \n// if (nameLength > 0 && nameLength < 100)\n// {\n// String name = new String(m_buffer, bufferIndex+index+4, nameLength, CharsetHelper.UTF16LE);\n// System.out.println(\"Name: \" + name);\n// }\n \n return nameLength > 0 && nameLength < 100;\n }"
] | [
"public AnalysisContext copyWithConfiguration(ModelNode configuration) {\n return new AnalysisContext(this.locale, configuration, this.oldApi, this.newApi, this.data);\n }",
"public AirMapViewBuilder builder(AirMapViewTypes mapType) {\n switch (mapType) {\n case NATIVE:\n if (isNativeMapSupported) {\n return new NativeAirMapViewBuilder();\n }\n break;\n case WEB:\n return getWebMapViewBuilder();\n }\n throw new UnsupportedOperationException(\"Requested map type is not supported\");\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 base_responses add(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 addresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new ntpserver();\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].minpoll = resources[i].minpoll;\n\t\t\t\taddresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\taddresources[i].autokey = resources[i].autokey;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"private void validate() {\n if (Strings.emptyToNull(random) == null) {\n random = Strings.emptyToNull(getProject().getProperty(SYSPROP_RANDOM_SEED())); \n }\n \n if (random == null) {\n throw new BuildException(\"Required attribute 'seed' must not be empty. Look at <junit4:pickseed>.\");\n }\n \n long[] seeds = SeedUtils.parseSeedChain(random);\n if (seeds.length < 1) {\n throw new BuildException(\"Random seed is required.\");\n }\n \n if (values.isEmpty() && !allowUndefined) {\n throw new BuildException(\"No values to pick from and allowUndefined=false.\");\n }\n }",
"public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\n }",
"public List<T> resolveConflicts(List<T> values) {\n if(values.size() > 1)\n return values;\n else\n return Collections.singletonList(values.get(0));\n }",
"public ItemRequest<Project> findById(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"GET\");\n }"
] |
Returns the device push token or null
@param type com.clevertap.android.sdk.PushType (FCM or GCM)
@return String device token or null
NOTE: on initial install calling getDevicePushToken may return null, as the device token is
not yet available
Implement CleverTapAPI.DevicePushTokenRefreshListener to get a callback once the token is
available | [
"@SuppressWarnings(\"unused\")\n public String getDevicePushToken(final PushType type) {\n switch (type) {\n case GCM:\n return getCachedGCMToken();\n case FCM:\n return getCachedFCMToken();\n default:\n return null;\n }\n }"
] | [
"public void useNewSOAPServiceWithOldClient() throws Exception {\n \n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServicePort();\n\n // The outgoing new Customer data needs to be transformed for \n // the old service to understand it and the response from the old service\n // needs to be transformed for this new client to understand it.\n Client client = ClientProxy.getClient(customerService);\n addTransformInterceptors(client.getInInterceptors(),\n client.getOutInterceptors(),\n false);\n \n System.out.println(\"Using new SOAP CustomerService with old client\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP\");\n printOldCustomerDetails(customer);\n }",
"public static boolean isSpreadSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSpreadSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSpreadSafe();\r\n }\r\n return false;\r\n }",
"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 final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }",
"public static ThreadPoolExecutor newFixedThreadPool(int threads, String groupname, int queueSize) {\n\t\treturn new ThreadPoolExecutor( threads, threads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(\n\t\t\t\tqueueSize ), new SearchThreadFactory( groupname ), new BlockPolicy() );\n\t}",
"public static base_response delete(nitro_service client, String username) throws Exception {\n\t\tsystemuser deleteresource = new systemuser();\n\t\tdeleteresource.username = username;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private static int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }",
"private void createCodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int realOffsetStart, int realOffsetEnd, List<Integer> codePositions)\n throws IOException {\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, filterString(stringValues[0].trim()));\n token.setOffset(offsetStart, offsetEnd);\n token.setRealOffset(realOffsetStart, realOffsetEnd);\n token.addPositions(codePositions.stream().mapToInt(i -> i).toArray());\n tokenCollection.add(token);\n level.tokens.add(token);\n }",
"static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\n }"
] |
slave=true | [
"public static ExtensibleConfigurationPersister createTransientDomainXmlConfigurationPersister(ExecutorService executorService, ExtensionRegistry extensionRegistry) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n ExtensibleConfigurationPersister persister = new NullConfigurationPersister(domainXml);\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }"
] | [
"private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}",
"private static List< Block > createBlocks(int[] data, boolean debug) {\r\n\r\n List< Block > blocks = new ArrayList<>();\r\n Block current = null;\r\n\r\n for (int i = 0; i < data.length; i++) {\r\n EncodingMode mode = chooseMode(data[i]);\r\n if ((current != null && current.mode == mode) &&\r\n (mode != EncodingMode.NUM || current.length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n current.length++;\r\n } else {\r\n current = new Block(mode);\r\n blocks.add(current);\r\n }\r\n }\r\n\r\n if (debug) {\r\n System.out.println(\"Initial block pattern: \" + blocks);\r\n }\r\n\r\n smoothBlocks(blocks);\r\n\r\n if (debug) {\r\n System.out.println(\"Final block pattern: \" + blocks);\r\n }\r\n\r\n return blocks;\r\n }",
"private void readRelationships(Document cdp)\n {\n for (Link link : cdp.getLinks().getLink())\n {\n readRelationship(link);\n }\n }",
"private void readRelationships(Project gpProject)\n {\n for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask())\n {\n readRelationships(gpTask);\n }\n }",
"private String parseRssFeed(String feed) {\n String[] result = feed.split(\"<br />\");\n String[] result2 = result[2].split(\"<BR />\");\n\n return result2[0];\n }",
"public static void main(String[] args) {\r\n\r\n String[] s = {\"there once was a man\", \"this one is a manic\", \"hey there\", \"there once was a mane\", \"once in a manger.\", \"where is one match?\", \"Jo3seph Smarr!\", \"Joseph R Smarr\"};\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.println(\"s1: \" + s[i]);\r\n System.out.println(\"s2: \" + s[j]);\r\n System.out.println(\"edit distance: \" + editDistance(s[i], s[j]));\r\n System.out.println(\"LCS: \" + longestCommonSubstring(s[i], s[j]));\r\n System.out.println(\"LCCS: \" + longestCommonContiguousSubstring(s[i], s[j]));\r\n System.out.println();\r\n }\r\n }\r\n }",
"private void cascadeDeleteFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeDeleteSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeDeleteCollectionReferences(mod, colls, alreadyPrepared);\r\n }",
"@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n protected void addStoreToSession(String store) {\n\n Exception initializationException = null;\n\n storeNames.add(store);\n\n for(Node node: nodesToStream) {\n\n SocketDestination destination = null;\n SocketAndStreams sands = null;\n\n try {\n destination = new SocketDestination(node.getHost(),\n node.getAdminPort(),\n RequestFormatType.ADMIN_PROTOCOL_BUFFERS);\n sands = streamingSocketPool.checkout(destination);\n DataOutputStream outputStream = sands.getOutputStream();\n DataInputStream inputStream = sands.getInputStream();\n\n nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination);\n nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream);\n nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream);\n nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands);\n nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);\n\n remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId())\n .getValue();\n\n } catch(Exception e) {\n logger.error(e);\n try {\n close(sands.getSocket());\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n\n if(!faultyNodes.contains(node.getId()))\n faultyNodes.add(node.getId());\n initializationException = e;\n }\n\n }\n\n if(initializationException != null)\n throw new VoldemortException(initializationException);\n\n if(store.equals(\"slop\"))\n return;\n\n boolean foundStore = false;\n\n for(StoreDefinition remoteStoreDef: remoteStoreDefs) {\n if(remoteStoreDef.getName().equals(store)) {\n RoutingStrategyFactory factory = new RoutingStrategyFactory();\n RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef,\n adminClient.getAdminClientCluster());\n\n storeToRoutingStrategy.put(store, storeRoutingStrategy);\n validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef);\n foundStore = true;\n break;\n }\n }\n if(!foundStore) {\n logger.error(\"Store Name not found on the cluster\");\n throw new VoldemortException(\"Store Name not found on the cluster\");\n\n }\n\n }",
"private static int[] getErrorCorrection(int[] codewords, int ecclen) {\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n rs.init_gf(0x43);\r\n rs.init_code(ecclen, 1);\r\n rs.encode(codewords.length, codewords);\r\n\r\n int[] results = new int[ecclen];\r\n for (int i = 0; i < ecclen; i++) {\r\n results[i] = rs.getResult(results.length - 1 - i);\r\n }\r\n\r\n return results;\r\n }"
] |
copied and altered from TransactionHelper | [
"private Serializable doWorkInIsolationTransaction(final SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\tclass Work extends AbstractReturningWork<IntegralDataTypeHolder> {\n\t\t\tprivate final SharedSessionContractImplementor localSession = session;\n\n\t\t\t@Override\n\t\t\tpublic IntegralDataTypeHolder execute(Connection connection) throws SQLException {\n\t\t\t\ttry {\n\t\t\t\t\treturn doWorkInCurrentTransactionIfAny( localSession );\n\t\t\t\t}\n\t\t\t\tcatch ( RuntimeException sqle ) {\n\t\t\t\t\tthrow new HibernateException( \"Could not get or update next value\", sqle );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//we want to work out of transaction\n\t\tboolean workInTransaction = false;\n\t\tWork work = new Work();\n\t\tSerializable generatedValue = session.getTransactionCoordinator().createIsolationDelegate().delegateWork( work, workInTransaction );\n\t\treturn generatedValue;\n\t}"
] | [
"public static base_response unset(nitro_service client, sslservice resource, String[] args) throws Exception{\n\t\tsslservice unsetresource = new sslservice();\n\t\tunsetresource.servicename = resource.servicename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }",
"public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {\n Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);\n for (final ContentAssistContext context : _filteredContexts) {\n ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();\n for (final AbstractElement element : _firstSetGrammarElements) {\n {\n boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();\n boolean _not = (!_canAcceptMoreProposals);\n if (_not) {\n return;\n }\n this.createProposals(element, context, acceptor);\n }\n }\n }\n }",
"public ItemRequest<Task> removeDependencies(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc));\n final ClientResponse response = resource\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = FAILED_TO_GET_CORPORATE_FILTERS;\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<String>>(){});\n\n }",
"public void signIn(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>();\n for (WebSocketConnection conn : connections) {\n newMap.put(conn, conn);\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.putAll(newMap);\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 }",
"void forcedUndeployScan() {\n\n if (acquireScanLock()) {\n try {\n ROOT_LOGGER.tracef(\"Performing a post-boot forced undeploy scan for scan directory %s\", deploymentDir.getAbsolutePath());\n ScanContext scanContext = new ScanContext(deploymentOperations);\n\n // Add remove actions to the plan for anything we count as\n // deployed that we didn't find on the scan\n for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) {\n // remove successful deployment and left will be removed\n if (scanContext.registeredDeployments.containsKey(missing.getKey())) {\n scanContext.registeredDeployments.remove(missing.getKey());\n }\n }\n Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet());\n scannedDeployments.removeAll(scanContext.persistentDeployments);\n\n List<ScannerTask> scannerTasks = scanContext.scannerTasks;\n for (String toUndeploy : scannedDeployments) {\n scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true));\n }\n try {\n executeScannerTasks(scannerTasks, deploymentOperations, true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n\n ROOT_LOGGER.tracef(\"Forced undeploy scan complete\");\n } catch (Exception e) {\n ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath());\n } finally {\n releaseScanLock();\n }\n }\n }",
"@Override\n public Object[] getAgentPlans(String agent_name, Connector connector) {\n // Not supported in JADE\n connector.getLogger().warning(\"Non suported method for Jade Platform. There is no plans in Jade platform.\");\n throw new java.lang.UnsupportedOperationException(\"Non suported method for Jade Platform. There is no extra properties.\");\n }"
] |
Mutate the gradient.
@param amount the amount in the range zero to one | [
"public void mutate(float amount) {\n\t\tfor (int i = 0; i < numKnots; i++) {\n\t\t\tint rgb = yKnots[i];\n\t\t\tint r = ((rgb >> 16) & 0xff);\n\t\t\tint g = ((rgb >> 8) & 0xff);\n\t\t\tint b = (rgb & 0xff);\n\t\t\tr = PixelUtils.clamp( (int)(r + amount * 255 * (Math.random()-0.5)) );\n\t\t\tg = PixelUtils.clamp( (int)(g + amount * 255 * (Math.random()-0.5)) );\n\t\t\tb = PixelUtils.clamp( (int)(b + amount * 255 * (Math.random()-0.5)) );\n\t\t\tyKnots[i] = 0xff000000 | (r << 16) | (g << 8) | b;\n\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\t}\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}"
] | [
"private boolean evaluateLogicalOperator(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = false;\n\n if (m_criteriaList.size() == 0)\n {\n result = true;\n }\n else\n {\n for (GenericCriteria criteria : m_criteriaList)\n {\n result = criteria.evaluate(container, promptValues);\n if ((m_operator == TestOperator.AND && !result) || (m_operator == TestOperator.OR && result))\n {\n break;\n }\n }\n }\n\n return result;\n }",
"public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}",
"public BsonDocument toUpdateDocument() {\n final List<BsonElement> unsets = new ArrayList<>();\n for (final String removedField : this.removedFields) {\n unsets.add(new BsonElement(removedField, new BsonBoolean(true)));\n }\n final BsonDocument updateDocument = new BsonDocument();\n\n if (this.updatedFields.size() > 0) {\n updateDocument.append(\"$set\", this.updatedFields);\n }\n\n if (unsets.size() > 0) {\n updateDocument.append(\"$unset\", new BsonDocument(unsets));\n }\n\n return updateDocument;\n }",
"public void updateLinks(ServiceReference<S> serviceReference) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);\n boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);\n if (isAlreadyLinked && !canBeLinked) {\n linkerManagement.unlink(declaration, serviceReference);\n } else if (!isAlreadyLinked && canBeLinked) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }",
"private OAuth1RequestToken constructToken(Response response) {\r\n Element authElement = response.getPayload();\r\n String oauthToken = XMLUtilities.getChildValue(authElement, \"oauth_token\");\r\n String oauthTokenSecret = XMLUtilities.getChildValue(authElement, \"oauth_token_secret\");\r\n\r\n OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret);\r\n return token;\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 }",
"public static boolean intArrayContains(int[] array, int numToCheck) {\n for (int i = 0; i < array.length; i++) {\n if (array[i] == numToCheck) {\n return true;\n }\n }\n return false;\n }",
"public synchronized ModelNode doCommand(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n return execute(request, isSlowCommand(command)).getResponseNode();\n }",
"public BufferedImage getImage() {\n ByteBuffer artwork = getRawBytes();\n artwork.rewind();\n byte[] imageBytes = new byte[artwork.remaining()];\n artwork.get(imageBytes);\n try {\n return ImageIO.read(new ByteArrayInputStream(imageBytes));\n } catch (IOException e) {\n logger.error(\"Weird! Caught exception creating image from artwork bytes\", e);\n return null;\n }\n }"
] |
Use this API to add sslcertkey. | [
"public static base_response add(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey addresource = new sslcertkey();\n\t\taddresource.certkey = resource.certkey;\n\t\taddresource.cert = resource.cert;\n\t\taddresource.key = resource.key;\n\t\taddresource.password = resource.password;\n\t\taddresource.fipskey = resource.fipskey;\n\t\taddresource.inform = resource.inform;\n\t\taddresource.passplain = resource.passplain;\n\t\taddresource.expirymonitor = resource.expirymonitor;\n\t\taddresource.notificationperiod = resource.notificationperiod;\n\t\taddresource.bundle = resource.bundle;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"public static Chart getMSDLineWithFreeModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double intercept) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = intercept + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + a\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"private void populateMilestone(Row row, Task task)\n {\n task.setMilestone(true);\n //PROJID\n task.setUniqueID(row.getInteger(\"MILESTONEID\"));\n task.setStart(row.getDate(\"GIVEN_DATE_TIME\"));\n task.setFinish(row.getDate(\"GIVEN_DATE_TIME\"));\n //PROGREST_PERIOD\n //SYMBOL_APPEARANCE\n //MILESTONE_TYPE\n //PLACEMENU\n task.setPercentageComplete(row.getBoolean(\"COMPLETED\") ? COMPLETE : INCOMPLETE);\n //INTERRUPTIBLE_X\n //ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n //ACTUAL_DURATIONHOURS\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //EFFORT_BUDGET\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n //OVERALL_PERCENV_COMPLETE\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n //NOTET\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n //STARZ\n //ENJ\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n task.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }",
"public void setBooleanAttribute(String name, Boolean value) {\n\t\tensureValue();\n\t\tAttribute attribute = new BooleanAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"private long validateMessage(FileChannel channel, long start, long len, ByteBuffer buffer) throws IOException {\n buffer.rewind();\n int read = channel.read(buffer, start);\n if (read < 4) return -1;\n\n // check that we have sufficient bytes left in the file\n int size = buffer.getInt(0);\n if (size < Message.MinHeaderSize) return -1;\n\n long next = start + 4 + size;\n if (next > len) return -1;\n\n // read the message\n ByteBuffer messageBuffer = ByteBuffer.allocate(size);\n long curr = start + 4;\n while (messageBuffer.hasRemaining()) {\n read = channel.read(messageBuffer, curr);\n if (read < 0) throw new IllegalStateException(\"File size changed during recovery!\");\n else curr += read;\n }\n messageBuffer.rewind();\n Message message = new Message(messageBuffer);\n if (!message.isValid()) return -1;\n else return next;\n }",
"public List<AssignmentRow> getAssignmentRows(VariableType varType) {\n List<AssignmentRow> rows = new ArrayList<AssignmentRow>();\n List<Variable> handledVariables = new ArrayList<Variable>();\n // Create an AssignmentRow for each Assignment\n for (Assignment assignment : assignments) {\n if (assignment.getVariableType() == varType) {\n String dataType = getDisplayNameFromDataType(assignment.getDataType());\n AssignmentRow row = new AssignmentRow(assignment.getName(),\n assignment.getVariableType(),\n dataType,\n assignment.getCustomDataType(),\n assignment.getProcessVarName(),\n assignment.getConstant());\n rows.add(row);\n handledVariables.add(assignment.getVariable());\n }\n }\n List<Variable> vars = null;\n if (varType == VariableType.INPUT) {\n vars = inputVariables;\n } else {\n vars = outputVariables;\n }\n // Create an AssignmentRow for each Variable that doesn't have an Assignment\n for (Variable var : vars) {\n if (!handledVariables.contains(var)) {\n AssignmentRow row = new AssignmentRow(var.getName(),\n var.getVariableType(),\n var.getDataType(),\n var.getCustomDataType(),\n null,\n null);\n rows.add(row);\n }\n }\n\n return rows;\n }",
"public static File createFolder(String path, String dest_dir)\n throws BeastException {\n File f = new File(dest_dir);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n logger.severe(\"Problem creating directory: \" + path\n + File.separator + dest_dir);\n }\n }\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n String message = \"Problem creating directory: \" + path\n + File.separator + dest_dir;\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n\n return f;\n }",
"public static <T> List<T> makeList(T... items) {\r\n List<T> s = new ArrayList<T>(items.length);\r\n for (int i = 0; i < items.length; i++) {\r\n s.add(items[i]);\r\n }\r\n return s;\r\n }",
"private static void addProperties(EndpointReferenceType epr, SLProperties props) {\n MetadataType metadata = WSAEndpointReferenceUtils.getSetMetadata(epr);\n ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter.toServiceLocatorPropertiesType(props);\n\n JAXBElement<ServiceLocatorPropertiesType>\n slp = SL_OBJECT_FACTORY.createServiceLocatorProperties(jaxbProps);\n metadata.getAny().add(slp);\n }",
"public static base_response enable(nitro_service client, String id) throws Exception {\n\t\tInterface enableresource = new Interface();\n\t\tenableresource.id = id;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}"
] |
Start a managed server.
@param factory the boot command factory | [
"synchronized void start(final ManagedServerBootCmdFactory factory) {\n final InternalState required = this.requiredState;\n // Ignore if the server is already started\n if(required == InternalState.SERVER_STARTED) {\n return;\n }\n // In case the server failed to start, try to start it again\n if(required != InternalState.FAILED) {\n final InternalState current = this.internalState;\n if(current != required) {\n // TODO this perhaps should wait?\n throw new IllegalStateException();\n }\n }\n operationID = CurrentOperationIdHolder.getCurrentOperationID();\n bootConfiguration = factory.createConfiguration();\n requiredState = InternalState.SERVER_STARTED;\n ROOT_LOGGER.startingServer(serverName);\n transition();\n }"
] | [
"private OAuth1RequestToken constructToken(Response response) {\r\n Element authElement = response.getPayload();\r\n String oauthToken = XMLUtilities.getChildValue(authElement, \"oauth_token\");\r\n String oauthTokenSecret = XMLUtilities.getChildValue(authElement, \"oauth_token_secret\");\r\n\r\n OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret);\r\n return token;\r\n }",
"private void writeComma() throws IOException\n {\n if (m_firstNameValuePair.peek().booleanValue())\n {\n m_firstNameValuePair.pop();\n m_firstNameValuePair.push(Boolean.FALSE);\n }\n else\n {\n m_writer.write(',');\n }\n }",
"public static Observable<Void> mapToVoid(Observable<?> fromObservable) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<Void>());\n } else {\n return Observable.empty();\n }\n }",
"public void fireAssignmentWrittenEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentWritten(resourceAssignment);\n }\n }\n }",
"public void increasePriority(int overrideId, int ordinal, int pathId, String clientUUID) {\n logger.info(\"Increase priority\");\n\n int origPriority = -1;\n int newPriority = -1;\n int origId = 0;\n int newId = 0;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n results = null;\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n statement.setInt(1, pathId);\n statement.setString(2, clientUUID);\n results = statement.executeQuery();\n\n int ordinalCount = 0;\n while (results.next()) {\n if (results.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID) == overrideId) {\n ordinalCount++;\n if (ordinalCount == ordinal) {\n origPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n origId = results.getInt(Constants.GENERIC_ID);\n break;\n }\n }\n newPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n newId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // update priorities\n if (origPriority != -1 && newPriority != -1) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, origPriority);\n statement.setInt(2, newId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, newPriority);\n statement.setInt(2, origId);\n statement.executeUpdate();\n }\n } catch (Exception e) {\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"public void recordResourceRequestTimeUs(SocketDestination dest, long resourceRequestTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n } else {\n this.resourceRequestTimeRequestCounter.addRequest(resourceRequestTimeUs\n * Time.NS_PER_US);\n }\n }",
"public <T> T find(Class<T> classType, String id, String rev) {\n assertNotEmpty(classType, \"Class\");\n assertNotEmpty(id, \"id\");\n assertNotEmpty(id, \"rev\");\n final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, \"rev\", rev);\n return couchDbClient.get(uri, classType);\n }",
"private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }"
] |
Creates a timestamp from the equivalent long value. This conversion
takes account of the time zone and any daylight savings time.
@param timestamp timestamp expressed as a long integer
@return new Date instance | [
"public static Date getTimestampFromLong(long timestamp)\n {\n TimeZone tz = TimeZone.getDefault();\n Date result = new Date(timestamp - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n return (result);\n }"
] | [
"private void writeWBS(Task mpxj)\n {\n if (mpxj.getUniqueID().intValue() != 0)\n {\n WBSType xml = m_factory.createWBSType();\n m_project.getWBS().add(xml);\n String code = mpxj.getWBS();\n code = code == null || code.length() == 0 ? DEFAULT_WBS_CODE : code;\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setCode(code);\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setName(mpxj.getName());\n\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(parentObjectID);\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSequenceNumber(Integer.valueOf(m_wbsSequence++));\n\n xml.setStatus(\"Active\");\n }\n\n writeChildTasks(mpxj);\n }",
"private static void loadFile(String filePath) {\n final Path path = FileSystems.getDefault().getPath(filePath);\n\n try {\n data.clear();\n data.load(Files.newBufferedReader(path));\n } catch(IOException e) {\n LOG.warn(\"Exception while loading \" + path.toString(), e);\n }\n }",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }",
"public AT_Row setPaddingLeftRight(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static double Taneja(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double pq = p[i] + q[i];\n r += (pq / 2) * Math.log(pq / (2 * Math.sqrt(p[i] * q[i])));\n }\n }\n return r;\n }",
"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 }",
"TrackMetadata queryMetadata(final DataReference track, final CdjStatus.TrackType trackType, final Client client)\n throws IOException, InterruptedException, TimeoutException {\n\n // Send the metadata menu request\n if (client.tryLockingForMenuOperations(20, TimeUnit.SECONDS)) {\n try {\n final Message.KnownType requestType = (trackType == CdjStatus.TrackType.REKORDBOX) ?\n Message.KnownType.REKORDBOX_METADATA_REQ : Message.KnownType.UNANALYZED_METADATA_REQ;\n final Message response = client.menuRequestTyped(requestType, Message.MenuIdentifier.MAIN_MENU,\n track.slot, trackType, new NumberField(track.rekordboxId));\n final long count = response.getMenuResultsCount();\n if (count == Message.NO_MENU_RESULTS_AVAILABLE) {\n return null;\n }\n\n // Gather the cue list and all the metadata menu items\n final List<Message> items = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, track.slot, trackType, response);\n final CueList cueList = getCueList(track.rekordboxId, track.slot, client);\n return new TrackMetadata(track, trackType, items, cueList);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock the player for menu operations\");\n }\n }",
"public Map<String, String> getUploadParameters() {\r\n Map<String, String> parameters = new TreeMap<>();\r\n\r\n\r\n String title = getTitle();\r\n if (title != null) {\r\n parameters.put(\"title\", title);\r\n }\r\n\r\n String description = getDescription();\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\r\n\r\n Collection<String> tags = getTags();\r\n if (tags != null) {\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \"));\r\n }\r\n\r\n if (isHidden() != null) {\r\n parameters.put(\"hidden\", isHidden().booleanValue() ? \"1\" : \"0\");\r\n }\r\n\r\n if (getSafetyLevel() != null) {\r\n parameters.put(\"safety_level\", getSafetyLevel());\r\n }\r\n\r\n if (getContentType() != null) {\r\n parameters.put(\"content_type\", getContentType());\r\n }\r\n\r\n if (getPhotoId() != null) {\r\n parameters.put(\"photo_id\", getPhotoId());\r\n }\r\n\r\n parameters.put(\"is_public\", isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"async\", isAsync() ? \"1\" : \"0\");\r\n\r\n return parameters;\r\n }"
] |
Sets page shift orientation. The pages might be shifted horizontally or vertically relative
to each other to make the content of each page on the screen at least partially visible
@param orientation | [
"public void setShiftOrientation(OrientedLayout.Orientation orientation) {\n if (mShiftLayout.getOrientation() != orientation &&\n orientation != OrientedLayout.Orientation.STACK) {\n mShiftLayout.setOrientation(orientation);\n requestLayout();\n }\n }"
] | [
"synchronized void asyncReconnect(final URI reconnectUri, String authKey, final ReconnectCallback callback) {\n if (getState() != State.OPEN) {\n return;\n }\n // Update the configuration with the new credentials\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(createClientCallbackHandler(userName, authKey));\n config.setUri(reconnectUri);\n this.configuration = config;\n\n final ReconnectRunner reconnectTask = this.reconnectRunner;\n if (reconnectTask == null) {\n final ReconnectRunner task = new ReconnectRunner();\n task.callback = callback;\n task.future = executorService.submit(task);\n } else {\n reconnectTask.callback = callback;\n }\n }",
"public static lbvserver_scpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_scpolicy_binding obj = new lbvserver_scpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_scpolicy_binding response[] = (lbvserver_scpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\n }",
"public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }",
"public void addDependency(final ProcessorGraphNode node) {\n Assert.isTrue(node != this, \"A processor can't depends on himself\");\n\n this.dependencies.add(node);\n node.addRequirement(this);\n }",
"public static String decodeUrlIso(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"public static boolean isOperationDefined(final ModelNode operation) {\n for (final AttributeDefinition def : ROOT_ATTRIBUTES) {\n if (operation.hasDefined(def.getName())) {\n return true;\n }\n }\n return false;\n }",
"public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }",
"private File extractThriftFile(String artifactId, String fileName, Set<File> thriftFiles) {\n for (File thriftFile : thriftFiles) {\n boolean fileFound = false;\n if (fileName.equals(thriftFile.getName())) {\n for (String pathComponent : thriftFile.getPath().split(File.separator)) {\n if (pathComponent.equals(artifactId)) {\n fileFound = true;\n }\n }\n }\n\n if (fileFound) {\n return thriftFile;\n }\n }\n return null;\n }"
] |
Inserts a single document locally and being to synchronize it based on its _id. Inserting
a document with the same _id twice will result in a duplicate key exception.
@param namespace the namespace to put the document in.
@param document the document to insert. | [
"void insertOne(final MongoNamespace namespace, final BsonDocument document) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n // Remove forbidden fields from the document before inserting it into the local collection.\n final BsonDocument docForStorage = sanitizeDocument(document);\n\n final NamespaceSynchronizationConfig nsConfig =\n this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n final ChangeEvent<BsonDocument> event;\n final BsonValue documentId;\n try {\n getLocalCollection(namespace).insertOne(docForStorage);\n documentId = BsonUtils.getDocumentId(docForStorage);\n event = ChangeEvents.changeEventForLocalInsert(namespace, docForStorage, true);\n final CoreDocumentSynchronizationConfig config = syncConfig.addAndGetSynchronizedDocument(\n namespace,\n documentId\n );\n config.setSomePendingWritesAndSave(logicalT, event);\n } finally {\n lock.unlock();\n }\n checkAndInsertNamespaceListener(namespace);\n eventDispatcher.emitEvent(nsConfig, event);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }"
] | [
"public void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n }",
"private String getIntegerString(Number value)\n {\n return (value == null ? null : Integer.toString(value.intValue()));\n }",
"private void createResultSubClassesMultipleJoinedTables(List result, ClassDescriptor cld, boolean wholeTree)\r\n {\r\n List tmp = (List) superClassMultipleJoinedTablesMap.get(cld.getClassOfObject());\r\n if(tmp != null)\r\n {\r\n result.addAll(tmp);\r\n if(wholeTree)\r\n {\r\n for(int i = 0; i < tmp.size(); i++)\r\n {\r\n Class subClass = (Class) tmp.get(i);\r\n ClassDescriptor subCld = getDescriptorFor(subClass);\r\n createResultSubClassesMultipleJoinedTables(result, subCld, wholeTree);\r\n }\r\n }\r\n }\r\n }",
"public void selectTab() {\n for (Widget child : getChildren()) {\n if (child instanceof HasHref) {\n String href = ((HasHref) child).getHref();\n if (parent != null && !href.isEmpty()) {\n parent.selectTab(href.replaceAll(\"[^a-zA-Z\\\\d\\\\s:]\", \"\"));\n parent.reload();\n break;\n }\n }\n }\n }",
"private static void freeTempLOB(ClobWrapper clob, BlobWrapper blob)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (clob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the CLOB is open, close it\r\n\t\t\t\tif (clob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tclob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this CLOB\r\n\t\t\t\tclob.freeTemporary();\r\n\t\t\t}\r\n\r\n\t\t\tif (blob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the BLOB is open, close it\r\n\t\t\t\tif (blob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tblob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this BLOB\r\n\t\t\t\tblob.freeTemporary();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n logger.error(\"Error during temporary LOB release\", e);\r\n\t\t}\r\n\t}",
"public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}",
"public static Object parsePrimitive(\n final String fieldName, final PrimitiveAttribute<?> pAtt, final PObject requestData) {\n Class<?> valueClass = pAtt.getValueClass();\n Object value;\n try {\n value = parseValue(false, new String[0], valueClass, fieldName, requestData);\n } catch (UnsupportedTypeException e) {\n String type = e.type.getName();\n if (e.type.isArray()) {\n type = e.type.getComponentType().getName() + \"[]\";\n }\n throw new RuntimeException(\n \"The type '\" + type + \"' is not a supported type when parsing json. \" +\n \"See documentation for supported types.\\n\\nUnsupported type found in attribute \" +\n fieldName\n + \"\\n\\nTo support more types add the type to \" +\n \"parseValue and parseArrayValue in this class and add a test to the test class\",\n e);\n }\n pAtt.validateValue(value);\n\n return value;\n }",
"public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException {\n\n // Determine the patch id to rollback\n String patchId;\n final List<String> oneOffs = modification.getPatchIDs();\n if (oneOffs.isEmpty()) {\n patchId = modification.getCumulativePatchID();\n if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) {\n throw PatchLogger.ROOT_LOGGER.noPatchesApplied();\n }\n } else {\n patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1);\n }\n return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification);\n }",
"public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize,\n long totalSizeOfFile) {\n\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n //Read the partSize bytes from the stream\n byte[] bytes = new byte[partSize];\n try {\n stream.read(bytes);\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading data from stream failed.\", ioe);\n }\n\n return this.uploadPart(bytes, offset, partSize, totalSizeOfFile);\n }"
] |
Read project calendars. | [
"private void readCalendars()\n {\n Table cal = m_tables.get(\"CAL\");\n for (MapRow row : cal)\n {\n ProjectCalendar calendar = m_projectFile.addCalendar();\n m_calendarMap.put(row.getInteger(\"CALENDAR_ID\"), calendar);\n Integer[] days =\n {\n row.getInteger(\"SUNDAY_HOURS\"),\n row.getInteger(\"MONDAY_HOURS\"),\n row.getInteger(\"TUESDAY_HOURS\"),\n row.getInteger(\"WEDNESDAY_HOURS\"),\n row.getInteger(\"THURSDAY_HOURS\"),\n row.getInteger(\"FRIDAY_HOURS\"),\n row.getInteger(\"SATURDAY_HOURS\")\n };\n\n calendar.setName(row.getString(\"NAME\"));\n readHours(calendar, Day.SUNDAY, days[0]);\n readHours(calendar, Day.MONDAY, days[1]);\n readHours(calendar, Day.TUESDAY, days[2]);\n readHours(calendar, Day.WEDNESDAY, days[3]);\n readHours(calendar, Day.THURSDAY, days[4]);\n readHours(calendar, Day.FRIDAY, days[5]);\n readHours(calendar, Day.SATURDAY, days[6]);\n\n int workingDaysPerWeek = 0;\n for (Day day : Day.values())\n {\n if (calendar.isWorkingDay(day))\n {\n ++workingDaysPerWeek;\n }\n }\n\n Integer workingHours = null;\n for (int index = 0; index < 7; index++)\n {\n if (days[index].intValue() != 0)\n {\n workingHours = days[index];\n break;\n }\n }\n\n if (workingHours != null)\n {\n int workingHoursPerDay = countHours(workingHours);\n int minutesPerDay = workingHoursPerDay * 60;\n int minutesPerWeek = minutesPerDay * workingDaysPerWeek;\n int minutesPerMonth = 4 * minutesPerWeek;\n int minutesPerYear = 52 * minutesPerWeek;\n\n calendar.setMinutesPerDay(Integer.valueOf(minutesPerDay));\n calendar.setMinutesPerWeek(Integer.valueOf(minutesPerWeek));\n calendar.setMinutesPerMonth(Integer.valueOf(minutesPerMonth));\n calendar.setMinutesPerYear(Integer.valueOf(minutesPerYear));\n }\n }\n }"
] | [
"public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\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 }",
"public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }",
"public static boolean isToStringMethod(Method method) {\n return (method != null && method.getName().equals(\"readString\") && method.getParameterTypes().length == 0);\n }",
"protected boolean equivalentClaims(Claim claim1, Claim claim2) {\n\t\treturn claim1.getMainSnak().equals(claim2.getMainSnak())\n\t\t\t\t&& isSameSnakSet(claim1.getAllQualifiers(),\n\t\t\t\t\t\tclaim2.getAllQualifiers());\n\t}",
"public BufferedImage getNewImageInstance() {\n BufferedImage buf = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());\n buf.setData(image.getData());\n return buf;\n }",
"public AsciiTable setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private JSONValue datesToJsonArray(Collection<Date> dates) {\n\n if (null != dates) {\n JSONArray result = new JSONArray();\n for (Date d : dates) {\n result.set(result.size(), dateToJson(d));\n }\n return result;\n }\n return null;\n }",
"public static String getAt(String text, int index) {\n index = normaliseIndex(index, text.length());\n return text.substring(index, index + 1);\n }"
] |
Utility function that fetches quota types. | [
"public static List<QuotaType> getQuotaTypes(List<String> strQuotaTypes) {\n if(strQuotaTypes.size() < 1) {\n throw new VoldemortException(\"Quota type not specified.\");\n }\n List<QuotaType> quotaTypes;\n if(strQuotaTypes.size() == 1 && strQuotaTypes.get(0).equals(AdminToolUtils.QUOTATYPE_ALL)) {\n quotaTypes = Arrays.asList(QuotaType.values());\n } else {\n quotaTypes = new ArrayList<QuotaType>();\n for(String strQuotaType: strQuotaTypes) {\n QuotaType type = QuotaType.valueOf(strQuotaType);\n quotaTypes.add(type);\n }\n }\n return quotaTypes;\n }"
] | [
"public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }",
"public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }",
"public static nsacl6_stats get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6_stats obj = new nsacl6_stats();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6_stats response = (nsacl6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"private void debugLogEnd(String operationType,\n Long OriginTimeInMs,\n Long RequestStartTimeInMs,\n Long ResponseReceivedTimeInMs,\n String keyString,\n int numVectorClockEntries) {\n long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs;\n logger.debug(\"Received a response from voldemort server for Operation Type: \"\n + operationType\n + \" , For key(s): \"\n + keyString\n + \" , Store: \"\n + this.storeName\n + \" , Origin time of request (in ms): \"\n + OriginTimeInMs\n + \" , Response received at time (in ms): \"\n + ResponseReceivedTimeInMs\n + \" . Request sent at(in ms): \"\n + RequestStartTimeInMs\n + \" , Num vector clock entries: \"\n + numVectorClockEntries\n + \" , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): \"\n + durationInMs);\n }",
"private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation,\n ModelNode host) {\n final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR));\n if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) {\n //We have a composite operation resulting from a transformation to redeploy affected deployments\n //See redeploying deployments affected by an overlay.\n ModelNode serverOp = operation.clone();\n Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>();\n for (ModelNode step : serverOp.get(STEPS).asList()) {\n ModelNode newStep = step.clone();\n String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue();\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies);\n for(ServerIdentity server : servers) {\n if(!composite.containsKey(server)) {\n composite.put(server, Operations.CompositeOperationBuilder.create());\n }\n composite.get(server).addStep(newStep);\n }\n if(!servers.isEmpty()) {\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n }\n }\n if(!composite.isEmpty()) {\n Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>();\n for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) {\n result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation());\n }\n return result;\n }\n return Collections.emptyMap();\n }\n final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies);\n return Collections.singletonMap(allServers, operation.clone());\n }",
"public static List<String> getArgumentNames(MethodCallExpression methodCall) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n Expression arguments = methodCall.getArguments();\r\n List<Expression> argExpressions = null;\r\n if (arguments instanceof ArrayExpression) {\r\n argExpressions = ((ArrayExpression) arguments).getExpressions();\r\n } else if (arguments instanceof ListExpression) {\r\n argExpressions = ((ListExpression) arguments).getExpressions();\r\n } else if (arguments instanceof TupleExpression) {\r\n argExpressions = ((TupleExpression) arguments).getExpressions();\r\n } else {\r\n LOG.warn(\"getArgumentNames arguments is not an expected type\");\r\n }\r\n\r\n if (argExpressions != null) {\r\n for (Expression exp : argExpressions) {\r\n if (exp instanceof VariableExpression) {\r\n result.add(((VariableExpression) exp).getName());\r\n }\r\n }\r\n }\r\n return result;\r\n }",
"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 }",
"protected List<String> extractWords() throws IOException\n {\n while( true ) {\n lineNumber++;\n String line = in.readLine();\n if( line == null ) {\n return null;\n }\n\n // skip comment lines\n if( hasComment ) {\n if( line.charAt(0) == comment )\n continue;\n }\n\n // extract the words, which are the variables encoded\n return parseWords(line);\n }\n }",
"public static vpnglobal_authenticationsamlpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_authenticationsamlpolicy_binding obj = new vpnglobal_authenticationsamlpolicy_binding();\n\t\tvpnglobal_authenticationsamlpolicy_binding response[] = (vpnglobal_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
overridden in ipv6 to handle zone | [
"protected String toHexString(boolean with0xPrefix, CharSequence zone) {\n\t\tif(isDualString()) {\n\t\t\treturn toNormalizedStringRange(toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams), getLower(), getUpper(), zone);\n\t\t}\n\t\treturn toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams).toString(this, zone);\n\t}"
] | [
"@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null == baseTmsUrl) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"baseTmsUrl\");\n\t\t}\n\n\t\t// Make sure we have a base URL we can work with:\n\t\tif ((baseTmsUrl.startsWith(\"http://\") || baseTmsUrl.startsWith(\"https://\")) && !baseTmsUrl.endsWith(\"/\")) {\n\t\t\tbaseTmsUrl += \"/\";\n\t\t}\n\n\t\t// Make sure there is a correct RasterLayerInfo object:\n\t\tif (layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO) {\n\t\t\ttry {\n\t\t\t\ttileMap = configurationService.getCapabilities(this);\n\t\t\t\tversion = tileMap.getVersion();\n\t\t\t\textension = tileMap.getTileFormat().getExtension();\n\t\t\t\tlayerInfo = configurationService.asLayerInfo(tileMap);\n\t\t\t\tusable = true;\n\t\t\t} catch (TmsLayerException e) {\n\t\t\t\t// a layer needs an info object to keep the DtoConfigurationPostProcessor happy !\n\t\t\t\tlayerInfo = UNUSABLE_LAYER_INFO;\n\t\t\t\tusable = false;\n\t\t\t\tlog.warn(\"The layer could not be correctly initialized: \" + getId(), e);\n\t\t\t}\n\t\t} else if (extension == null) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"extension\");\n\t\t}\n\n\t\tif (layerInfo != null) {\n\t\t\t// Finally prepare some often needed values:\n\t\t\tstate = new TileServiceState(geoService, layerInfo);\n\t\t\t// when proxying the real url will be resolved later on, just use a simple one for now\n\t\t\tboolean proxying = useCache || useProxy || null != authentication;\n\t\t\tif (tileMap != null && !proxying) {\n\t\t\t\turlBuilder = new TileMapUrlBuilder(tileMap);\n\t\t\t} else {\n\t\t\t\turlBuilder = new SimpleTmsUrlBuilder(extension);\n\t\t\t}\n\t\t}\n\t}",
"protected Boolean getIgnoreExpirationDate() {\n\n Boolean isIgnoreExpirationDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_EXPIRATION_DATE);\n return (null == isIgnoreExpirationDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreExpirationDate())\n : isIgnoreExpirationDate;\n }",
"private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\n }",
"protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n if (jobTypes == null) {\n throw new IllegalArgumentException(\"jobTypes must not be null\");\n }\n for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) {\n try {\n checkJobType(entry.getKey(), entry.getValue());\n } catch (IllegalArgumentException iae) {\n throw new IllegalArgumentException(\"jobTypes contained invalid value\", iae);\n }\n }\n }",
"protected boolean isReserved( String name ) {\n if( functions.isFunctionName(name))\n return true;\n\n for (int i = 0; i < name.length(); i++) {\n if( !isLetter(name.charAt(i)) )\n return true;\n }\n return false;\n }",
"protected void beforeMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.beforeMaterialization(this, _id);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public DbOrganization getMatchingOrganization(final DbModule dbModule) {\n if(dbModule.getOrganization() != null\n && !dbModule.getOrganization().isEmpty()){\n return getOrganization(dbModule.getOrganization());\n }\n\n for(final DbOrganization organization: repositoryHandler.getAllOrganizations()){\n final CorporateFilter corporateFilter = new CorporateFilter(organization);\n if(corporateFilter.matches(dbModule)){\n return organization;\n }\n }\n\n return null;\n }",
"public AsciiTable setPaddingBottom(int paddingBottom) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static <T> T[] concat(T[] first, T... second) {\n\t\tint firstLength = first.length;\n\t\tint secondLength = second.length;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( first.getClass().getComponentType(), firstLength + secondLength );\n\t\tSystem.arraycopy( first, 0, result, 0, firstLength );\n\t\tSystem.arraycopy( second, 0, result, firstLength, secondLength );\n\n\t\treturn result;\n\t}"
] |
Returns an array with the width of the longest word per column calculated from the given table.
Default padding will be added per column.
Padding for individual columns will be added if defined.
@param rows the table rows for calculations
@param colNumbers number of columns in the table
@return array with width of longest word for each column, null if input table was null | [
"public static int[] longestWord(LinkedList<AT_Row> rows, int colNumbers){\r\n\t\tif(rows==null){\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif(rows.size()==0){\r\n\t\t\treturn new int[0];\r\n\t\t}\r\n\r\n\t\tint[] ret = new int[colNumbers];\r\n\r\n\t\tfor(AT_Row row : rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT) {\r\n\t\t\t\tLinkedList<AT_Cell> cells = row.getCells();\r\n\r\n\t\t\t\tfor(int i=0; i<cells.size(); i++) {\r\n\t\t\t\t\tif(cells.get(i).getContent()!=null){\r\n\t\t\t\t\t\tString[] ar = StringUtils.split(Object_To_StrBuilder.convert(cells.get(i).getContent()).toString());\r\n\t\t\t\t\t\tfor(int k=0; k<ar.length; k++){\r\n\t\t\t\t\t\t\tint count = ar[k].length() + cells.get(i).getContext().getPaddingLeft() + cells.get(i).getContext().getPaddingRight();\r\n\t\t\t\t\t\t\tif(count>ret[i]){\r\n\t\t\t\t\t\t\t\tret[i] = count;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn ret;\r\n\t}"
] | [
"private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)\r\n {\r\n IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());\r\n\r\n if (indexDef == null)\r\n {\r\n indexDef = new IndexDef(indexDescDef.getName(),\r\n indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));\r\n tableDef.addIndex(indexDef);\r\n }\r\n\r\n try\r\n {\r\n String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n }\r\n catch (NoSuchFieldException ex)\r\n {\r\n // won't happen if we already checked the constraints\r\n }\r\n }",
"@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\n }",
"private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }",
"public synchronized void setDeviceName(String name) {\n if (name.getBytes().length > DEVICE_NAME_LENGTH) {\n throw new IllegalArgumentException(\"name cannot be more than \" + DEVICE_NAME_LENGTH + \" bytes long\");\n }\n Arrays.fill(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH, (byte)0);\n System.arraycopy(name.getBytes(), 0, announcementBytes, DEVICE_NAME_OFFSET, name.getBytes().length);\n }",
"public void createTag(final String tagUrl, final String commitMessage)\n throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new SVNCreateTagCallable(tagUrl, commitMessage, getLocation(), getSvnAuthenticationProvider(build),\n buildListener));\n }",
"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}",
"private static void bodyWithBuilder(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename,\n Predicate<PropertyCodeGenerator> isOptional) {\n Variable result = new Variable(\"result\");\n\n code.add(\" %1$s %2$s = new %1$s(\\\"%3$s{\", StringBuilder.class, result, typename);\n boolean midStringLiteral = true;\n boolean midAppends = true;\n boolean prependCommas = false;\n\n PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values()\n .stream()\n .filter(isOptional)\n .reduce((first, second) -> second)\n .get();\n\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n if (isOptional.test(generator)) {\n if (midStringLiteral) {\n code.add(\"\\\")\");\n }\n if (midAppends) {\n code.add(\";%n \");\n }\n code.add(\"if (\");\n if (generator.initialState() == Initially.OPTIONAL) {\n generator.addToStringCondition(code);\n } else {\n code.add(\"!%s.contains(%s.%s)\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n }\n code.add(\") {%n %s.append(\\\"\", result);\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), property.getField());\n if (!prependCommas) {\n code.add(\".append(\\\", \\\")\");\n }\n code.add(\";%n }%n \");\n if (generator.equals(lastOptionalGenerator)) {\n code.add(\"return %s.append(\\\"\", result);\n midStringLiteral = true;\n midAppends = true;\n } else {\n midStringLiteral = false;\n midAppends = false;\n }\n } else {\n if (!midAppends) {\n code.add(\"%s\", result);\n }\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), (Excerpt) generator::addToStringValue);\n midStringLiteral = false;\n midAppends = true;\n prependCommas = true;\n }\n }\n\n checkState(prependCommas, \"Unexpected state at end of toString method\");\n checkState(midAppends, \"Unexpected state at end of toString method\");\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n code.add(\"}\\\").toString();%n\", result);\n }",
"public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Metadata createMetadata(String templateName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.createMetadata(templateName, scope, metadata);\n }"
] |
Helper method that encapsulates the logic to acquire a lock.
@param jedis
the connection to Redis
@param namespace
the Resque namespace
@param lockName
all calls to this method will contend for a unique lock with
the name of lockName
@param timeout
seconds until the lock will expire
@param lockHolder
a unique string used to tell if you are the current holder of
a lock for both acquisition, and extension
@return Whether or not the lock was acquired. | [
"public static boolean doAcquireLock(final Jedis jedis, final String namespace, final String lockName, final String lockHolder, final int timeout) {\n final String key = JesqueUtils.createKey(namespace, lockName);\n // If lock already exists, extend it\n String existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n }\n // Check to see if the key exists and is expired for cleanup purposes\n if (jedis.exists(key) && (jedis.ttl(key) < 0)) {\n // It is expired, but it may be in the process of being created, so\n // sleep and check again\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ie) {\n } // Ignore interruptions\n if (jedis.ttl(key) < 0) {\n existingLockHolder = jedis.get(key);\n // If it is our lock mark the time to live\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n } else { // The key is expired, whack it!\n jedis.del(key);\n }\n } else { // Someone else locked it while we were sleeping\n return false;\n }\n }\n // Ignore the cleanup steps above, start with no assumptions test\n // creating the key\n if (jedis.setnx(key, lockHolder) == 1) {\n // Created the lock, now set the expiration\n if (jedis.expire(key, timeout) == 1) { // Set the timeout\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n } else { // Don't know why it failed, but for now just report failed\n // acquisition\n return false;\n }\n }\n // Failed to create the lock\n return false;\n }"
] | [
"protected I_CmsSearchDocument appendFieldMappingsFromElementsOnThePage(\n I_CmsSearchDocument document,\n CmsObject cms,\n CmsResource resource,\n List<String> systemFields) {\n\n try {\n CmsFile file = cms.readFile(resource);\n CmsXmlContainerPage containerPage = CmsXmlContainerPageFactory.unmarshal(cms, file);\n CmsContainerPageBean containerBean = containerPage.getContainerPage(cms);\n if (containerBean != null) {\n for (CmsContainerElementBean element : containerBean.getElements()) {\n element.initResource(cms);\n CmsResource elemResource = element.getResource();\n Set<CmsSearchField> mappedFields = getXSDMappingsForPage(cms, elemResource);\n if (mappedFields != null) {\n\n for (CmsSearchField field : mappedFields) {\n if (!systemFields.contains(field.getName())) {\n document = appendFieldMapping(\n document,\n field,\n cms,\n elemResource,\n CmsSolrDocumentXmlContent.extractXmlContent(cms, elemResource, getIndex()),\n cms.readPropertyObjects(resource, false),\n cms.readPropertyObjects(resource, true));\n } else {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.LOG_SOLR_ERR_MAPPING_TO_INTERNALLY_USED_FIELD_3,\n elemResource.getRootPath(),\n field.getName(),\n resource.getRootPath()));\n }\n }\n }\n }\n }\n } catch (CmsException e) {\n // Should be thrown if element on the page does not exist anymore - this is possible, but not necessarily an error.\n // Hence, just notice it in the debug log.\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n }\n return document;\n }",
"public void setOwner(Graph<DataT, NodeT> ownerGraph) {\n if (this.ownerGraph != null) {\n throw new RuntimeException(\"Changing owner graph is not allowed\");\n }\n this.ownerGraph = ownerGraph;\n }",
"public static int optionLength(String option) {\n\tint result = Standard.optionLength(option);\n\tif (result != 0)\n\t return result;\n\telse\n\t return UmlGraph.optionLength(option);\n }",
"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 }",
"public static clusternodegroup get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tobj.set_name(name);\n\t\tclusternodegroup response = (clusternodegroup) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }",
"public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }",
"public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}",
"public int getTotalCreatedConnections(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}"
] |
Sets the value of a UDF.
@param udf user defined field
@param dataType MPXJ data type
@param value field value | [
"private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }"
] | [
"private Resolvable createMetadataProvider(Class<?> rawType) {\n Set<Type> types = Collections.<Type>singleton(rawType);\n return new ResolvableImpl(rawType, types, declaringBean, qualifierInstances, delegate);\n }",
"public void runOnInvariantViolationPlugins(Invariant invariant,\n\t\t\tCrawlerContext context) {\n\t\tLOGGER.debug(\"Running OnInvariantViolationPlugins...\");\n\t\tcounters.get(OnInvariantViolationPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {\n\t\t\tif (plugin instanceof OnInvariantViolationPlugin) {\n\t\t\t\ttry {\n\t\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\t\t((OnInvariantViolationPlugin) plugin).onInvariantViolation(\n\t\t\t\t\t\t\tinvariant, context);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static Class getClass(String name) throws ClassNotFoundException\r\n {\r\n try\r\n {\r\n return Class.forName(name);\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ClassNotFoundException(name);\r\n }\r\n }",
"public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }",
"private void readColumnBlock(int startIndex, int blockLength) throws Exception\n {\n int endIndex = startIndex + blockLength;\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = startIndex; index < endIndex - 11; index++)\n {\n if (matchChildBlock(index))\n {\n int childBlockStart = index - 2;\n blocks.add(Integer.valueOf(childBlockStart));\n }\n }\n blocks.add(Integer.valueOf(endIndex));\n\n int childBlockStart = -1;\n for (int childBlockEnd : blocks)\n {\n if (childBlockStart != -1)\n {\n int childblockLength = childBlockEnd - childBlockStart;\n try\n {\n readColumn(childBlockStart, childblockLength);\n }\n catch (UnexpectedStructureException ex)\n {\n logUnexpectedStructure();\n }\n }\n childBlockStart = childBlockEnd;\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}",
"static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final\n ViewQueryParameters<K, V> initialParameters) {\n\n // Decode the base64 token into JSON\n String json = new String(Base64.decodeBase64(paginationToken), Charset.forName(\"UTF-8\"));\n\n // Get a suitable Gson, we need any adapter registered for the K key type\n Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters);\n\n // Deserialize the pagination token JSON, using the appropriate K, V types\n PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class);\n\n // Create new query parameters using the initial ViewQueryParameters as a starting point.\n ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy();\n\n // Merge the values from the token into the new query parameters\n tokenPageParameters.descending = token.descending;\n tokenPageParameters.endkey = token.endkey;\n tokenPageParameters.endkey_docid = token.endkey_docid;\n tokenPageParameters.inclusive_end = token.inclusive_end;\n tokenPageParameters.startkey = token.startkey;\n tokenPageParameters.startkey_docid = token.startkey_docid;\n\n return new PageMetadata<K, V>(token.direction, token\n .pageNumber, tokenPageParameters);\n }",
"private static int getTrimmedWidth(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int trimmedWidth = 0;\n\n for (int i = 0; i < height; i++) {\n for (int j = width - 1; j >= 0; j--) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {\n trimmedWidth = j;\n break;\n }\n }\n }\n\n return trimmedWidth;\n }",
"public void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }"
] |
Loads the tag definitions from the files with a ".tags.xml" suffix from the addons. | [
"@PostConstruct\n public void loadTagDefinitions()\n {\n Map<Addon, List<URL>> addonToResourcesMap = scanner.scanForAddonMap(new FileExtensionFilter(\"tags.xml\"));\n for (Map.Entry<Addon, List<URL>> entry : addonToResourcesMap.entrySet())\n {\n for (URL resource : entry.getValue())\n {\n log.info(\"Reading tags definitions from: \" + resource.toString() + \" from addon \" + entry.getKey().getId());\n try(InputStream is = resource.openStream())\n {\n tagService.readTags(is);\n }\n catch( Exception ex )\n {\n throw new WindupException(\"Failed reading tags definition: \" + resource.toString() + \" from addon \" + entry.getKey().getId() + \":\\n\" + ex.getMessage(), ex);\n }\n }\n }\n }"
] | [
"public final void setIndividualDates(SortedSet<Date> dates) {\n\n m_individualDates.clear();\n if (null != dates) {\n m_individualDates.addAll(dates);\n }\n for (Date d : getExceptions()) {\n if (!m_individualDates.contains(d)) {\n m_exceptions.remove(d);\n }\n }\n\n }",
"public static int cudnnPoolingForward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnPoolingForwardNative(handle, poolingDesc, alpha, xDesc, x, beta, yDesc, y));\n }",
"public static boolean isFalse(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"FALSE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression())\r\n || \"Boolean.FALSE\".equals(expression.getText());\r\n }",
"public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }",
"private String escapeText(StringBuilder sb, String text)\n {\n int length = text.length();\n char c;\n\n sb.setLength(0);\n\n for (int loop = 0; loop < length; loop++)\n {\n c = text.charAt(loop);\n\n switch (c)\n {\n case '<':\n {\n sb.append(\"<\");\n break;\n }\n\n case '>':\n {\n sb.append(\">\");\n break;\n }\n\n case '&':\n {\n sb.append(\"&\");\n break;\n }\n\n default:\n {\n if (validXMLCharacter(c))\n {\n if (c > 127)\n {\n sb.append(\"&#\" + (int) c + \";\");\n }\n else\n {\n sb.append(c);\n }\n }\n\n break;\n }\n }\n }\n\n return (sb.toString());\n }",
"private void writeAssignments()\n {\n Allocations allocations = m_factory.createAllocations();\n m_plannerProject.setAllocations(allocations);\n\n List<Allocation> allocationList = allocations.getAllocation();\n for (ResourceAssignment mpxjAssignment : m_projectFile.getResourceAssignments())\n {\n Allocation plannerAllocation = m_factory.createAllocation();\n allocationList.add(plannerAllocation);\n\n plannerAllocation.setTaskId(getIntegerString(mpxjAssignment.getTask().getUniqueID()));\n plannerAllocation.setResourceId(getIntegerString(mpxjAssignment.getResourceUniqueID()));\n plannerAllocation.setUnits(getIntegerString(mpxjAssignment.getUnits()));\n\n m_eventManager.fireAssignmentWrittenEvent(mpxjAssignment);\n }\n }",
"private void readCalendar(net.sf.mpxj.planner.schema.Calendar plannerCalendar, ProjectCalendar parentMpxjCalendar) throws MPXJException\n {\n //\n // Create a calendar instance\n //\n ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();\n\n //\n // Populate basic details\n //\n mpxjCalendar.setUniqueID(getInteger(plannerCalendar.getId()));\n mpxjCalendar.setName(plannerCalendar.getName());\n mpxjCalendar.setParent(parentMpxjCalendar);\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = plannerCalendar.getDefaultWeek();\n setWorkingDay(mpxjCalendar, Day.MONDAY, dw.getMon());\n setWorkingDay(mpxjCalendar, Day.TUESDAY, dw.getTue());\n setWorkingDay(mpxjCalendar, Day.WEDNESDAY, dw.getWed());\n setWorkingDay(mpxjCalendar, Day.THURSDAY, dw.getThu());\n setWorkingDay(mpxjCalendar, Day.FRIDAY, dw.getFri());\n setWorkingDay(mpxjCalendar, Day.SATURDAY, dw.getSat());\n setWorkingDay(mpxjCalendar, Day.SUNDAY, dw.getSun());\n\n //\n // Set working hours\n //\n processWorkingHours(mpxjCalendar, plannerCalendar);\n\n //\n // Process exception days\n //\n processExceptionDays(mpxjCalendar, plannerCalendar);\n\n m_eventManager.fireCalendarReadEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n for (net.sf.mpxj.planner.schema.Calendar cal : calendarList)\n {\n readCalendar(cal, mpxjCalendar);\n }\n }",
"public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}",
"public void add(StatementRank rank, Resource subject) {\n\t\tif (this.bestRank == rank) {\n\t\t\tsubjects.add(subject);\n\t\t} else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) {\n\t\t\t//We found a preferred statement\n\t\t\tsubjects.clear();\n\t\t\tbestRank = StatementRank.PREFERRED;\n\t\t\tsubjects.add(subject);\n\t\t}\n\t}"
] |
Initialize the various DAO configurations after the various setters have been called. | [
"public void initialize() throws SQLException {\n\t\tif (initialized) {\n\t\t\t// just skip it if already initialized\n\t\t\treturn;\n\t\t}\n\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalStateException(\"connectionSource was never set on \" + getClass().getSimpleName());\n\t\t}\n\n\t\tdatabaseType = connectionSource.getDatabaseType();\n\t\tif (databaseType == null) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"connectionSource is getting a null DatabaseType in \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableConfig == null) {\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, dataClass);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t}\n\t\tstatementExecutor = new StatementExecutor<T, ID>(databaseType, tableInfo, this);\n\n\t\t/*\n\t\t * This is a bit complex. Initially, when we were configuring the field types, external DAO information would be\n\t\t * configured for auto-refresh, foreign BaseDaoEnabled classes, and foreign-collections. This would cause the\n\t\t * system to go recursive and for class loops, a stack overflow.\n\t\t * \n\t\t * Then we fixed this by putting a level counter in the FieldType constructor that would stop the configurations\n\t\t * when we reach some recursion level. But this created some bad problems because we were using the DaoManager\n\t\t * to cache the created DAOs that had been constructed already limited by the level.\n\t\t * \n\t\t * What we do now is have a 2 phase initialization. The constructor initializes most of the fields but then we\n\t\t * go back and call FieldType.configDaoInformation() after we are done. So for every DAO that is initialized\n\t\t * here, we have to see if it is the top DAO. If not we save it for dao configuration later.\n\t\t */\n\t\tList<BaseDaoImpl<?, ?>> daoConfigList = daoConfigLevelLocal.get();\n\t\tdaoConfigList.add(this);\n\t\tif (daoConfigList.size() > 1) {\n\t\t\t// if we have recursed then just save the dao for later configuration\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t/*\n\t\t\t * WARNING: We do _not_ use an iterator here because we may be adding to the list as we process it and we'll\n\t\t\t * get exceptions otherwise. This is an ArrayList so the get(i) should be efficient.\n\t\t\t * \n\t\t\t * Also, do _not_ get a copy of daoConfigLevel.doArray because that array may be replaced by another, larger\n\t\t\t * one during the recursion.\n\t\t\t */\n\t\t\tfor (int i = 0; i < daoConfigList.size(); i++) {\n\t\t\t\tBaseDaoImpl<?, ?> dao = daoConfigList.get(i);\n\n\t\t\t\t/*\n\t\t\t\t * Here's another complex bit. The first DAO that is being constructed as part of a DAO chain is not yet\n\t\t\t\t * in the DaoManager cache. If we continue onward we might come back around and try to configure this\n\t\t\t\t * DAO again. Forcing it into the cache here makes sure it won't be configured twice. This will cause it\n\t\t\t\t * to be stuck in twice when it returns out to the DaoManager but that's a small price to pay. This also\n\t\t\t\t * applies to self-referencing classes.\n\t\t\t\t */\n\t\t\t\tDaoManager.registerDao(connectionSource, dao);\n\n\t\t\t\ttry {\n\t\t\t\t\t// config our fields which may go recursive\n\t\t\t\t\tfor (FieldType fieldType : dao.getTableInfo().getFieldTypes()) {\n\t\t\t\t\t\tfieldType.configDaoInformation(connectionSource, dao.getDataClass());\n\t\t\t\t\t}\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t// unregister the DAO we just pre-registered\n\t\t\t\t\tDaoManager.unregisterDao(connectionSource, dao);\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\n\t\t\t\t// it's now been fully initialized\n\t\t\t\tdao.initialized = true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// if we throw we want to clear our class hierarchy here\n\t\t\tdaoConfigList.clear();\n\t\t\tdaoConfigLevelLocal.remove();\n\t\t}\n\t}"
] | [
"public static double getRobustTreeEditDistance(String dom1, String dom2) {\n\n\t\tLblTree domTree1 = null, domTree2 = null;\n\t\ttry {\n\t\t\tdomTree1 = getDomTree(dom1);\n\t\t\tdomTree2 = getDomTree(dom2);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tdouble DD = 0.0;\n\t\tRTED_InfoTree_Opt rted;\n\t\tdouble ted;\n\n\t\trted = new RTED_InfoTree_Opt(1, 1, 1);\n\n\t\t// compute tree edit distance\n\t\trted.init(domTree1, domTree2);\n\n\t\tint maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());\n\n\t\trted.computeOptimalStrategy();\n\t\tted = rted.nonNormalizedTreeDist();\n\t\tted /= (double) maxSize;\n\n\t\tDD = ted;\n\t\treturn DD;\n\t}",
"public void pause(ServerActivityCallback requestCountListener) {\n if (paused) {\n throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();\n }\n this.paused = true;\n listenerUpdater.set(this, requestCountListener);\n if (activeRequestCountUpdater.get(this) == 0) {\n if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {\n requestCountListener.done();\n }\n }\n }",
"public static String parseString(String value)\n {\n if (value != null)\n {\n // Strip angle brackets if present\n if (!value.isEmpty() && value.charAt(0) == '<')\n {\n value = value.substring(1, value.length() - 1);\n }\n\n // Strip quotes if present\n if (!value.isEmpty() && value.charAt(0) == '\"')\n {\n value = value.substring(1, value.length() - 1);\n }\n }\n return value;\n }",
"private void readProject(Project project)\n {\n Task mpxjTask = m_projectFile.addTask();\n //project.getAuthor()\n mpxjTask.setBaselineCost(project.getBaselineCost());\n mpxjTask.setBaselineFinish(project.getBaselineFinishDate());\n mpxjTask.setBaselineStart(project.getBaselineStartDate());\n //project.getBudget();\n //project.getCompany()\n mpxjTask.setFinish(project.getFinishDate());\n //project.getGoal()\n //project.getHyperlinks()\n //project.getMarkerID()\n mpxjTask.setName(project.getName());\n mpxjTask.setNotes(project.getNote());\n mpxjTask.setPriority(project.getPriority());\n // project.getSite()\n mpxjTask.setStart(project.getStartDate());\n // project.getStyleProject()\n // project.getTask()\n // project.getTimeScale()\n // project.getViewProperties()\n\n String projectIdentifier = project.getID().toString();\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(projectIdentifier.getBytes()));\n\n //\n // Sort the tasks into the correct order\n //\n List<Document.Projects.Project.Task> tasks = new ArrayList<Document.Projects.Project.Task>(project.getTask());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(tasks, new Comparator<Document.Projects.Project.Task>()\n {\n @Override public int compare(Document.Projects.Project.Task o1, Document.Projects.Project.Task o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n Map<String, Task> map = new HashMap<String, Task>();\n map.put(\"\", mpxjTask);\n\n for (Document.Projects.Project.Task task : tasks)\n {\n readTask(projectIdentifier, map, task);\n }\n }",
"public static wisite_accessmethod_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_accessmethod_binding obj = new wisite_accessmethod_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_accessmethod_binding response[] = (wisite_accessmethod_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static ResourceBundle tryBundle(String baseName, Locale locale, boolean wantBase) {\n\n I_CmsResourceBundle first = null; // The most specialized bundle.\n I_CmsResourceBundle last = null; // The least specialized bundle.\n\n List<String> bundleNames = CmsLocaleManager.getLocaleVariants(baseName, locale, true, true);\n for (String bundleName : bundleNames) {\n // break if we would try the base bundle, but we do not want it directly\n if (bundleName.equals(baseName) && !wantBase && (first == null)) {\n break;\n }\n I_CmsResourceBundle foundBundle = tryBundle(bundleName);\n if (foundBundle != null) {\n if (first == null) {\n first = foundBundle;\n }\n\n if (last != null) {\n last.setParent((ResourceBundle)foundBundle);\n }\n foundBundle.setLocale(locale);\n\n last = foundBundle;\n }\n }\n return (ResourceBundle)first;\n }",
"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 }",
"protected void updatePicker(MotionEvent event, boolean isActive)\n {\n final MotionEvent newEvent = (event != null) ? event : null;\n final ControllerPick controllerPick = new ControllerPick(mPicker, newEvent, isActive);\n context.runOnGlThread(controllerPick);\n }",
"public static base_response update(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 updateresource = new nsacl6();\n\t\tupdateresource.acl6name = resource.acl6name;\n\t\tupdateresource.aclaction = resource.aclaction;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.icmptype = resource.icmptype;\n\t\tupdateresource.icmpcode = resource.icmpcode;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.established = resource.established;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Generate a schedule for the given start and end date.
@param referenceDate The reference date (corresponds to \( t = 0 \).
@param startDate The start date.
@param endDate The end date.
@return The schedule | [
"public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) {\r\n\t\treturn ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(),\r\n\t\t\t\tgetShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}"
] | [
"public final void notifyHeaderItemChanged(int position) {\n if (position < 0 || position >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position);\n }",
"public static base_response unset(nitro_service client, sslservice resource, String[] args) throws Exception{\n\t\tsslservice unsetresource = new sslservice();\n\t\tunsetresource.servicename = resource.servicename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags)\n );\n }",
"public void setActiveView(View v, int position) {\n final View oldView = mActiveView;\n mActiveView = v;\n mActivePosition = position;\n\n if (mAllowIndicatorAnimation && oldView != null) {\n startAnimatingIndicator();\n }\n\n invalidate();\n }",
"public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }",
"public static base_response add(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 addresource = new nsacl6();\n\t\taddresource.acl6name = resource.acl6name;\n\t\taddresource.acl6action = resource.acl6action;\n\t\taddresource.td = resource.td;\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.ttl = resource.ttl;\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.established = resource.established;\n\t\taddresource.icmptype = resource.icmptype;\n\t\taddresource.icmpcode = resource.icmpcode;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\treturn addresource.add_resource(client);\n\t}",
"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 static Timer getNamedTotalTimer(String timerName) {\n\t\tlong totalCpuTime = 0;\n\t\tlong totalSystemTime = 0;\n\t\tint measurements = 0;\n\t\tint timerCount = 0;\n\t\tint todoFlags = RECORD_NONE;\n\n\t\tTimer previousTimer = null;\n\t\tfor (Map.Entry<Timer, Timer> entry : registeredTimers.entrySet()) {\n\t\t\tif (entry.getValue().name.equals(timerName)) {\n\t\t\t\tpreviousTimer = entry.getValue();\n\t\t\t\ttimerCount += 1;\n\t\t\t\ttotalCpuTime += previousTimer.totalCpuTime;\n\t\t\t\ttotalSystemTime += previousTimer.totalWallTime;\n\t\t\t\tmeasurements += previousTimer.measurements;\n\t\t\t\ttodoFlags |= previousTimer.todoFlags;\n\t\t\t}\n\t\t}\n\n\t\tif (timerCount == 1) {\n\t\t\treturn previousTimer;\n\t\t} else {\n\t\t\tTimer result = new Timer(timerName, todoFlags, 0);\n\t\t\tresult.totalCpuTime = totalCpuTime;\n\t\t\tresult.totalWallTime = totalSystemTime;\n\t\t\tresult.measurements = measurements;\n\t\t\tresult.threadCount = timerCount;\n\t\t\treturn result;\n\t\t}\n\t}",
"public void initializePersistenceStrategy(CacheMappingType cacheMappingType, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes, Iterable<Namespace> namespaces) {\n\t\tpersistenceStrategy = PersistenceStrategy.getInstance(\n\t\t\t\tcacheMappingType,\n\t\t\t\texternalCacheManager,\n\t\t\t\tconfig.getConfigurationUrl(),\n\t\t\t\tjtaPlatform,\n\t\t\t\tentityTypes,\n\t\t\t\tassociationTypes,\n\t\t\t\tidSourceTypes\n\t\t);\n\n\t\t// creates handler for TableGenerator Id sources\n\t\tboolean requiresCounter = hasIdGeneration( idSourceTypes );\n\t\tif ( requiresCounter ) {\n\t\t\tthis.tableClusterHandler = new TableClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager() );\n\t\t}\n\n\t\t// creates handlers for SequenceGenerator Id sources\n\t\tfor ( Namespace namespace : namespaces ) {\n\t\t\tfor ( Sequence seq : namespace.getSequences() ) {\n\t\t\t\tthis.sequenceCounterHandlers.put( seq.getExportIdentifier(),\n\t\t\t\t\t\tnew SequenceClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager(), seq ) );\n\t\t\t}\n\t\t}\n\n\t\t// clear resources\n\t\tthis.externalCacheManager = null;\n\t\tthis.jtaPlatform = null;\n\t}"
] |
Writes OWL declarations for all basic vocabulary elements used in the
dump.
@throws RDFHandlerException | [
"public void writeBasicDeclarations() throws RDFHandlerException {\n\t\tfor (Map.Entry<String, String> uriType : Vocabulary\n\t\t\t\t.getKnownVocabularyTypes().entrySet()) {\n\t\t\tthis.rdfWriter.writeTripleUriObject(uriType.getKey(),\n\t\t\t\t\tRdfWriter.RDF_TYPE, uriType.getValue());\n\t\t}\n\t}"
] | [
"public static <T> T flattenOption(scala.Option<T> option) {\n if (option.isEmpty()) {\n return null;\n } else {\n return option.get();\n }\n }",
"public static void closeMASCaseManager(File caseManager) {\n\n FileWriter caseManagerWriter;\n try {\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\"}\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger\n .getLogger(\"CreateMASCaseManager.closeMASCaseManager\");\n logger.info(\"ERROR: There is a mistake closing caseManager file.\\n\");\n }\n\n }",
"public static Trajectory addPositionNoise(Trajectory t, double sd){\n\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\tTrajectory newt = new Trajectory(t.getDimension());\n\t\t\n\t\tfor(int i = 0; i < t.size(); i++){\n\t\t\tnewt.add(t.get(i));\n\t\t\tfor(int j = 1; j <= t.getDimension(); j++){\n\t\t\t\tswitch (j) {\n\t\t\t\tcase 1:\n\t\t\t\t\tnewt.get(i).setX(newt.get(i).x + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tnewt.get(i).setY(newt.get(i).y + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tnewt.get(i).setZ(newt.get(i).z + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn newt;\n\t\t\n\t}",
"private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }",
"public boolean process( DMatrixSparseCSC A ) {\n init(A);\n\n TriangularSolver_DSCC.eliminationTree(A,true,parent,gwork);\n\n countNonZeroInR(parent);\n countNonZeroInV(parent);\n\n // if more columns than rows it's possible that Q*R != A. That's because a householder\n // would need to be created that's outside the m by m Q matrix. In reality it has\n // a partial solution. Column pivot are needed.\n if( m < n ) {\n for (int row = 0; row <m; row++) {\n if( gwork.data[head+row] < 0 ) {\n return false;\n }\n }\n }\n return true;\n }",
"public static lbvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tlbvserver[] response = (lbvserver[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding)\n throws JMException, UnsupportedEncodingException {\n return new WebMBeanAdapter(mBeanServer, mBeanName, encoding);\n }",
"private void buildJoinTree(Criteria crit)\r\n {\r\n Enumeration e = crit.getElements();\r\n\r\n while (e.hasMoreElements())\r\n {\r\n Object o = e.nextElement();\r\n if (o instanceof Criteria)\r\n {\r\n buildJoinTree((Criteria) o);\r\n }\r\n else\r\n {\r\n SelectionCriteria c = (SelectionCriteria) o;\r\n \r\n // BRJ skip SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n continue;\r\n }\r\n \r\n // BRJ: Outer join for OR\r\n boolean useOuterJoin = (crit.getType() == Criteria.OR);\r\n\r\n // BRJ: do not build join tree for subQuery attribute \r\n if (c.getAttribute() != null && c.getAttribute() instanceof String)\r\n {\r\n\t\t\t\t\t//buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getAlias(), c.getPathClasses());\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n if (c instanceof FieldCriteria)\r\n {\r\n FieldCriteria cc = (FieldCriteria) c;\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) cc.getValue(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n }\r\n }\r\n }",
"protected boolean waitForJobs() throws InterruptedException {\n final Pair<Long, Job> peekPair;\n try (Guard ignored = timeQueue.lock()) {\n peekPair = timeQueue.peekPair();\n }\n if (peekPair == null) {\n awake.acquire();\n return true;\n }\n final long timeout = Long.MAX_VALUE - peekPair.getFirst() - System.currentTimeMillis();\n if (timeout < 0) {\n return false;\n }\n return awake.tryAcquire(timeout, TimeUnit.MILLISECONDS);\n }"
] |
Read an optional string value form a JSON Object.
@param json the JSON object to read from.
@param key the key for the string value in the provided JSON object.
@param defaultValue the default value, to be returned if the string can not be read from the JSON object.
@return the string or the default value if reading the string fails. | [
"private String readOptionalString(JSONObject json, String key, String defaultValue) {\n\n try {\n String str = json.getString(key);\n if (str != null) {\n return str;\n }\n\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON string failed. Default to provided default value.\", e);\n }\n return defaultValue;\n }"
] | [
"private String convertOutputToHtml(String content) {\n\n if (content.length() == 0) {\n return \"\";\n }\n StringBuilder buffer = new StringBuilder();\n for (String line : content.split(\"\\n\")) {\n buffer.append(CmsEncoder.escapeXml(line) + \"<br>\");\n }\n return buffer.toString();\n }",
"public static void acceptsNodeMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id list\")\n .withRequiredArg()\n .describedAs(\"node-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\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 }",
"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 }",
"@Override public int getItemViewType(int position) {\n T content = getItem(position);\n return rendererBuilder.getItemViewType(content);\n }",
"public Date getEnd() {\n\n if (null != m_explicitEnd) {\n return isWholeDay() ? adjustForWholeDay(m_explicitEnd, true) : m_explicitEnd;\n }\n if ((null == m_end) && (m_series.getInstanceDuration() != null)) {\n m_end = new Date(m_start.getTime() + m_series.getInstanceDuration().longValue());\n }\n return isWholeDay() && !m_series.isWholeDay() ? adjustForWholeDay(m_end, true) : m_end;\n }",
"InputStream openContentStream(final ContentItem item) throws IOException {\n final File file = getFile(item);\n if (file == null) {\n throw new IllegalStateException();\n }\n return new FileInputStream(file);\n }",
"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 String getPublicIPAddress() throws Exception {\n final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\n\n String ipAddr = null;\n Enumeration e = NetworkInterface.getNetworkInterfaces();\n while (e.hasMoreElements()) {\n NetworkInterface n = (NetworkInterface) e.nextElement();\n Enumeration ee = n.getInetAddresses();\n while (ee.hasMoreElements()) {\n InetAddress i = (InetAddress) ee.nextElement();\n\n // Pick the first non loop back address\n if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) ||\n i.getHostAddress().matches(IPV4_REGEX)) {\n ipAddr = i.getHostAddress();\n break;\n }\n }\n if (ipAddr != null) {\n break;\n }\n }\n\n return ipAddr;\n }"
] |
Use this API to clear configuration on netscaler.
@param force clear confirmation without prompting.
@param level clear config according to the level. eg: basic, extended, full
@return status of the operation performed.
@throws Exception Nitro exception is thrown. | [
"public base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}"
] | [
"private String formatDateTimeNull(Date value)\n {\n return (value == null ? m_formats.getNullText() : m_formats.getDateTimeFormat().format(value));\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 DesignDocument get(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id), rev);\r\n }",
"private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {\n\t\tLOGGER.debug(\"addStateToCurrentState currentState: {} newState {}\",\n\t\t\t\tcurrentState.getName(), newState.getName());\n\n\t\t// Add the state to the stateFlowGraph. Store the result\n\t\tStateVertex cloneState = stateFlowGraph.putIfAbsent(newState);\n\n\t\t// Is there a clone detected?\n\t\tif (cloneState != null) {\n\t\t\tLOGGER.info(\"CLONE State detected: {} and {} are the same.\", newState.getName(),\n\t\t\t\t\tcloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CURRENT STATE: {}\", currentState.getName());\n\t\t\tLOGGER.debug(\"CLONE STATE: {}\", cloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CLICKABLE: {}\", eventable);\n\t\t\tboolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);\n\t\t\tif (!added) {\n\t\t\t\tLOGGER.debug(\"Clone edge !! Need to fix the crawlPath??\");\n\t\t\t}\n\t\t} else {\n\t\t\tstateFlowGraph.addEdge(currentState, newState, eventable);\n\t\t\tLOGGER.info(\"State {} added to the StateMachine.\", newState.getName());\n\t\t}\n\n\t\treturn cloneState;\n\t}",
"protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }",
"public static Cluster getCluster(ZkClient zkClient) {\n Cluster cluster = new Cluster();\n List<String> nodes = getChildrenParentMayNotExist(zkClient, BrokerIdsPath);\n for (String node : nodes) {\n final String brokerInfoString = readData(zkClient, BrokerIdsPath + \"/\" + node);\n cluster.add(Broker.createBroker(Integer.valueOf(node), brokerInfoString));\n }\n return cluster;\n }",
"public static Boolean compareMultipleClientConfigAvro(String configAvro1, String configAvro2) {\n Map<String, Properties> mapStoreToProps1 = readMultipleClientConfigAvro(configAvro1);\n Map<String, Properties> mapStoreToProps2 = readMultipleClientConfigAvro(configAvro2);\n Set<String> keySet1 = mapStoreToProps1.keySet();\n Set<String> keySet2 = mapStoreToProps2.keySet();\n if(!keySet1.equals(keySet2)) {\n return false;\n }\n for(String storeName: keySet1) {\n Properties props1 = mapStoreToProps1.get(storeName);\n Properties props2 = mapStoreToProps2.get(storeName);\n if(!props1.equals(props2)) {\n return false;\n }\n }\n return true;\n }",
"public void addBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final boolean statementBatchingSupported = m_batchStatementsInProgress.containsKey(stmt);\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n stmt.executeUpdate();\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.addBatch(stmt);\r\n }\r\n }",
"private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }"
] |
Print a time value.
@param value time value
@return time value | [
"public static final String printTime(Date value)\n {\n return (value == null ? null : TIME_FORMAT.get().format(value));\n }"
] | [
"public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"public static base_response add(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance addresource = new clusterinstance();\n\t\taddresource.clid = resource.clid;\n\t\taddresource.deadinterval = resource.deadinterval;\n\t\taddresource.hellointerval = resource.hellointerval;\n\t\taddresource.preemption = resource.preemption;\n\t\treturn addresource.add_resource(client);\n\t}",
"static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }",
"protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }",
"public static Date getTimestampFromLong(long timestamp)\n {\n TimeZone tz = TimeZone.getDefault();\n Date result = new Date(timestamp - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n return (result);\n }",
"@JmxGetter(name = \"avgSlopUpdateNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgSlopUpdateNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.SLOP_UPDATE).getAvgEventValue() / Time.NS_PER_MS;\n }",
"private long doMemoryManagementAndPerFrameCallbacks() {\n long currentTime = GVRTime.getCurrentTime();\n mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f;\n mPreviousTimeNanos = currentTime;\n\n /*\n * Without the sensor data, can't draw a scene properly.\n */\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n Runnable runnable;\n while ((runnable = mRunnables.poll()) != null) {\n try {\n runnable.run();\n } catch (final Exception exc) {\n Log.e(TAG, \"Runnable-on-GL %s threw %s\", runnable, exc.toString());\n exc.printStackTrace();\n }\n }\n\n final List<GVRDrawFrameListener> frameListeners = mFrameListeners;\n for (GVRDrawFrameListener listener : frameListeners) {\n try {\n listener.onDrawFrame(mFrameTime);\n } catch (final Exception exc) {\n Log.e(TAG, \"DrawFrameListener %s threw %s\", listener, exc.toString());\n exc.printStackTrace();\n }\n }\n }\n\n return currentTime;\n }",
"public static nstrafficdomain_binding[] get(nitro_service service, Long td[]) throws Exception{\n\t\tif (td !=null && td.length>0) {\n\t\t\tnstrafficdomain_binding response[] = new nstrafficdomain_binding[td.length];\n\t\t\tnstrafficdomain_binding obj[] = new nstrafficdomain_binding[td.length];\n\t\t\tfor (int i=0;i<td.length;i++) {\n\t\t\t\tobj[i] = new nstrafficdomain_binding();\n\t\t\t\tobj[i].set_td(td[i]);\n\t\t\t\tresponse[i] = (nstrafficdomain_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}"
] |
Updates all inverse associations managed by a given entity. | [
"public void addNavigationalInformationForInverseSide() {\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Adding inverse navigational information for entity: \" + MessageHelper.infoString( persister, id, persister.getFactory() ) );\n\t\t}\n\n\t\tfor ( int propertyIndex = 0; propertyIndex < persister.getEntityMetamodel().getPropertySpan(); propertyIndex++ ) {\n\t\t\tif ( persister.isPropertyOfTable( propertyIndex, tableIndex ) ) {\n\t\t\t\tAssociationKeyMetadata associationKeyMetadata = getInverseAssociationKeyMetadata( propertyIndex );\n\n\t\t\t\t// there is no inverse association for the given property\n\t\t\t\tif ( associationKeyMetadata == null ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tObject[] newColumnValues = LogicalPhysicalConverterHelper.getColumnValuesFromResultset(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tpersister.getPropertyColumnNames( propertyIndex )\n\t\t\t\t);\n\n\t\t\t\t//don't index null columns, this means no association\n\t\t\t\tif ( ! CollectionHelper.isEmptyOrContainsOnlyNull( ( newColumnValues ) ) ) {\n\t\t\t\t\taddNavigationalInformationForInverseSide( propertyIndex, associationKeyMetadata, newColumnValues );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] | [
"public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames)\n {\n Map<String, Object> results = new HashMap<>();\n\n for (String varName : varNames)\n {\n WindupVertexFrame payload = null;\n try\n {\n payload = Iteration.getCurrentPayload(variables, null, varName);\n }\n catch (IllegalStateException | IllegalArgumentException e)\n {\n // oh well\n }\n\n if (payload != null)\n {\n results.put(varName, payload);\n }\n else\n {\n Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName);\n if (var != null)\n {\n results.put(varName, var);\n }\n }\n }\n return results;\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getTimeElapsed() {\n int currentSession = getCurrentSession();\n if (currentSession == 0) return -1;\n\n int now = (int) (System.currentTimeMillis() / 1000);\n return now - currentSession;\n }",
"public static Map<String, String[]> mapUrlEncodedParameters(byte[] dataArray) throws Exception {\n Map<String, String[]> mapPostParameters = new HashMap<String, String[]>();\n\n try {\n ByteArrayOutputStream byteout = new ByteArrayOutputStream();\n for (int x = 0; x < dataArray.length; x++) {\n // split the data up by & to get the parts\n if (dataArray[x] == '&' || x == (dataArray.length - 1)) {\n if (x == (dataArray.length - 1)) {\n byteout.write(dataArray[x]);\n }\n // find '=' and split the data up into key value pairs\n int equalsPos = -1;\n ByteArrayOutputStream key = new ByteArrayOutputStream();\n ByteArrayOutputStream value = new ByteArrayOutputStream();\n byte[] byteArray = byteout.toByteArray();\n for (int xx = 0; xx < byteArray.length; xx++) {\n if (byteArray[xx] == '=') {\n equalsPos = xx;\n } else {\n if (equalsPos == -1) {\n key.write(byteArray[xx]);\n } else {\n value.write(byteArray[xx]);\n }\n }\n }\n\n ArrayList<String> values = new ArrayList<String>();\n\n if (mapPostParameters.containsKey(key.toString())) {\n values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(key.toString())));\n mapPostParameters.remove(key.toString());\n }\n\n values.add(value.toString());\n /**\n * If equalsPos is not -1, then there was a '=' for the key\n * If value.size is 0, then there is no value so want to add in the '='\n * Since it will not be added later like params with keys and valued\n */\n if (equalsPos != -1 && value.size() == 0) {\n key.write((byte) '=');\n }\n\n mapPostParameters.put(key.toString(), values.toArray(new String[values.size()]));\n\n byteout = new ByteArrayOutputStream();\n } else {\n byteout.write(dataArray[x]);\n }\n }\n } catch (Exception e) {\n throw new Exception(\"Could not parse request data: \" + e.getMessage());\n }\n\n return mapPostParameters;\n }",
"private void readTable(InputStream is, SynchroTable table) throws IOException\n {\n int skip = table.getOffset() - m_offset;\n if (skip != 0)\n {\n StreamHelper.skip(is, skip);\n m_offset += skip;\n }\n\n String tableName = DatatypeConverter.getString(is);\n int tableNameLength = 2 + tableName.length();\n m_offset += tableNameLength;\n\n int dataLength;\n if (table.getLength() == -1)\n {\n dataLength = is.available();\n }\n else\n {\n dataLength = table.getLength() - tableNameLength;\n }\n\n SynchroLogger.log(\"READ\", tableName);\n\n byte[] compressedTableData = new byte[dataLength];\n is.read(compressedTableData);\n m_offset += dataLength;\n\n Inflater inflater = new Inflater();\n inflater.setInput(compressedTableData);\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedTableData.length);\n byte[] buffer = new byte[1024];\n while (!inflater.finished())\n {\n int count;\n\n try\n {\n count = inflater.inflate(buffer);\n }\n catch (DataFormatException ex)\n {\n throw new IOException(ex);\n }\n outputStream.write(buffer, 0, count);\n }\n outputStream.close();\n byte[] uncompressedTableData = outputStream.toByteArray();\n\n SynchroLogger.log(uncompressedTableData);\n\n m_tableData.put(table.getName(), uncompressedTableData);\n }",
"public void close()\t{\n\t\tif (watchdog != null) {\n\t\t\twatchdog.cancel();\n\t\t\twatchdog = null;\n\t\t}\n\t\t\n\t\tdisconnect();\n\t\t\n\t\t// clear nodes collection and send queue\n\t\tfor (Object listener : this.zwaveEventListeners.toArray()) {\n\t\t\tif (!(listener instanceof ZWaveNode))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tthis.zwaveEventListeners.remove(listener);\n\t\t}\n\t\t\n\t\tthis.zwaveNodes.clear();\n\t\tthis.sendQueue.clear();\n\t\t\n\t\tlogger.info(\"Stopped Z-Wave controller\");\n\t}",
"protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public static base_responses unset(nitro_service client, String trapname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm unsetresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tunsetresources[i] = new snmpalarm();\n\t\t\t\tunsetresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public static aaauser_auditsyslogpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_auditsyslogpolicy_binding obj = new aaauser_auditsyslogpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_auditsyslogpolicy_binding response[] = (aaauser_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static boolean pushImage(Launcher launcher, final JenkinsBuildInfoLog log, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n String message = \"Pushing image: \" + imageTag;\n if (StringUtils.isNotEmpty(host)) {\n message += \" using docker daemon host: \" + host;\n }\n\n log.info(message);\n DockerUtils.pushImage(imageTag, username, password, host);\n return true;\n }\n });\n }"
] |
Performs a partial BFS on model until the search frontier reaches the desired bootstrap size
@param min the desired bootstrap size
@return a list of found PossibleState
@throws ModelException if the desired bootstrap can not be reached | [
"public List<PossibleState> bfs(int min) throws ModelException {\r\n List<PossibleState> bootStrap = new LinkedList<>();\n\r\n TransitionTarget initial = model.getInitialTarget();\r\n PossibleState initialState = new PossibleState(initial, fillInitialVariables());\r\n bootStrap.add(initialState);\n\r\n while (bootStrap.size() < min) {\r\n PossibleState state = bootStrap.remove(0);\r\n TransitionTarget nextState = state.nextState;\n\r\n if (nextState.getId().equalsIgnoreCase(\"end\")) {\r\n throw new ModelException(\"Could not achieve required bootstrap without reaching end state\");\r\n }\n\r\n //run every action in series\r\n List<Map<String, String>> product = new LinkedList<>();\r\n product.add(new HashMap<>(state.variables));\n\r\n OnEntry entry = nextState.getOnEntry();\r\n List<Action> actions = entry.getActions();\n\r\n for (Action action : actions) {\r\n for (CustomTagExtension tagExtension : tagExtensionList) {\r\n if (tagExtension.getTagActionClass().isInstance(action)) {\r\n product = tagExtension.pipelinePossibleStates(action, product);\r\n }\r\n }\r\n }\n\r\n //go through every transition and see which of the products are valid, adding them to the list\r\n List<Transition> transitions = nextState.getTransitionsList();\n\r\n for (Transition transition : transitions) {\r\n String condition = transition.getCond();\r\n TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0);\n\r\n for (Map<String, String> p : product) {\r\n Boolean pass;\n\r\n if (condition == null) {\r\n pass = true;\r\n } else {\r\n //scrub the context clean so we may use it to evaluate transition conditional\r\n Context context = this.getRootContext();\r\n context.reset();\n\r\n //set up new context\r\n for (Map.Entry<String, String> e : p.entrySet()) {\r\n context.set(e.getKey(), e.getValue());\r\n }\n\r\n //evaluate condition\r\n try {\r\n pass = (Boolean) this.getEvaluator().eval(context, condition);\r\n } catch (SCXMLExpressionException ex) {\r\n pass = false;\r\n }\r\n }\n\r\n //transition condition satisfied, add to bootstrap list\r\n if (pass) {\r\n PossibleState result = new PossibleState(target, p);\r\n bootStrap.add(result);\r\n }\r\n }\r\n }\r\n }\n\r\n return bootStrap;\r\n }"
] | [
"public boolean detectOperaMobile() {\r\n\r\n if ((userAgent.indexOf(engineOpera) != -1)\r\n && ((userAgent.indexOf(mini) != -1) || (userAgent.indexOf(mobi) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }",
"public FieldType getFieldByAlias(FieldTypeClass typeClass, String alias)\n {\n return m_aliasMap.get(new Pair<FieldTypeClass, String>(typeClass, alias));\n }",
"protected void reportStorageOpTime(long startNs) {\n if(streamStats != null) {\n streamStats.reportStreamingScan(operation);\n streamStats.reportStorageTime(operation,\n Utils.elapsedTimeNs(startNs, System.nanoTime()));\n }\n }",
"@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal);\n }",
"public Filter geoSearch(String value) {\n GeopositionComparator comp = (GeopositionComparator) prop.getComparator();\n double dist = comp.getMaxDistance();\n double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0);\n Shape circle = spatialctx.makeCircle(parsePoint(value), degrees);\n SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);\n return strategy.makeFilter(args);\n }",
"public void bindSelect(PreparedStatement stmt, Identity oid, ClassDescriptor cld, boolean callableStmt) throws SQLException\r\n {\r\n ValueContainer[] values = null;\r\n int i = 0;\r\n int j = 0;\r\n\r\n if (cld == null)\r\n {\r\n cld = m_broker.getClassDescriptor(oid.getObjectsRealClass());\r\n }\r\n try\r\n {\r\n if(callableStmt)\r\n {\r\n // First argument is the result set\r\n m_platform.registerOutResultSet((CallableStatement) stmt, 1);\r\n j++;\r\n }\r\n\r\n values = getKeyValues(m_broker, cld, oid);\r\n for (/*void*/; i < values.length; i++, j++)\r\n {\r\n setObjectForStatement(stmt, j + 1, values[i].getValue(), values[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindSelect failed for: \" + oid.toString() + \", PK: \" + i + \", value: \" + values[i]);\r\n throw e;\r\n }\r\n }",
"@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }",
"void registerAlias(FieldType type, String alias)\n {\n m_aliasMap.put(new Pair<FieldTypeClass, String>(type.getFieldTypeClass(), alias), type);\n }"
] |
In this method perform the actual override in runtime.
@see org.apache.log4j.spi.HierarchyEventListener#addAppenderEvent(org.apache.log4j.Category, org.apache.log4j.Appender) | [
"public void addAppenderEvent(final Category cat, final Appender appender) {\n\n\t\tupdateDefaultLayout(appender);\n\n\t\tif (appender instanceof FoundationFileRollingAppender) {\n\t\t\tfinal FoundationFileRollingAppender timeSizeRollingAppender = (FoundationFileRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\t//updateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout(); //So application state will not make any problems\n\n\t\t}else if(!(appender instanceof FoundationFileRollingAppender) && (appender instanceof TimeAndSizeRollingAppender)){ //TimeAndSizeRollingAppender\n\t\t\tfinal TimeAndSizeRollingAppender timeSizeRollingAppender = (TimeAndSizeRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\tupdateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout();\n\t\t}\n\t\tif ( ! (appender instanceof org.apache.log4j.AsyncAppender))\n initiateAsyncSupport(appender);\n\n\t}"
] | [
"public void createLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference<S> serviceReference : linkerManagement.getMatchedBinderServiceRef()) {\n if (linkerManagement.canBeLinked(declaration, serviceReference)) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }",
"public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }",
"private List<MapRow> sort(List<MapRow> rows, final String attribute)\n {\n Collections.sort(rows, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n String value1 = o1.getString(attribute);\n String value2 = o2.getString(attribute);\n return value1.compareTo(value2);\n }\n });\n return rows;\n }",
"public static vpath get(nitro_service service, String name) throws Exception{\n\t\tvpath obj = new vpath();\n\t\tobj.set_name(name);\n\t\tvpath response = (vpath) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private static int readDataBlock(String text, int offset, int length, List<byte[]> blocks)\n {\n int bytes = length / 2;\n byte[] data = new byte[bytes];\n\n for (int index = 0; index < bytes; index++)\n {\n data[index] = (byte) Integer.parseInt(text.substring(offset, offset + 2), 16);\n offset += 2;\n }\n\n blocks.add(data);\n return (offset);\n }",
"private double sumSquaredDiffs()\n { \n double mean = getArithmeticMean();\n double squaredDiffs = 0;\n for (int i = 0; i < getSize(); i++)\n {\n double diff = mean - dataSet[i];\n squaredDiffs += (diff * diff);\n }\n return squaredDiffs;\n }",
"public static Value.Builder makeValue(Value value1, Value value2, Value... rest) {\n ArrayValue.Builder arrayValue = ArrayValue.newBuilder();\n arrayValue.addValues(value1);\n arrayValue.addValues(value2);\n arrayValue.addAllValues(Arrays.asList(rest));\n return Value.newBuilder().setArrayValue(arrayValue);\n }",
"public E get(int i) {\r\n if (i < 0 || i >= objects.size())\r\n throw new ArrayIndexOutOfBoundsException(\"Index \" + i + \r\n \" outside the bounds [0,\" + \r\n size() + \")\");\r\n return objects.get(i);\r\n }",
"public double[][] getU() {\n double[][] X = new double[n][n];\n double[][] U = X;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i <= j) {\n U[i][j] = LU[i][j];\n } else {\n U[i][j] = 0.0;\n }\n }\n }\n return X;\n }"
] |
Stop the service and end the program | [
"public static void stopService() {\n DaemonStarter.currentPhase.set(LifecyclePhase.STOPPING);\n final CountDownLatch cdl = new CountDownLatch(1);\n Executors.newSingleThreadExecutor().execute(() -> {\n DaemonStarter.getLifecycleListener().stopping();\n DaemonStarter.daemon.stop();\n cdl.countDown();\n });\n\n try {\n int timeout = DaemonStarter.lifecycleListener.get().getShutdownTimeoutSeconds();\n if (!cdl.await(timeout, TimeUnit.SECONDS)) {\n DaemonStarter.rlog.error(\"Failed to stop gracefully\");\n DaemonStarter.abortSystem();\n }\n } catch (InterruptedException e) {\n DaemonStarter.rlog.error(\"Failure awaiting stop\", e);\n Thread.currentThread().interrupt();\n }\n\n }"
] | [
"public static Integer distance(String h1, String h2) {\n\t\tHammingDistance distance = new HammingDistance();\n\t\treturn distance.apply(h1, h2);\n\t}",
"public static appqoepolicy[] get(nitro_service service) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tappqoepolicy[] response = (appqoepolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private YearQuarter with(int newYear, Quarter newQuarter) {\n if (year == newYear && quarter == newQuarter) {\n return this;\n }\n return new YearQuarter(newYear, newQuarter);\n }",
"public void create(final DbProduct dbProduct) {\n if(repositoryHandler.getProduct(dbProduct.getName()) != null){\n throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity(\"Product already exist!\").build());\n }\n\n repositoryHandler.store(dbProduct);\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 void validate(final Organization organization) {\n if(organization.getName() == null ||\n organization.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Organization name cannot be null or empty!\")\n .build());\n }\n }",
"public StatementGroup findStatementGroup(String propertyIdValue) {\n\t\tif (this.claims.containsKey(propertyIdValue)) {\n\t\t\treturn new StatementGroupImpl(this.claims.get(propertyIdValue));\n\t\t}\n\t\treturn null;\n\t}",
"protected void deleteConflictingResources(CmsObject cms, CmsModule module, Map<CmsUUID, CmsUUID> conflictingIds)\n throws CmsException, Exception {\n\n CmsProject conflictProject = cms.createProject(\n \"Deletion of conflicting resources for \" + module.getName(),\n \"Deletion of conflicting resources for \" + module.getName(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n CmsObject deleteCms = OpenCms.initCmsObject(cms);\n deleteCms.getRequestContext().setCurrentProject(conflictProject);\n for (CmsUUID vfsId : conflictingIds.values()) {\n CmsResource toDelete = deleteCms.readResource(vfsId, CmsResourceFilter.ALL);\n lock(deleteCms, toDelete);\n deleteCms.deleteResource(toDelete, CmsResource.DELETE_PRESERVE_SIBLINGS);\n }\n OpenCms.getPublishManager().publishProject(deleteCms);\n OpenCms.getPublishManager().waitWhileRunning();\n }",
"public static Value.Builder makeValue(Value value1, Value value2, Value... rest) {\n ArrayValue.Builder arrayValue = ArrayValue.newBuilder();\n arrayValue.addValues(value1);\n arrayValue.addValues(value2);\n arrayValue.addAllValues(Arrays.asList(rest));\n return Value.newBuilder().setArrayValue(arrayValue);\n }"
] |
Get a unique reference to a media slot on the network from which tracks can be loaded.
@param player the player in which the slot is found
@param slot the specific type of the slot
@return the instance that will always represent the specified slot
@throws NullPointerException if {@code slot} is {@code null} | [
"@SuppressWarnings(\"WeakerAccess\")\n public static synchronized SlotReference getSlotReference(int player, CdjStatus.TrackSourceSlot slot) {\n Map<CdjStatus.TrackSourceSlot, SlotReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<CdjStatus.TrackSourceSlot, SlotReference>();\n instances.put(player, playerMap);\n }\n SlotReference result = playerMap.get(slot);\n if (result == null) {\n result = new SlotReference(player, slot);\n playerMap.put(slot, result);\n }\n return result;\n }"
] | [
"public static String pad(String str, int totalChars) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int slen = str.length();\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < totalChars - slen; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n }",
"public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST license\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"public final void notifyContentItemRemoved(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRemoved(position + headerItemCount);\n }",
"public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }",
"private void populateTask(Row row, Task task)\n {\n //\"PROJID\"\n task.setUniqueID(row.getInteger(\"TASKID\"));\n //GIVEN_DURATIONTYPF\n //GIVEN_DURATIONELA_MONTHS\n task.setDuration(row.getDuration(\"GIVEN_DURATIONHOURS\"));\n task.setResume(row.getDate(\"RESUME\"));\n //task.setStart(row.getDate(\"GIVEN_START\"));\n //LATEST_PROGRESS_PERIOD\n //TASK_WORK_RATE_TIME_UNIT\n //TASK_WORK_RATE\n //PLACEMENT\n //BEEN_SPLIT\n //INTERRUPTIBLE\n //HOLDING_PIN\n ///ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n task.setActualDuration(row.getDuration(\"ACTUAL_DURATIONHOURS\"));\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //task.setBaselineWork(row.getDuration(\"EFFORT_BUDGET\"));\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n task.setPercentageComplete(row.getDouble(\"OVERALL_PERCENV_COMPLETE\"));\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n task.setNotes(getNotes(row));\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //BAR\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n task.setStart(row.getDate(\"STARZ\"));\n task.setFinish(row.getDate(\"ENJ\"));\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n\n processConstraints(row, task);\n\n if (NumberHelper.getInt(task.getPercentageComplete()) != 0)\n {\n task.setActualStart(task.getStart());\n if (task.getPercentageComplete().intValue() == 100)\n {\n task.setActualFinish(task.getFinish());\n task.setDuration(task.getActualDuration());\n }\n }\n }",
"public File getBootFile() {\n if (bootFile == null) {\n synchronized (this) {\n if (bootFile == null) {\n if (bootFileReset) {\n //Reset the done bootup and the sequence, so that the old file we are reloading from\n // overwrites the main file on successful boot, and history is reset as when booting new\n doneBootup.set(false);\n sequence.set(0);\n }\n // If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile,\n // as that's where we persist\n if (bootFileReset && !interactionPolicy.isReadOnly() && newReloadBootFileName == null) {\n // we boot from mainFile\n bootFile = mainFile;\n } else {\n // It's either first boot, or a reload where we're not persisting our config or with a new boot file.\n // So we need to figure out which file we're meant to boot from\n\n String bootFileName = this.bootFileName;\n if (newReloadBootFileName != null) {\n //A non-null new boot file on reload takes precedence over the reloadUsingLast functionality\n //A new boot file was specified. Use that and reset the new name to null\n bootFileName = newReloadBootFileName;\n newReloadBootFileName = null;\n } else if (interactionPolicy.isReadOnly() && reloadUsingLast) {\n //If we were reloaded, and it is not a persistent configuration we want to use the last from the history\n bootFileName = LAST;\n }\n boolean usingRawFile = bootFileName.equals(rawFileName);\n if (usingRawFile) {\n bootFile = mainFile;\n } else {\n bootFile = determineBootFile(configurationDir, bootFileName);\n try {\n bootFile = bootFile.getCanonicalFile();\n } catch (IOException ioe) {\n throw ControllerLogger.ROOT_LOGGER.canonicalBootFileNotFound(ioe, bootFile);\n }\n }\n\n\n if (!bootFile.exists()) {\n if (!usingRawFile) { // TODO there's no reason usingRawFile should be an exception,\n // but the test infrastructure stuff is built around an assumption\n // that ConfigurationFile doesn't fail if test files are not\n // in the normal spot\n if (bootFileReset || interactionPolicy.isRequireExisting()) {\n throw ControllerLogger.ROOT_LOGGER.fileNotFound(bootFile.getAbsolutePath());\n }\n }\n // Create it for the NEW and DISCARD cases\n if (!bootFileReset && !interactionPolicy.isRequireExisting()) {\n createBootFile(bootFile);\n }\n } else if (!bootFileReset) {\n if (interactionPolicy.isRejectExisting() && bootFile.length() > 0) {\n throw ControllerLogger.ROOT_LOGGER.rejectEmptyConfig(bootFile.getAbsolutePath());\n } else if (interactionPolicy.isRemoveExisting() && bootFile.length() > 0) {\n if (!bootFile.delete()) {\n throw ControllerLogger.ROOT_LOGGER.cannotDelete(bootFile.getAbsoluteFile());\n }\n createBootFile(bootFile);\n }\n } // else after first boot we want the file to exist\n }\n }\n }\n }\n return bootFile;\n }",
"@RequestMapping(value = \"/cert\", method = {RequestMethod.GET, RequestMethod.HEAD})\n public String certPage() throws Exception {\n return \"cert\";\n }",
"public Set<ConstraintViolation> validate(DataSetInfo info) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\ttry {\r\n\t\t\tif (info.isMandatory() && get(info.getDataSetNumber()) == null) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));\r\n\t\t\t}\r\n\t\t\tif (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));\r\n\t\t\t}\r\n\t\t} catch (SerializationException e) {\r\n\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}"
] |
absolute for basicJDBCSupport
@param row | [
"private boolean absoluteBasic(int row)\r\n {\r\n boolean retval = false;\r\n \r\n if (row > m_current_row)\r\n {\r\n try\r\n {\r\n while (m_current_row < row && getRsAndStmt().m_rs.next())\r\n {\r\n m_current_row++;\r\n }\r\n if (m_current_row == row)\r\n {\r\n retval = true;\r\n }\r\n else\r\n {\r\n setHasCalledCheck(true);\r\n setHasNext(false);\r\n retval = false;\r\n autoReleaseDbResources();\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n setHasCalledCheck(true);\r\n setHasNext(false);\r\n retval = false;\r\n }\r\n }\r\n else\r\n {\r\n logger.info(\"Your driver does not support advanced JDBC Functionality, \" +\r\n \"you cannot call absolute() with a position < current\");\r\n }\r\n return retval;\r\n }"
] | [
"public T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}",
"public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }",
"public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {\n Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);\n for (final ContentAssistContext context : _filteredContexts) {\n ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();\n for (final AbstractElement element : _firstSetGrammarElements) {\n {\n boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();\n boolean _not = (!_canAcceptMoreProposals);\n if (_not) {\n return;\n }\n this.createProposals(element, context, acceptor);\n }\n }\n }\n }",
"public byte[] serialize() throws PersistenceBrokerException\r\n {\r\n // Identity is serialized and written to an ObjectOutputStream\r\n // This ObjectOutputstream is compressed by a GZIPOutputStream\r\n // and finally written to a ByteArrayOutputStream.\r\n // the resulting byte[] is returned\r\n try\r\n {\r\n final ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n final GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n final ObjectOutputStream oos = new ObjectOutputStream(gos);\r\n oos.writeObject(this);\r\n oos.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }\r\n catch (Exception ignored)\r\n {\r\n throw new PersistenceBrokerException(ignored);\r\n }\r\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushEvent(String eventName) {\n if (eventName == null || eventName.trim().equals(\"\"))\n return;\n\n pushEvent(eventName, null);\n }",
"public final static int readXMLUntil(final StringBuilder out, final String in, final int start, final char... end)\n {\n int pos = start;\n boolean inString = false;\n char stringChar = 0;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (inString)\n {\n if (ch == '\\\\')\n {\n out.append(ch);\n pos++;\n if (pos < in.length())\n {\n out.append(ch);\n pos++;\n }\n continue;\n }\n if (ch == stringChar)\n {\n inString = false;\n out.append(ch);\n pos++;\n continue;\n }\n }\n switch (ch)\n {\n case '\"':\n case '\\'':\n inString = true;\n stringChar = ch;\n break;\n }\n if (!inString)\n {\n boolean endReached = false;\n for (int n = 0; n < end.length; n++)\n {\n if (ch == end[n])\n {\n endReached = true;\n break;\n }\n }\n if (endReached)\n {\n break;\n }\n }\n out.append(ch);\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {\n List<T> foundServices = new ArrayList<>();\n Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();\n\n while (checkHasNextSafely(iterator)) {\n try {\n T item = iterator.next();\n foundServices.add(item);\n LOGGER.debug(String.format(\"Found %s [%s]\", serviceType.getSimpleName(), item.toString()));\n } catch (ServiceConfigurationError e) {\n LOGGER.trace(\"Can't find services using Java SPI\", e);\n LOGGER.error(e.getMessage());\n }\n }\n return foundServices;\n }",
"public synchronized void hide() {\n if (focusedQuad != null) {\n\n mDefocusAnimationFactory.create(focusedQuad)\n .setRequestLayoutOnTargetChange(false)\n .start().finish();\n\n focusedQuad = null;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"hide Picker!\");\n }",
"private static String getScheme(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n\n return DEFAULT_SCHEME;\n }"
] |
Close all JDBC objects related to this connection. | [
"public void close()\n {\n if (transac_open)\n {\n try\n {\n this._cnx.rollback();\n }\n catch (Exception e)\n {\n // Ignore.\n }\n }\n\n for (Statement s : toClose)\n {\n closeQuietly(s);\n }\n toClose.clear();\n\n closeQuietly(_cnx);\n _cnx = null;\n }"
] | [
"private static void checkSorted(int[] sorted) {\r\n for (int i = 0; i < sorted.length-1; i++) {\r\n if (sorted[i] > sorted[i+1]) {\r\n throw new RuntimeException(\"input must be sorted!\");\r\n }\r\n }\r\n }",
"protected int readByte(InputStream is) throws IOException\n {\n byte[] data = new byte[1];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getByte(data, 0));\n }",
"public void shutdown() {\n\n for (Entry<HttpClientType, AsyncHttpClient> entry : map.entrySet()) {\n AsyncHttpClient client = entry.getValue();\n if (client != null)\n client.close();\n }\n\n }",
"public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\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 }",
"public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }",
"public void addRow(final String... cells){\n final Row row = new Row((Object[]) cells);\n\n if(!rows.contains(row)){\n rows.add(row);\n }\n }",
"public float getBitangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_bitangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {\n\t\tdocument.writeElement(\"vml:shape\", asChild);\n\t\tPoint p = (Point) o;\n\t\tString adj = document.getFormatter().format(p.getX()) + \",\"\n\t\t\t\t+ document.getFormatter().format(p.getY());\n\t\tdocument.writeAttribute(\"adj\", adj);\n\t}"
] |
Create a new server group for a profile
@param model
@param profileId
@return
@throws Exception | [
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerGroup createServerGroup(Model model,\n @RequestParam(value = \"name\") String name,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId);\n return ServerRedirectService.getInstance().getServerGroup(groupId, profileId);\n }"
] | [
"public int readFrom(byte[] src, int srcOffset, long destOffset, int length) {\n int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length));\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src, srcOffset, readLen);\n return readLen;\n }",
"public void prettyPrint(StringBuffer sb, int indent) {\n sb.append(Log.getSpaces(indent));\n sb.append(getClass().getSimpleName());\n sb.append(\" [name=\");\n sb.append(this.getName());\n sb.append(\"]\");\n sb.append(System.lineSeparator());\n GVRRenderData rdata = getRenderData();\n GVRTransform trans = getTransform();\n\n if (rdata == null) {\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"RenderData: null\");\n sb.append(System.lineSeparator());\n } else {\n rdata.prettyPrint(sb, indent + 2);\n }\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"Transform: \"); sb.append(trans);\n sb.append(System.lineSeparator());\n\n // dump its children\n for (GVRSceneObject child : getChildren()) {\n child.prettyPrint(sb, indent + 2);\n }\n }",
"private static void unpackFace(File outputDirectory) throws IOException {\n ClassLoader loader = AllureMain.class.getClassLoader();\n for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) {\n Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName());\n if (matcher.find()) {\n String resourcePath = matcher.group(1);\n File dest = new File(outputDirectory, resourcePath);\n Files.createParentDirs(dest);\n try (FileOutputStream output = new FileOutputStream(dest);\n InputStream input = info.url().openStream()) {\n IOUtils.copy(input, output);\n LOGGER.debug(\"{} successfully copied.\", resourcePath);\n }\n }\n }\n }",
"public final OutputFormat getOutputFormat(final PJsonObject specJson) {\n final String format = specJson.getString(MapPrinterServlet.JSON_OUTPUT_FORMAT);\n final boolean mapExport =\n this.configuration.getTemplate(specJson.getString(Constants.JSON_LAYOUT_KEY)).isMapExport();\n final String beanName =\n format + (mapExport ? MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING : OUTPUT_FORMAT_BEAN_NAME_ENDING);\n\n if (!this.outputFormat.containsKey(beanName)) {\n throw new RuntimeException(\"Format '\" + format + \"' with mapExport '\" + mapExport\n + \"' is not supported.\");\n }\n\n return this.outputFormat.get(beanName);\n }",
"public T removeFile(final String name, final List<String> path, final byte[] existingHash, final boolean isDirectory) {\n return removeFile(name, path, existingHash, isDirectory, null);\n }",
"private List<String> parseRssFeedForeCast(String feed) {\n String[] result = feed.split(\"<br />\");\n List<String> returnList = new ArrayList<String>();\n String[] result2 = result[2].split(\"<BR />\");\n\n returnList.add(result2[3] + \"\\n\");\n returnList.add(result[3] + \"\\n\");\n returnList.add(result[4] + \"\\n\");\n returnList.add(result[5] + \"\\n\");\n returnList.add(result[6] + \"\\n\");\n\n return returnList;\n }",
"public void addCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(!dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().add(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.addModulesOrganization(corporateGroupId, dbOrganization);\n }",
"private void setMax(MtasRBTreeNode n) {\n n.max = n.right;\n if (n.leftChild != null) {\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.max = Math.max(n.max, n.rightChild.max);\n }\n }",
"public JSONObject getPathFromEndpoint(String pathValue, String requestType) throws Exception {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n JSONObject response = new JSONObject(doGet(url, null));\n JSONArray paths = response.getJSONArray(\"paths\");\n for (int i = 0; i < paths.length(); i++) {\n JSONObject path = paths.getJSONObject(i);\n if (path.getString(\"path\").equals(pathValue) && path.getInt(\"requestType\") == type) {\n return path;\n }\n }\n return null;\n }"
] |
Get the number of views, comments and favorites on a photo for a given date.
@param date
(Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will
automatically be rounded down to the start of the day.
@param photoId
(Required) The id of the photo to get stats for.
@see "http://www.flickr.com/services/api/flickr.stats.getPhotoStats.htm" | [
"public Stats getPhotoStats(String photoId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTO_STATS, \"photo_id\", photoId, date);\n }"
] | [
"MACAddressSegment[] toEUISegments(boolean extended) {\n\t\tIPv6AddressSegment seg0, seg1, seg2, seg3;\n\t\tint start = addressSegmentIndex;\n\t\tint segmentCount = getSegmentCount();\n\t\tint segmentIndex;\n\t\tif(start < 4) {\n\t\t\tstart = 0;\n\t\t\tsegmentIndex = 4 - start;\n\t\t} else {\n\t\t\tstart -= 4;\n\t\t\tsegmentIndex = 0;\n\t\t}\n\t\tint originalSegmentIndex = segmentIndex;\n\t\tseg0 = (start == 0 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg1 = (start <= 1 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg2 = (start <= 2 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg3 = (start <= 3 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tint macSegCount = (segmentIndex - originalSegmentIndex) << 1;\n\t\tif(!extended) {\n\t\t\tmacSegCount -= 2;\n\t\t}\n\t\tif((seg1 != null && !seg1.matchesWithMask(0xff, 0xff)) || (seg2 != null && !seg2.matchesWithMask(0xfe00, 0xff00)) || macSegCount == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\tMACAddressSegment ZERO_SEGMENT = creator.createSegment(0);\n\t\tMACAddressSegment newSegs[] = creator.createSegmentArray(macSegCount);\n\t\tint macStartIndex = 0;\n\t\tif(seg0 != null) {\n\t\t\tseg0.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t//toggle the u/l bit\n\t\t\tMACAddressSegment macSegment0 = newSegs[0];\n\t\t\tint lower0 = macSegment0.getSegmentValue();\n\t\t\tint upper0 = macSegment0.getUpperSegmentValue();\n\t\t\tint mask2ndBit = 0x2;\n\t\t\tif(!macSegment0.matchesWithMask(mask2ndBit & lower0, mask2ndBit)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t//you can use matches with mask\n\t\t\tlower0 ^= mask2ndBit;//flip the universal/local bit\n\t\t\tupper0 ^= mask2ndBit;\n\t\t\tnewSegs[0] = creator.createSegment(lower0, upper0, null);\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg1 != null) {\n\t\t\tseg1.getSplitSegments(newSegs, macStartIndex, creator); //a ff fe b\n\t\t\tif(!extended) {\n\t\t\t\tnewSegs[macStartIndex + 1] = ZERO_SEGMENT;\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg2 != null) {\n\t\t\tif(!extended) {\n\t\t\t\tif(seg1 != null) {\n\t\t\t\t\tmacStartIndex -= 2;\n\t\t\t\t\tMACAddressSegment first = newSegs[macStartIndex];\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = first;\n\t\t\t\t} else {\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = ZERO_SEGMENT;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg3 != null) {\n\t\t\tseg3.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t}\n\t\treturn newSegs;\n\t}",
"private void deleteRecursive(final File file) {\n if (file.isDirectory()) {\n final String[] files = file.list();\n if (files != null) {\n for (String name : files) {\n deleteRecursive(new File(file, name));\n }\n }\n }\n\n if (!file.delete()) {\n ControllerLogger.ROOT_LOGGER.cannotDeleteFileOrDirectory(file);\n }\n }",
"public static long readBytes(byte[] bytes, int offset, int numBytes) {\n int shift = 0;\n long value = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n value |= (bytes[i] & 0xFFL) << shift;\n shift += 8;\n }\n return value;\n }",
"private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) {\n\t\tif (fieldType.isEscapedDefaultValue()) {\n\t\t\tappendEscapedWord(sb, defaultValue.toString());\n\t\t} else {\n\t\t\tsb.append(defaultValue);\n\t\t}\n\t}",
"public static dnspolicy_dnsglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnsglobal_binding obj = new dnspolicy_dnsglobal_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnsglobal_binding response[] = (dnspolicy_dnsglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static boolean isMapLiteralWithOnlyConstantValues(Expression expression) {\r\n if (expression instanceof MapExpression) {\r\n List<MapEntryExpression> entries = ((MapExpression) expression).getMapEntryExpressions();\r\n for (MapEntryExpression entry : entries) {\r\n if (!isConstantOrConstantLiteral(entry.getKeyExpression()) ||\r\n !isConstantOrConstantLiteral(entry.getValueExpression())) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public String formatCueCountdown() {\n int count = getCueCountdown();\n\n if (count == 511) {\n return \"--.-\";\n }\n\n if ((count >= 1) && (count <= 256)) {\n int bars = (count - 1) / 4;\n int beats = ((count - 1) % 4) + 1;\n return String.format(\"%02d.%d\", bars, beats);\n }\n\n if (count == 0) {\n return \"00.0\";\n }\n\n return \"??.?\";\n }",
"public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }",
"private void setCalendarToOrdinalRelativeDay(Calendar calendar, int dayNumber)\n {\n int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n int requiredDayOfWeek = getDayOfWeek().getValue();\n int dayOfWeekOffset = 0;\n if (requiredDayOfWeek > currentDayOfWeek)\n {\n dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek;\n }\n else\n {\n if (requiredDayOfWeek < currentDayOfWeek)\n {\n dayOfWeekOffset = 7 - (currentDayOfWeek - requiredDayOfWeek);\n }\n }\n\n if (dayOfWeekOffset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset);\n }\n\n if (dayNumber > 1)\n {\n calendar.add(Calendar.DAY_OF_YEAR, (7 * (dayNumber - 1)));\n }\n }"
] |
Returns the collection definition of the given name if it exists.
@param name The name of the collection
@return The collection definition or <code>null</code> if there is no such collection | [
"public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }"
] | [
"public static void checkMinimumArrayLength(String parameterName,\n int actualLength, int minimumLength) {\n if (actualLength < minimumLength) {\n throw Exceptions\n .IllegalArgument(\n \"Array %s should have at least %d elements, but it only has %d\",\n parameterName, minimumLength, actualLength);\n }\n }",
"public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster,\n int zoneId) {\n Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster,\n zoneId);\n String prettyHistogram = \"[\";\n boolean first = true;\n Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet());\n for(int runLength: runLengths) {\n if(first) {\n first = false;\n } else {\n prettyHistogram += \", \";\n }\n prettyHistogram += \"{\" + runLength + \" : \" + runLengthToCount.get(runLength) + \"}\";\n }\n prettyHistogram += \"]\";\n return prettyHistogram;\n }",
"private synchronized Schema getInputPathAvroSchema() throws IOException {\n if (inputPathAvroSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathAvroSchema = AvroUtils.getAvroSchemaFromPath(getInputPath());\n }\n return inputPathAvroSchema;\n }",
"public void sendJsonToUrl(Object data, String url) {\n sendToUrl(JSON.toJSONString(data), url);\n }",
"public static int optionLength(String option) {\n\tint result = Standard.optionLength(option);\n\tif (result != 0)\n\t return result;\n\telse\n\t return UmlGraph.optionLength(option);\n }",
"public static base_response update(nitro_service client, cmpparameter resource) throws Exception {\n\t\tcmpparameter updateresource = new cmpparameter();\n\t\tupdateresource.cmplevel = resource.cmplevel;\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.servercmp = resource.servercmp;\n\t\tupdateresource.heurexpiry = resource.heurexpiry;\n\t\tupdateresource.heurexpirythres = resource.heurexpirythres;\n\t\tupdateresource.heurexpiryhistwt = resource.heurexpiryhistwt;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.cmpbypasspct = resource.cmpbypasspct;\n\t\tupdateresource.cmponpush = resource.cmponpush;\n\t\tupdateresource.policytype = resource.policytype;\n\t\tupdateresource.addvaryheader = resource.addvaryheader;\n\t\tupdateresource.externalcache = resource.externalcache;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static <T> boolean addAll(Collection<T> self, Iterable<T> items) {\n boolean changed = false;\n for (T next : items) {\n if (self.add(next)) changed = true;\n }\n return changed;\n }",
"public void addStep(String name, String robot, Map<String, Object> options) {\n all.put(name, new Step(name, robot, options));\n }",
"private void store(final PrintJobStatus printJobStatus) throws JSONException {\n JSONObject metadata = new JSONObject();\n metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());\n metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());\n metadata.put(JSON_START_DATE, printJobStatus.getStartTime());\n metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());\n if (printJobStatus.getCompletionDate() != null) {\n metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());\n }\n metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));\n if (printJobStatus.getError() != null) {\n metadata.put(JSON_ERROR, printJobStatus.getError());\n }\n if (printJobStatus.getResult() != null) {\n metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());\n metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());\n metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());\n metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());\n }\n this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);\n }"
] |
Returns a Span that covers all rows beginning with a prefix String parameters will be encoded
as UTF-8 | [
"public static Span prefix(CharSequence rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n return prefix(Bytes.of(rowPrefix));\n }"
] | [
"@Override\n public void invert( ZMatrixRMaj inv ) {\n if( inv.numRows != n || inv.numCols != n ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n if( inv.data == t ) {\n throw new IllegalArgumentException(\"Passing in the same matrix that was decomposed.\");\n }\n\n if(decomposer.isLower()) {\n setToInverseL(inv.data);\n } else {\n throw new RuntimeException(\"Implement\");\n }\n }",
"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 byte[] removeContentFromExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItemNode = getContentItem(deploymentResource);\n final byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();\n final List<String> paths = REMOVED_PATHS.unwrap(context, operation);\n final byte[] hash = contentRepository.removeContentFromExploded(oldHash, paths);\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 slave.get(CONTENT).add().get(ARCHIVE).set(false);\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 }",
"public ProducerPoolData<V> getProducerPoolData(String topic, Partition bidPid, List<V> data) {\n return new ProducerPoolData<V>(topic, bidPid, data);\n }",
"protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException\n {\n StringBuilder pstyle = new StringBuilder(\"position:absolute;\");\n pstyle.append(\"left:\").append(x).append(UNIT).append(';');\n pstyle.append(\"top:\").append(y).append(UNIT).append(';');\n pstyle.append(\"width:\").append(width).append(UNIT).append(';');\n pstyle.append(\"height:\").append(height).append(UNIT).append(';');\n //pstyle.append(\"border:1px solid red;\");\n \n Element el = doc.createElement(\"img\");\n el.setAttribute(\"style\", pstyle.toString());\n\n String imgSrc = config.getImageHandler().handleResource(resource);\n\n if (!disableImageData && !imgSrc.isEmpty())\n el.setAttribute(\"src\", imgSrc);\n else\n el.setAttribute(\"src\", \"\");\n \n return el;\n }",
"public CmsResource buildResource() {\n\n return new CmsResource(\n m_structureId,\n m_resourceId,\n m_rootPath,\n m_type,\n m_flags,\n m_projectLastModified,\n m_state,\n m_dateCreated,\n m_userCreated,\n m_dateLastModified,\n m_userLastModified,\n m_dateReleased,\n m_dateExpired,\n m_length,\n m_flags,\n m_dateContent,\n m_version);\n }",
"private void readProjectHeader()\n {\n Table table = m_tables.get(\"DIR\");\n MapRow row = table.find(\"\");\n if (row != null)\n {\n setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());\n m_wbsFormat = new P3WbsFormat(row);\n }\n }",
"public static String getFileFormat(POIFSFileSystem fs) throws IOException\n {\n String fileFormat = \"\";\n DirectoryEntry root = fs.getRoot();\n if (root.getEntryNames().contains(\"\\1CompObj\"))\n {\n CompObj compObj = new CompObj(new DocumentInputStream((DocumentEntry) root.getEntry(\"\\1CompObj\")));\n fileFormat = compObj.getFileFormat();\n }\n return fileFormat;\n }",
"public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)\n\t\t\tthrows SQLException {\n\t\tDao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\treturn doCreateTable(dao, false);\n\t}"
] |
Position the child inside the layout based on the offset and axis-s factors
@param dataIndex data index | [
"protected void layoutChild(final int dataIndex) {\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n float offset = mOffset.get(Axis.X);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.X, offset);\n }\n\n offset = mOffset.get(Axis.Y);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Y, offset);\n }\n\n offset = mOffset.get(Axis.Z);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Z, offset);\n }\n }\n }"
] | [
"public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }",
"public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }",
"public static vridparam get(nitro_service service) throws Exception{\n\t\tvridparam obj = new vridparam();\n\t\tvridparam[] response = (vridparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) {\n try {\n Configuration conf = new Configuration();\n conf.setInt(\"io.file.buffer.size\", 4096);\n SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration());\n SequenceFile.Metadata meta = reader.getMetadata();\n reader.close();\n TreeMap<Text, Text> map = meta.getMetadata();\n Map<String, String> values = new HashMap<String, String>();\n for(Map.Entry<Text, Text> entry: map.entrySet())\n values.put(entry.getKey().toString(), entry.getValue().toString());\n\n return values;\n } catch(IOException e) {\n throw new RuntimeException(e);\n }\n }",
"public void restoreSecurityContext(CacheContext context) {\n\t\tSavedAuthorization cached = context.get(CacheContext.SECURITY_CONTEXT_KEY, SavedAuthorization.class);\n\t\tif (cached != null) {\n\t\t\tlog.debug(\"Restoring security context {}\", cached);\n\t\t\tsecurityManager.restoreSecurityContext(cached);\n\t\t} else {\n\t\t\tsecurityManager.clearSecurityContext();\n\t\t}\n\t}",
"public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\n }",
"public static responderhtmlpage get(nitro_service service, String name) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tobj.set_name(name);\n\t\tresponderhtmlpage response = (responderhtmlpage) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public ViewPort then(Functions.Func1<ViewPortChange> then, ViewPortFallback fallback) {\n assert then != null : \"'then' callback cannot be null\";\n this.then = then;\n this.fallback = fallback;\n return load();\n }",
"public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }"
] |
This method writes resource data to a JSON file. | [
"private void writeResources() throws IOException\n {\n writeAttributeTypes(\"resource_types\", ResourceField.values());\n\n m_writer.writeStartList(\"resources\");\n for (Resource resource : m_projectFile.getResources())\n {\n writeFields(null, resource, ResourceField.values());\n }\n m_writer.writeEndList();\n }"
] | [
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"public static nsrpcnode[] get(nitro_service service) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tnsrpcnode[] response = (nsrpcnode[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void disconnect() {\n\t\tif (sendThread != null) {\n\t\t\tsendThread.interrupt();\n\t\t\ttry {\n\t\t\t\tsendThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\tsendThread = null;\n\t\t}\n\t\tif (receiveThread != null) {\n\t\t\treceiveThread.interrupt();\n\t\t\ttry {\n\t\t\t\treceiveThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\treceiveThread = null;\n\t\t}\n\t\tif(transactionCompleted.availablePermits() < 0)\n\t\t\ttransactionCompleted.release(transactionCompleted.availablePermits());\n\t\t\n\t\ttransactionCompleted.drainPermits();\n\t\tlogger.trace(\"Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\tif (this.serialPort != null) {\n\t\t\tthis.serialPort.close();\n\t\t\tthis.serialPort = null;\n\t\t}\n\t\tlogger.info(\"Disconnected from serial port\");\n\t}",
"public float getTexCoordU(int vertex, int coords) {\n if (!hasTexCoords(coords)) {\n throw new IllegalStateException(\n \"mesh has no texture coordinate set \" + coords);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for coords are done by java for us */\n \n return m_texcoords[coords].getFloat(\n vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);\n }",
"public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }",
"public void deleteInactiveContent() throws PatchingException {\n List<File> dirs = getInactiveHistory();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n dirs = getInactiveOverlays();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n }",
"public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException\n\t{\n\t\tRandomVariableInterface values = getValue(evaluationTime, model);\n\n\t\tif(values == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sum up values on path\n\t\tdouble value = values.getAverage();\n\t\tdouble error = values.getStandardError();\n\n\t\tMap<String, Object> results = new HashMap<String, Object>();\n\t\tresults.put(\"value\", value);\n\t\tresults.put(\"error\", error);\n\n\t\treturn results;\n\t}",
"public String getCanonicalTypeName(Object object) {\n ensureNotNull(\"object\", object);\n\n for (TypeDetector typeDetector : typeDetectors) {\n if (typeDetector.canHandle(object)) {\n return typeDetector.detectType(object);\n }\n }\n\n throw LOG.unableToDetectCanonicalType(object);\n }",
"protected String getBundleJarPath() throws MalformedURLException {\n Path path = PROPERTIES.getAllureHome().resolve(\"app/allure-bundle.jar\").toAbsolutePath();\n if (Files.notExists(path)) {\n throw new AllureCommandException(String.format(\"Bundle not found by path <%s>\", path));\n }\n return path.toUri().toURL().toString();\n }"
] |
Add BoxMetaDataFilter to the JsonArray boxMetadataFilterRequestArray.
@param @param bmf accepts a filter that has templateKey, scope, and filters populated.
@return JsonArray that is formated Json request | [
"private JsonArray formatBoxMetadataFilterRequest() {\n JsonArray boxMetadataFilterRequestArray = new JsonArray();\n\n JsonObject boxMetadataFilter = new JsonObject()\n .add(\"templateKey\", this.metadataFilter.getTemplateKey())\n .add(\"scope\", this.metadataFilter.getScope())\n .add(\"filters\", this.metadataFilter.getFiltersList());\n boxMetadataFilterRequestArray.add(boxMetadataFilter);\n\n return boxMetadataFilterRequestArray;\n }"
] | [
"public String getSearchJsonModel() throws IOException {\n DbSearch search = new DbSearch();\n search.setArtifacts(new ArrayList<>());\n search.setModules(new ArrayList<>());\n return JsonUtils.serialize(search);\n }",
"public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n final List<String> list = readLines(self);\n T result = null;\n for (String line : list) {\n List vals = Arrays.asList(pattern.split(line));\n result = closure.call(vals);\n }\n return result;\n }",
"public ConfigOptionBuilder setStringConverter( StringConverter converter ) {\n co.setConverter( converter );\n co.setHasArgument( true );\n return this;\n }",
"private ProjectCalendar deriveResourceCalendar(Integer parentCalendarID)\n {\n ProjectCalendar calendar = m_project.addDefaultDerivedCalendar();\n calendar.setUniqueID(Integer.valueOf(m_project.getProjectConfig().getNextCalendarUniqueID()));\n calendar.setParent(m_project.getCalendarByUniqueID(parentCalendarID));\n return calendar;\n }",
"public String getAttributeValue(String attributeName)\n throws JMException, UnsupportedEncodingException {\n String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding);\n return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName));\n }",
"public ReplyObject getReplyList(String topicId, int perPage, int page) throws FlickrException {\r\n ReplyList<Reply> reply = new ReplyList<Reply>();\r\n TopicList<Topic> topic = new TopicList<Topic>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_LIST);\r\n\r\n parameters.put(\"topic_id\", topicId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element replyElements = response.getPayload();\r\n ReplyObject ro = new ReplyObject();\r\n NodeList replyNodes = replyElements.getElementsByTagName(\"reply\");\r\n for (int i = 0; i < replyNodes.getLength(); i++) {\r\n Element replyNodeElement = (Element) replyNodes.item(i);\r\n // Element replyElement = XMLUtilities.getChild(replyNodeElement, \"reply\");\r\n reply.add(parseReply(replyNodeElement));\r\n ro.setReplyList(reply);\r\n\r\n }\r\n NodeList topicNodes = replyElements.getElementsByTagName(\"topic\");\r\n for (int i = 0; i < topicNodes.getLength(); i++) {\r\n Element replyNodeElement = (Element) replyNodes.item(i);\r\n // Element topicElement = XMLUtilities.getChild(replyNodeElement, \"topic\");\r\n topic.add(parseTopic(replyNodeElement));\r\n ro.setTopicList(topic);\r\n }\r\n\r\n return ro;\r\n }",
"public List<DbModule> getAncestors(final String gavc, final FiltersHolder filters) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n return repositoryHandler.getAncestors(dbArtifact, filters);\n }",
"public void postProcess() {\n\t\tif (foreignColumnName != null) {\n\t\t\tforeignAutoRefresh = true;\n\t\t}\n\t\tif (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {\n\t\t\tmaxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;\n\t\t}\n\t}",
"private int[] getCompressIndexAndCount(CompressOptions options, boolean createMixed) {\n\t\tif(options != null) {\n\t\t\tCompressionChoiceOptions rangeSelection = options.rangeSelection;\n\t\t\tRangeList compressibleSegs = rangeSelection.compressHost() ? getZeroRangeSegments() : getZeroSegments();\n\t\t\tint maxIndex = -1, maxCount = 0;\n\t\t\tint segmentCount = getSegmentCount();\n\t\t\t\n\t\t\tboolean compressMixed = createMixed && options.compressMixedOptions.compressMixed(this);\n\t\t\tboolean preferHost = (rangeSelection == CompressOptions.CompressionChoiceOptions.HOST_PREFERRED);\n\t\t\tboolean preferMixed = createMixed && (rangeSelection == CompressOptions.CompressionChoiceOptions.MIXED_PREFERRED);\n\t\t\tfor(int i = compressibleSegs.size() - 1; i >= 0 ; i--) {\n\t\t\t\tRange range = compressibleSegs.getRange(i);\n\t\t\t\tint index = range.index;\n\t\t\t\tint count = range.length;\n\t\t\t\tif(createMixed) {\n\t\t\t\t\t//so here we shorten the range to exclude the mixed part if necessary\n\t\t\t\t\tint mixedIndex = IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - addressSegmentIndex;\n\t\t\t\t\tif(!compressMixed ||\n\t\t\t\t\t\t\tindex > mixedIndex || index + count < segmentCount) { //range does not include entire mixed part. We never compress only part of a mixed part.\n\t\t\t\t\t\t//the compressible range must stop at the mixed part\n\t\t\t\t\t\tcount = Math.min(count, mixedIndex - index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//select this range if is the longest\n\t\t\t\tif(count > 0 && count >= maxCount && (options.compressSingle || count > 1)) {\n\t\t\t\t\tmaxIndex = index;\n\t\t\t\t\tmaxCount = count;\n\t\t\t\t}\n\t\t\t\tif(preferHost && isPrefixed() &&\n\t\t\t\t\t\t((index + count) * IPv6Address.BITS_PER_SEGMENT) > getNetworkPrefixLength()) { //this range contains the host\n\t\t\t\t\t//Since we are going backwards, this means we select as the maximum any zero segment that includes the host\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(preferMixed && index + count >= segmentCount) { //this range contains the mixed section\n\t\t\t\t\t//Since we are going backwards, this means we select to compress the mixed segment\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(maxIndex >= 0) {\n\t\t\t\treturn new int[] {maxIndex, maxCount};\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}"
] |
Whether the address is IPv4-compatible
@see java.net.Inet6Address#isIPv4CompatibleAddress() | [
"public boolean isIPv4Compatible() {\n\t\treturn getSegment(0).isZero() && getSegment(1).isZero() && getSegment(2).isZero() &&\n\t\t\t\tgetSegment(3).isZero() && getSegment(4).isZero() && getSegment(5).isZero();\n\t}"
] | [
"public static String addFolderSlashIfNeeded(String folderName) {\n if (!\"\".equals(folderName) && !folderName.endsWith(\"/\")) {\n return folderName + \"/\";\n } else {\n return folderName;\n }\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 void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {\n if (!getWaveformListeners().isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);\n for (final WaveformListener listener : getWaveformListeners()) {\n try {\n listener.detailChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform detail update to listener\", t);\n }\n }\n }\n });\n }\n }",
"@Override\n public int read(char[] cbuf, int off, int len) throws IOException {\n int numChars = super.read(cbuf, off, len);\n replaceBadXmlCharactersBySpace(cbuf, off, len);\n return numChars;\n }",
"private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }",
"protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException {\n return boot(bootOperations, rollbackOnRuntimeFailure, false, ModelControllerImpl.getMutableRootResourceRegistrationProvider());\n }",
"public static void append(File file, Object text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file, true);\n if (!file.exists()) {\n writeUTF16BomIfRequired(charset, out);\n }\n writer = new OutputStreamWriter(out, charset);\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }",
"@Deprecated\r\n public Location resolvePlaceId(String placeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_ID);\r\n\r\n parameters.put(\"place_id\", placeId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }",
"protected Renderer build() {\n validateAttributes();\n\n Renderer renderer;\n if (isRecyclable(convertView, content)) {\n renderer = recycle(convertView, content);\n } else {\n renderer = createRenderer(content, parent);\n }\n return renderer;\n }"
] |
This logic is shared for all actual types i.e. raw types, parameterized types and generic array types. | [
"private static boolean isAssignableFrom(WildcardType type1, Type type2) {\n if (!isAssignableFrom(type1.getUpperBounds()[0], type2)) {\n return false;\n }\n if (type1.getLowerBounds().length > 0 && !isAssignableFrom(type2, type1.getLowerBounds()[0])) {\n return false;\n }\n return true;\n }"
] | [
"Document convertSelectorToDocument(Document selector) {\n Document document = new Document();\n for (String key : selector.keySet()) {\n if (key.startsWith(\"$\")) {\n continue;\n }\n\n Object value = selector.get(key);\n if (!Utils.containsQueryExpression(value)) {\n Utils.changeSubdocumentValue(document, key, value, (AtomicReference<Integer>) null);\n }\n }\n return document;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<InternationalFixedDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<InternationalFixedDate>) super.localDateTime(temporal);\n }",
"static void showWarning(final String caption, final String description) {\n\n Notification warning = new Notification(caption, description, Type.WARNING_MESSAGE, true);\n warning.setDelayMsec(-1);\n warning.show(UI.getCurrent().getPage());\n\n }",
"public void unbind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props));\n updateSortedServices();\n }\n }",
"void rollback() {\n if (publishedFullRegistry == null) {\n return;\n }\n writeLock.lock();\n try {\n publishedFullRegistry.readLock.lock();\n try {\n clear(true);\n copy(publishedFullRegistry, this);\n modified = false;\n } finally {\n publishedFullRegistry.readLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }",
"public void setBaselineDurationText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber), value);\n }",
"public void process(Connection connection, String directory) throws Exception\n {\n connection.setAutoCommit(true);\n\n //\n // Retrieve meta data about the connection\n //\n DatabaseMetaData dmd = connection.getMetaData();\n\n String[] types =\n {\n \"TABLE\"\n };\n\n FileWriter fw = new FileWriter(directory);\n PrintWriter pw = new PrintWriter(fw);\n\n pw.println(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n pw.println();\n pw.println(\"<database>\");\n\n ResultSet tables = dmd.getTables(null, null, null, types);\n while (tables.next() == true)\n {\n processTable(pw, connection, tables.getString(\"TABLE_NAME\"));\n }\n\n pw.println(\"</database>\");\n\n pw.close();\n\n tables.close();\n }",
"private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\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 }"
] |
This method is called if the data set has been scrolled. | [
"private void onScrollImpl(final Vector3Axis offset, final LayoutScroller.OnScrollListener listener) {\n if (!isScrolling()) {\n mScroller = new ScrollingProcessor(offset, listener);\n mScroller.scroll();\n }\n }"
] | [
"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 }",
"private void writeTaskExtendedAttributes(Project.Tasks.Task xml, Task mpx)\n {\n Project.Tasks.Task.ExtendedAttribute attrib;\n List<Project.Tasks.Task.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (TaskField mpxFieldID : getAllTaskExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPTaskField.getID(mpxFieldID) | MPPTaskField.TASK_FIELD_BASE);\n\n attrib = m_factory.createProjectTasksTaskExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }",
"@UiHandler(\"m_everyDay\")\r\n void onEveryDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setInterval(m_everyDay.getFormValueAsString());\r\n }\r\n\r\n }",
"@Nullable public GeoTarget getCanonAncestor(GeoTarget.Type type) {\n for (GeoTarget target = this; target != null; target = target.canonParent()) {\n if (target.key.type == type) {\n return target;\n }\n }\n\n return null;\n }",
"public static base_response update(nitro_service client, route6 resource) throws Exception {\n\t\troute6 updateresource = new route6();\n\t\tupdateresource.network = resource.network;\n\t\tupdateresource.gateway = resource.gateway;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.distance = resource.distance;\n\t\tupdateresource.cost = resource.cost;\n\t\tupdateresource.advertise = resource.advertise;\n\t\tupdateresource.msr = resource.msr;\n\t\tupdateresource.monitor = resource.monitor;\n\t\tupdateresource.td = resource.td;\n\t\treturn updateresource.update_resource(client);\n\t}",
"static BsonDocument getVersionedFilter(\n @Nonnull final BsonValue documentId,\n @Nullable final BsonValue version\n ) {\n final BsonDocument filter = new BsonDocument(\"_id\", documentId);\n if (version == null) {\n filter.put(DOCUMENT_VERSION_FIELD, new BsonDocument(\"$exists\", BsonBoolean.FALSE));\n } else {\n filter.put(DOCUMENT_VERSION_FIELD, version);\n }\n return filter;\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 }",
"private void readSubProjects(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n while (uniqueIDOffset < filePathOffset)\n {\n readSubProject(data, uniqueIDOffset, filePathOffset, fileNameOffset, subprojectIndex++);\n uniqueIDOffset += 4;\n }\n }",
"private static boolean containsGreekLetter(String s) {\r\n Matcher m = biogreek.matcher(s);\r\n return m.find();\r\n }"
] |
Translate the each ByteArray in an iterable into a hexadecimal string
@param arrays The array of bytes to translate
@return An iterable of converted strings | [
"public static Iterable<String> toHexStrings(Iterable<ByteArray> arrays) {\n ArrayList<String> ret = new ArrayList<String>();\n for(ByteArray array: arrays)\n ret.add(ByteUtils.toHexString(array.get()));\n return ret;\n }"
] | [
"public static Iterable<BoxRetentionPolicy.Info> getAll(final BoxAPIConnection api, String ... fields) {\r\n return getAll(null, null, null, DEFAULT_LIMIT, api, fields);\r\n }",
"public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }",
"@Override\n public Optional<SoyMapData> toSoyMap(@Nullable final Object model) throws Exception {\n if (model instanceof SoyMapData) {\n return Optional.of((SoyMapData) model);\n }\n if (model instanceof Map) {\n return Optional.of(new SoyMapData(model));\n }\n\n return Optional.of(new SoyMapData());\n }",
"private BasicCredentialsProvider getCredentialsProvider() {\n return new BasicCredentialsProvider() {\n private Set<AuthScope> authAlreadyTried = Sets.newHashSet();\n\n @Override\n public Credentials getCredentials(AuthScope authscope) {\n if (authAlreadyTried.contains(authscope)) {\n return null;\n }\n authAlreadyTried.add(authscope);\n return super.getCredentials(authscope);\n }\n };\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }",
"public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) {\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path(\"_find\").build();\n return this.query(uri, query, classOfT);\n }",
"public void initLocator() throws InterruptedException,\n ServiceLocatorException {\n if (locatorClient == null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Instantiate locatorClient client for Locator Server \"\n + locatorEndpoints + \"...\");\n }\n ServiceLocatorImpl client = new ServiceLocatorImpl();\n client.setLocatorEndpoints(locatorEndpoints);\n client.setConnectionTimeout(connectionTimeout);\n client.setSessionTimeout(sessionTimeout);\n if (null != authenticationName)\n client.setName(authenticationName);\n if (null != authenticationPassword)\n client.setPassword(authenticationPassword);\n locatorClient = client;\n locatorClient.connect();\n }\n }",
"private void readTaskCustomPropertyDefinitions(Tasks gpTasks)\n {\n for (Taskproperty definition : gpTasks.getTaskproperties().getTaskproperty())\n {\n //\n // Ignore everything but custom values\n //\n if (!\"custom\".equals(definition.getType()))\n {\n continue;\n }\n\n //\n // Find the next available field of the correct type.\n //\n String type = definition.getValuetype();\n FieldType fieldType = TASK_PROPERTY_TYPES.get(type).getField();\n\n //\n // If we have run out of fields of the right type, try using a text field.\n //\n if (fieldType == null)\n {\n fieldType = TASK_PROPERTY_TYPES.get(\"text\").getField();\n }\n\n //\n // If we actually have a field available, set the alias to match\n // the name used in GanttProject.\n //\n if (fieldType != null)\n {\n CustomField field = m_projectFile.getCustomFields().getCustomField(fieldType);\n field.setAlias(definition.getName());\n String defaultValue = definition.getDefaultvalue();\n if (defaultValue != null && defaultValue.isEmpty())\n {\n defaultValue = null;\n }\n m_taskPropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue));\n }\n }\n }"
] |
Set the map attribute.
@param name the attribute name
@param attribute the attribute | [
"public void setAttribute(final String name, final Attribute attribute) {\n if (name.equals(MAP_KEY)) {\n this.mapAttribute = (MapAttribute) attribute;\n }\n }"
] | [
"public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void setPlaybackPosition(long milliseconds) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.position != milliseconds) {\n setPlaybackState(oldState.player, milliseconds, oldState.playing);\n }\n }",
"public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }",
"public void updatePathOrder(int profileId, int[] pathOrder) {\n for (int i = 0; i < pathOrder.length; i++) {\n EditService.updatePathTable(Constants.PATH_PROFILE_PATH_ORDER, (i + 1), pathOrder[i]);\n }\n }",
"public static base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {\n return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);\n }",
"public void prepare(Properties p, Connection cnx)\n {\n this.tablePrefix = p.getProperty(\"com.enioka.jqm.jdbc.tablePrefix\", \"\");\n queries.putAll(DbImplBase.queries);\n for (Map.Entry<String, String> entry : DbImplBase.queries.entrySet())\n {\n queries.put(entry.getKey(), this.adaptSql(entry.getValue()));\n }\n }",
"@Api\n\tpublic void setUrl(String url) throws LayerException {\n\t\ttry {\n\t\t\tthis.url = url;\n\t\t\tMap<String, Object> params = new HashMap<String, Object>();\n\t\t\tparams.put(\"url\", url);\n\t\t\tDataStore store = DataStoreFactory.create(params);\n\t\t\tsetDataStore(store);\n\t\t} catch (IOException ioe) {\n\t\t\tthrow new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url);\n\t\t}\n\t}",
"public static base_response convert(nitro_service client, sslpkcs8 resource) throws Exception {\n\t\tsslpkcs8 convertresource = new sslpkcs8();\n\t\tconvertresource.pkcs8file = resource.pkcs8file;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.keyform = resource.keyform;\n\t\tconvertresource.password = resource.password;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}"
] |
We have received notification that a device is no longer on the network, so clear out its metadata.
@param announcement the packet which reported the device’s disappearance | [
"private void clearMetadata(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverTrackMetadataUpdate(player, null); // Inform listeners the metadata is gone.\n }\n }\n }\n }"
] | [
"@UiHandler(\"m_endTime\")\n void onEndTimeChange(CmsDateBoxEvent event) {\n\n if (handleChange() && !event.isUserTyping()) {\n m_controller.setEndTime(event.getDate());\n }\n }",
"public boolean detectOperaMobile() {\r\n\r\n if ((userAgent.indexOf(engineOpera) != -1)\r\n && ((userAgent.indexOf(mini) != -1) || (userAgent.indexOf(mobi) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }",
"public List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }",
"public RuleEnvelope getRule(String ruleId) throws ApiException {\n ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId);\n return resp.getData();\n }",
"public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}",
"protected static <T, A> ManagementRequestHandler<T, A> getFallbackHandler(final ManagementRequestHeader header) {\n return new ManagementRequestHandler<T, A>() {\n @Override\n public void handleRequest(final DataInput input, ActiveOperation.ResultHandler<T> resultHandler, ManagementRequestContext<A> context) throws IOException {\n final Exception error = ProtocolLogger.ROOT_LOGGER.noSuchResponseHandler(Integer.toHexString(header.getRequestId()));\n if(resultHandler.failed(error)) {\n safeWriteErrorResponse(context.getChannel(), context.getRequestHeader(), error);\n }\n }\n };\n }",
"public void setDirectory(final String directory) {\n this.directory = new File(this.configuration.getDirectory(), directory);\n if (!this.directory.exists()) {\n throw new IllegalArgumentException(String.format(\n \"Directory does not exist: %s.\\n\" +\n \"Configuration contained value %s which is supposed to be relative to \" +\n \"configuration directory.\",\n this.directory, directory));\n }\n\n if (!this.directory.getAbsolutePath()\n .startsWith(this.configuration.getDirectory().getAbsolutePath())) {\n throw new IllegalArgumentException(String.format(\n \"All files and directories must be contained in the configuration directory the \" +\n \"directory provided in the configuration breaks that contract: %s in config \" +\n \"file resolved to %s.\",\n directory, this.directory));\n }\n }",
"public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n children.add(parsedItemInfo);\n }\n }\n return children;\n }",
"public static base_response update(nitro_service client, snmpoption resource) throws Exception {\n\t\tsnmpoption updateresource = new snmpoption();\n\t\tupdateresource.snmpset = resource.snmpset;\n\t\tupdateresource.snmptraplogging = resource.snmptraplogging;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
do 'Distinct' operation
@param queryDescriptor descriptor of MongoDB query
@param collection collection for execute the operation
@return result iterator
@see <a href ="https://docs.mongodb.com/manual/reference/method/db.collection.distinct/">distinct</a> | [
"private static ClosableIterator<Tuple> doDistinct(final MongoDBQueryDescriptor queryDescriptor, final MongoCollection<Document> collection) {\n\t\tDistinctIterable<?> distinctFieldValues = collection.distinct( queryDescriptor.getDistinctFieldName(), queryDescriptor.getCriteria(), String.class );\n\t\tCollation collation = getCollation( queryDescriptor.getOptions() );\n\n\t\tdistinctFieldValues = collation != null ? distinctFieldValues.collation( collation ) : distinctFieldValues;\n\n\t\tMongoCursor<?> cursor = distinctFieldValues.iterator();\n\t\tList<Object> documents = new ArrayList<>();\n\t\twhile ( cursor.hasNext() ) {\n\t\t\tdocuments.add( cursor.next() );\n\t\t}\n\t\tMapTupleSnapshot snapshot = new MapTupleSnapshot( Collections.<String, Object>singletonMap( \"n\", documents ) );\n\t\treturn CollectionHelper.newClosableIterator( Collections.singletonList( new Tuple( snapshot, SnapshotType.UNKNOWN ) ) );\n\t}"
] | [
"public static java.sql.Timestamp getTimestamp(Object value) {\n try {\n return toTimestamp(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }",
"public ItemRequest<Project> addFollowers(String project) {\n \n String path = String.format(\"/projects/%s/addFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }",
"public DocumentReaderAndWriter<IN> makeReaderAndWriter() {\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>)\r\n Class.forName(flags.readerAndWriter).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.readerAndWriter: '%s'\", flags.readerAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }",
"public WebSocketContext sendToTagged(String message, String tag) {\n return sendToTagged(message, tag, false);\n }",
"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 static <T> String listToString(List<T> list, final boolean justValue) {\r\n return listToString(list, justValue, null);\r\n }",
"public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tautoscalepolicy_binding obj = new autoscalepolicy_binding();\n\t\tobj.set_name(name);\n\t\tautoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }",
"public void checkpoint(ObjectEnvelope mod) throws PersistenceBrokerException\r\n {\r\n mod.doInsert();\r\n mod.setModificationState(StateOldClean.getInstance());\r\n }"
] |
Crop the image between two points.
@param top Top bound.
@param left Left bound.
@param bottom Bottom bound.
@param right Right bound.
@throws IllegalArgumentException if {@code top} or {@code left} are less than zero or {@code
bottom} or {@code right} are less than one or less than {@code top} or {@code left},
respectively. | [
"public ThumborUrlBuilder crop(int top, int left, int bottom, int right) {\n if (top < 0) {\n throw new IllegalArgumentException(\"Top must be greater or equal to zero.\");\n }\n if (left < 0) {\n throw new IllegalArgumentException(\"Left must be greater or equal to zero.\");\n }\n if (bottom < 1 || bottom <= top) {\n throw new IllegalArgumentException(\"Bottom must be greater than zero and top.\");\n }\n if (right < 1 || right <= left) {\n throw new IllegalArgumentException(\"Right must be greater than zero and left.\");\n }\n hasCrop = true;\n cropTop = top;\n cropLeft = left;\n cropBottom = bottom;\n cropRight = right;\n return this;\n }"
] | [
"public static Object xmlToObject(String fileName) throws FileNotFoundException {\r\n\t\tFileInputStream fi = new FileInputStream(fileName);\r\n\t\tXMLDecoder decoder = new XMLDecoder(fi);\r\n\t\tObject object = decoder.readObject();\r\n\t\tdecoder.close();\r\n\t\treturn object;\r\n\t}",
"public void removeExtension(Resource rootResource, String moduleName, ManagementResourceRegistration rootRegistration) throws IllegalStateException {\n final ManagementResourceRegistration profileReg;\n if (rootRegistration.getPathAddress().size() == 0) {\n //domain or server extension\n // Can't use processType.isServer() to determine where to look for profile reg because a lot of test infrastructure\n // doesn't add the profile mrr even in HC-based tests\n ManagementResourceRegistration reg = rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(PROFILE)));\n if (reg == null) {\n reg = rootRegistration;\n }\n profileReg = reg;\n } else {\n //host model extension\n profileReg = rootRegistration;\n }\n ManagementResourceRegistration deploymentsReg = processType.isServer() ? rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT))) : null;\n\n ExtensionInfo extension = extensions.remove(moduleName);\n if (extension != null) {\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (extension) {\n Set<String> subsystemNames = extension.subsystems.keySet();\n\n final boolean dcExtension = processType.isHostController() ?\n rootRegistration.getPathAddress().size() == 0 : false;\n\n for (String subsystem : subsystemNames) {\n if (hasSubsystemsRegistered(rootResource, subsystem, dcExtension)) {\n // Restore the data\n extensions.put(moduleName, extension);\n throw ControllerLogger.ROOT_LOGGER.removingExtensionWithRegisteredSubsystem(moduleName, subsystem);\n }\n }\n for (Map.Entry<String, SubsystemInformation> entry : extension.subsystems.entrySet()) {\n String subsystem = entry.getKey();\n profileReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n if (deploymentsReg != null) {\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBDEPLOYMENT, subsystem));\n }\n\n if (extension.xmlMapper != null) {\n SubsystemInformationImpl subsystemInformation = SubsystemInformationImpl.class.cast(entry.getValue());\n for (String namespace : subsystemInformation.getXMLNamespaces()) {\n extension.xmlMapper.unregisterRootElement(new QName(namespace, SUBSYSTEM));\n }\n }\n }\n }\n }\n }",
"private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }",
"public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n final List<String> list = readLines(self);\n T result = null;\n for (String line : list) {\n List vals = Arrays.asList(pattern.split(line));\n result = closure.call(vals);\n }\n return result;\n }",
"private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {\n\t\tif ( configurationResourceUrl != null ) {\n\t\t\ttry ( InputStream openStream = configurationResourceUrl.openStream() ) {\n\t\t\t\thotRodConfiguration.load( openStream );\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow log.failedLoadingHotRodConfigurationProperties( e );\n\t\t\t}\n\t\t}\n\t}",
"public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }",
"@Nonnull\n\tpublic static InterfaceAnalysis analyze(@Nonnull final String code) {\n\t\tCheck.notNull(code, \"code\");\n\n\t\tfinal CompilationUnit unit = Check.notNull(SourceCodeReader.parse(code), \"compilationUnit\");\n\t\tfinal List<TypeDeclaration> types = Check.notEmpty(unit.getTypes(), \"typeDeclarations\");\n\t\tCheck.stateIsTrue(types.size() == 1, \"only one interface declaration per analysis is supported\");\n\n\t\tfinal ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) types.get(0);\n\n\t\tfinal Imports imports = SourceCodeReader.findImports(unit.getImports());\n\t\tfinal Package pkg = unit.getPackage() != null ? new Package(unit.getPackage().getName().toString()) : Package.UNDEFINED;\n\t\tfinal List<Annotation> annotations = SourceCodeReader.findAnnotations(type.getAnnotations(), imports);\n\t\tfinal List<Method> methods = SourceCodeReader.findMethods(type.getMembers(), imports);\n\t\tCheck.stateIsTrue(!hasPossibleMutatingMethods(methods), \"The passed interface '%s' seems to have mutating methods\", type.getName());\n\t\tfinal List<Interface> extendsInterfaces = SourceCodeReader.findExtends(type);\n\t\tfinal String interfaceName = type.getName();\n\t\treturn new ImmutableInterfaceAnalysis(annotations, extendsInterfaces, imports.asList(), interfaceName, methods, pkg);\n\t}",
"private 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 }",
"@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}"
] |
Write the domain controller data to a byte buffer.
@param data the domain controller data
@return the byte buffer
@throws Exception | [
"public static byte[] domainControllerDataToByteBuffer(List<DomainControllerData> data) throws Exception {\n final ByteArrayOutputStream out_stream = new ByteArrayOutputStream(512);\n byte[] result;\n try (DataOutputStream out = new DataOutputStream(out_stream)) {\n Iterator<DomainControllerData> iter = data.iterator();\n while (iter.hasNext()) {\n DomainControllerData dcData = iter.next();\n dcData.writeTo(out);\n if (iter.hasNext()) {\n S3Util.writeString(SEPARATOR, out);\n }\n }\n result = out_stream.toByteArray();\n }\n return result;\n }"
] | [
"public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }",
"private static double threePointsAngle(Point vertex, Point A, Point B) {\n double b = pointsDistance(vertex, A);\n double c = pointsDistance(A, B);\n double a = pointsDistance(B, vertex);\n\n return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));\n\n }",
"public static double blackModelDgitialCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;\n\t}",
"public static base_response update(nitro_service client, appfwlearningsettings resource) throws Exception {\n\t\tappfwlearningsettings updateresource = new appfwlearningsettings();\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.starturlminthreshold = resource.starturlminthreshold;\n\t\tupdateresource.starturlpercentthreshold = resource.starturlpercentthreshold;\n\t\tupdateresource.cookieconsistencyminthreshold = resource.cookieconsistencyminthreshold;\n\t\tupdateresource.cookieconsistencypercentthreshold = resource.cookieconsistencypercentthreshold;\n\t\tupdateresource.csrftagminthreshold = resource.csrftagminthreshold;\n\t\tupdateresource.csrftagpercentthreshold = resource.csrftagpercentthreshold;\n\t\tupdateresource.fieldconsistencyminthreshold = resource.fieldconsistencyminthreshold;\n\t\tupdateresource.fieldconsistencypercentthreshold = resource.fieldconsistencypercentthreshold;\n\t\tupdateresource.crosssitescriptingminthreshold = resource.crosssitescriptingminthreshold;\n\t\tupdateresource.crosssitescriptingpercentthreshold = resource.crosssitescriptingpercentthreshold;\n\t\tupdateresource.sqlinjectionminthreshold = resource.sqlinjectionminthreshold;\n\t\tupdateresource.sqlinjectionpercentthreshold = resource.sqlinjectionpercentthreshold;\n\t\tupdateresource.fieldformatminthreshold = resource.fieldformatminthreshold;\n\t\tupdateresource.fieldformatpercentthreshold = resource.fieldformatpercentthreshold;\n\t\tupdateresource.xmlwsiminthreshold = resource.xmlwsiminthreshold;\n\t\tupdateresource.xmlwsipercentthreshold = resource.xmlwsipercentthreshold;\n\t\tupdateresource.xmlattachmentminthreshold = resource.xmlattachmentminthreshold;\n\t\tupdateresource.xmlattachmentpercentthreshold = resource.xmlattachmentpercentthreshold;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private String getResponseString(boolean async, UploaderResponse response) {\r\n return async ? response.getTicketId() : response.getPhotoId();\r\n }",
"@SuppressForbidden(\"legitimate sysstreams.\")\n private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) {\n final PrintStream origSysOut = System.out;\n final PrintStream origSysErr = System.err;\n\n // Set warnings stream to System.err.\n warnings = System.err;\n AccessController.doPrivileged(new PrivilegedAction<Void>() {\n @SuppressForbidden(\"legitimate PrintStream with default charset.\")\n @Override\n public Void run() {\n System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysOut.write(b, off, len);\n }\n serializer.serialize(new AppendStdOutEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n\n System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysErr.write(b, off, len);\n }\n serializer.serialize(new AppendStdErrEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n return null;\n }\n });\n }",
"private boolean keyAlreadyExists(String newKey) {\n\n Collection<?> itemIds = m_table.getItemIds();\n for (Object itemId : itemIds) {\n if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {\n return true;\n }\n }\n return false;\n }",
"public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }",
"private void readAssignments(Project plannerProject)\n {\n Allocations allocations = plannerProject.getAllocations();\n List<Allocation> allocationList = allocations.getAllocation();\n Set<Task> tasksWithAssignments = new HashSet<Task>();\n\n for (Allocation allocation : allocationList)\n {\n Integer taskID = getInteger(allocation.getTaskId());\n Integer resourceID = getInteger(allocation.getResourceId());\n Integer units = getInteger(allocation.getUnits());\n\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n\n if (task != null && resource != null)\n {\n Duration work = task.getWork();\n int percentComplete = NumberHelper.getInt(task.getPercentageComplete());\n\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setUnits(units);\n assignment.setWork(work);\n\n if (percentComplete != 0)\n {\n Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());\n assignment.setActualWork(actualWork);\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n else\n {\n assignment.setRemainingWork(work);\n }\n\n assignment.setStart(task.getStart());\n assignment.setFinish(task.getFinish());\n\n tasksWithAssignments.add(task);\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n\n //\n // Adjust work per assignment for tasks with multiple assignments\n //\n for (Task task : tasksWithAssignments)\n {\n List<ResourceAssignment> assignments = task.getResourceAssignments();\n if (assignments.size() > 1)\n {\n double maxUnits = 0;\n for (ResourceAssignment assignment : assignments)\n {\n maxUnits += assignment.getUnits().doubleValue();\n }\n\n for (ResourceAssignment assignment : assignments)\n {\n Duration work = assignment.getWork();\n double factor = assignment.getUnits().doubleValue() / maxUnits;\n\n work = Duration.getInstance(work.getDuration() * factor, work.getUnits());\n assignment.setWork(work);\n Duration actualWork = assignment.getActualWork();\n if (actualWork != null)\n {\n actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits());\n assignment.setActualWork(actualWork);\n }\n\n Duration remainingWork = assignment.getRemainingWork();\n if (remainingWork != null)\n {\n remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits());\n assignment.setRemainingWork(remainingWork);\n }\n }\n }\n }\n }"
] |
Set a Java classname path to ignore when printing stack traces
@param classToIgnoreInTraces The class name (with packages, etc) to ignore.
@return this | [
"public RedwoodConfiguration loggingClass(final String classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces); } });\r\n return this;\r\n }"
] | [
"private long size(final Jedis jedis, final String queueName) {\n final String key = key(QUEUE, queueName);\n final long size;\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZCARD\n size = jedis.zcard(key);\n } else { // Else, use LLEN\n size = jedis.llen(key);\n }\n return size;\n }",
"public static void openLogFile(String logPath) {\n\t\tif (logPath == null) {\n\t\t\tprintStream = System.out;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tprintStream = new PrintStream(new File(logPath));\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Log file \" + logPath + \" was not found\", e);\n\t\t\t}\n\t\t}\n\t}",
"public Bitmap drawableToBitmap(Drawable drawable) {\n\t\tif (drawable == null) // Don't do anything without a proper drawable\n\t\t\treturn null;\n\t\telse if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable\n\t\t\tLog.i(TAG, \"Bitmap drawable!\");\n\t\t\treturn ((BitmapDrawable) drawable).getBitmap();\n\t\t}\n\n\t\tint intrinsicWidth = drawable.getIntrinsicWidth();\n\t\tint intrinsicHeight = drawable.getIntrinsicHeight();\n\n\t\tif (!(intrinsicWidth > 0 && intrinsicHeight > 0))\n\t\t\treturn null;\n\n\t\ttry {\n\t\t\t// Create Bitmap object out of the drawable\n\t\t\tBitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888);\n\t\t\tCanvas canvas = new Canvas(bitmap);\n\t\t\tdrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n\t\t\tdrawable.draw(canvas);\n\t\t\treturn bitmap;\n\t\t} catch (OutOfMemoryError e) {\n\t\t\t// Simply return null of failed bitmap creations\n\t\t\tLog.e(TAG, \"Encountered OutOfMemoryError while generating bitmap!\");\n\t\t\treturn null;\n\t\t}\n\t}",
"static void doDifference(\n Map<String, String> left,\n Map<String, String> right,\n Map<String, String> onlyOnLeft,\n Map<String, String> onlyOnRight,\n Map<String, String> updated\n ) {\n onlyOnRight.clear();\n onlyOnRight.putAll(right);\n for (Map.Entry<String, String> entry : left.entrySet()) {\n String leftKey = entry.getKey();\n String leftValue = entry.getValue();\n if (right.containsKey(leftKey)) {\n String rightValue = onlyOnRight.remove(leftKey);\n if (!leftValue.equals(rightValue)) {\n updated.put(leftKey, leftValue);\n }\n } else {\n onlyOnLeft.put(leftKey, leftValue);\n }\n }\n }",
"private int getColorWaveformBits(final ByteBuffer waveBytes, final int segment) {\n final int base = (segment * 2);\n final int big = Util.unsign(waveBytes.get(base));\n final int small = Util.unsign(waveBytes.get(base + 1));\n return big * 256 + small;\n }",
"protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) {\n //noinspection unchecked\n return (ActiveOperation<T, A>) activeRequests.get(id);\n }",
"public static base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<String, Field> getValueAsMap() {\n return (Map<String, Field>) type.convert(getValue(), Type.MAP);\n }"
] |
returns a sorted array of methods | [
"public GroovyMethodDoc[] methods() {\n Collections.sort(methods);\n return methods.toArray(new GroovyMethodDoc[methods.size()]);\n }"
] | [
"public static String getOffsetCodeFromSchedule(Schedule schedule) {\r\n\r\n\t\tdouble doubleLength = 0;\r\n\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i ++) {\r\n\t\t\tdoubleLength += schedule.getPeriodLength(i);\r\n\t\t}\r\n\t\tdoubleLength /= schedule.getNumberOfPeriods();\r\n\r\n\t\tdoubleLength *= 12;\r\n\t\tint periodLength = (int) Math.round(doubleLength);\r\n\r\n\r\n\t\tString offsetCode = periodLength + \"M\";\r\n\t\treturn offsetCode;\r\n\t}",
"public static PredicateExpression nin(Object... rhs) {\n PredicateExpression ex = new PredicateExpression(\"$nin\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }",
"private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }",
"public ItemRequest<User> findById(String user) {\n \n String path = String.format(\"/users/%s\", user);\n return new ItemRequest<User>(this, User.class, path, \"GET\");\n }",
"public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }",
"public void beforeClose(PBStateEvent event)\r\n {\r\n /*\r\n arminw:\r\n this is a workaround for use in managed environments. When a PB instance is used\r\n within a container a PB.close call is done when leave the container method. This close\r\n the PB handle (but the real instance is still in use) and the PB listener are notified.\r\n But the JTA tx was not committed at\r\n this point in time and the session cache should not be cleared, because the updated/new\r\n objects will be pushed to the real cache on commit call (if we clear, nothing to push).\r\n So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle\r\n is closed), if true we don't reset the session cache.\r\n */\r\n if(!broker.isInTransaction())\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clearing the session cache\");\r\n resetSessionCache();\r\n }\r\n }",
"synchronized boolean doReConnect() throws IOException {\n\n // In case we are still connected, test the connection and see if we can reuse it\n if(connectionManager.isConnected()) {\n try {\n final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();\n result.get(15, TimeUnit.SECONDS); // Hmm, perhaps 15 is already too much\n return true;\n } catch (Exception e) {\n ServerLogger.AS_ROOT_LOGGER.debugf(e, \"failed to ping the host-controller, going to reconnect\");\n }\n // Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect\n final Connection connection = connectionManager.getConnection();\n StreamUtils.safeClose(connection);\n if(connection != null) {\n try {\n // Wait for the connection to be closed\n connection.awaitClosed();\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n }\n }\n\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n // Reconnect to the host-controller\n final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);\n try {\n boolean inSync = result.getResult().get();\n ok = true;\n reconnectRunner = null;\n return inSync;\n } catch (ExecutionException e) {\n throw new IOException(e);\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n } finally {\n if(!ok) {\n StreamUtils.safeClose(connection);\n }\n }\n }",
"public void setSizes(Collection<Size> sizes) {\r\n for (Size size : sizes) {\r\n if (size.getLabel() == Size.SMALL) {\r\n smallSize = size;\r\n } else if (size.getLabel() == Size.SQUARE) {\r\n squareSize = size;\r\n } else if (size.getLabel() == Size.THUMB) {\r\n thumbnailSize = size;\r\n } else if (size.getLabel() == Size.MEDIUM) {\r\n mediumSize = size;\r\n } else if (size.getLabel() == Size.LARGE) {\r\n largeSize = size;\r\n } else if (size.getLabel() == Size.LARGE_1600) {\r\n large1600Size = size;\r\n } else if (size.getLabel() == Size.LARGE_2048) {\r\n large2048Size = size;\r\n } else if (size.getLabel() == Size.ORIGINAL) {\r\n originalSize = size;\r\n } else if (size.getLabel() == Size.SQUARE_LARGE) {\r\n squareLargeSize = size;\r\n } else if (size.getLabel() == Size.SMALL_320) {\r\n small320Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_640) {\r\n medium640Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_800) {\r\n medium800Size = size;\r\n } else if (size.getLabel() == Size.VIDEO_PLAYER) {\r\n videoPlayer = size;\r\n } else if (size.getLabel() == Size.SITE_MP4) {\r\n siteMP4 = size;\r\n } else if (size.getLabel() == Size.VIDEO_ORIGINAL) {\r\n videoOriginal = size;\r\n }\r\n else if (size.getLabel() == Size.MOBILE_MP4) {\r\n \tmobileMP4 = size;\r\n }\r\n else if (size.getLabel() == Size.HD_MP4) {\r\n \thdMP4 = size;\r\n }\r\n }\r\n }",
"public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] |
Gets the event type from message.
@param message the message
@return the event type | [
"private EventTypeEnum getEventType(Message message) {\n boolean isRequestor = MessageUtils.isRequestor(message);\n boolean isFault = MessageUtils.isFault(message);\n boolean isOutbound = MessageUtils.isOutbound(message);\n\n //Needed because if it is rest request and method does not exists had better to return Fault\n if(!isFault && isRestMessage(message)) {\n isFault = (message.getExchange().get(\"org.apache.cxf.resource.operation.name\") == null);\n if (!isFault) {\n Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);\n if (null != responseCode) {\n isFault = (responseCode >= 400);\n }\n }\n }\n if (isOutbound) {\n if (isFault) {\n return EventTypeEnum.FAULT_OUT;\n } else {\n return isRequestor ? EventTypeEnum.REQ_OUT : EventTypeEnum.RESP_OUT;\n }\n } else {\n if (isFault) {\n return EventTypeEnum.FAULT_IN;\n } else {\n return isRequestor ? EventTypeEnum.RESP_IN : EventTypeEnum.REQ_IN;\n }\n }\n }"
] | [
"public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }",
"private static Pod getRandomPod(KubernetesClient client, String name, String namespace) {\n Endpoints endpoints = client.endpoints().inNamespace(namespace).withName(name).get();\n List<String> pods = new ArrayList<>();\n if (endpoints != null) {\n for (EndpointSubset subset : endpoints.getSubsets()) {\n for (EndpointAddress address : subset.getAddresses()) {\n if (address.getTargetRef() != null && POD.equals(address.getTargetRef().getKind())) {\n String pod = address.getTargetRef().getName();\n if (pod != null && !pod.isEmpty()) {\n pods.add(pod);\n }\n }\n }\n }\n }\n if (pods.isEmpty()) {\n return null;\n } else {\n String chosen = pods.get(RANDOM.nextInt(pods.size()));\n return client.pods().inNamespace(namespace).withName(chosen).get();\n }\n }",
"public static base_responses clear(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"public void load(String soundFile)\n {\n if (mSoundFile != null)\n {\n unload();\n }\n mSoundFile = soundFile;\n if (mAudioListener != null)\n {\n mAudioListener.getAudioEngine().preloadSoundFile(soundFile);\n Log.d(\"SOUND\", \"loaded audio file %s\", getSoundFile());\n }\n }",
"private void logRequestHistory(HttpMethod httpMethodProxyRequest, PluginResponse httpServletResponse,\n History history) {\n try {\n if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) {\n logger.info(\"Storing history\");\n String createdDate;\n SimpleDateFormat sdf = new SimpleDateFormat();\n sdf.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n sdf.applyPattern(\"dd MMM yyyy HH:mm:ss\");\n createdDate = sdf.format(new Date()) + \" GMT\";\n\n history.setCreatedAt(createdDate);\n history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? \"\"\n : httpMethodProxyRequest.getQueryString());\n history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest));\n history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setResponseContentType(httpServletResponse.getContentType());\n history.setResponseData(httpServletResponse.getContentString());\n history.setResponseBodyDecoded(httpServletResponse.isContentDecoded());\n HistoryService.getInstance().addHistory(history);\n logger.info(\"Done storing\");\n }\n } catch (URIException e) {\n e.printStackTrace();\n }\n }",
"public static String getDateTimeStr(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSSZ\");\n // 20140315 test will problem +0000\n return sdf.format(d);\n }",
"@Override\n public Set<String> getProviderNames() {\n Set<String> result = new HashSet<>();\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n result.add(prov.getProviderName());\n } catch (Exception e) {\n Logger.getLogger(Monetary.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n return result;\n }",
"public PhotoContext getContext(String photoId, String groupId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"group_id\", groupId);\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 Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else if (!elementName.equals(\"count\")) {\r\n _log.warn(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n return photoContext;\r\n }",
"public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }"
] |
Loads the leap second rules from a URL, often in a jar file.
@param url the jar file to load, not null
@throws Exception if an error occurs | [
"private static Data loadLeapSeconds(URL url) throws ClassNotFoundException, IOException {\n List<String> lines;\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {\n lines = reader.lines().collect(Collectors.toList());\n }\n List<Long> dates = new ArrayList<>();\n List<Integer> offsets = new ArrayList<>();\n for (String line : lines) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\")) {\n continue;\n }\n Matcher matcher = LEAP_FILE_FORMAT.matcher(line);\n if (matcher.matches() == false) {\n throw new StreamCorruptedException(\"Invalid leap second file\");\n }\n dates.add(LocalDate.parse(matcher.group(1)).getLong(JulianFields.MODIFIED_JULIAN_DAY));\n offsets.add(Integer.valueOf(matcher.group(2)));\n }\n long[] datesData = new long[dates.size()];\n int[] offsetsData = new int[dates.size()];\n long[] taiData = new long[dates.size()];\n for (int i = 0; i < datesData.length; i++) {\n datesData[i] = dates.get(i);\n offsetsData[i] = offsets.get(i);\n taiData[i] = tai(datesData[i], offsetsData[i]);\n }\n return new Data(datesData, offsetsData, taiData);\n }"
] | [
"private Date adjustForWholeDay(Date date, boolean isEnd) {\n\n Calendar result = new GregorianCalendar();\n result.setTime(date);\n result.set(Calendar.HOUR_OF_DAY, 0);\n result.set(Calendar.MINUTE, 0);\n result.set(Calendar.SECOND, 0);\n result.set(Calendar.MILLISECOND, 0);\n if (isEnd) {\n result.add(Calendar.DATE, 1);\n }\n\n return result.getTime();\n }",
"public int getIndexMax() {\n int indexMax = 0;\n double max = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m > max ) {\n max = m;\n indexMax = i;\n }\n }\n\n return indexMax;\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 }",
"public static void applyToOrTransparent(ColorHolder colorHolder, Context ctx, GradientDrawable gradientDrawable) {\n if (colorHolder != null && gradientDrawable != null) {\n colorHolder.applyTo(ctx, gradientDrawable);\n } else if (gradientDrawable != null) {\n gradientDrawable.setColor(Color.TRANSPARENT);\n }\n }",
"public static onlinkipv6prefix get(nitro_service service, String ipv6prefix) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tobj.set_ipv6prefix(ipv6prefix);\n\t\tonlinkipv6prefix response = (onlinkipv6prefix) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static List<ObjectModelResolver> getResolvers() {\n if (resolvers == null) {\n synchronized (serviceLoader) {\n if (resolvers == null) {\n List<ObjectModelResolver> foundResolvers = new ArrayList<ObjectModelResolver>();\n for (ObjectModelResolver resolver : serviceLoader) {\n foundResolvers.add(resolver);\n }\n resolvers = foundResolvers;\n }\n }\n }\n\n return resolvers;\n }",
"public void declareInternalData(int maxRows, int maxCols) {\n this.maxRows = maxRows;\n this.maxCols = maxCols;\n\n U_tran = new DMatrixRMaj(maxRows,maxRows);\n Qm = new DMatrixRMaj(maxRows,maxRows);\n\n r_row = new double[ maxCols ];\n }",
"protected String createName() {\n final StringBuilder buf = new StringBuilder(128);\n try {\n buf.append(InetAddress.getLocalHost().getHostName()).append(COLON)\n .append(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]) // PID\n .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);\n for (final String queueName : this.queueNames) {\n buf.append(',').append(queueName);\n }\n } catch (UnknownHostException uhe) {\n throw new RuntimeException(uhe);\n }\n return buf.toString();\n }",
"public void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}"
] |
Initialize that Foundation Logging library. | [
"static void init() {// NOPMD\n\n\t\tdetermineIfNTEventLogIsSupported();\n\n\t\tURL resource = null;\n\n\t\tfinal String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, null);\n\n\t\tif (configurationOptionStr != null) {\n\t\t\ttry {\n\t\t\t\tresource = new URL(configurationOptionStr);\n\t\t\t} catch (MalformedURLException ex) {\n\t\t\t\t// so, resource is not a URL:\n\t\t\t\t// attempt to get the resource from the class path\n\t\t\t\tresource = Loader.getResource(configurationOptionStr);\n\t\t\t}\n\t\t}\n\t\tif (resource == null) {\n\t\t\tresource = Loader.getResource(DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\tif (resource == null) {\n\t\t\tSystem.err.println(\"[FoundationLogger] Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t\tthrow new FoundationIOException(\"Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\t// update the log manager to use the Foundation repository.\n\t\tfinal RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector(FoundationLogFactory.foundationLogHierarchy);\n\t\tLogManager.setRepositorySelector(foundationRepositorySelector, null);\n\n\t\t// set logger to info so we always want to see these logs even if root\n\t\t// is set to ERROR.\n\t\tfinal Logger logger = getLogger(FoundationLogger.class);\n\n\t\tfinal String logPropFile = resource.getPath();\n\t\tlog4jConfigProps = getLogProperties(resource);\n\t\t\n\t\t// select and configure again so the loggers are created with the right\n\t\t// level after the repository selector was updated.\n\t\tOptionConverter.selectAndConfigure(resource, null, FoundationLogFactory.foundationLogHierarchy);\n\n\t\t// start watching for property changes\n\t\tsetUpPropFileReloading(logger, logPropFile, log4jConfigProps);\n\n\t\t// add syslog appender or windows event viewer appender\n//\t\tsetupOSSystemLog(logger, log4jConfigProps);\n\n\t\t// parseMarkerPatterns(log4jConfigProps);\n\t\t// parseMarkerPurePattern(log4jConfigProps);\n//\t\tudpateMarkerStructuredLogOverrideMap(logger);\n\n AbstractFoundationLoggingMarker.init();\n\n\t\tupdateSniffingLoggersLevel(logger);\n\n setupJULSupport(resource);\n\n }"
] | [
"@JmxGetter(name = \"avgFetchKeysNetworkTimeMs\", description = \"average time spent on network, for fetch keys\")\n public double getAvgFetchKeysNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_KEYS).getAvgEventValue() / Time.NS_PER_MS;\n }",
"protected void copyClasspathResource(File outputDirectory,\n String resourceName,\n String targetFileName) throws IOException\n {\n String resourcePath = classpathPrefix + resourceName;\n InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);\n copyStream(outputDirectory, resourceStream, targetFileName);\n }",
"private void processBaseFonts(byte[] data)\n {\n int offset = 0;\n\n int blockCount = MPPUtility.getShort(data, 0);\n offset += 2;\n\n int size;\n String name;\n\n for (int loop = 0; loop < blockCount; loop++)\n {\n /*unknownAttribute = MPPUtility.getShort(data, offset);*/\n offset += 2;\n\n size = MPPUtility.getShort(data, offset);\n offset += 2;\n\n name = MPPUtility.getUnicodeString(data, offset);\n offset += 64;\n\n if (name.length() != 0)\n {\n FontBase fontBase = new FontBase(Integer.valueOf(loop), name, size);\n m_fontBases.put(fontBase.getIndex(), fontBase);\n }\n }\n }",
"public NestedDef getNested(String name)\r\n {\r\n NestedDef nestedDef = null;\r\n\r\n for (Iterator it = _nested.iterator(); it.hasNext(); )\r\n {\r\n nestedDef = (NestedDef)it.next();\r\n if (nestedDef.getName().equals(name))\r\n {\r\n return nestedDef;\r\n }\r\n }\r\n return null;\r\n }",
"public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }",
"public static CmsGalleryTabConfiguration resolve(String configStr) {\r\n\r\n CmsGalleryTabConfiguration tabConfig;\r\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(configStr)) {\r\n configStr = \"*sitemap,types,galleries,categories,vfstree,search,results\";\r\n }\r\n if (DEFAULT_CONFIGURATIONS != null) {\r\n tabConfig = DEFAULT_CONFIGURATIONS.get(configStr);\r\n if (tabConfig != null) {\r\n return tabConfig;\r\n }\r\n\r\n }\r\n return parse(configStr);\r\n }",
"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 synchronized boolean put(byte value) {\n if (available == capacity) {\n return false;\n }\n buffer[idxPut] = value;\n idxPut = (idxPut + 1) % capacity;\n available++;\n return true;\n }",
"protected I_CmsSearchConfigurationFacetRange parseRangeFacet(String pathPrefix) {\n\n try {\n final String range = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_RANGE);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final String start = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_START);\n final String end = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_END);\n final String gap = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_GAP);\n final String sother = parseOptionalStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_OTHER);\n List<I_CmsSearchConfigurationFacetRange.Other> other = null;\n if (sother != null) {\n final List<String> sothers = Arrays.asList(sother.split(\",\"));\n other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sothers.size());\n for (String so : sothers) {\n try {\n I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf(\n so);\n other.add(o);\n } catch (final Exception e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e);\n }\n }\n }\n final Boolean hardEnd = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_RANGE_FACET_HARDEND);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetRange(\n range,\n start,\n end,\n gap,\n other,\n hardEnd,\n name,\n minCount,\n label,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_RANGE_FACET_RANGE\n + \", \"\n + XML_ELEMENT_RANGE_FACET_START\n + \", \"\n + XML_ELEMENT_RANGE_FACET_END\n + \", \"\n + XML_ELEMENT_RANGE_FACET_GAP),\n e);\n return null;\n }\n\n }"
] |
Builds IMAP envelope String from pre-parsed data. | [
"private String parseEnvelope() {\r\n List<String> response = new ArrayList<>();\r\n //1. Date ---------------\r\n response.add(LB + Q + sentDateEnvelopeString + Q + SP);\r\n //2. Subject ---------------\r\n if (subject != null && (subject.length() != 0)) {\r\n response.add(Q + escapeHeader(subject) + Q + SP);\r\n } else {\r\n response.add(NIL + SP);\r\n }\r\n //3. From ---------------\r\n addAddressToEnvelopeIfAvailable(from, response);\r\n response.add(SP);\r\n //4. Sender ---------------\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(sender, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailableWithNetscapeFeature(replyTo, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(to, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(cc, response);\r\n response.add(SP);\r\n addAddressToEnvelopeIfAvailable(bcc, response);\r\n response.add(SP);\r\n if (inReplyTo != null && inReplyTo.length > 0) {\r\n response.add(inReplyTo[0]);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(SP);\r\n if (messageID != null && messageID.length > 0) {\r\n messageID[0] = escapeHeader(messageID[0]);\r\n response.add(Q + messageID[0] + Q);\r\n } else {\r\n response.add(NIL);\r\n }\r\n response.add(RB);\r\n\r\n StringBuilder buf = new StringBuilder(16 * response.size());\r\n for (String aResponse : response) {\r\n buf.append(aResponse);\r\n }\r\n\r\n return buf.toString();\r\n }"
] | [
"private void readWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar)\n {\n WorkWeeks ww = xmlCalendar.getWorkWeeks();\n if (ww != null)\n {\n for (WorkWeek xmlWeek : ww.getWorkWeek())\n {\n ProjectCalendarWeek week = mpxjCalendar.addWorkWeek();\n week.setName(xmlWeek.getName());\n Date startTime = xmlWeek.getTimePeriod().getFromDate();\n Date endTime = xmlWeek.getTimePeriod().getToDate();\n week.setDateRange(new DateRange(startTime, endTime));\n\n WeekDays xmlWeekDays = xmlWeek.getWeekDays();\n if (xmlWeekDays != null)\n {\n for (WeekDay xmlWeekDay : xmlWeekDays.getWeekDay())\n {\n int dayNumber = xmlWeekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n week.setWorkingDay(day, BooleanHelper.getBoolean(xmlWeekDay.isDayWorking()));\n ProjectCalendarHours hours = week.addCalendarHours(day);\n\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = xmlWeekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n startTime = period.getFromTime();\n 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 hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }\n }\n }\n }",
"public static void hideOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.showAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }",
"public String getProfileIdFromClientId(int id) {\n return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);\n }",
"public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) {\n if(timeout < 0)\n throw new IllegalArgumentException(\"The timeout must be a non-negative number.\");\n this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit);\n return this;\n }",
"public void clearRequestSettings(int pathId, String clientUUID) throws Exception {\n this.setRequestEnabled(pathId, false, clientUUID);\n OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_REQUEST);\n EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_REQUEST, pathId, clientUUID);\n }",
"public Versioned<E> getVersionedById(int id) {\n Versioned<VListNode<E>> listNode = getListNode(id);\n if(listNode == null)\n throw new IndexOutOfBoundsException();\n return new Versioned<E>(listNode.getValue().getValue(), listNode.getVersion());\n }",
"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 void readCalendars(Project ganttProject)\n {\n m_mpxjCalendar = m_projectFile.addCalendar();\n m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n Calendars gpCalendar = ganttProject.getCalendars();\n setWorkingDays(m_mpxjCalendar, gpCalendar);\n setExceptions(m_mpxjCalendar, gpCalendar);\n m_eventManager.fireCalendarReadEvent(m_mpxjCalendar);\n }",
"public void setDuration(float start, float end)\n {\n for (GVRAnimation anim : mAnimations)\n {\n anim.setDuration(start,end);\n }\n }"
] |
Joins the given ranges into the fewest number of ranges.
If no joining can take place, the original array is returned.
@param ranges
@return | [
"public static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}"
] | [
"public static <T, ID> int dropTable(Dao<T, ID> dao, boolean ignoreErrors) throws SQLException {\n\t\tConnectionSource connectionSource = dao.getConnectionSource();\n\t\tClass<T> dataClass = dao.getDataClass();\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, dataClass);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}",
"public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }",
"public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }",
"public void stopListenting() {\n if (channel != null) {\n log.info(\"closing server channel\");\n channel.close().syncUninterruptibly();\n channel = null;\n }\n }",
"public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\n }",
"private void init() {\n logger.info(\"metadata init().\");\n\n writeLock.lock();\n try {\n // Required keys\n initCache(CLUSTER_KEY);\n\n // If stores definition storage engine is not null, initialize metadata\n // Add the mapping from key to the storage engine used\n if(this.storeDefinitionsStorageEngine != null) {\n initStoreDefinitions(null);\n } else {\n initCache(STORES_KEY);\n }\n\n // Initialize system store in the metadata cache\n initSystemCache();\n initSystemRoutingStrategies(getCluster());\n\n // Initialize with default if not present\n initCache(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY, true);\n initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);\n initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));\n initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());\n initCache(REBALANCING_SOURCE_CLUSTER_XML, null);\n initCache(REBALANCING_SOURCE_STORES_XML, null);\n\n\n } finally {\n writeLock.unlock();\n }\n }",
"public double[] getZeroRates(double[] maturities)\n\t{\n\t\tdouble[] values = new double[maturities.length];\n\n\t\tfor(int i=0; i<maturities.length; i++) {\n\t\t\tvalues[i] = getZeroRate(maturities[i]);\n\t\t}\n\n\t\treturn values;\n\t}",
"private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}",
"protected void createNewFile(final File file) {\n try {\n file.createNewFile();\n setFileNotWorldReadablePermissions(file);\n } catch (IOException e){\n throw new RuntimeException(e);\n }\n }"
] |
Inserts a Serializable value into the mapping of the underlying Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value a Serializable object, or null
@return this bundler instance to chain method calls | [
"public Bundler put(String key, Serializable value) {\n delegate.putSerializable(key, value);\n return this;\n }"
] | [
"protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {\n\n m_foundResources = new ArrayList<I_CmsSearchResourceBean>();\n for (final CmsSearchResource searchResult : searchResults) {\n m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));\n }\n }",
"ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }",
"public BufferedImage toNewBufferedImage(int type) {\n BufferedImage target = new BufferedImage(width, height, type);\n Graphics2D g2 = (Graphics2D) target.getGraphics();\n g2.drawImage(awt, 0, 0, null);\n g2.dispose();\n return target;\n }",
"public static lbroute[] get(nitro_service service) throws Exception{\n\t\tlbroute obj = new lbroute();\n\t\tlbroute[] response = (lbroute[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ProjectCalendar getByName(String calendarName)\n {\n ProjectCalendar calendar = null;\n\n if (calendarName != null && calendarName.length() != 0)\n {\n Iterator<ProjectCalendar> iter = iterator();\n while (iter.hasNext() == true)\n {\n calendar = iter.next();\n String name = calendar.getName();\n\n if ((name != null) && (name.equalsIgnoreCase(calendarName) == true))\n {\n break;\n }\n\n calendar = null;\n }\n }\n\n return (calendar);\n }",
"private void initStoreDefinitions(Version storesXmlVersion) {\n if(this.storeDefinitionsStorageEngine == null) {\n throw new VoldemortException(\"The store definitions directory is empty\");\n }\n\n String allStoreDefinitions = \"<stores>\";\n Version finalStoresXmlVersion = null;\n if(storesXmlVersion != null) {\n finalStoresXmlVersion = storesXmlVersion;\n }\n this.storeNames.clear();\n\n ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();\n\n // Some test setups may result in duplicate entries for 'store' element.\n // Do the de-dup here\n Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();\n Version maxVersion = null;\n while(storesIterator.hasNext()) {\n Pair<String, Versioned<String>> storeDetail = storesIterator.next();\n String storeName = storeDetail.getFirst();\n Versioned<String> versionedStoreDef = storeDetail.getSecond();\n storeNameToDefMap.put(storeName, versionedStoreDef);\n Version curVersion = versionedStoreDef.getVersion();\n\n // Get the highest version from all the store entries\n if(maxVersion == null) {\n maxVersion = curVersion;\n } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {\n maxVersion = curVersion;\n }\n }\n\n // If the specified version is null, assign highest Version to\n // 'stores.xml' key\n if(finalStoresXmlVersion == null) {\n finalStoresXmlVersion = maxVersion;\n }\n\n // Go through all the individual stores and update metadata\n for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {\n String storeName = storeEntry.getKey();\n Versioned<String> versionedStoreDef = storeEntry.getValue();\n\n // Add all the store names to the list of storeNames\n this.storeNames.add(storeName);\n\n this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),\n versionedStoreDef.getVersion()));\n }\n\n Collections.sort(this.storeNames);\n for(String storeName: this.storeNames) {\n Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);\n // Stitch together to form the complete store definition list.\n allStoreDefinitions += versionedStoreDef.getValue();\n\n }\n\n allStoreDefinitions += \"</stores>\";\n\n // Update cache with the composite store definition list.\n metadataCache.put(STORES_KEY,\n convertStringToObject(STORES_KEY,\n new Versioned<String>(allStoreDefinitions,\n finalStoresXmlVersion)));\n }",
"private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}",
"public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public T toObject(byte[] bytes) {\n try {\n return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();\n } catch(IOException e) {\n throw new SerializationException(e);\n } catch(ClassNotFoundException c) {\n throw new SerializationException(c);\n }\n }"
] |
Performs a get operation with the specified composite request object
@param requestWrapper A composite request object containing the key (and
/ or default value) and timeout.
@return The Versioned value corresponding to the key | [
"public List<Versioned<V>> getWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {\n try {\n long startTimeInMs = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"GET\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n keyHexString);\n }\n List<Versioned<V>> items = store.get(requestWrapper);\n if(logger.isDebugEnabled()) {\n int vcEntrySize = 0;\n for(Versioned<V> vc: items) {\n vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size();\n }\n debugLogEnd(\"GET\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n keyHexString,\n vcEntrySize);\n }\n return items;\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during get [ \" + e.getMessage()\n + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n }"
] | [
"private DBHandling createDBHandling() throws BuildException\r\n {\r\n if ((_handling == null) || (_handling.length() == 0))\r\n {\r\n throw new BuildException(\"No handling specified\");\r\n }\r\n try\r\n {\r\n String className = \"org.apache.ojb.broker.platforms.\"+\r\n \t\t\t\t\t Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+\r\n \t\t\t\t\t \"DBHandling\";\r\n Class handlingClass = ClassHelper.getClass(className);\r\n\r\n return (DBHandling)handlingClass.newInstance();\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Invalid handling '\"+_handling+\"' specified\");\r\n }\r\n }",
"public void refreshConnection() throws SQLException{\r\n\t\tthis.connection.close(); // if it's still in use, close it.\r\n\t\ttry{\r\n\t\t\tthis.connection = this.pool.obtainRawInternalConnection();\r\n\t\t} catch(SQLException e){\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"public void init(LblTree t1, LblTree t2) {\n\t\tLabelDictionary ld = new LabelDictionary();\n\t\tit1 = new InfoTree(t1, ld);\n\t\tit2 = new InfoTree(t2, ld);\n\t\tsize1 = it1.getSize();\n\t\tsize2 = it2.getSize();\n\t\tIJ = new int[Math.max(size1, size2)][Math.max(size1, size2)];\n\t\tdelta = new double[size1][size2];\n\t\tdeltaBit = new byte[size1][size2];\n\t\tcostV = new long[3][size1][size2];\n\t\tcostW = new long[3][size2];\n\n\t\t// Calculate delta between every leaf in G (empty tree) and all the nodes in F.\n\t\t// Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of\n\t\t// F.\n\t\tint[] labels1 = it1.getInfoArray(POST2_LABEL);\n\t\tint[] labels2 = it2.getInfoArray(POST2_LABEL);\n\t\tint[] sizes1 = it1.getInfoArray(POST2_SIZE);\n\t\tint[] sizes2 = it2.getInfoArray(POST2_SIZE);\n\t\tfor (int x = 0; x < sizes1.length; x++) { // for all nodes of initially left tree\n\t\t\tfor (int y = 0; y < sizes2.length; y++) { // for all nodes of initially right tree\n\n\t\t\t\t// This is an attempt for distances of single-node subtree and anything alse\n\t\t\t\t// The differences between pairs of labels are stored\n\t\t\t\tif (labels1[x] == labels2[y]) {\n\t\t\t\t\tdeltaBit[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tdeltaBit[x][y] =\n\t\t\t\t\t\t\t1; // if this set, the labels differ, cost of relabeling is set\n\t\t\t\t\t// to costMatch\n\t\t\t\t}\n\n\t\t\t\tif (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs\n\t\t\t\t\tdelta[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tif (sizes1[x] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes2[y] - 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (sizes2[y] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes1[x] - 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public void deployApplication(String applicationName, URL... urls) throws IOException {\n this.applicationName = applicationName;\n\n for (URL url : urls) {\n try (InputStream inputStream = url.openStream()) {\n deploy(inputStream);\n }\n }\n }",
"public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) {\r\n\t\treturn ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(),\r\n\t\t\t\tgetShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}",
"public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }",
"protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }",
"public InsertBuilder set(String column, String value) {\n columns.add(column);\n values.add(value);\n return this;\n }",
"public static double blackModelSwaptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble swapAnnuity)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t}"
] |
Attempts shared acquisition with a max wait time.
@param permit - the permit Integer for this operation. May not be {@code null}.
@param timeout - the time value to wait for acquiring the lock
@param unit - See {@code TimeUnit} for valid values
@return {@code boolean} true on success. | [
"boolean lockShared(final Integer permit, final long timeout, final TimeUnit unit) {\n boolean result = false;\n try {\n result = lockSharedInterruptibly(permit, timeout, unit);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return result;\n }"
] | [
"public Integer getTextureMagFilter(AiTextureType type, int index) {\n checkTexRange(type, index);\n\n Property p = getProperty(PropertyKey.TEX_MAG_FILTER.m_key);\n\n if (null == p || null == p.getData()) {\n return (Integer) m_defaults.get(PropertyKey.TEX_MAG_FILTER);\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.IntBuffer ibuf = ((java.nio.ByteBuffer) rawValue).asIntBuffer();\n return ibuf.get();\n }\n else\n {\n return (Integer) rawValue;\n }\n }",
"public void unregisterComponent(java.awt.Component c)\r\n {\r\n java.awt.dnd.DragGestureRecognizer recognizer = \r\n (java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);\r\n if (recognizer != null)\r\n recognizer.setComponent(null);\r\n }",
"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 }",
"private void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {\n if (!getTrackMetadataListeners().isEmpty()) {\n final TrackMetadataUpdate update = new TrackMetadataUpdate(player, metadata);\n for (final TrackMetadataListener listener : getTrackMetadataListeners()) {\n try {\n listener.metadataChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering track metadata update to listener\", t);\n }\n }\n }\n }",
"@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) {\n View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false);\n /*\n * You don't have to use ButterKnife library to implement the mapping between your layout\n * and your widgets you can implement setUpView and hookListener methods declared in\n * Renderer<T> class.\n */\n ButterKnife.bind(this, inflatedView);\n return inflatedView;\n }",
"private String createMethodSignature(Method method)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(\"(\");\n for (Class<?> type : method.getParameterTypes())\n {\n sb.append(getTypeString(type));\n }\n sb.append(\")\");\n Class<?> type = method.getReturnType();\n if (type.getName().equals(\"void\"))\n {\n sb.append(\"V\");\n }\n else\n {\n sb.append(getTypeString(type));\n }\n return sb.toString();\n }",
"public static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) {\n Node parent = childElement.unwrap().getParentNode();\n if (parent == null || !parentElement.unwrap().isEqualNode(parent)) {\n throw LOG.elementIsNotChildOfThisElement(childElement, parentElement);\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 void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }"
] |
Returns the field descriptors given in the the field names list.
@param fieldNames The field names, separated by commas
@return The field descriptors in the order given by the field names
@throws NoSuchFieldException If a field hasn't been found | [
"public ArrayList getFields(String fieldNames) throws NoSuchFieldException\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new NoSuchFieldException(name);\r\n }\r\n result.add(fieldDef);\r\n }\r\n return result;\r\n }"
] | [
"public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }",
"public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }",
"private 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 }",
"public static PipelineConfiguration.Builder parse(ModelNode json) {\n ModelNode analyzerIncludeNode = json.get(\"analyzers\").get(\"include\");\n ModelNode analyzerExcludeNode = json.get(\"analyzers\").get(\"exclude\");\n ModelNode filterIncludeNode = json.get(\"filters\").get(\"include\");\n ModelNode filterExcludeNode = json.get(\"filters\").get(\"exclude\");\n ModelNode transformIncludeNode = json.get(\"transforms\").get(\"include\");\n ModelNode transformExcludeNode = json.get(\"transforms\").get(\"exclude\");\n ModelNode reporterIncludeNode = json.get(\"reporters\").get(\"include\");\n ModelNode reporterExcludeNode = json.get(\"reporters\").get(\"exclude\");\n\n return builder()\n .withTransformationBlocks(json.get(\"transformBlocks\"))\n .withAnalyzerExtensionIdsInclude(asStringList(analyzerIncludeNode))\n .withAnalyzerExtensionIdsExclude(asStringList(analyzerExcludeNode))\n .withFilterExtensionIdsInclude(asStringList(filterIncludeNode))\n .withFilterExtensionIdsExclude(asStringList(filterExcludeNode))\n .withTransformExtensionIdsInclude(asStringList(transformIncludeNode))\n .withTransformExtensionIdsExclude(asStringList(transformExcludeNode))\n .withReporterExtensionIdsInclude(asStringList(reporterIncludeNode))\n .withReporterExtensionIdsExclude(asStringList(reporterExcludeNode));\n }",
"void logAuditRecord() {\n trackConfigurationChange();\n if (!auditLogged) {\n try {\n AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();\n Caller caller = getCaller();\n auditLogger.log(\n isReadOnly(),\n resultAction,\n caller == null ? null : caller.getName(),\n accessContext == null ? null : accessContext.getDomainUuid(),\n accessContext == null ? null : accessContext.getAccessMechanism(),\n accessContext == null ? null : accessContext.getRemoteAddress(),\n getModel(),\n controllerOperations);\n auditLogged = true;\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);\n }\n }\n }",
"private void setExpressionForPrecalculatedTotalValue(\n\t\t\tDJCrosstabColumn[] auxCols, DJCrosstabRow[] auxRows, JRDesignExpression measureExp, DJCrosstabMeasure djmeasure,\n\t\t\tDJCrosstabColumn crosstabColumn, DJCrosstabRow crosstabRow, String meausrePrefix) {\n\n\t\tString rowValuesExp = \"new Object[]{\";\n\t\tString rowPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxRows.length; i++) {\n\t\t\tif (auxRows[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\trowValuesExp += \"$V{\" + auxRows[i].getProperty().getProperty() +\"}\";\n\t\t\trowPropsExp += \"\\\"\" + auxRows[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxRows.length && auxRows[i+1].getProperty()!= null){\n\t\t\t\trowValuesExp += \", \";\n\t\t\t\trowPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\trowValuesExp += \"}\";\n\t\trowPropsExp += \"}\";\n\n\t\tString colValuesExp = \"new Object[]{\";\n\t\tString colPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxCols.length; i++) {\n\t\t\tif (auxCols[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\tcolValuesExp += \"$V{\" + auxCols[i].getProperty().getProperty() +\"}\";\n\t\t\tcolPropsExp += \"\\\"\" + auxCols[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxCols.length && auxCols[i+1].getProperty()!= null){\n\t\t\t\tcolValuesExp += \", \";\n\t\t\t\tcolPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\tcolValuesExp += \"}\";\n\t\tcolPropsExp += \"}\";\n\n\t\tString measureProperty = meausrePrefix + djmeasure.getProperty().getProperty();\n\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_totalProvider}).getValueFor( \"\n\t\t+ colPropsExp +\", \"\n\t\t+ colValuesExp +\", \"\n\t\t+ rowPropsExp\n\t\t+ \", \"\n\t\t+ rowValuesExp\n\t\t+\" ))\";\n\n\t\tif (djmeasure.getValueFormatter() != null){\n\n\t\t\tString fieldsMap = ExpressionUtils.getTextForFieldsFromScriptlet();\n\t\t\tString parametersMap = ExpressionUtils.getTextForParametersFromScriptlet();\n\t\t\tString variablesMap = ExpressionUtils.getTextForVariablesFromScriptlet();\n\n\t\t\tString stringExpression = \"(((\"+DJValueFormatter.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_vf}).evaluate( \"\n\t\t\t\t+ \"(\"+expText+\"), \" + fieldsMap +\", \" + variablesMap + \", \" + parametersMap +\" ))\";\n\n\t\t\tmeasureExp.setText(stringExpression);\n\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t} else {\n\n//\t\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+djmeasure.getProperty().getProperty()+\"_totalProvider}).getValueFor( \"\n//\t\t\t+ colPropsExp +\", \"\n//\t\t\t+ colValuesExp +\", \"\n//\t\t\t+ rowPropsExp\n//\t\t\t+ \", \"\n//\t\t\t+ rowValuesExp\n//\t\t\t+\" ))\";\n//\n\t\t\tlog.debug(\"text for crosstab total provider is: \" + expText);\n\n\t\t\tmeasureExp.setText(expText);\n//\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t\tString valueClassNameForOperation = ExpressionUtils.getValueClassNameForOperation(djmeasure.getOperation(),djmeasure.getProperty());\n\t\t\tmeasureExp.setValueClassName(valueClassNameForOperation);\n\t\t}\n\n\t}",
"public void useOldRESTService() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using old RESTful CustomerService with old client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old REST\");\n printOldCustomerDetails(customer);\n }",
"private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\n }",
"public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Returns the value of the identified field as a Float.
@param fieldName the name of the field
@return the value of the field as a Float
@throws FqlException if the field cannot be expressed as an Float | [
"public Float getFloat(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}"
] | [
"void execute(ExecutableBuilder builder,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n Future<Void> task = executorService.submit(() -> {\n builder.build().execute();\n return null;\n });\n try {\n if (timeout <= 0) { //Synchronous\n task.get();\n } else { // Guarded execution\n try {\n task.get(timeout, unit);\n } catch (TimeoutException ex) {\n // First make the context unusable\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).timeout();\n }\n // Then cancel the task.\n task.cancel(true);\n throw ex;\n }\n }\n } catch (InterruptedException ex) {\n // Could have been interrupted by user (Ctrl-C)\n Thread.currentThread().interrupt();\n cancelTask(task, builder.getCommandContext(), null);\n // Interrupt running operation.\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).interrupted();\n }\n throw ex;\n }\n }",
"public Date getBaselineStart()\n {\n Object result = getCachedValue(TaskField.BASELINE_START);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_START);\n }\n\n if (!(result instanceof Date))\n {\n result = null;\n }\n return (Date) result;\n }",
"public static String buildDynamicCapabilityName(String baseName, String ... dynamicNameElement) {\n assert baseName != null;\n assert dynamicNameElement != null;\n assert dynamicNameElement.length > 0;\n StringBuilder sb = new StringBuilder(baseName);\n for (String part:dynamicNameElement){\n sb.append(\".\").append(part);\n }\n return sb.toString();\n }",
"public EventBus emitSync(String event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }",
"private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }",
"public static snmpuser get(nitro_service service, String name) throws Exception{\n\t\tsnmpuser obj = new snmpuser();\n\t\tobj.set_name(name);\n\t\tsnmpuser response = (snmpuser) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private String formatUnits(Number value)\n {\n return (value == null ? null : m_formats.getUnitsDecimalFormat().format(value.doubleValue() / 100));\n }",
"public void setPrefix(String prefix) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_PREFIX()))) {\n log(\"Ignoring prefix attribute because it is overridden by user properties.\", Project.MSG_WARN);\n } else {\n SysGlobals.initializeWith(prefix);\n }\n }",
"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 }"
] |
Invoked when an action occurs. | [
"public void actionPerformed(java.awt.event.ActionEvent e)\r\n {\r\n System.out.println(\"Action Command: \" + e.getActionCommand());\r\n System.out.println(\"Action Params : \" + e.paramString());\r\n System.out.println(\"Action Source : \" + e.getSource());\r\n System.out.println(\"Action SrcCls : \" + e.getSource().getClass().getName());\r\n org.apache.ojb.broker.metadata.ClassDescriptor cld =\r\n new org.apache.ojb.broker.metadata.ClassDescriptor(rootNode.getRepository());\r\n // cld.setClassNameOfObject(\"New Class\");\r\n cld.setTableName(\"New Table\");\r\n rootNode.addClassDescriptor(cld);\r\n }"
] | [
"protected byte[] getBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache() || (cached = valueCache.lowerBytes) == null) {\n\t\t\tvalueCache.lowerBytes = cached = getBytesImpl(true);\n\t\t}\n\t\treturn cached;\n\t}",
"public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}",
"public static final Bytes of(byte[] data, int offset, int length) {\n Objects.requireNonNull(data);\n if (length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return new Bytes(copy);\n }",
"public static final Duration parseDuration(String value)\n {\n return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);\n }",
"protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\n }",
"@Override\n public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {\n return delegate.getMatrixHistory(start, limit);\n }",
"public static String pad(String str, int totalChars) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int slen = str.length();\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < totalChars - slen; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n }",
"protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }",
"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 }"
] |
Splits timephased work segments in line with cost rates. Note that this is
an approximation - where a rate changes during a working day, the second
rate is used for the whole day.
@param table cost rate table
@param calendar calendar used by this assignment
@param work timephased work segment
@param rateIndex rate applicable at the start of the timephased work segment
@return list of segments which replace the one supplied by the caller | [
"private List<TimephasedWork> splitWork(CostRateTable table, ProjectCalendar calendar, TimephasedWork work, int rateIndex)\n {\n List<TimephasedWork> result = new LinkedList<TimephasedWork>();\n work.setTotalAmount(Duration.getInstance(0, work.getAmountPerDay().getUnits()));\n\n while (true)\n {\n CostRateTableEntry rate = table.get(rateIndex);\n Date splitDate = rate.getEndDate();\n if (splitDate.getTime() >= work.getFinish().getTime())\n {\n result.add(work);\n break;\n }\n\n Date currentPeriodEnd = calendar.getPreviousWorkFinish(splitDate);\n\n TimephasedWork currentPeriod = new TimephasedWork(work);\n currentPeriod.setFinish(currentPeriodEnd);\n result.add(currentPeriod);\n\n Date nextPeriodStart = calendar.getNextWorkStart(splitDate);\n work.setStart(nextPeriodStart);\n\n ++rateIndex;\n }\n\n return result;\n }"
] | [
"public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }",
"void commitTempFile(File temp) throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n if (!interactionPolicy.isReadOnly()) {\n FilePersistenceUtils.moveTempFileToMain(temp, mainFile);\n } else {\n FilePersistenceUtils.moveTempFileToMain(temp, lastFile);\n }\n }",
"@JsonProperty(\"descriptions\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getDescriptionUpdates() {\n \treturn getMonolingualUpdatedValues(newDescriptions);\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public int segmentHeight(final int segment, final boolean front) {\n final ByteBuffer bytes = getData();\n if (isColor) {\n final int base = segment * 6;\n final int frontHeight = Util.unsign(bytes.get(base + 5));\n if (front) {\n return frontHeight;\n } else {\n return Math.max(frontHeight, Math.max(Util.unsign(bytes.get(base + 3)), Util.unsign(bytes.get(base + 4))));\n }\n } else {\n return getData().get(segment * 2) & 0x1f;\n }\n }",
"private void adjustOptionsColumn(\n CmsMessageBundleEditorTypes.EditMode oldMode,\n CmsMessageBundleEditorTypes.EditMode newMode) {\n\n if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {\n m_table.removeGeneratedColumn(TableProperty.OPTIONS);\n if (m_model.isShowOptionsColumn(newMode)) {\n // Don't know why exactly setting the filter field invisible is necessary here,\n // it should be already set invisible - but apparently not setting it invisible again\n // will result in the field being visible.\n m_table.setFilterFieldVisible(TableProperty.OPTIONS, false);\n m_table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);\n }\n }\n }",
"public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }",
"private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }",
"public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }"
] |
Reads Phoenix resource assignments.
@param mpxjResource MPXJ resource
@param res Phoenix resource | [
"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 LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {\n\t\tMap<Double, RandomVariable> sum = new HashMap<>();\n\n\t\tfor(double time: timeDiscretization) {\n\t\t\tsum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));\n\t\t}\n\n\t\treturn new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);\n\t}",
"static void loadFromOrigin(JobContext origin) {\n if (origin.bag_.isEmpty()) {\n return;\n }\n ActContext<?> actContext = ActContext.Base.currentContext();\n if (null != actContext) {\n Locale locale = (Locale) origin.bag_.get(\"locale\");\n if (null != locale) {\n actContext.locale(locale);\n }\n H.Session session = (H.Session) origin.bag_.get(\"session\");\n if (null != session) {\n actContext.attribute(\"__session\", session);\n }\n }\n }",
"public void viewDocument(DocumentEntry entry)\n {\n InputStream is = null;\n\n try\n {\n is = new DocumentInputStream(entry);\n byte[] data = new byte[is.available()];\n is.read(data);\n m_model.setData(data);\n updateTables();\n }\n\n catch (IOException ex)\n {\n throw new RuntimeException(ex);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n\n }",
"public static ModelNode getParentAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final ModelNode result = new ModelNode();\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n for (int i = 0; i < addressParts.size() - 1; ++i) {\n final Property property = addressParts.get(i);\n result.add(property.getName(), property.getValue());\n }\n return result;\n }",
"public static String findReplacement(final String variableName, final Date date) {\n if (variableName.equalsIgnoreCase(\"date\")) {\n return cleanUpName(DateFormat.getDateInstance().format(date));\n } else if (variableName.equalsIgnoreCase(\"datetime\")) {\n return cleanUpName(DateFormat.getDateTimeInstance().format(date));\n } else if (variableName.equalsIgnoreCase(\"time\")) {\n return cleanUpName(DateFormat.getTimeInstance().format(date));\n } else {\n try {\n return new SimpleDateFormat(variableName).format(date);\n } catch (Exception e) {\n LOGGER.error(\"Unable to format timestamp according to pattern: {}\", variableName, e);\n return \"${\" + variableName + \"}\";\n }\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushNotificationViewedEvent(Bundle extras){\n\n if (extras == null || extras.isEmpty() || extras.get(Constants.NOTIFICATION_TAG) == null) {\n getConfigLogger().debug(getAccountId(), \"Push notification: \" + (extras == null ? \"NULL\" : extras.toString()) + \" not from CleverTap - will not process Notification Viewed event.\");\n return;\n }\n\n if (!extras.containsKey(Constants.NOTIFICATION_ID_TAG) || (extras.getString(Constants.NOTIFICATION_ID_TAG) == null)) {\n getConfigLogger().debug(getAccountId(), \"Push notification ID Tag is null, not processing Notification Viewed event for: \" + extras.toString());\n return;\n }\n\n // Check for dupe notification views; if same notficationdId within specified time interval (2 secs) don't process\n boolean isDuplicate = checkDuplicateNotificationIds(extras, notificationViewedIdTagMap, Constants.NOTIFICATION_VIEWED_ID_TAG_INTERVAL);\n if (isDuplicate) {\n getConfigLogger().debug(getAccountId(), \"Already processed Notification Viewed event for \" + extras.toString() + \", dropping duplicate.\");\n return;\n }\n\n JSONObject event = new JSONObject();\n try {\n JSONObject notif = getWzrkFields(extras);\n event.put(\"evtName\", Constants.NOTIFICATION_VIEWED_EVENT_NAME);\n event.put(\"evtData\", notif);\n } catch (Throwable ignored) {\n //no-op\n }\n queueEvent(context, event, Constants.RAISED_EVENT);\n }",
"public int compareTo(WordTag wordTag) { \r\n int first = (word != null ? word().compareTo(wordTag.word()) : 0);\r\n if(first != 0)\r\n return first;\r\n else {\r\n if (tag() == null) {\r\n if (wordTag.tag() == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return tag().compareTo(wordTag.tag());\r\n }\r\n }",
"public Iterable<BoxItem.Info> getChildren(final String... fields) {\n return new Iterable<BoxItem.Info>() {\n @Override\n public Iterator<BoxItem.Info> iterator() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID());\n return new BoxItemIterator(getAPI(), url);\n }\n };\n }",
"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 }"
] |
create a broker with given broker info
@param id broker id
@param brokerInfoString broker info format: <b>creatorId:host:port:autocreated</b>
@return broker instance with connection config
@see #getZKString() | [
"public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }"
] | [
"@JsonAnySetter\n public void setUnknownField(final String name, final Object value) {\n this.unknownFields.put(name, value);\n }",
"private void deliverLostAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceLost(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device lost announcement to listener\", t);\n }\n }\n });\n }\n }",
"private Object filterValue(Object value)\n {\n if (value instanceof Boolean && !((Boolean) value).booleanValue())\n {\n value = null;\n }\n if (value instanceof String && ((String) value).isEmpty())\n {\n value = null;\n }\n if (value instanceof Double && ((Double) value).doubleValue() == 0.0)\n {\n value = null;\n }\n if (value instanceof Integer && ((Integer) value).intValue() == 0)\n {\n value = null;\n }\n if (value instanceof Duration && ((Duration) value).getDuration() == 0.0)\n {\n value = null;\n }\n\n return value;\n }",
"protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n queue.add(event);\n }",
"public 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> T[] sort(T[] self, Comparator<T> comparator) {\n return sort(self, true, comparator);\n }",
"public static base_responses add(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite addresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbsite();\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].sitetype = resources[i].sitetype;\n\t\t\t\taddresources[i].siteipaddress = resources[i].siteipaddress;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\taddresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\taddresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\taddresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t\taddresources[i].parentsite = resources[i].parentsite;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private String swapStore(String storeName, String directory) throws VoldemortException {\n\n ReadOnlyStorageEngine store = getReadOnlyStorageEngine(metadataStore,\n storeRepository,\n storeName);\n\n if(!Utils.isReadableDir(directory))\n throw new VoldemortException(\"Store directory '\" + directory\n + \"' is not a readable directory.\");\n\n String currentDirPath = store.getCurrentDirPath();\n\n logger.info(\"Swapping RO store '\" + storeName + \"' to version directory '\" + directory\n + \"'\");\n store.swapFiles(directory);\n logger.info(\"Swapping swapped RO store '\" + storeName + \"' to version directory '\"\n + directory + \"'\");\n\n return currentDirPath;\n }",
"@Override\n public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener)\n throws InterruptedException, IOException {\n build.executeAsync(new BuildCallable<Void, IOException>() {\n // record is transient, so needs to make a copy first\n private final Set<MavenDependency> d = dependencies;\n\n public Void call(MavenBuild build) throws IOException, InterruptedException {\n // add the action\n //TODO: [by yl] These actions are persisted into the build.xml of each build run - we need another\n //context to store these actions\n build.getActions().add(new MavenDependenciesRecord(build, d));\n return null;\n }\n });\n return true;\n }"
] |
Bounds are calculated locally, can use any filter, but slower than native.
@param filter
filter which needs to be applied
@return the bounds of the specified features
@throws LayerException
oops | [
"private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}"
] | [
"public Map<Integer, String> listProjects(InputStream is) throws MPXJException\n {\n try\n {\n m_tables = new HashMap<String, List<Row>>();\n processFile(is);\n\n Map<Integer, String> result = new HashMap<Integer, String>();\n\n List<Row> rows = getRows(\"project\", null, null);\n for (Row row : rows)\n {\n Integer id = row.getInteger(\"proj_id\");\n String name = row.getString(\"proj_short_name\");\n result.put(id, name);\n }\n\n return result;\n }\n\n finally\n {\n m_tables = null;\n m_currentTable = null;\n m_currentFieldNames = null;\n }\n }",
"public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException {\n FilePath someWorkspace = project.getSomeWorkspace();\n if (someWorkspace == null) {\n throw new IllegalStateException(\"Couldn't find workspace\");\n }\n\n Map<String, String> workspaceEnv = Maps.newHashMap();\n workspaceEnv.put(\"WORKSPACE\", someWorkspace.getRemote());\n\n for (Builder builder : getBuilders()) {\n if (builder instanceof Gradle) {\n Gradle gradleBuilder = (Gradle) builder;\n String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();\n if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) {\n String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv);\n rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv);\n return new FilePath(someWorkspace, rootBuildScriptNormalized);\n } else {\n return someWorkspace;\n }\n }\n }\n\n throw new IllegalArgumentException(\"Couldn't find Gradle builder in the current builders list\");\n }",
"public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }",
"public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {\n MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();\n\n Object[] values = new Object[parameterInfoArray.length];\n String[] types = new String[parameterInfoArray.length];\n\n MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);\n\n for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {\n MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];\n String type = parameterInfo.getType();\n types[parameterNum] = type;\n values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);\n }\n\n return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);\n }",
"public Diff compare(File f1, File f2) throws Exception {\n\t\treturn this.compare(getCtType(f1), getCtType(f2));\n\t}",
"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 authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public int getShort(Integer id, Integer type)\n {\n int result = 0;\n\n Integer offset = m_meta.getOffset(id, type);\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n\n if (value != null && value.length >= 2)\n {\n result = MPPUtility.getShort(value, 0);\n }\n }\n\n return (result);\n }",
"private void verifiedCopyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileInputStream source = null;\n FileOutputStream destination = null;\n LogVerificationInputStream verifyStream = null;\n try {\n source = new FileInputStream(sourceFile);\n destination = new FileOutputStream(destFile);\n verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName());\n\n final byte[] buf = new byte[LOGVERIFY_BUFSIZE];\n\n while(true) {\n final int len = verifyStream.read(buf);\n if(len < 0) {\n break;\n }\n destination.write(buf, 0, len);\n }\n\n } finally {\n if(verifyStream != null) {\n verifyStream.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }"
] |
Use this API to fetch all the sslcertkey resources that are configured on netscaler. | [
"public static sslcertkey[] get(nitro_service service) throws Exception{\n\t\tsslcertkey obj = new sslcertkey();\n\t\tsslcertkey[] response = (sslcertkey[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n Boolean lastExpandedState = savedLastExpansionState.get(parent);\n boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState;\n\n generateParentWrapper(flatItemList, parent, shouldExpand);\n }\n\n return flatItemList;\n }",
"private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) {\n\t\tif (fieldType.isEscapedDefaultValue()) {\n\t\t\tappendEscapedWord(sb, defaultValue.toString());\n\t\t} else {\n\t\t\tsb.append(defaultValue);\n\t\t}\n\t}",
"private String extractAndConvertTaskType(Task task)\n {\n String activityType = (String) task.getCachedValue(m_activityTypeField);\n if (activityType == null)\n {\n activityType = \"Resource Dependent\";\n }\n else\n {\n if (ACTIVITY_TYPE_MAP.containsKey(activityType))\n {\n activityType = ACTIVITY_TYPE_MAP.get(activityType);\n }\n }\n return activityType;\n }",
"@Override\n public void stop()\n {\n synchronized (killHook)\n {\n jqmlogger.info(\"JQM engine \" + this.node.getName() + \" has received a stop order\");\n\n // Kill hook should be removed\n try\n {\n if (!Runtime.getRuntime().removeShutdownHook(killHook))\n {\n jqmlogger.error(\"The engine could not unregister its shutdown hook\");\n }\n }\n catch (IllegalStateException e)\n {\n // This happens if the stop sequence is initiated by the shutdown hook itself.\n jqmlogger.info(\"Stop order is due to an admin operation (KILL/INT)\");\n }\n }\n\n // Stop pollers\n int pollerCount = pollers.size();\n for (QueuePoller p : pollers.values())\n {\n p.stop();\n }\n\n // Scheduler\n this.scheduler.stop();\n\n // Jetty is closed automatically when all pollers are down\n\n // Wait for the end of the world\n if (pollerCount > 0)\n {\n try\n {\n this.ended.acquire();\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n // Send a KILL signal to remaining job instances, and wait some more.\n if (this.getCurrentlyRunningJobCount() > 0)\n {\n this.runningJobInstanceManager.killAll();\n try\n {\n Thread.sleep(10000);\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n jqmlogger.debug(\"Stop order was correctly handled. Engine for node \" + this.node.getName() + \" has stopped.\");\n }",
"private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}",
"private void nodeProperties(Options opt) {\n\tOptions def = opt.getGlobalOptions();\n\tif (opt.nodeFontName != def.nodeFontName)\n\t w.print(\",fontname=\\\"\" + opt.nodeFontName + \"\\\"\");\n\tif (opt.nodeFontColor != def.nodeFontColor)\n\t w.print(\",fontcolor=\\\"\" + opt.nodeFontColor + \"\\\"\");\n\tif (opt.nodeFontSize != def.nodeFontSize)\n\t w.print(\",fontsize=\" + fmt(opt.nodeFontSize));\n\tw.print(opt.shape.style);\n\tw.println(\"];\");\n }",
"public Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}",
"public static void log(String label, byte[] data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(ByteArrayHelper.hexdump(data, true));\n LOG.flush();\n }\n }",
"public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] |
This method searches in the Component Management Service, so given an
agent name returns its IExternalAccess
@param agent_name
The name of the agent in the platform
@return The IComponentIdentifier of the agent in the platform | [
"public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }"
] | [
"public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {\n\t\treturn getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,\n\t\t\t\tlagMin));\n\t}",
"public void commandLoop() throws IOException {\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliEnterLoop();\n }\n }\n output.output(appName, outputConverter);\n String command = \"\";\n while (true) {\n try {\n command = input.readCommand(path);\n if (command.trim().equals(\"exit\")) {\n if (lineProcessor == null)\n break;\n else {\n path = savedPath;\n lineProcessor = null;\n }\n }\n\n processLine(command);\n } catch (TokenException te) {\n lastException = te;\n output.outputException(command, te);\n } catch (CLIException clie) {\n lastException = clie;\n if (!command.trim().equals(\"exit\")) {\n output.outputException(clie);\n }\n }\n }\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliLeaveLoop();\n }\n }\n }",
"private void readWBS()\n {\n Map<Integer, List<MapRow>> levelMap = new HashMap<Integer, List<MapRow>>();\n for (MapRow row : m_tables.get(\"STR\"))\n {\n Integer level = row.getInteger(\"LEVEL_NUMBER\");\n List<MapRow> items = levelMap.get(level);\n if (items == null)\n {\n items = new ArrayList<MapRow>();\n levelMap.put(level, items);\n }\n items.add(row);\n }\n\n int level = 1;\n while (true)\n {\n List<MapRow> items = levelMap.get(Integer.valueOf(level++));\n if (items == null)\n {\n break;\n }\n\n for (MapRow row : items)\n {\n m_wbsFormat.parseRawValue(row.getString(\"CODE_VALUE\"));\n String parentWbsValue = m_wbsFormat.getFormattedParentValue();\n String wbsValue = m_wbsFormat.getFormattedValue();\n row.setObject(\"WBS\", wbsValue);\n row.setObject(\"PARENT_WBS\", parentWbsValue);\n }\n\n final AlphanumComparator comparator = new AlphanumComparator();\n Collections.sort(items, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n return comparator.compare(o1.getString(\"WBS\"), o2.getString(\"WBS\"));\n }\n });\n\n for (MapRow row : items)\n {\n String wbs = row.getString(\"WBS\");\n if (wbs != null && !wbs.isEmpty())\n {\n ChildTaskContainer parent = m_wbsMap.get(row.getString(\"PARENT_WBS\"));\n if (parent == null)\n {\n parent = m_projectFile;\n }\n\n Task task = parent.addTask();\n String name = row.getString(\"CODE_TITLE\");\n if (name == null || name.isEmpty())\n {\n name = wbs;\n }\n task.setName(name);\n task.setWBS(wbs);\n task.setSummary(true);\n m_wbsMap.put(wbs, task);\n }\n }\n }\n }",
"@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}",
"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 }",
"public static boolean toBoolean(String value, boolean defaultValue)\r\n {\r\n return \"true\".equals(value) ? true : (\"false\".equals(value) ? false : defaultValue);\r\n }",
"protected Query buildPrefetchQuery(Collection ids)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n query.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n\r\n return query;\r\n }",
"public void applyToOr(TextView textView, ColorStateList colorDefault) {\n if (mColorInt != 0) {\n textView.setTextColor(mColorInt);\n } else if (mColorRes != -1) {\n textView.setTextColor(ContextCompat.getColor(textView.getContext(), mColorRes));\n } else if (colorDefault != null) {\n textView.setTextColor(colorDefault);\n }\n }",
"private void calcCurrentItem() {\n int pointerAngle;\n\n // calculate the correct pointer angle, depending on clockwise drawing or not\n if(mOpenClockwise) {\n pointerAngle = (mIndicatorAngle + 360 - mPieRotation) % 360;\n }\n else {\n pointerAngle = (mIndicatorAngle + 180 + mPieRotation) % 360;\n }\n\n for (int i = 0; i < mPieData.size(); ++i) {\n PieModel model = mPieData.get(i);\n if (model.getStartAngle() <= pointerAngle && pointerAngle <= model.getEndAngle()) {\n if (i != mCurrentItem) {\n setCurrentItem(i, false);\n }\n break;\n }\n }\n }"
] |
Add a raw SQL "GROUP BY" clause to the SQL query statement. This should not include the "GROUP BY". | [
"public QueryBuilder<T, ID> groupByRaw(String rawSql) {\n\t\taddGroupBy(ColumnNameOrRawSql.withRawSql(rawSql));\n\t\treturn this;\n\t}"
] | [
"@SuppressWarnings(\"unchecked\")\r\n\tpublic <T> T convertElement(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\treturn (T) elementConverter.convert(context, source, destinationType);\r\n\t}",
"public void update(int width, int height, byte[] grayscaleData)\n {\n NativeBitmapImage.updateFromMemory(getNative(), width, height, grayscaleData);\n }",
"private void checkBindings(EnhancedAnnotation<T> annotatedAnnotation) {\n Set<Annotation> bindings = annotatedAnnotation.getMetaAnnotations(Qualifier.class);\n if (bindings.size() > 0) {\n for (Annotation annotation : bindings) {\n if (!annotation.annotationType().equals(Named.class)) {\n throw MetadataLogger.LOG.qualifierOnStereotype(annotatedAnnotation);\n }\n }\n }\n }",
"public void forAllForeignkeys(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )\r\n {\r\n _curForeignkeyDef = (ForeignkeyDef)it.next();\r\n generate(template);\r\n }\r\n _curForeignkeyDef = null;\r\n }",
"public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }",
"private static void addVersionInfo(byte[] grid, int size, int version) {\n // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/\n long version_data = QR_ANNEX_D[version - 7];\n for (int i = 0; i < 6; i++) {\n grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;\n grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;\n grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;\n grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;\n }\n }",
"protected int mapGanttBarHeight(int height)\n {\n switch (height)\n {\n case 0:\n {\n height = 6;\n break;\n }\n\n case 1:\n {\n height = 8;\n break;\n }\n\n case 2:\n {\n height = 10;\n break;\n }\n\n case 3:\n {\n height = 12;\n break;\n }\n\n case 4:\n {\n height = 14;\n break;\n }\n\n case 5:\n {\n height = 18;\n break;\n }\n\n case 6:\n {\n height = 24;\n break;\n }\n }\n\n return (height);\n }",
"public FieldType getFieldByAlias(FieldTypeClass typeClass, String alias)\n {\n return m_aliasMap.get(new Pair<FieldTypeClass, String>(typeClass, alias));\n }",
"private ResourceAssignment getExistingResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = null;\n Integer resourceUniqueID = null;\n\n if (resource != null)\n {\n Iterator<ResourceAssignment> iter = m_assignments.iterator();\n resourceUniqueID = resource.getUniqueID();\n\n while (iter.hasNext() == true)\n {\n assignment = iter.next();\n Integer uniqueID = assignment.getResourceUniqueID();\n if (uniqueID != null && uniqueID.equals(resourceUniqueID) == true)\n {\n break;\n }\n assignment = null;\n }\n }\n\n return assignment;\n }"
] |
Restores a BoxAPIConnection from a saved state.
@see #save
@param clientID the client ID to use with the connection.
@param clientSecret the client secret to use with the connection.
@param state the saved state that was created with {@link #save}.
@return a restored API connection. | [
"public static BoxAPIConnection restore(String clientID, String clientSecret, String state) {\n BoxAPIConnection api = new BoxAPIConnection(clientID, clientSecret);\n api.restore(state);\n return api;\n }"
] | [
"public base_response enable_features(String[] features) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsfeature resource = new nsfeature();\n\t\tresource.set_feature(features);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }",
"public static Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static void dumpRow(Map<String, Object> row)\n {\n for (Entry<String, Object> entry : row.entrySet())\n {\n Object value = entry.getValue();\n System.out.println(entry.getKey() + \" = \" + value + \" ( \" + (value == null ? \"\" : value.getClass().getName()) + \")\");\n }\n }",
"private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action,\r\n RetentionPolicyParams optionalParams) {\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_name\", name)\r\n .add(\"policy_type\", type)\r\n .add(\"disposition_action\", action);\r\n if (!type.equals(TYPE_INDEFINITE)) {\r\n requestJSON.add(\"retention_length\", length);\r\n }\r\n if (optionalParams != null) {\r\n requestJSON.add(\"can_owner_extend_retention\", optionalParams.getCanOwnerExtendRetention());\r\n requestJSON.add(\"are_owners_notified\", optionalParams.getAreOwnersNotified());\r\n\r\n List<BoxUser.Info> customNotificationRecipients = optionalParams.getCustomNotificationRecipients();\r\n if (customNotificationRecipients.size() > 0) {\r\n JsonArray users = new JsonArray();\r\n for (BoxUser.Info user : customNotificationRecipients) {\r\n JsonObject userJSON = new JsonObject()\r\n .add(\"type\", \"user\")\r\n .add(\"id\", user.getID());\r\n users.add(userJSON);\r\n }\r\n requestJSON.add(\"custom_notification_recipients\", users);\r\n }\r\n }\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicy createdPolicy = new BoxRetentionPolicy(api, responseJSON.get(\"id\").asString());\r\n return createdPolicy.new Info(responseJSON);\r\n }",
"public void addCell(TableLayoutCell cell) {\n GridBagConstraints constraints = cell.getConstraints();\n constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding);\n add(cell.getComponent(), constraints);\n }",
"public static sslfipskey[] get(nitro_service service, String fipskeyname[]) throws Exception{\n\t\tif (fipskeyname !=null && fipskeyname.length>0) {\n\t\t\tsslfipskey response[] = new sslfipskey[fipskeyname.length];\n\t\t\tsslfipskey obj[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++) {\n\t\t\t\tobj[i] = new sslfipskey();\n\t\t\t\tobj[i].set_fipskeyname(fipskeyname[i]);\n\t\t\t\tresponse[i] = (sslfipskey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"void writeBestRankTriples() {\n\t\tfor (Resource resource : this.rankBuffer.getBestRankedStatements()) {\n\t\t\ttry {\n\t\t\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\t\t\tRdfWriter.RDF_TYPE, RdfWriter.WB_BEST_RANK.toString());\n\t\t\t} catch (RDFHandlerException e) {\n\t\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tthis.rankBuffer.clear();\n\t}",
"protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {\r\n MethodNode setter = new MethodNode(\r\n setterName,\r\n propertyNode.getModifiers(),\r\n ClassHelper.VOID_TYPE,\r\n params(param(propertyNode.getType(), \"value\")),\r\n ClassNode.EMPTY_ARRAY,\r\n setterBlock);\r\n setter.setSynthetic(true);\r\n // add it to the class\r\n declaringClass.addMethod(setter);\r\n }"
] |
Export the modules that should be checked in into git. | [
"private void exportModules() {\n\n // avoid to export modules if unnecessary\n if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue())\n || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) {\n m_logStream.println();\n m_logStream.println(\"NOT EXPORTING MODULES - you disabled copy and unzip.\");\n m_logStream.println();\n return;\n }\n CmsModuleManager moduleManager = OpenCms.getModuleManager();\n\n Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty())\n ? m_currentConfiguration.getConfiguredModules()\n : m_modulesToExport;\n\n for (String moduleName : modulesToExport) {\n CmsModule module = moduleManager.getModule(moduleName);\n if (module != null) {\n CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler(\n getCmsObject(),\n module,\n \"Git export handler\");\n try {\n handler.exportData(\n getCmsObject(),\n new CmsPrintStreamReport(\n m_logStream,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()),\n false));\n } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) {\n e.printStackTrace(m_logStream);\n }\n }\n }\n }"
] | [
"public static base_response delete(nitro_service client, application resource) throws Exception {\n\t\tapplication deleteresource = new application();\n\t\tdeleteresource.appname = resource.appname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public ItemRequest<Task> findById(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public Duration getWorkVariance()\n {\n Duration variance = (Duration) getCachedValue(ResourceField.WORK_VARIANCE);\n if (variance == null)\n {\n Duration work = getWork();\n Duration baselineWork = getBaselineWork();\n if (work != null && baselineWork != null)\n {\n variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectProperties()).getDuration(), work.getUnits());\n set(ResourceField.WORK_VARIANCE, variance);\n }\n }\n return (variance);\n }",
"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 }",
"@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 static String readTag(Reader r) throws IOException {\r\n if ( ! r.ready()) {\r\n return null;\r\n }\r\n StringBuilder b = new StringBuilder(\"<\");\r\n int c = r.read();\r\n while (c >= 0) {\r\n b.append((char) c);\r\n if (c == '>') {\r\n break;\r\n }\r\n c = r.read();\r\n }\r\n if (b.length() == 1) {\r\n return null;\r\n }\r\n return b.toString();\r\n }",
"public static String getAt(String text, int index) {\n index = normaliseIndex(index, text.length());\n return text.substring(index, index + 1);\n }",
"@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addAllFields() {\n\t\tList<Field> fields = getAllDeclaredFields(instance.getClass());\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}",
"protected X509Certificate wireUpSslWithCyberVilliansCAOdo(String host, SslListener listener) {\n host = requestOriginalHostName.get();\n\n // Add cybervillians CA(from browsermob)\n try {\n // see https://github.com/webmetrics/browsermob-proxy/issues/105\n String escapedHost = host.replace('*', '_');\n\n KeyStoreManager keyStoreManager = Utils.getKeyStoreManager(escapedHost);\n keyStoreManager.getKeyStore().deleteEntry(KeyStoreManager._caPrivKeyAlias);\n keyStoreManager.persist();\n listener.setKeystore(new File(\"seleniumSslSupport\" + File.separator + escapedHost + File.separator + \"cybervillainsCA.jks\").getAbsolutePath());\n\n return keyStoreManager.getCertificateByAlias(escapedHost);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] |
Returns a flag, indicating if search should be performed using a wildcard if the empty query is given.
@return A flag, indicating if search should be performed using a wildcard if the empty query is given. | [
"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 }"
] | [
"private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }",
"public static Map<FieldType, String> getDefaultWbsFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(TaskField.UNIQUE_ID, \"wbs_id\");\n map.put(TaskField.GUID, \"guid\");\n map.put(TaskField.NAME, \"wbs_name\");\n map.put(TaskField.BASELINE_COST, \"orig_cost\");\n map.put(TaskField.REMAINING_COST, \"indep_remain_total_cost\");\n map.put(TaskField.REMAINING_WORK, \"indep_remain_work_qty\");\n map.put(TaskField.DEADLINE, \"anticip_end_date\");\n map.put(TaskField.DATE1, \"suspend_date\");\n map.put(TaskField.DATE2, \"resume_date\");\n map.put(TaskField.TEXT1, \"task_code\");\n map.put(TaskField.WBS, \"wbs_short_name\");\n\n return map;\n }",
"public boolean isInBounds(int row, int col) {\n return row >= 0 && col >= 0 && row < mat.getNumRows() && col < mat.getNumCols();\n }",
"private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n m_project.getProjectProperties().setFileApplication(\"Synchro\");\n m_project.getProjectProperties().setFileType(\"SP\");\n\n CustomFieldContainer fields = m_project.getCustomFields();\n fields.getCustomField(TaskField.TEXT1).setAlias(\"Code\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n processCalendars();\n processResources();\n processTasks();\n processPredecessors();\n\n return m_project;\n }",
"public static Iterable<BoxRetentionPolicy.Info> getAll(\r\n String name, String type, String userID, int limit, final BoxAPIConnection api, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (name != null) {\r\n queryString.appendParam(\"policy_name\", name);\r\n }\r\n if (type != null) {\r\n queryString.appendParam(\"policy_type\", type);\r\n }\r\n if (userID != null) {\r\n queryString.appendParam(\"created_by_user_id\", userID);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString());\r\n return new BoxResourceIterable<BoxRetentionPolicy.Info>(api, url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get(\"id\").asString());\r\n return policy.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }",
"private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }",
"public PayloadBuilder category(final String category) {\n if (category != null) {\n aps.put(\"category\", category);\n } else {\n aps.remove(\"category\");\n }\n return this;\n }",
"public List<GVRAtlasInformation> getAtlasInformation()\n {\n if ((mImage != null) && (mImage instanceof GVRImageAtlas))\n {\n return ((GVRImageAtlas) mImage).getAtlasInformation();\n }\n return null;\n }",
"public String getFormattedParentValue()\n {\n String result = null;\n if (m_elements.size() > 2)\n {\n result = joinElements(m_elements.size() - 2);\n }\n return result;\n }"
] |
Emit an enum event with parameters and force all listeners to be called asynchronously.
@param event
the target event
@param args
the arguments passed in
@see #emit(Enum, Object...) | [
"public EventBus emitAsync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }"
] | [
"public static Priority getInstance(int priority)\n {\n Priority result;\n\n if (priority >= LOWEST && priority <= DO_NOT_LEVEL && (priority % 100 == 0))\n {\n result = VALUE[(priority / 100) - 1];\n }\n else\n {\n result = new Priority(priority);\n }\n\n return (result);\n }",
"@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)\n throws CmsException {\n\n CmsObject cmsClone;\n if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {\n cmsClone = cms;\n } else {\n cmsClone = OpenCms.initCmsObject(cms);\n cmsClone.getRequestContext().setSiteRoot(module.getSite());\n }\n\n return cmsClone;\n }",
"public static boolean pushImage(Launcher launcher, final JenkinsBuildInfoLog log, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n String message = \"Pushing image: \" + imageTag;\n if (StringUtils.isNotEmpty(host)) {\n message += \" using docker daemon host: \" + host;\n }\n\n log.info(message);\n DockerUtils.pushImage(imageTag, username, password, host);\n return true;\n }\n });\n }",
"public static Object[] filterMapToObjectArray(final Map<String, ?> values, final String[] nameMapping) {\n\t\t\n\t\tif( values == null ) {\n\t\t\tthrow new NullPointerException(\"values should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal Object[] targetArray = new Object[nameMapping.length];\n\t\tint i = 0;\n\t\tfor( final String name : nameMapping ) {\n\t\t\ttargetArray[i++] = values.get(name);\n\t\t}\n\t\treturn targetArray;\n\t}",
"public static String getEncoding(CmsObject cms, CmsResource file) {\n\n CmsProperty encodingProperty = CmsProperty.getNullProperty();\n try {\n encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n return CmsEncoder.lookupEncoding(encodingProperty.getValue(\"\"), OpenCms.getSystemInfo().getDefaultEncoding());\n }",
"protected void copyClasspathResource(File outputDirectory,\n String resourceName,\n String targetFileName) throws IOException\n {\n String resourcePath = classpathPrefix + resourceName;\n InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);\n copyStream(outputDirectory, resourceStream, targetFileName);\n }",
"private void writeCalendarHours(ProjectCalendar parentCalendar, ProjectCalendarHours record) throws IOException\n {\n m_buffer.setLength(0);\n\n int recordNumber;\n\n if (!parentCalendar.isDerived())\n {\n recordNumber = MPXConstants.BASE_CALENDAR_HOURS_RECORD_NUMBER;\n }\n else\n {\n recordNumber = MPXConstants.RESOURCE_CALENDAR_HOURS_RECORD_NUMBER;\n }\n\n DateRange range1 = record.getRange(0);\n if (range1 == null)\n {\n range1 = DateRange.EMPTY_RANGE;\n }\n\n DateRange range2 = record.getRange(1);\n if (range2 == null)\n {\n range2 = DateRange.EMPTY_RANGE;\n }\n\n DateRange range3 = record.getRange(2);\n if (range3 == null)\n {\n range3 = DateRange.EMPTY_RANGE;\n }\n\n m_buffer.append(recordNumber);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getDay()));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range1.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range1.getEnd())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range2.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range2.getEnd())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range3.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range3.getEnd())));\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }"
] |
Add a range to this LOD group. Specify the scene object that should be displayed in this
range. Add the LOG group as a component to the parent scene object. The scene objects
associated with each range will automatically be added as children to the parent.
@param range show the scene object if the camera distance is greater than this value
@param sceneObject scene object that should be rendered when in this range
@throws IllegalArgumentException if range is negative or sceneObject null | [
"public synchronized void addRange(final float range, final GVRSceneObject sceneObject)\n {\n if (null == sceneObject) {\n throw new IllegalArgumentException(\"sceneObject must be specified!\");\n }\n if (range < 0) {\n throw new IllegalArgumentException(\"range cannot be negative\");\n }\n\n final int size = mRanges.size();\n final float rangePow2 = range*range;\n final Object[] newElement = new Object[] {rangePow2, sceneObject};\n\n for (int i = 0; i < size; ++i) {\n final Object[] el = mRanges.get(i);\n final Float r = (Float)el[0];\n if (r > rangePow2) {\n mRanges.add(i, newElement);\n break;\n }\n }\n\n if (mRanges.size() == size) {\n mRanges.add(newElement);\n }\n\n final GVRSceneObject owner = getOwnerObject();\n if (null != owner) {\n owner.addChildObject(sceneObject);\n }\n }"
] | [
"protected void addFacetPart(CmsSolrQuery query) {\n\n query.set(\"facet\", \"true\");\n String excludes = \"\";\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n excludes = \"{!ex=\" + m_config.getIgnoreTags() + \"}\";\n }\n\n for (I_CmsFacetQueryItem q : m_config.getQueryList()) {\n query.add(\"facet.query\", excludes + q.getQuery());\n }\n }",
"public Client findClient(String clientUUID, Integer profileId) throws Exception {\n Client client = null;\n /* ERROR CODE: 500 WHEN TRYING TO DELETE A SERVER GROUP.\n THIS APPEARS TO BE BECAUSE CLIENT UUID IS NULL.\n */\n /* CODE ADDED TO PREVENT NULL POINTERS. */\n if (clientUUID == null) {\n clientUUID = \"\";\n }\n\n // first see if the clientUUID is actually a uuid.. it might be a friendlyName and need conversion\n /* A UUID IS A UNIVERSALLY UNIQUE IDENTIFIER. */\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) != 0 &&\n !clientUUID.matches(\"[\\\\w]{8}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{12}\")) {\n Client tmpClient = this.findClientFromFriendlyName(profileId, clientUUID);\n\n // if we can't find a client then fall back to the default ID\n if (tmpClient == null) {\n clientUUID = Constants.PROFILE_CLIENT_DEFAULT_ID;\n } else {\n return tmpClient;\n }\n }\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = ?\";\n\n if (profileId != null) {\n queryString += \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n if (profileId != null) {\n statement.setInt(2, profileId);\n }\n\n results = statement.executeQuery();\n if (results.next()) {\n client = this.getClientFromResultSet(results);\n }\n } catch (Exception 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 (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return client;\n }",
"public void setDateAttribute(String name, Date value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DateAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\t}",
"public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }",
"public <L extends Listener> void popEvent(Event<?, L> expected) {\n synchronized (this.stack) {\n final Event<?, ?> actual = this.stack.pop();\n if (actual != expected) {\n throw new IllegalStateException(String.format(\n \"Unbalanced pop: expected '%s' but encountered '%s'\",\n expected.getListenerClass(), actual));\n }\n }\n }",
"public static long getVisibilityCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\n \"Cache size must be positive for \" + VISIBILITY_CACHE_WEIGHT);\n }\n return size;\n }",
"public void setLongAttribute(String name, Long value) {\n\t\tensureValue();\n\t\tAttribute attribute = new LongAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"protected boolean isStoreValid() {\n boolean result = false;\n String requestURI = this.request.getUri();\n this.storeName = parseStoreName(requestURI);\n if(storeName != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. Missing store name.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing store name. Critical error.\");\n }\n return result;\n }",
"protected static String jacksonObjectToString(Object object) {\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(object);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tlogger.error(\"Failed to serialize JSON data: \" + e.toString());\n\t\t\treturn null;\n\t\t}\n\t}"
] |
Shutdown the container.
@see Weld#initialize() | [
"public synchronized void shutdown() {\n checkIsRunning();\n try {\n beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);\n } finally {\n discard(id);\n // Destroy all the dependent beans correctly\n creationalContext.release();\n beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);\n bootstrap.shutdown();\n WeldSELogger.LOG.weldContainerShutdown(id);\n }\n }"
] | [
"public static cmppolicylabel_cmppolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_cmppolicy_binding obj = new cmppolicylabel_cmppolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_cmppolicy_binding response[] = (cmppolicylabel_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }",
"public static PersistenceBroker createPersistenceBroker(String jcdAlias,\r\n String user,\r\n String password) throws PBFactoryException\r\n {\r\n return PersistenceBrokerFactoryFactory.instance().\r\n createPersistenceBroker(jcdAlias, user, password);\r\n }",
"private HashMap<String, StoreDefinition> makeStoreDefinitionMap(List<StoreDefinition> storeDefs) {\n HashMap<String, StoreDefinition> storeDefMap = new HashMap<String, StoreDefinition>();\n for(StoreDefinition storeDef: storeDefs)\n storeDefMap.put(storeDef.getName(), storeDef);\n return storeDefMap;\n }",
"private TableModel createTableModel(Object object, Set<String> excludedMethods)\n {\n List<Method> methods = new ArrayList<Method>();\n for (Method method : object.getClass().getMethods())\n {\n if ((method.getParameterTypes().length == 0) || (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == int.class))\n {\n String name = method.getName();\n if (!excludedMethods.contains(name) && (name.startsWith(\"get\") || name.startsWith(\"is\")))\n {\n methods.add(method);\n }\n }\n }\n\n Map<String, String> map = new TreeMap<String, String>();\n for (Method method : methods)\n {\n if (method.getParameterTypes().length == 0)\n {\n getSingleValue(method, object, map);\n }\n else\n {\n getMultipleValues(method, object, map);\n }\n }\n\n String[] headings = new String[]\n {\n \"Property\",\n \"Value\"\n };\n\n String[][] data = new String[map.size()][2];\n int rowIndex = 0;\n for (Entry<String, String> entry : map.entrySet())\n {\n data[rowIndex][0] = entry.getKey();\n data[rowIndex][1] = entry.getValue();\n ++rowIndex;\n }\n\n TableModel tableModel = new DefaultTableModel(data, headings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n return tableModel;\n }",
"static List<NamedArgument> getNamedArgs( ExtensionContext context ) {\n List<NamedArgument> namedArgs = new ArrayList<>();\n\n if( context.getTestMethod().get().getParameterCount() > 0 ) {\n try {\n if( context.getClass().getCanonicalName().equals( METHOD_EXTENSION_CONTEXT ) ) {\n Field field = context.getClass().getSuperclass().getDeclaredField( \"testDescriptor\" );\n Object testDescriptor = ReflectionUtil.getFieldValueOrNull( field, context, ERROR );\n if( testDescriptor != null\n && testDescriptor.getClass().getCanonicalName().equals( TEST_TEMPLATE_INVOCATION_TEST_DESCRIPTOR ) ) {\n Object invocationContext = ReflectionUtil.getFieldValueOrNull( \"invocationContext\", testDescriptor, ERROR );\n if( invocationContext != null\n && invocationContext.getClass().getCanonicalName().equals( PARAMETERIZED_TEST_INVOCATION_CONTEXT ) ) {\n Object arguments = ReflectionUtil.getFieldValueOrNull( \"arguments\", invocationContext, ERROR );\n List<Object> args = Arrays.asList( (Object[]) arguments );\n namedArgs = ParameterNameUtil.mapArgumentsWithParameterNames( context.getTestMethod().get(), args );\n }\n }\n }\n } catch( Exception e ) {\n log.warn( ERROR, e );\n }\n }\n\n return namedArgs;\n }",
"public static base_responses update(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite updateresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbsite();\n\t\t\t\tupdateresources[i].sitename = resources[i].sitename;\n\t\t\t\tupdateresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\tupdateresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\tupdateresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\tupdateresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static void main(String[] args) throws Exception {\n Logger logger = Logger.getLogger(\"MASReader.main\");\n\n Properties beastConfigProperties = new Properties();\n String beastConfigPropertiesFile = null;\n if (args.length > 0) {\n beastConfigPropertiesFile = args[0];\n beastConfigProperties.load(new FileInputStream(\n beastConfigPropertiesFile));\n logger.info(\"Properties file selected -> \"\n + beastConfigPropertiesFile);\n } else {\n logger.severe(\"No properties file found. Set the path of properties file as argument.\");\n throw new BeastException(\n \"No properties file found. Set the path of properties file as argument.\");\n }\n String loggerConfigPropertiesFile;\n if (args.length > 1) {\n Properties loggerConfigProperties = new Properties();\n loggerConfigPropertiesFile = args[1];\n try {\n FileInputStream loggerConfigFile = new FileInputStream(\n loggerConfigPropertiesFile);\n loggerConfigProperties.load(loggerConfigFile);\n LogManager.getLogManager().readConfiguration(loggerConfigFile);\n logger.info(\"Logging properties configured successfully. Logger config file: \"\n + loggerConfigPropertiesFile);\n } catch (IOException ex) {\n logger.warning(\"WARNING: Could not open configuration file\");\n logger.warning(\"WARNING: Logging not configured (console output only)\");\n }\n } else {\n loggerConfigPropertiesFile = null;\n }\n\n MASReader.generateJavaFiles(\n beastConfigProperties.getProperty(\"requirementsFolder\"), \"\\\"\"\n + beastConfigProperties.getProperty(\"MASPlatform\")\n + \"\\\"\",\n beastConfigProperties.getProperty(\"srcTestRootFolder\"),\n beastConfigProperties.getProperty(\"storiesPackage\"),\n beastConfigProperties.getProperty(\"caseManagerPackage\"),\n loggerConfigPropertiesFile,\n beastConfigProperties.getProperty(\"specificationPhase\"));\n\n }"
] |
Parses a type annotation table to find the labels, and to visit the try
catch block annotations.
@param u
the start offset of a type annotation table.
@param mv
the method visitor to be used to visit the try catch block
annotations.
@param context
information about the class being parsed.
@param visible
if the type annotation table to parse contains runtime visible
annotations.
@return the start offset of each type annotation in the parsed table. | [
"private int[] readTypeAnnotations(final MethodVisitor mv,\n final Context context, int u, boolean visible) {\n char[] c = context.buffer;\n int[] offsets = new int[readUnsignedShort(u)];\n u += 2;\n for (int i = 0; i < offsets.length; ++i) {\n offsets[i] = u;\n int target = readInt(u);\n switch (target >>> 24) {\n case 0x00: // CLASS_TYPE_PARAMETER\n case 0x01: // METHOD_TYPE_PARAMETER\n case 0x16: // METHOD_FORMAL_PARAMETER\n u += 2;\n break;\n case 0x13: // FIELD\n case 0x14: // METHOD_RETURN\n case 0x15: // METHOD_RECEIVER\n u += 1;\n break;\n case 0x40: // LOCAL_VARIABLE\n case 0x41: // RESOURCE_VARIABLE\n for (int j = readUnsignedShort(u + 1); j > 0; --j) {\n int start = readUnsignedShort(u + 3);\n int length = readUnsignedShort(u + 5);\n createLabel(start, context.labels);\n createLabel(start + length, context.labels);\n u += 6;\n }\n u += 3;\n break;\n case 0x47: // CAST\n case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT\n case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT\n case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT\n case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT\n u += 4;\n break;\n // case 0x10: // CLASS_EXTENDS\n // case 0x11: // CLASS_TYPE_PARAMETER_BOUND\n // case 0x12: // METHOD_TYPE_PARAMETER_BOUND\n // case 0x17: // THROWS\n // case 0x42: // EXCEPTION_PARAMETER\n // case 0x43: // INSTANCEOF\n // case 0x44: // NEW\n // case 0x45: // CONSTRUCTOR_REFERENCE\n // case 0x46: // METHOD_REFERENCE\n default:\n u += 3;\n break;\n }\n int pathLength = readByte(u);\n if ((target >>> 24) == 0x42) {\n TypePath path = pathLength == 0 ? null : new TypePath(b, u);\n u += 1 + 2 * pathLength;\n u = readAnnotationValues(u + 2, c, true,\n mv.visitTryCatchAnnotation(target, path,\n readUTF8(u, c), visible));\n } else {\n u = readAnnotationValues(u + 3 + 2 * pathLength, c, true, null);\n }\n }\n return offsets;\n }"
] | [
"private static <T> void writeConfig(BufferedWriter writer, DatabaseTableConfig<T> config) throws IOException,\n\t\t\tSQLException {\n\t\twriter.append(CONFIG_FILE_START_MARKER);\n\t\twriter.newLine();\n\t\tif (config.getDataClass() != null) {\n\t\t\twriter.append(FIELD_NAME_DATA_CLASS).append('=').append(config.getDataClass().getName());\n\t\t\twriter.newLine();\n\t\t}\n\t\tif (config.getTableName() != null) {\n\t\t\twriter.append(FIELD_NAME_TABLE_NAME).append('=').append(config.getTableName());\n\t\t\twriter.newLine();\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_START);\n\t\twriter.newLine();\n\t\tif (config.getFieldConfigs() != null) {\n\t\t\tfor (DatabaseFieldConfig field : config.getFieldConfigs()) {\n\t\t\t\tDatabaseFieldConfigLoader.write(writer, field, config.getTableName());\n\t\t\t}\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_END);\n\t\twriter.newLine();\n\t\twriter.append(CONFIG_FILE_END_MARKER);\n\t\twriter.newLine();\n\t}",
"public V get(K key) {\n ManagedReference<V> ref = internalMap.get(key);\n if (ref!=null) return ref.get();\n return null;\n }",
"public static void acceptsUrlMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"coordinator bootstrap urls\")\n .withRequiredArg()\n .describedAs(\"url-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"public static IndexedContainer getGroupsOfUser(\n CmsObject cms,\n CmsUser user,\n String caption,\n String iconProp,\n String ou,\n String propStatus,\n Function<CmsGroup, CmsCssIcon> iconProvider) {\n\n IndexedContainer container = new IndexedContainer();\n container.addContainerProperty(caption, String.class, \"\");\n container.addContainerProperty(ou, String.class, \"\");\n container.addContainerProperty(propStatus, Boolean.class, new Boolean(true));\n if (iconProvider != null) {\n container.addContainerProperty(iconProp, CmsCssIcon.class, null);\n }\n try {\n for (CmsGroup group : cms.getGroupsOfUser(user.getName(), true)) {\n Item item = container.addItem(group);\n item.getItemProperty(caption).setValue(group.getSimpleName());\n item.getItemProperty(ou).setValue(group.getOuFqn());\n if (iconProvider != null) {\n item.getItemProperty(iconProp).setValue(iconProvider.apply(group));\n }\n }\n } catch (CmsException e) {\n LOG.error(\"Unable to read groups from user\", e);\n }\n return container;\n }",
"public <V> V getAttachment(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.get(key));\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }",
"public int getTotalCreatedConnections(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}",
"public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }",
"public Headers toHeaders() {\n Headers headers = new Headers();\n if (!getMatch().isEmpty()) {\n headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch())));\n }\n if (!getNoneMatch().isEmpty()) {\n headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch())));\n }\n if (modifiedSince.isPresent()) {\n headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get()));\n }\n if (unModifiedSince.isPresent()) {\n headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get()));\n }\n\n return headers;\n }"
] |
Retrieve a duration in the form required by Primavera.
@param duration Duration instance
@return formatted duration | [
"private Double getDuration(Duration duration)\n {\n Double result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.HOURS)\n {\n duration = duration.convertUnits(TimeUnit.HOURS, m_projectFile.getProjectProperties());\n }\n\n result = Double.valueOf(duration.getDuration());\n }\n return result;\n }"
] | [
"public double getValueAsPrice(double evaluationTime, AnalyticModel model) {\n\t\tForwardCurve\tforwardCurve\t= model.getForwardCurve(forwardCurveName);\n\t\tDiscountCurve\tdiscountCurve\t= model.getDiscountCurve(discountCurveName);\n\n\t\tDiscountCurve\tdiscountCurveForForward = null;\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\t// User might like to get forward from discount curve.\n\t\t\tdiscountCurveForForward\t= model.getDiscountCurve(forwardCurveName);\n\n\t\t\tif(discountCurveForForward == null) {\n\t\t\t\t// User specified a name for the forward curve, but no curve was found.\n\t\t\t\tthrow new IllegalArgumentException(\"No curve of the name \" + forwardCurveName + \" was found in the model.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble value = 0.0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {\n\t\t\tdouble fixingDate\t= schedule.getFixing(periodIndex);\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\n\t\t\t/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */\n\t\t\tif(periodLength == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble forward = 0.0;\n\t\t\tif(forwardCurve != null) {\n\t\t\t\tforward\t\t\t+= forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);\n\t\t\t}\n\t\t\telse if(discountCurveForForward != null) {\n\t\t\t\t/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */\n\t\t\t\tif(fixingDate != paymentDate) {\n\t\t\t\t\tforward\t\t\t+= (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble discountFactor\t= paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;\n\t\t\tdouble payoffUnit = discountFactor * periodLength;\n\n\t\t\tdouble effektiveStrike = strike;\n\t\t\tif(isStrikeMoneyness) {\n\t\t\t\teffektiveStrike += getATMForward(model, true);\n\t\t\t}\n\n\t\t\tVolatilitySurface volatilitySurface\t= model.getVolatilitySurface(volatiltiySufaceName);\n\t\t\tif(volatilitySurface == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Volatility surface not found in model: \" + volatiltiySufaceName);\n\t\t\t}\n\t\t\tif(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Default to normal volatility as quoting convention\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t}\n\n\t\treturn value / discountCurve.getDiscountFactor(model, evaluationTime);\n\t}",
"public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\n }",
"public static Class<?>[] toClassArray(Collection<Class<?>> collection) {\n\t\tif (collection == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn collection.toArray(new Class<?>[collection.size()]);\n\t}",
"public void setProxy(String proxyHost, int proxyPort) {\n System.setProperty(\"http.proxySet\", \"true\");\n System.setProperty(\"http.proxyHost\", proxyHost);\n System.setProperty(\"http.proxyPort\", \"\" + proxyPort);\n System.setProperty(\"https.proxyHost\", proxyHost);\n System.setProperty(\"https.proxyPort\", \"\" + proxyPort);\n }",
"protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {\n StringBuilder baseURL = new StringBuilder();\n if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {\n baseURL.append(httpServletRequest.getContextPath());\n }\n if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {\n baseURL.append(httpServletRequest.getServletPath());\n }\n return baseURL;\n }",
"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 Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}",
"private boolean isBundleProperty(Object property) {\n\n return (property.equals(TableProperty.KEY) || property.equals(TableProperty.TRANSLATION));\n }",
"public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Returns the list of user defined attribute names.
@return the list of user defined attribute names, if there are none it returns an empty set. | [
"public Set<String> getAttributeNames() {\n if (attributes == null) {\n return Collections.emptySet();\n } else {\n return Collections.unmodifiableSet(attributes.keySet());\n }\n }"
] | [
"public static int read(ReadableByteChannel channel, ByteBuffer buffer) throws IOException {\n int count = channel.read(buffer);\n if (count == -1) throw new EOFException(\"Received -1 when reading from channel, socket has likely been closed.\");\n return count;\n }",
"@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addDeclaredFields() {\n\t\tField[] fields = instance.getClass().getDeclaredFields();\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}",
"public static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"public void insert( Token where , Token token ) {\n if( where == null ) {\n // put at the front of the list\n if( size == 0 )\n push(token);\n else {\n first.previous = token;\n token.previous = null;\n token.next = first;\n first = token;\n size++;\n }\n } else if( where == last || null == last ) {\n push(token);\n } else {\n token.next = where.next;\n token.previous = where;\n where.next.previous = token;\n where.next = token;\n size++;\n }\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 }",
"int read(InputStream is, int contentLength) {\n if (is != null) {\n try {\n int capacity = (contentLength > 0) ? (contentLength + 4096) : 16384;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream(capacity);\n int nRead;\n byte[] data = new byte[16384];\n while ((nRead = is.read(data, 0, data.length)) != -1) {\n buffer.write(data, 0, nRead);\n }\n buffer.flush();\n\n read(buffer.toByteArray());\n } catch (IOException e) {\n Logger.d(TAG, \"Error reading data from stream\", e);\n }\n } else {\n status = STATUS_OPEN_ERROR;\n }\n\n try {\n if (is != null) {\n is.close();\n }\n } catch (IOException e) {\n Logger.d(TAG, \"Error closing stream\", e);\n }\n\n return status;\n }",
"public Class getRealClass(Object objectOrProxy)\r\n {\r\n IndirectionHandler handler;\r\n\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n handler = getIndirectionHandler(objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n handler = VirtualProxy.getIndirectionHandler((VirtualProxy) objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n else\r\n {\r\n return objectOrProxy.getClass();\r\n }\r\n }",
"public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {\r\n Timing timer = new Timing();\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(testFile, readerAndWriter);\r\n int numWords = 0;\r\n int numSentences = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n DFSA<String, Integer> tagLattice = getViterbiSearchGraph(doc, AnswerAnnotation.class);\r\n numWords += doc.size();\r\n PrintWriter latticeWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences\r\n + \".wlattice\"));\r\n PrintWriter vsgWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences + \".lattice\"));\r\n if (readerAndWriter instanceof LatticeWriter)\r\n ((LatticeWriter) readerAndWriter).printLattice(tagLattice, doc, latticeWriter);\r\n tagLattice.printAttFsmFormat(vsgWriter);\r\n latticeWriter.close();\r\n vsgWriter.close();\r\n numSentences++;\r\n }\r\n\r\n long millis = timer.stop();\r\n double wordspersec = numWords / (((double) millis) / 1000);\r\n NumberFormat nf = new DecimalFormat(\"0.00\"); // easier way!\r\n System.err.println(this.getClass().getName() + \" tagged \" + numWords + \" words in \" + numSentences\r\n + \" documents at \" + nf.format(wordspersec) + \" words per second.\");\r\n }"
] |
Use this API to fetch all the snmpuser resources that are configured on netscaler. | [
"public static snmpuser[] get(nitro_service service, options option) throws Exception{\n\t\tsnmpuser obj = new snmpuser();\n\t\tsnmpuser[] response = (snmpuser[])obj.get_resources(service,option);\n\t\treturn response;\n\t}"
] | [
"private void writeTasks() throws IOException\n {\n writeAttributeTypes(\"task_types\", TaskField.values());\n\n m_writer.writeStartList(\"tasks\");\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task);\n }\n m_writer.writeEndList();\n }",
"private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) {\n return buildFilesStream\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath()))\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath()))\n .map(org.jfrog.hudson.pipeline.types.File::new)\n .distinct()\n .collect(Collectors.toList());\n }",
"public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void allRelation(Options opt, RelationType rt, ClassDoc from) {\n\tString tagname = rt.lower;\n\tfor (Tag tag : from.tags(tagname)) {\n\t String t[] = tokenize(tag.text()); // l-src label l-dst target\n\t t = t.length == 1 ? new String[] { \"-\", \"-\", \"-\", t[0] } : t; // Shorthand\n\t if (t.length != 4) {\n\t\tSystem.err.println(\"Error in \" + from + \"\\n\" + tagname + \" expects four fields (l-src label l-dst target): \" + tag.text());\n\t\treturn;\n\t }\n\t ClassDoc to = from.findClass(t[3]);\n\t if (to != null) {\n\t\tif(hidden(to))\n\t\t continue;\n\t\trelation(opt, rt, from, to, t[0], t[1], t[2]);\n\t } else {\n\t\tif(hidden(t[3]))\n\t\t continue;\n\t\trelation(opt, rt, from, from.toString(), to, t[3], t[0], t[1], t[2]);\n\t }\n\t}\n }",
"public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }",
"public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) {\n\t\tList<MwDumpFile> dumps = findAllDumps(dumpContentType);\n\n\t\tfor (MwDumpFile dump : dumps) {\n\t\t\tif (dump.isAvailable()) {\n\t\t\t\treturn dump;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"private static boolean mayBeIPv6Address(String input) {\n if (input == null) {\n return false;\n }\n\n boolean result = false;\n int colonsCounter = 0;\n int length = input.length();\n for (int i = 0; i < length; i++) {\n char c = input.charAt(i);\n if (c == '.' || c == '%') {\n // IPv4 in IPv6 or Zone ID detected, end of checking.\n break;\n }\n if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')\n || (c >= 'A' && c <= 'F') || c == ':')) {\n return false;\n } else if (c == ':') {\n colonsCounter++;\n }\n }\n if (colonsCounter >= 2) {\n result = true;\n }\n return result;\n }",
"public static TaskField getMpxjField(int value)\n {\n TaskField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }",
"private void readRelationships(Project gpProject)\n {\n for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask())\n {\n readRelationships(gpTask);\n }\n }"
] |
any possible bean invocations from other ADV observers | [
"public void afterDeploymentValidation(@Observes @Priority(1) AfterDeploymentValidation event, BeanManager beanManager) {\n BeanManagerImpl manager = BeanManagerProxy.unwrap(beanManager);\n probe.init(manager);\n if (isJMXSupportEnabled(manager)) {\n try {\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n mbs.registerMBean(new ProbeDynamicMBean(jsonDataProvider, JsonDataProvider.class), constructProbeJsonDataMBeanName(manager, probe));\n } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {\n event.addDeploymentProblem(ProbeLogger.LOG.unableToRegisterMBean(JsonDataProvider.class, manager.getContextId(), e));\n }\n }\n addContainerLifecycleEvent(event, null, beanManager);\n exportDataIfNeeded(manager);\n }"
] | [
"private List<TimephasedCost> getTimephasedCostMultipleRates(List<TimephasedWork> standardWorkList, List<TimephasedWork> overtimeWorkList)\n {\n List<TimephasedWork> standardWorkResult = new LinkedList<TimephasedWork>();\n List<TimephasedWork> overtimeWorkResult = new LinkedList<TimephasedWork>();\n CostRateTable table = getCostRateTable();\n ProjectCalendar calendar = getCalendar();\n\n Iterator<TimephasedWork> iter = overtimeWorkList.iterator();\n for (TimephasedWork standardWork : standardWorkList)\n {\n TimephasedWork overtimeWork = iter.hasNext() ? iter.next() : null;\n\n int startIndex = getCostRateTableEntryIndex(standardWork.getStart());\n int finishIndex = getCostRateTableEntryIndex(standardWork.getFinish());\n\n if (startIndex == finishIndex)\n {\n standardWorkResult.add(standardWork);\n if (overtimeWork != null)\n {\n overtimeWorkResult.add(overtimeWork);\n }\n }\n else\n {\n standardWorkResult.addAll(splitWork(table, calendar, standardWork, startIndex));\n if (overtimeWork != null)\n {\n overtimeWorkResult.addAll(splitWork(table, calendar, overtimeWork, startIndex));\n }\n }\n }\n\n return getTimephasedCostSingleRate(standardWorkResult, overtimeWorkResult);\n }",
"public static vlan_interface_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_interface_binding obj = new vlan_interface_binding();\n\t\tobj.set_id(id);\n\t\tvlan_interface_binding response[] = (vlan_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }",
"@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }",
"private Object readKey(\n FieldDescriptor field,\n JsonParser parser,\n DeserializationContext context\n ) throws IOException {\n if (parser.getCurrentToken() != JsonToken.FIELD_NAME) {\n throw reportWrongToken(JsonToken.FIELD_NAME, context, \"Expected FIELD_NAME token\");\n }\n\n String fieldName = parser.getCurrentName();\n switch (field.getJavaType()) {\n case INT:\n // lifted from StdDeserializer since there's no method to call\n try {\n return NumberInput.parseInt(fieldName.trim());\n } catch (IllegalArgumentException iae) {\n Number number = (Number) context.handleWeirdStringValue(\n _valueClass,\n fieldName.trim(),\n \"not a valid int value\"\n );\n return number == null ? 0 : number.intValue();\n }\n case LONG:\n // lifted from StdDeserializer since there's no method to call\n try {\n return NumberInput.parseLong(fieldName.trim());\n } catch (IllegalArgumentException iae) {\n Number number = (Number) context.handleWeirdStringValue(\n _valueClass,\n fieldName.trim(),\n \"not a valid long value\"\n );\n return number == null ? 0L : number.longValue();\n }\n case BOOLEAN:\n // lifted from StdDeserializer since there's no method to call\n String text = fieldName.trim();\n if (\"true\".equals(text) || \"True\".equals(text)) {\n return true;\n }\n if (\"false\".equals(text) || \"False\".equals(text)) {\n return false;\n }\n Boolean b = (Boolean) context.handleWeirdStringValue(\n _valueClass,\n text,\n \"only \\\"true\\\" or \\\"false\\\" recognized\"\n );\n return Boolean.TRUE.equals(b);\n case STRING:\n return fieldName;\n case ENUM:\n EnumValueDescriptor enumValueDescriptor = field.getEnumType().findValueByName(parser.getText());\n\n if (enumValueDescriptor == null && !ignorableEnum(parser.getText().trim(), context)) {\n throw context.weirdStringException(parser.getText(), field.getEnumType().getClass(),\n \"value not one of declared Enum instance names\");\n }\n\n return enumValueDescriptor;\n default:\n throw new IllegalArgumentException(\"Unexpected map key type: \" + field.getJavaType());\n }\n }",
"public static DMatrixRMaj identity(int numRows , int numCols )\n {\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int small = numRows < numCols ? numRows : numCols;\n\n for( int i = 0; i < small; i++ ) {\n ret.set(i,i,1.0);\n }\n\n return ret;\n }",
"public static SPIProviderResolver getInstance(ClassLoader cl)\n {\n SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl);\n return resolver;\n }",
"static Type parseType(String value, ResourceLoader resourceLoader) {\n value = value.trim();\n // Wildcards\n if (value.equals(WILDCARD)) {\n return WildcardTypeImpl.defaultInstance();\n }\n if (value.startsWith(WILDCARD_EXTENDS)) {\n Type upperBound = parseType(value.substring(WILDCARD_EXTENDS.length(), value.length()), resourceLoader);\n if (upperBound == null) {\n return null;\n }\n return WildcardTypeImpl.withUpperBound(upperBound);\n }\n if (value.startsWith(WILDCARD_SUPER)) {\n Type lowerBound = parseType(value.substring(WILDCARD_SUPER.length(), value.length()), resourceLoader);\n if (lowerBound == null) {\n return null;\n }\n return WildcardTypeImpl.withLowerBound(lowerBound);\n }\n // Array\n if (value.contains(ARRAY)) {\n Type componentType = parseType(value.substring(0, value.indexOf(ARRAY)), resourceLoader);\n if (componentType == null) {\n return null;\n }\n return new GenericArrayTypeImpl(componentType);\n }\n int chevLeft = value.indexOf(CHEVRONS_LEFT);\n String rawValue = chevLeft < 0 ? value : value.substring(0, chevLeft);\n Class<?> rawRequiredType = tryLoadClass(rawValue, resourceLoader);\n if (rawRequiredType == null) {\n return null;\n }\n if (rawRequiredType.getTypeParameters().length == 0) {\n return rawRequiredType;\n }\n // Parameterized type\n int chevRight = value.lastIndexOf(CHEVRONS_RIGHT);\n if (chevRight < 0) {\n return null;\n }\n List<String> parts = split(value.substring(chevLeft + 1, chevRight), ',', CHEVRONS_LEFT.charAt(0), CHEVRONS_RIGHT.charAt(0));\n Type[] typeParameters = new Type[parts.size()];\n for (int i = 0; i < typeParameters.length; i++) {\n Type typeParam = parseType(parts.get(i), resourceLoader);\n if (typeParam == null) {\n return null;\n }\n typeParameters[i] = typeParam;\n }\n return new ParameterizedTypeImpl(rawRequiredType, typeParameters);\n }"
] |
Produces a string in which the lower 4 bytes are expressed as an IPv4 address and the remaining upper bytes are expressed in IPv6 format.
This the mixed IPv6/IPv4 format described in RFC 1884 https://tools.ietf.org/html/rfc1884
@return | [
"public String toMixedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.mixedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.mixedString = result = toNormalizedString(IPv6StringCache.mixedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toMixedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public boolean isConnectionHandleAlive(ConnectionHandle connection) {\r\n\t\tStatement stmt = null;\r\n\t\tboolean result = false;\r\n\t\tboolean logicallyClosed = connection.logicallyClosed.get();\r\n\t\ttry {\r\n\t\t\tconnection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed.\r\n\t\t\tString testStatement = this.config.getConnectionTestStatement();\r\n\t\t\tResultSet rs = null;\r\n\r\n\t\t\tif (testStatement == null) {\r\n\t\t\t\t// Make a call to fetch the metadata instead of a dummy query.\r\n\t\t\t\trs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE );\r\n\t\t\t} else {\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(testStatement);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (rs != null) {\r\n\t\t\t\trs.close();\r\n\t\t\t}\r\n\r\n\t\t\tresult = true;\r\n\t\t} catch (SQLException e) {\r\n\t\t\t// connection must be broken!\r\n\t\t\tresult = false;\r\n\t\t} finally {\r\n\t\t\tconnection.logicallyClosed.set(logicallyClosed);\r\n\t\t\tconnection.setConnectionLastResetInMs(System.currentTimeMillis());\r\n\t\t\tresult = closeStatement(stmt, result);\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n long result;\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Throwable e)\r\n {\r\n // maybe the sequence was not created\r\n try\r\n {\r\n log.info(\"Create DB sequence key '\"+sequenceName+\"'\");\r\n createSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\r\n SystemUtils.LINE_SEPARATOR +\r\n \"Could not grab next id, failed with \" + SystemUtils.LINE_SEPARATOR +\r\n e.getMessage() + SystemUtils.LINE_SEPARATOR +\r\n \"Creation of new sequence failed with \" +\r\n SystemUtils.LINE_SEPARATOR + e1.getMessage() + SystemUtils.LINE_SEPARATOR\r\n , e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Throwable e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id, sequence seems to exist\", e);\r\n }\r\n }\r\n return result;\r\n }",
"public void addEmailStats(final InternetAddress[] recipients, final boolean storageUsed) {\n this.storageUsed = storageUsed;\n for (InternetAddress recipient: recipients) {\n emailDests.add(recipient.getAddress());\n }\n }",
"public static appfwprofile_csrftag_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_csrftag_binding obj = new appfwprofile_csrftag_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_csrftag_binding response[] = (appfwprofile_csrftag_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void processBlock(List<GenericCriteria> list, byte[] block)\n {\n if (block != null)\n {\n if (MPPUtility.getShort(block, 0) > 0x3E6)\n {\n addCriteria(list, block);\n }\n else\n {\n switch (block[0])\n {\n case (byte) 0x0B:\n {\n processBlock(list, getChildBlock(block));\n break;\n }\n\n case (byte) 0x06:\n {\n processBlock(list, getListNextBlock(block));\n break;\n }\n\n case (byte) 0xED: // EQUALS\n {\n addCriteria(list, block);\n break;\n }\n\n case (byte) 0x19: // AND\n case (byte) 0x1B:\n {\n addBlock(list, block, TestOperator.AND);\n break;\n }\n\n case (byte) 0x1A: // OR\n case (byte) 0x1C:\n {\n addBlock(list, block, TestOperator.OR);\n break;\n }\n }\n }\n }\n }",
"public void close() {\n Iterator<SocketDestination> it = getStatsMap().keySet().iterator();\n while(it.hasNext()) {\n try {\n SocketDestination destination = it.next();\n JmxUtils.unregisterMbean(JmxUtils.createObjectName(JmxUtils.getPackageName(ClientRequestExecutor.class),\n \"stats_\"\n + destination.toString()\n .replace(':',\n '_')\n + identifierString));\n } catch(Exception e) {}\n }\n }",
"private void recordRollbackLoader(final String patchId, PatchableTarget.TargetInfo target) {\n // setup the content loader paths\n final DirectoryStructure structure = target.getDirectoryStructure();\n final InstalledImage image = structure.getInstalledImage();\n final File historyDir = image.getPatchHistoryDir(patchId);\n final File miscRoot = new File(historyDir, PatchContentLoader.MISC);\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(miscRoot, bundlesRoot, modulesRoot);\n //\n recordContentLoader(patchId, loader);\n }",
"public ApiClient setHttpClient(OkHttpClient newHttpClient) {\n if (!httpClient.equals(newHttpClient)) {\n newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());\n httpClient.networkInterceptors().clear();\n newHttpClient.interceptors().addAll(httpClient.interceptors());\n httpClient.interceptors().clear();\n this.httpClient = newHttpClient;\n }\n return this;\n }",
"public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }"
] |
Internal method that finds the matching enum for a configured field that has the name argument.
@return The matching enum value or null if blank enum name.
@throws IllegalArgumentException
If the enum name is not known. | [
"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}"
] | [
"List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files) throws IOException {\n HashFunction hashFun = Hashing.md5();\n File dir = new File(new File(project.getFile().getParent(), \"target\"), outputDirectory);\n if (dir.exists()) {\n URI baseDir = getFileURI(dir);\n for (File f : findThriftFilesInDirectory(dir)) {\n URI fileURI = getFileURI(f);\n String relPath = baseDir.relativize(fileURI).getPath();\n File destFolder = getResourcesOutputDirectory();\n destFolder.mkdirs();\n File destFile = new File(destFolder, relPath);\n if (!destFile.exists() || (destFile.isFile() && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {\n getLog().info(format(\"copying %s to %s\", f.getCanonicalPath(), destFile.getCanonicalPath()));\n copyFile(f, destFile);\n }\n files.add(destFile);\n }\n }\n Map<String, MavenProject> refs = project.getProjectReferences();\n for (String name : refs.keySet()) {\n getRecursiveThriftFiles(refs.get(name), outputDirectory, files);\n }\n return files;\n }",
"public static Color cueColor(CueList.Entry entry) {\n if (entry.hotCueNumber > 0) {\n return Color.GREEN;\n }\n if (entry.isLoop) {\n return Color.ORANGE;\n }\n return Color.RED;\n }",
"public void setTimeWarp(String l) {\n\n long warp = CmsContextInfo.CURRENT_TIME;\n try {\n warp = Long.parseLong(l);\n } catch (NumberFormatException e) {\n // if parsing the time warp fails, it will be set to -1 (i.e. disabled)\n }\n m_settings.setTimeWarp(warp);\n }",
"public void cleanup() {\n synchronized (_sslMap) {\n for (SslRelayOdo relay : _sslMap.values()) {\n if (relay.getHttpServer() != null && relay.isStarted()) {\n relay.getHttpServer().removeListener(relay);\n }\n }\n\n sslRelays.clear();\n }\n }",
"public Criteria copy(boolean includeGroupBy, boolean includeOrderBy, boolean includePrefetchedRelationships)\r\n {\r\n Criteria copy = new Criteria();\r\n\r\n copy.m_criteria = new Vector(this.m_criteria);\r\n copy.m_negative = this.m_negative;\r\n\r\n if (includeGroupBy)\r\n {\r\n copy.groupby = this.groupby;\r\n }\r\n if (includeOrderBy)\r\n {\r\n copy.orderby = this.orderby;\r\n }\r\n if (includePrefetchedRelationships)\r\n {\r\n copy.prefetchedRelationships = this.prefetchedRelationships;\r\n }\r\n\r\n return copy;\r\n }",
"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 }",
"@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }",
"@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"public void setWriteTimeout(int writeTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}"
] |
this method mimics EMC behavior | [
"public Object getProperty(String property) {\n if(ExpandoMetaClass.isValidExpandoProperty(property)) {\n if(property.equals(ExpandoMetaClass.STATIC_QUALIFIER) ||\n property.equals(ExpandoMetaClass.CONSTRUCTOR) ||\n myMetaClass.hasProperty(this, property) == null) {\n return replaceDelegate().getProperty(property);\n }\n }\n return myMetaClass.getProperty(this, property);\n }"
] | [
"@Override\n public GroupDiscussInterface getDiscussionInterface() {\n if (discussionInterface == null) {\n discussionInterface = new GroupDiscussInterface(apiKey, sharedSecret, transport);\n }\n return discussionInterface;\n }",
"public PhotoList<Photo> getRecent(Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_RECENT);\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }",
"public void updateLockingValues(Object obj) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n if (fmd.isUpdateLock())\r\n {\r\n PersistentField f = fmd.getPersistentField();\r\n Object cv = f.get(obj);\r\n // int\r\n if ((f.getType() == int.class) || (f.getType() == Integer.class))\r\n {\r\n int newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).intValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Integer(newCv));\r\n }\r\n // long\r\n else if ((f.getType() == long.class) || (f.getType() == Long.class))\r\n {\r\n long newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).longValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Long(newCv));\r\n }\r\n // Timestamp\r\n else if (f.getType() == Timestamp.class)\r\n {\r\n long newCv = System.currentTimeMillis();\r\n f.set(obj, new Timestamp(newCv));\r\n }\r\n }\r\n }\r\n }",
"protected Class getPrototypeClass(T content) {\n if (prototypes.size() == 1) {\n return prototypes.get(0).getClass();\n } else {\n return binding.get(content.getClass());\n }\n }",
"static File getTargetFile(final File root, final MiscContentItem item) {\n return PatchContentLoader.getMiscPath(root, item);\n }",
"private void checkAndAddLengths(final int... requiredLengths) {\n\t\tfor( final int length : requiredLengths ) {\n\t\t\tif( length < 0 ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\"required length cannot be negative but was %d\",\n\t\t\t\t\tlength));\n\t\t\t}\n\t\t\tthis.requiredLengths.add(length);\n\t\t}\n\t}",
"public void addModuleDir(final String moduleDir) {\n if (moduleDir == null) {\n throw LauncherMessages.MESSAGES.nullParam(\"moduleDir\");\n }\n // Validate the path\n final Path path = Paths.get(moduleDir).normalize();\n modulesDirs.add(path.toString());\n }",
"private void verifyXopResponse(XopBean xopOriginal, XopBean xopResponse) {\n if (!Arrays.equals(xopResponse.getBytes(), xopOriginal.getBytes())) {\n throw new RuntimeException(\"Received XOP attachment is corrupted\");\n }\n System.out.println();\n System.out.println(\"XOP attachment has been successfully received\");\n }",
"public void setBaseCalendar(String val)\n {\n set(ResourceField.BASE_CALENDAR, val == null || val.length() == 0 ? \"Standard\" : val);\n }"
] |
Processes the template for all extents of the current class.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void forAllExtents(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getExtentClasses(); it.hasNext(); )\r\n {\r\n _curExtent = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curExtent = null;\r\n }"
] | [
"public <T extends Widget & Checkable> void clearChecks() {\n List<T> children = getCheckableChildren();\n for (T c : children) {\n c.setChecked(false);\n }\n }",
"public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"file\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n requestJSON.add(\"action\", action.toJSONString());\n\n if (message != null && !message.isEmpty()) {\n requestJSON.add(\"message\", message);\n }\n\n if (dueAt != null) {\n requestJSON.add(\"due_at\", BoxDateFormat.format(dueAt));\n }\n\n URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedTask.new Info(responseJSON);\n }",
"public static boolean distributeAndCheckResponse(DistributionBuilder distributionBuilder, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber, boolean dryRun) throws IOException {\n // do a dry run first\n listener.getLogger().println(\"Performing dry run distribution (no changes are made during dry run) ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, true)) {\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully\");\n if (!dryRun) {\n listener.getLogger().println(\"Performing distribution ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, false)) {\n return false;\n }\n listener.getLogger().println(\"Distribution completed successfully!\");\n }\n return true;\n }",
"@PostConstruct\n public void init() {\n //init Bus and LifeCycle listeners\n if (bus != null && sendLifecycleEvent ) {\n ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class);\n if (null != slcm) {\n ServiceListenerImpl svrListener = new ServiceListenerImpl();\n svrListener.setSendLifecycleEvent(sendLifecycleEvent);\n svrListener.setQueue(queue);\n svrListener.setMonitoringServiceClient(monitoringServiceClient);\n slcm.registerListener(svrListener);\n }\n\n ClientLifeCycleManager clcm = bus.getExtension(ClientLifeCycleManager.class);\n if (null != clcm) {\n ClientListenerImpl cltListener = new ClientListenerImpl();\n cltListener.setSendLifecycleEvent(sendLifecycleEvent);\n cltListener.setQueue(queue);\n cltListener.setMonitoringServiceClient(monitoringServiceClient);\n clcm.registerListener(cltListener);\n }\n }\n\n if(executorQueueSize == 0) {\r\n \texecutor = Executors.newFixedThreadPool(this.executorPoolSize);\n }else{\r\n executor = new ThreadPoolExecutor(executorPoolSize, executorPoolSize, 0, TimeUnit.SECONDS, \r\n \t\tnew LinkedBlockingQueue<Runnable>(executorQueueSize), Executors.defaultThreadFactory(), \r\n \t\t\tnew RejectedExecutionHandlerImpl());\r\n }\r\n\n scheduler = new Timer();\n scheduler.scheduleAtFixedRate(new TimerTask() {\n public void run() {\n sendEventsFromQueue();\n }\n }, 0, getDefaultInterval());\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 @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final BsonValue documentId\n ) {\n final ChangeEvent<BsonDocument> event;\n nsLock.readLock().lock();\n try {\n event = this.events.get(documentId);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.remove(documentId);\n return event;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"public static int validateZone(CharSequence zone) {\n\t\tfor(int i = 0; i < zone.length(); i++) {\n\t\t\tchar c = zone.charAt(i);\n\t\t\tif (c == IPAddress.PREFIX_LEN_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tif (c == IPv6Address.SEGMENT_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}",
"protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }",
"public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Reads the next chunk for the intermediate work buffer. | [
"private void readChunkIfNeeded() {\n if (workBufferSize > workBufferPosition) {\n return;\n }\n if (workBuffer == null) {\n workBuffer = bitmapProvider.obtainByteArray(WORK_BUFFER_SIZE);\n }\n workBufferPosition = 0;\n workBufferSize = Math.min(rawData.remaining(), WORK_BUFFER_SIZE);\n rawData.get(workBuffer, 0, workBufferSize);\n }"
] | [
"private static void listTimephasedWork(ResourceAssignment assignment)\n {\n Task task = assignment.getTask();\n int days = (int) ((task.getFinish().getTime() - task.getStart().getTime()) / (1000 * 60 * 60 * 24)) + 1;\n if (days > 1)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yy\");\n\n TimescaleUtility timescale = new TimescaleUtility();\n ArrayList<DateRange> dates = timescale.createTimescale(task.getStart(), TimescaleUnits.DAYS, days);\n TimephasedUtility timephased = new TimephasedUtility();\n\n ArrayList<Duration> durations = timephased.segmentWork(assignment.getCalendar(), assignment.getTimephasedWork(), TimescaleUnits.DAYS, dates);\n for (DateRange range : dates)\n {\n System.out.print(df.format(range.getStart()) + \"\\t\");\n }\n System.out.println();\n for (Duration duration : durations)\n {\n System.out.print(duration.toString() + \" \".substring(0, 7) + \"\\t\");\n }\n System.out.println();\n }\n }",
"public int addCollidable(GVRSceneObject sceneObj)\n {\n synchronized (mCollidables)\n {\n int index = mCollidables.indexOf(sceneObj);\n if (index >= 0)\n {\n return index;\n }\n mCollidables.add(sceneObj);\n return mCollidables.size() - 1;\n }\n }",
"private ArrayList handleDependentReferences(Identity oid, Object userObject,\r\n Object[] origFields, Object[] newFields, Object[] newRefs)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(userObject.getClass());\r\n FieldDescriptor[] fieldDescs = mif.getFieldDescriptions();\r\n Collection refDescs = mif.getObjectReferenceDescriptors();\r\n int count = 1 + fieldDescs.length;\r\n ArrayList newObjects = new ArrayList();\r\n int countRefs = 0;\r\n\r\n for (Iterator it = refDescs.iterator(); it.hasNext(); count++, countRefs++)\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) it.next();\r\n Identity origOid = (origFields == null ? null : (Identity) origFields[count]);\r\n Identity newOid = (Identity) newFields[count];\r\n\r\n if (rds.getOtmDependent())\r\n {\r\n if ((origOid == null) && (newOid != null))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n Object relObj = newRefs[countRefs];\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, oid, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n else if ((origOid != null) &&\r\n ((newOid == null) || !newOid.equals(origOid)))\r\n {\r\n markDelete(origOid, oid, false);\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }",
"@Override public int getItemViewType(int position) {\n T content = getItem(position);\n return rendererBuilder.getItemViewType(content);\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 String getWrappingHint(String fieldName) {\n if (isEmpty()) {\n return \"\";\n }\n\n return String.format(\" You can use this expression: %s(%s(%s))\",\n formatMethod(wrappingMethodOwnerName, wrappingMethodName, \"\"),\n formatMethod(copyMethodOwnerName, copyMethodName, copyTypeParameterName),\n fieldName);\n }",
"public void remove(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n m_container.removeComponent(row);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }",
"public void setVertexBuffer(GVRVertexBuffer vbuf)\n {\n if (vbuf == null)\n {\n throw new IllegalArgumentException(\"Vertex buffer cannot be null\");\n }\n mVertices = vbuf;\n NativeMesh.setVertexBuffer(getNative(), vbuf.getNative());\n }",
"public CurrencyQueryBuilder setNumericCodes(int... codes) {\n return set(CurrencyQuery.KEY_QUERY_NUMERIC_CODES,\n Arrays.stream(codes).boxed().collect(Collectors.toList()));\n }"
] |
Gets the matching beans for binding criteria from a list of beans
@param resolvable the resolvable
@return A set of filtered beans | [
"private Set<T> findMatching(R resolvable) {\n Set<T> result = new HashSet<T>();\n for (T bean : getAllBeans(resolvable)) {\n if (matches(resolvable, bean)) {\n result.add(bean);\n }\n }\n return result;\n }"
] | [
"public static String unexpand(CharSequence self, int tabStop) {\n String s = self.toString();\n if (s.length() == 0) return s;\n try {\n StringBuilder builder = new StringBuilder();\n for (String line : readLines((CharSequence) s)) {\n builder.append(unexpandLine(line, tabStop));\n builder.append(\"\\n\");\n }\n // remove the normalized ending line ending if it was not present\n if (!s.endsWith(\"\\n\")) {\n builder.deleteCharAt(builder.length() - 1);\n }\n return builder.toString();\n } catch (IOException e) {\n /* ignore */\n }\n return s;\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 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 }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n private void cleanupSessions(List<String> storeNamesToCleanUp) {\n\n logger.info(\"Performing cleanup\");\n for(String store: storeNamesToCleanUp) {\n\n for(Node node: nodesToStream) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store,\n node.getId()));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n node.getId()));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n\n }\n\n cleanedUp = true;\n\n }",
"private void resetCalendar() {\n _calendar = getCalendar();\n if (_defaultTimeZone != null) {\n _calendar.setTimeZone(_defaultTimeZone);\n }\n _currentYear = _calendar.get(Calendar.YEAR);\n }",
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }",
"protected boolean isPrefixBlock(long divisionValue, long upperValue, int divisionPrefixLen) {\n\t\tif(divisionPrefixLen == 0) {\n\t\t\treturn divisionValue == 0 && upperValue == getMaxValue();\n\t\t}\n\t\tlong ones = ~0L;\n\t\tlong divisionBitMask = ~(ones << getBitCount());\n\t\tlong divisionPrefixMask = ones << (getBitCount() - divisionPrefixLen);\n\t\tlong divisionNonPrefixMask = ~divisionPrefixMask;\n\t\treturn testRange(divisionValue,\n\t\t\t\tupperValue,\n\t\t\t\tupperValue,\n\t\t\t\tdivisionPrefixMask & divisionBitMask,\n\t\t\t\tdivisionNonPrefixMask);\n\t}",
"public static String regexFindFirst(String pattern, String str) {\n return regexFindFirst(Pattern.compile(pattern), str, 1);\n }",
"public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }"
] |
One of facade methods for operating the Shell.
Run the obtained Shell with commandLoop().
@see org.gearvrf.debug.cli.Shell#Shell(org.gearvrf.debug.cli.Shell.Settings, org.gearvrf.debug.cli.CommandTable, java.util.List)
@param prompt Prompt to be displayed
@param appName The app name string
@param handlers Command handlers
@return Shell that can be either further customized or run directly by calling commandLoop(). | [
"public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {\n ConsoleIO io = new ConsoleIO();\n\n List<String> path = new ArrayList<String>(1);\n path.add(prompt);\n\n MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();\n modifAuxHandlers.put(\"!\", io);\n\n Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),\n new CommandTable(new DashJoinedNamer(true)), path);\n theShell.setAppName(appName);\n\n theShell.addMainHandler(theShell, \"!\");\n theShell.addMainHandler(new HelpCommandHandler(), \"?\");\n for (Object h : handlers) {\n theShell.addMainHandler(h, \"\");\n }\n\n return theShell;\n }"
] | [
"public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) {\n Class<?> superClass = typeInfo.getSuperClass();\n if (superClass.getName().startsWith(JAVA)) {\n ClassLoader cl = proxyServices.getClassLoader(proxiedType);\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass);\n }",
"public static Set<String> getRoundingNames(String... providers) {\n return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryRoundingsSpi loaded, query functionality is not available.\"))\n .getRoundingNames(providers);\n }",
"public LogStreamResponse getLogs(String appName, Boolean tail) {\n return connection.execute(new Log(appName, tail), apiKey);\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 void setAppender(final Appender appender) {\n if (this.appender != null) {\n close();\n }\n checkAccess(this);\n if (applyLayout && appender != null) {\n final Formatter formatter = getFormatter();\n appender.setLayout(formatter == null ? null : new FormatterLayout(formatter));\n }\n appenderUpdater.set(this, appender);\n }",
"public ParallelTaskBuilder prepareTcp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.TCP);\n cb.getTcpMeta().setCommand(command);\n return cb;\n }",
"public Set<String> rangeByScoreReverse(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (scoreRange.hasLimit()) {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse(), scoreRange.offset(), scoreRange.count());\n } else {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse());\n }\n }\n });\n }",
"private double getConstraint(double x1, double x2)\n {\n double c1,c2,h;\n c1 = -x1*x1-x2*x2+1+0.1*Math.cos(16*Math.atan(x1/x2));\n c2 = (x1-0.5)*(x1-0.5)+(x2-0.5)*(x2-0.5)-0.5;\n if(c1>c2)\n h = (c1>0)?c1:0;\n else\n h = (c2>0)?c2:0;\n return h;\n }",
"public String getUrl(){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(\"http://\");\n\t\tsb.append(getHttpConfiguration().getBindHost().get());\n\t\tsb.append(\":\");\n\t\tsb.append(getHttpConfiguration().getPort());\n\t\t\n\t\treturn sb.toString();\n\t}"
] |
Returns an array of all declared fields in the given class and all
super-classes. | [
"public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\n }"
] | [
"private boolean validate(CmsFavoriteEntry entry) {\n\n try {\n String siteRoot = entry.getSiteRoot();\n if (!m_okSiteRoots.contains(siteRoot)) {\n m_rootCms.readResource(siteRoot);\n m_okSiteRoots.add(siteRoot);\n }\n CmsUUID project = entry.getProjectId();\n if (!m_okProjects.contains(project)) {\n m_cms.readProject(project);\n m_okProjects.add(project);\n }\n for (CmsUUID id : Arrays.asList(entry.getDetailId(), entry.getStructureId())) {\n if ((id != null) && !m_okStructureIds.contains(id)) {\n m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n m_okStructureIds.add(id);\n }\n }\n return true;\n\n } catch (Exception e) {\n LOG.info(\"Favorite entry validation failed: \" + e.getLocalizedMessage(), e);\n return false;\n }\n\n }",
"public SqlStatement getPreparedInsertStatement(ClassDescriptor cld)\r\n {\r\n SqlStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getInsertSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getInsertProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlInsertStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setInsertSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"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 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 }",
"public static double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }",
"@Override\n public final String getString(final String key) {\n String result = optString(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"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 }",
"private int getMaxHeight() {\n int result = 0;\n for (int i = 0; i < segmentCount; i++) {\n result = Math.max(result, segmentHeight(i, false));\n }\n return result;\n }",
"public static Path getRootFolderForSource(Path sourceFilePath, String packageName)\n {\n if (packageName == null || packageName.trim().isEmpty())\n {\n return sourceFilePath.getParent();\n }\n String[] packageNameComponents = packageName.split(\"\\\\.\");\n Path currentPath = sourceFilePath.getParent();\n for (int i = packageNameComponents.length; i > 0; i--)\n {\n String packageComponent = packageNameComponents[i - 1];\n if (!StringUtils.equals(packageComponent, currentPath.getFileName().toString()))\n {\n return null;\n }\n currentPath = currentPath.getParent();\n }\n return currentPath;\n }"
] |
Shuts down the server. Active connections are not affected. | [
"public void shutdown() {\n debugConnection = null;\n shuttingDown = true;\n try {\n if (serverSocket != null) {\n serverSocket.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }"
] | [
"public static HashMap<Integer, List<Integer>>\n getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster,\n Map<Integer, Integer> targetPartitionsPerZone) {\n HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId),\n targetPartitionsPerZone.get(zoneId));\n numPartitionsPerNode.put(zoneId, partitionsOnNode);\n }\n return numPartitionsPerNode;\n }",
"public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}",
"public ParallelTaskBuilder prepareHttpPut(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.PUT);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }",
"@Override\n public void stop()\n {\n synchronized (killHook)\n {\n jqmlogger.info(\"JQM engine \" + this.node.getName() + \" has received a stop order\");\n\n // Kill hook should be removed\n try\n {\n if (!Runtime.getRuntime().removeShutdownHook(killHook))\n {\n jqmlogger.error(\"The engine could not unregister its shutdown hook\");\n }\n }\n catch (IllegalStateException e)\n {\n // This happens if the stop sequence is initiated by the shutdown hook itself.\n jqmlogger.info(\"Stop order is due to an admin operation (KILL/INT)\");\n }\n }\n\n // Stop pollers\n int pollerCount = pollers.size();\n for (QueuePoller p : pollers.values())\n {\n p.stop();\n }\n\n // Scheduler\n this.scheduler.stop();\n\n // Jetty is closed automatically when all pollers are down\n\n // Wait for the end of the world\n if (pollerCount > 0)\n {\n try\n {\n this.ended.acquire();\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n // Send a KILL signal to remaining job instances, and wait some more.\n if (this.getCurrentlyRunningJobCount() > 0)\n {\n this.runningJobInstanceManager.killAll();\n try\n {\n Thread.sleep(10000);\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n jqmlogger.debug(\"Stop order was correctly handled. Engine for node \" + this.node.getName() + \" has stopped.\");\n }",
"public static MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }",
"private String getSlashyPath(final String path) {\n String changedPath = path;\n if (File.separatorChar != '/')\n changedPath = changedPath.replace(File.separatorChar, '/');\n\n return changedPath;\n }",
"public void set(int i, double value) {\n switch (i) {\n case 0: {\n x = value;\n break;\n }\n case 1: {\n y = value;\n break;\n }\n case 2: {\n z = value;\n break;\n }\n default: {\n throw new ArrayIndexOutOfBoundsException(i);\n }\n }\n }",
"public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\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 }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.