query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
A fairly basic 5-way classifier, that notes digits, and upper
and lower case, mixed, and non-alphanumeric.
@param s String to find word shape of
@return Its word shape: a 5 way classification | [
"private static String wordShapeDan1(String s) {\r\n boolean digit = true;\r\n boolean upper = true;\r\n boolean lower = true;\r\n boolean mixed = true;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!Character.isDigit(c)) {\r\n digit = false;\r\n }\r\n if (!Character.isLowerCase(c)) {\r\n lower = false;\r\n }\r\n if (!Character.isUpperCase(c)) {\r\n upper = false;\r\n }\r\n if ((i == 0 && !Character.isUpperCase(c)) || (i >= 1 && !Character.isLowerCase(c))) {\r\n mixed = false;\r\n }\r\n }\r\n if (digit) {\r\n return \"ALL-DIGITS\";\r\n }\r\n if (upper) {\r\n return \"ALL-UPPER\";\r\n }\r\n if (lower) {\r\n return \"ALL-LOWER\";\r\n }\r\n if (mixed) {\r\n return \"MIXED-CASE\";\r\n }\r\n return \"OTHER\";\r\n }"
] | [
"public static double blackModelCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);\n\t}",
"private static void displayAvailableFilters(ProjectFile project)\n {\n System.out.println(\"Unknown filter name supplied.\");\n System.out.println(\"Available task filters:\");\n for (Filter filter : project.getFilters().getTaskFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n System.out.println(\"Available resource filters:\");\n for (Filter filter : project.getFilters().getResourceFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n }",
"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 Jar setJarPrefix(Path file) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (file != null && jarPrefixStr != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixStr + \")\");\n this.jarPrefixFile = file;\n return this;\n }",
"public MIMEType addParameter(String name, String value) {\n Map<String, String> copy = new LinkedHashMap<>(this.parameters);\n copy.put(name, value);\n return new MIMEType(type, subType, copy);\n }",
"public void reset( int N ) {\n this.N = N;\n\n this.diag = null;\n this.off = null;\n\n if( splits.length < N ) {\n splits = new int[N];\n }\n\n numSplits = 0;\n\n x1 = 0;\n x2 = N-1;\n\n steps = numExceptional = lastExceptional = 0;\n\n this.Q = null;\n }",
"public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }",
"public 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 sslglobal_sslpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\tsslglobal_sslpolicy_binding response[] = (sslglobal_sslpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
For each node in specified zones, tries swapping some minimum number of
random partitions per node with some minimum number of random partitions
from other specified nodes. Chooses the best swap in each iteration.
Large values of the greedSwapMaxPartitions... arguments make this method
equivalent to comparing every possible swap. This may get very expensive.
So if a node had partitions P1, P2, P3 and P4 and the other partitions
set was Q1, Q2, Q3, Q4, Q5 The combinations that will be tried for
swapping will be the cartesian product of the two sets. That is, {P1,
Q1}, {P2, Q2}...{P2,Q1}, {P2,Q2}, in total 20 such swap pairs will be
generated. The best among these swap pairs will be chosen.
@param nextCandidateCluster
@param nodeIds Node IDs within which to shuffle partitions
@param greedySwapMaxPartitionsPerNode See RebalanceCLI.
@param greedySwapMaxPartitionsPerZone See RebalanceCLI.
@param storeDefs
@return updated cluster | [
"public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\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 String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\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 boolean toggleProfile(Boolean enabled) {\n // TODO: make this return values properly\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"active\", enabled.toString())\n };\n try {\n String uri = BASE_PROFILE + uriEncode(this._profileName) + \"/\" + BASE_CLIENTS + \"/\";\n if (_clientId == null) {\n uri += \"-1\";\n } else {\n uri += _clientId;\n }\n JSONObject response = new JSONObject(doPost(uri, params));\n } catch (Exception e) {\n // some sort of error\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }",
"public Collection<Method> getAllMethods(String name) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n methods.addAll(map.values());\n }\n return methods;\n }",
"public void createEnvironment(@Observes(precedence = 10) BeforeClass event, OpenShiftAdapter client,\n CubeOpenShiftConfiguration cubeOpenShiftConfiguration) {\n final TestClass testClass = event.getTestClass();\n log.info(String.format(\"Creating environment for %s\", testClass.getName()));\n OpenShiftResourceFactory.createResources(testClass.getName(), client, testClass.getJavaClass(),\n cubeOpenShiftConfiguration.getProperties());\n classTemplateProcessor = new ClassTemplateProcessor(client, cubeOpenShiftConfiguration, testClass);\n final List<? extends OpenShiftResource> templateResources = classTemplateProcessor.processTemplateResources();\n templateDetailsProducer.set(() -> templateResources);\n }",
"protected void eigenvalue2by2( int x1 ) {\n double a = diag[x1];\n double b = off[x1];\n double c = diag[x1+1];\n\n // normalize to reduce overflow\n double absA = Math.abs(a);\n double absB = Math.abs(b);\n double absC = Math.abs(c);\n\n double scale = absA > absB ? absA : absB;\n if( absC > scale ) scale = absC;\n\n // see if it is a pathological case. the diagonal must already be zero\n // and the eigenvalues are all zero. so just return\n if( scale == 0 ) {\n off[x1] = 0;\n diag[x1] = 0;\n diag[x1+1] = 0;\n return;\n }\n\n a /= scale;\n b /= scale;\n c /= scale;\n\n eigenSmall.symm2x2_fast(a,b,c);\n\n off[x1] = 0;\n diag[x1] = scale*eigenSmall.value0.real;\n diag[x1+1] = scale*eigenSmall.value1.real;\n }",
"public static base_response update(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance updateresource = new clusterinstance();\n\t\tupdateresource.clid = resource.clid;\n\t\tupdateresource.deadinterval = resource.deadinterval;\n\t\tupdateresource.hellointerval = resource.hellointerval;\n\t\tupdateresource.preemption = resource.preemption;\n\t\treturn updateresource.update_resource(client);\n\t}",
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }"
] |
Use this API to fetch onlinkipv6prefix resource of given name . | [
"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 CollectionRequest<Task> findByTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"@Override\n public void setDraggable(Element elem, String draggable) {\n super.setDraggable(elem, draggable);\n if (\"true\".equals(draggable)) {\n elem.getStyle().setProperty(\"webkitUserDrag\", \"element\");\n } else {\n elem.getStyle().clearProperty(\"webkitUserDrag\");\n }\n }",
"public void subscriptionRequestReceived(SubscriptionRequest sr) throws SubscriptionException {\n\n LOG.info(\"Subscriber -> (Hub), new subscription request received.\", sr.getCallback());\n\n try {\n\n verifySubscriberRequestedSubscription(sr);\n\n if (\"subscribe\".equals(sr.getMode())) {\n LOG.info(\"Adding callback {} to the topic {}\", sr.getCallback(), sr.getTopic());\n addCallbackToTopic(sr.getCallback(), sr.getTopic());\n } else if (\"unsubscribe\".equals(sr.getMode())) {\n LOG.info(\"Removing callback {} from the topic {}\", sr.getCallback(), sr.getTopic());\n removeCallbackToTopic(sr.getCallback(), sr.getTopic());\n }\n\n } catch (Exception e) {\n throw new SubscriptionException(e);\n }\n\n }",
"public void setAddContentInfo(final Boolean doAddInfo) {\n\n if ((null != doAddInfo) && doAddInfo.booleanValue() && (null != m_addContentInfoForEntries)) {\n m_addContentInfoForEntries = Integer.valueOf(DEFAULT_CONTENTINFO_ROWS);\n }\n }",
"public void setIntegerAttribute(String name, Integer value) {\n\t\tensureValue();\n\t\tAttribute attribute = new IntegerAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"public DynamicReportBuilder setQuery(String text, String language) {\n this.report.setQuery(new DJQuery(text, language));\n return this;\n }",
"public void setHeaders(final Set<String> names) {\n // transform to lower-case because header names should be case-insensitive\n Set<String> lowerCaseNames = new HashSet<>();\n for (String name: names) {\n lowerCaseNames.add(name.toLowerCase());\n }\n this.headerNames = lowerCaseNames;\n }",
"public void render(OutputStream outputStream, Format format, int dpi) throws PrintingException {\n\t\ttry {\n\t\t\tif (baos == null) {\n\t\t\t\tprepare();\n\t\t\t}\n\t\t\twriteDocument(outputStream, format, dpi);\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);\n\t\t}\n\t}",
"public Object newInstance(String resource) {\n try {\n String name = resource.startsWith(\"/\") ? resource : \"/\" + resource;\n File file = new File(this.getClass().getResource(name).toURI());\n return newInstance(classLoader.parseClass(new GroovyCodeSource(file), true));\n } catch (Exception e) {\n throw new GroovyClassInstantiationFailed(classLoader, resource, e);\n }\n }"
] |
Returns next and previous favorites for a photo in a user's favorites
@param photoId
The photo id
@param userId
The user's ID
@see <a href="http://www.flickr.com/services/api/flickr.favorites.getContext.html">flickr.favorites.getContext</a> | [
"public PhotoContext getContext(String photoId, String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else {\r\n if (logger.isInfoEnabled()) {\r\n logger.info(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n }\r\n return photoContext;\r\n }"
] | [
"public Collection<Group> getGroups() throws FlickrException {\r\n GroupList<Group> groups = new GroupList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUPS);\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 groupsElement = response.getPayload();\r\n groups.setPage(groupsElement.getAttribute(\"page\"));\r\n groups.setPages(groupsElement.getAttribute(\"pages\"));\r\n groups.setPerPage(groupsElement.getAttribute(\"perpage\"));\r\n groups.setTotal(groupsElement.getAttribute(\"total\"));\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"id\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setPrivacy(groupElement.getAttribute(\"privacy\"));\r\n group.setIconServer(groupElement.getAttribute(\"iconserver\"));\r\n group.setIconFarm(groupElement.getAttribute(\"iconfarm\"));\r\n group.setPhotoCount(groupElement.getAttribute(\"photos\"));\r\n groups.add(group);\r\n }\r\n return groups;\r\n }",
"public void strokeEllipse(Rectangle rect, Color color, float linewidth) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),\n\t\t\t\torigY + rect.getTop());\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}",
"public Map<String, MBeanAttributeInfo> getAttributeMetadata() {\n\n MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes();\n\n Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>();\n for (MBeanAttributeInfo attribute: attributeList) {\n attributeMap.put(attribute.getName(), attribute);\n }\n return attributeMap;\n }",
"public static void convolveHV(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) {\n\t\tint index = 0;\n\t\tfloat[] matrix = kernel.getKernelData( null );\n\t\tint rows = kernel.getHeight();\n\t\tint cols = kernel.getWidth();\n\t\tint rows2 = rows/2;\n\t\tint cols2 = cols/2;\n\n\t\tfor (int y = 0; y < height; y++) {\n\t\t\tfor (int x = 0; x < width; x++) {\n\t\t\t\tfloat r = 0, g = 0, b = 0, a = 0;\n\n\t\t\t\tfor (int row = -rows2; row <= rows2; row++) {\n\t\t\t\t\tint iy = y+row;\n\t\t\t\t\tint ioffset;\n\t\t\t\t\tif (0 <= iy && iy < height)\n\t\t\t\t\t\tioffset = iy*width;\n\t\t\t\t\telse if ( edgeAction == CLAMP_EDGES )\n\t\t\t\t\t\tioffset = y*width;\n\t\t\t\t\telse if ( edgeAction == WRAP_EDGES )\n\t\t\t\t\t\tioffset = ((iy+height) % height) * width;\n\t\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tint moffset = cols*(row+rows2)+cols2;\n\t\t\t\t\tfor (int col = -cols2; col <= cols2; col++) {\n\t\t\t\t\t\tfloat f = matrix[moffset+col];\n\n\t\t\t\t\t\tif (f != 0) {\n\t\t\t\t\t\t\tint ix = x+col;\n\t\t\t\t\t\t\tif (!(0 <= ix && ix < width)) {\n\t\t\t\t\t\t\t\tif ( edgeAction == CLAMP_EDGES )\n\t\t\t\t\t\t\t\t\tix = x;\n\t\t\t\t\t\t\t\telse if ( edgeAction == WRAP_EDGES )\n\t\t\t\t\t\t\t\t\tix = (x+width) % width;\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tint rgb = inPixels[ioffset+ix];\n\t\t\t\t\t\t\ta += f * ((rgb >> 24) & 0xff);\n\t\t\t\t\t\t\tr += f * ((rgb >> 16) & 0xff);\n\t\t\t\t\t\t\tg += f * ((rgb >> 8) & 0xff);\n\t\t\t\t\t\t\tb += f * (rgb & 0xff);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tint ia = alpha ? PixelUtils.clamp((int)(a+0.5)) : 0xff;\n\t\t\t\tint ir = PixelUtils.clamp((int)(r+0.5));\n\t\t\t\tint ig = PixelUtils.clamp((int)(g+0.5));\n\t\t\t\tint ib = PixelUtils.clamp((int)(b+0.5));\n\t\t\t\toutPixels[index++] = (ia << 24) | (ir << 16) | (ig << 8) | ib;\n\t\t\t}\n\t\t}\n\t}",
"public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public ParsedWord pollParsedWord() {\n if(hasNextWord()) {\n //set correct next char\n if(parsedLine.words().size() > (word+1))\n character = parsedLine.words().get(word+1).lineIndex();\n else\n character = -1;\n return parsedLine.words().get(word++);\n }\n else\n return new ParsedWord(null, -1);\n }",
"public ConfigBuilder withMasterName(final String masterName) {\n if (masterName == null || \"\".equals(masterName)) {\n throw new IllegalArgumentException(\"masterName is null or empty: \" + masterName);\n }\n this.masterName = masterName;\n return this;\n }",
"protected static void checkQueues(final Iterable<String> queues) {\n if (queues == null) {\n throw new IllegalArgumentException(\"queues must not be null\");\n }\n for (final String queue : queues) {\n if (queue == null || \"\".equals(queue)) {\n throw new IllegalArgumentException(\"queues' members must not be null: \" + queues);\n }\n }\n }",
"public static Enum castToEnum(Object object, Class<? extends Enum> type) {\n if (object==null) return null;\n if (type.isInstance(object)) return (Enum) object;\n if (object instanceof String || object instanceof GString) {\n return Enum.valueOf(type, object.toString());\n }\n throw new GroovyCastException(object, type);\n }"
] |
Extract resource type from a resource ID string.
@param id the resource ID string
@return the resource type | [
"public static String resourceTypeFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceType() : null;\n }"
] | [
"protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public CliCommandBuilder setController(final String hostname, final int port) {\n setController(formatAddress(null, hostname, port));\n return this;\n }",
"public static gslbsite[] get(nitro_service service, String sitename[]) throws Exception{\n\t\tif (sitename !=null && sitename.length>0) {\n\t\t\tgslbsite response[] = new gslbsite[sitename.length];\n\t\t\tgslbsite obj[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++) {\n\t\t\t\tobj[i] = new gslbsite();\n\t\t\t\tobj[i].set_sitename(sitename[i]);\n\t\t\t\tresponse[i] = (gslbsite) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }",
"public String toRomanNumeral() {\n\t\tif (this.romanString == null) {\n\t\t\tthis.romanString = \"\";\n\t\t\tint remainder = this.value;\n\t\t\tfor (int i = 0; i < BASIC_VALUES.length; i++) {\n\t\t\t\twhile (remainder >= BASIC_VALUES[i]) {\n\t\t\t\t\tthis.romanString += BASIC_ROMAN_NUMERALS[i];\n\t\t\t\t\tremainder -= BASIC_VALUES[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this.romanString;\n\t}",
"public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) {\n ZkGroupDirs dirs = new ZkGroupDirs(group);\n List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir);\n //\n Map<String, List<String>> consumersPerTopicMap = new HashMap<String, List<String>>();\n for (String consumer : consumers) {\n TopicCount topicCount = getTopicCount(zkClient, group, consumer);\n for (Map.Entry<String, Set<String>> e : topicCount.getConsumerThreadIdsPerTopic().entrySet()) {\n final String topic = e.getKey();\n for (String consumerThreadId : e.getValue()) {\n List<String> list = consumersPerTopicMap.get(topic);\n if (list == null) {\n list = new ArrayList<String>();\n consumersPerTopicMap.put(topic, list);\n }\n //\n list.add(consumerThreadId);\n }\n }\n }\n //\n for (Map.Entry<String, List<String>> e : consumersPerTopicMap.entrySet()) {\n Collections.sort(e.getValue());\n }\n return consumersPerTopicMap;\n }",
"public final Object getValue(final String id, final String property) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n criteria.select(root.get(property));\n criteria.where(builder.equal(root.get(\"referenceId\"), id));\n return getSession().createQuery(criteria).uniqueResult();\n }",
"public MaterialSection getSectionByTitle(String title) {\n\n for(MaterialSection section : sectionList) {\n if(section.getTitle().equals(title)) {\n return section;\n }\n }\n\n for(MaterialSection section : bottomSectionList) {\n if(section.getTitle().equals(title))\n return section;\n }\n\n return null;\n }",
"public static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }"
] |
Get the relative path of an application
@param root the root to relativize against
@param path the path to relativize
@return the relative path | [
"public static String getRelativePathName(Path root, Path path) {\n Path relative = root.relativize(path);\n return Files.isDirectory(path) && !relative.toString().endsWith(\"/\") ? String.format(\"%s/\", relative.toString()) : relative.toString();\n }"
] | [
"public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid);\n return resp.getData();\n }",
"public Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\n }",
"public void removeOverride(int overrideId, int pathId, Integer ordinal, String clientUUID) {\n // TODO: reorder priorities after removal\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, enabledId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public static sslpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tsslpolicylabel response = (sslpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public boolean ifTaskCompletedSuccessOrFailureFromResponse(\n ResponseOnSingeRequest myResponse) {\n\n boolean isCompleted = false;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return isCompleted;\n }\n\n String responseBody = myResponse.getResponseBody();\n if (responseBody.matches(successRegex)\n || responseBody.matches(failureRegex)) {\n isCompleted = true;\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n return isCompleted;\n }",
"public static Integer getDays(String days)\n {\n Integer result = null;\n if (days != null)\n {\n result = Integer.valueOf(Integer.parseInt(days, 2));\n }\n return (result);\n }",
"private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {\n if (tries >= 5) {\n throw new BindException(\"Unable to bind to several ports, most recently \" + relay.getPort() + \". Giving up\");\n }\n try {\n if (server.isStarted()) {\n relay.start();\n } else {\n throw new RuntimeException(\"Can't start SslRelay: server is not started (perhaps it was just shut down?)\");\n }\n } catch (BindException e) {\n // doh - the port is being used up, let's pick a new port\n LOG.info(\"Unable to bind to port %d, going to try port %d now\", relay.getPort(), relay.getPort() + 1);\n relay.setPort(relay.getPort() + 1);\n startRelayWithPortTollerance(server, relay, tries + 1);\n }\n }",
"public boolean removeWriter(Object key, Object resourceId)\r\n {\r\n boolean result = false;\r\n ObjectLocks objectLocks = null;\r\n synchronized(locktable)\r\n {\r\n objectLocks = (ObjectLocks) locktable.get(resourceId);\r\n if(objectLocks != null)\r\n {\r\n /**\r\n * MBAIRD, last one out, close the door and turn off the lights.\r\n * if no locks (readers or writers) exist for this object, let's remove\r\n * it from the locktable.\r\n */\r\n LockEntry entry = objectLocks.getWriter();\r\n if(entry != null && entry.isOwnedBy(key))\r\n {\r\n objectLocks.setWriter(null);\r\n result = true;\r\n\r\n // no need to check if writer is null, we just set it.\r\n if(objectLocks.getReaders().size() == 0)\r\n {\r\n locktable.remove(resourceId);\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }",
"public synchronized ControlPoint getControlPoint(final String deploymentName, final String entryPointName) {\n ControlPointIdentifier id = new ControlPointIdentifier(deploymentName, entryPointName);\n ControlPoint ep = entryPoints.get(id);\n if (ep == null) {\n ep = new ControlPoint(this, deploymentName, entryPointName, trackIndividualControlPoints);\n entryPoints.put(id, ep);\n }\n ep.increaseReferenceCount();\n return ep;\n }"
] |
Creates a Bytes object by copying the data of a subsequence of the given byte array
@param data Byte data
@param offset Starting offset in byte array (inclusive)
@param length Number of bytes to include | [
"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 CompositeGeneratorNode appendNewLineIfNotEmpty(final CompositeGeneratorNode parent) {\n List<IGeneratorNode> _children = parent.getChildren();\n String _lineDelimiter = this.wsConfig.getLineDelimiter();\n NewLineNode _newLineNode = new NewLineNode(_lineDelimiter, true);\n _children.add(_newLineNode);\n return parent;\n }",
"public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID,\r\n String folderID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_FOLDER).add(\"id\", folderID), null);\r\n }",
"private void init()\r\n {\r\n jdbcProperties = new Properties();\r\n dbcpProperties = new Properties();\r\n setFetchSize(0);\r\n this.setTestOnBorrow(true);\r\n this.setTestOnReturn(false);\r\n this.setTestWhileIdle(false);\r\n this.setLogAbandoned(false);\r\n this.setRemoveAbandoned(false);\r\n }",
"private void executeResult() throws Exception {\n\t\tresult = createResult();\n\n\t\tString timerKey = \"executeResult: \" + getResultCode();\n\t\ttry {\n\t\t\tUtilTimerStack.push(timerKey);\n\t\t\tif (result != null) {\n\t\t\t\tresult.execute(this);\n\t\t\t} else if (resultCode != null && !Action.NONE.equals(resultCode)) {\n\t\t\t\tthrow new ConfigurationException(\"No result defined for action \" + getAction().getClass().getName()\n\t\t\t\t\t\t+ \" and result \" + getResultCode(), proxy.getConfig());\n\t\t\t} else {\n\t\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\t\tLOG.debug(\"No result returned for action \" + getAction().getClass().getName() + \" at \"\n\t\t\t\t\t\t\t+ proxy.getConfig().getLocation());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tUtilTimerStack.pop(timerKey);\n\t\t}\n\t}",
"public void set(int numRows, int numCols, boolean rowMajor, double ...data)\n {\n reshape(numRows,numCols);\n int length = numRows*numCols;\n\n if( length > this.data.length )\n throw new IllegalArgumentException(\"The length of this matrix's data array is too small.\");\n\n if( rowMajor ) {\n System.arraycopy(data,0,this.data,0,length);\n } else {\n int index = 0;\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n this.data[index++] = data[j*numRows+i];\n }\n }\n }\n }",
"@SuppressWarnings(\"unused\")\n public static void changeCredentials(String accountID, String token) {\n changeCredentials(accountID, token, null);\n }",
"private Number calculateDurationPercentComplete(Row row)\n {\n double result = 0;\n double targetDuration = row.getDuration(\"target_drtn_hr_cnt\").getDuration();\n double remainingDuration = row.getDuration(\"remain_drtn_hr_cnt\").getDuration();\n\n if (targetDuration == 0)\n {\n if (remainingDuration == 0)\n {\n if (\"TK_Complete\".equals(row.getString(\"status_code\")))\n {\n result = 100;\n }\n }\n }\n else\n {\n if (remainingDuration < targetDuration)\n {\n result = ((targetDuration - remainingDuration) * 100) / targetDuration;\n }\n }\n\n return NumberHelper.getDouble(result);\n }",
"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 }",
"private static void updateSniffingLoggersLevel(Logger logger) {\n\n\t\tInputStream settingIS = FoundationLogger.class\n\t\t\t\t.getResourceAsStream(\"/sniffingLogger.xml\");\n\t\tif (settingIS == null) {\n\t\t\tlogger.debug(\"file sniffingLogger.xml not found in classpath\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\t\tDocument document = builder.build(settingIS);\n\t\t\t\tsettingIS.close();\n\t\t\t\tElement rootElement = document.getRootElement();\n\t\t\t\tList<Element> sniffingloggers = rootElement\n\t\t\t\t\t\t.getChildren(\"sniffingLogger\");\n\t\t\t\tfor (Element sniffinglogger : sniffingloggers) {\n\t\t\t\t\tString loggerName = sniffinglogger.getAttributeValue(\"id\");\n\t\t\t\t\tLogger.getLogger(loggerName).setLevel(Level.TRACE);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t\t\"cannot load the sniffing logger configuration file. error is: \"\n\t\t\t\t\t\t\t\t+ e, e);\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Problem parsing sniffingLogger.xml\", e);\n\t\t\t}\n\t\t}\n\n\t}"
] |
Maps a bindingId to its corresponding BindingType.
@param bindingId
@return | [
"private static BindingType map2BindingType(String bindingId) {\n BindingType type;\n if (SOAP11_BINDING_ID.equals(bindingId)) {\n type = BindingType.SOAP11;\n } else if (SOAP12_BINDING_ID.equals(bindingId)) {\n type = BindingType.SOAP12;\n } else if (JAXRS_BINDING_ID.equals(bindingId)) {\n type = BindingType.JAXRS;\n } else {\n type = BindingType.OTHER;\n }\n return type;\n }"
] | [
"@SuppressWarnings(\"SameParameterValue\")\n public static long bytesToNumberLittleEndian(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start + length - 1; index >= start; index--) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }",
"private void writeResource(Resource record) throws IOException\n {\n m_buffer.setLength(0);\n\n //\n // Write the resource record\n //\n int[] fields = m_resourceModel.getModel();\n\n m_buffer.append(MPXConstants.RESOURCE_RECORD_NUMBER);\n for (int loop = 0; loop < fields.length; loop++)\n {\n int mpxFieldType = fields[loop];\n if (mpxFieldType == -1)\n {\n break;\n }\n\n ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);\n Object value = record.getCachedValue(resourceField);\n value = formatType(resourceField.getDataType(), value);\n\n m_buffer.append(m_delimiter);\n m_buffer.append(format(value));\n }\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n //\n // Write the resource notes\n //\n String notes = record.getNotes();\n if (notes.length() != 0)\n {\n writeNotes(MPXConstants.RESOURCE_NOTES_RECORD_NUMBER, notes);\n }\n\n //\n // Write the resource calendar\n //\n if (record.getResourceCalendar() != null)\n {\n writeCalendar(record.getResourceCalendar());\n }\n\n m_eventManager.fireResourceWrittenEvent(record);\n }",
"public static int cudnnGetRNNWorkspaceSize(\n cudnnHandle handle, \n cudnnRNNDescriptor rnnDesc, \n int seqLength, \n cudnnTensorDescriptor[] xDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetRNNWorkspaceSizeNative(handle, rnnDesc, seqLength, xDesc, sizeInBytes));\n }",
"public static int serialize(OutputStream stream, Object obj) {\n ObjectMapper mapper = createMapperWithJaxbAnnotationInspector();\n\n try (DataOutputStream data = new DataOutputStream(stream);\n OutputStreamWriter writer = new OutputStreamWriter(data, StandardCharsets.UTF_8)) {\n mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj);\n return data.size();\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }",
"@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"public Collection<Method> getAllMethods(String name, int paramCount) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n for (Method method : map.values()) {\n if (method.getParameterTypes().length == paramCount) {\n methods.add(method);\n }\n }\n }\n return methods;\n }",
"public static String getPrefixFromValue(String value) {\n if (value == null) {\n return null;\n } else if (value.contains(DELIMITER)) {\n String[] list = value.split(DELIMITER);\n if (list != null && list.length > 0) {\n return list[0].replaceAll(\"\\u0000\", \"\");\n } else {\n return null;\n }\n } else {\n return value.replaceAll(\"\\u0000\", \"\");\n }\n }",
"public void setHeader(String header, String value) {\n StringValidator.throwIfEmptyOrNull(\"header\", header);\n StringValidator.throwIfEmptyOrNull(\"value\", value);\n\n if (headers == null) {\n headers = new HashMap<String, String>();\n }\n\n headers.put(header, value);\n }",
"private void validateFilter(Filter filter) throws IllegalArgumentException {\n switch (filter.getFilterTypeCase()) {\n case COMPOSITE_FILTER:\n for (Filter subFilter : filter.getCompositeFilter().getFiltersList()) {\n validateFilter(subFilter);\n }\n break;\n case PROPERTY_FILTER:\n if (UNSUPPORTED_OPERATORS.contains(filter.getPropertyFilter().getOp())) {\n throw new IllegalArgumentException(\"Query cannot have any inequality filters.\");\n }\n break;\n default:\n throw new IllegalArgumentException(\n \"Unsupported filter type: \" + filter.getFilterTypeCase());\n }\n }"
] |
read offsets before given time
@param offsetRequest the offset request
@return offsets before given time | [
"public List<Long> getOffsets(OffsetRequest offsetRequest) {\n ILog log = getLog(offsetRequest.topic, offsetRequest.partition);\n if (log != null) {\n return log.getOffsetsBefore(offsetRequest);\n }\n return ILog.EMPTY_OFFSETS;\n }"
] | [
"public boolean isResourceExcluded(final PathAddress address) {\n if (!localHostControllerInfo.isMasterDomainController() && address.size() > 0) {\n IgnoredDomainResourceRoot root = this.rootResource;\n PathElement firstElement = address.getElement(0);\n IgnoreDomainResourceTypeResource typeResource = root == null ? null : root.getChildInternal(firstElement.getKey());\n if (typeResource != null) {\n if (typeResource.hasName(firstElement.getValue())) {\n return true;\n }\n }\n }\n return false;\n }",
"public static base_response disable(nitro_service client, String id) throws Exception {\n\t\tInterface disableresource = new Interface();\n\t\tdisableresource.id = id;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"protected BufferedImage fetchImage(\n @Nonnull final ClientHttpRequest request, @Nonnull final MapfishMapContext transformer)\n throws IOException {\n final String baseMetricName = getClass().getName() + \".read.\" +\n StatsUtils.quotePart(request.getURI().getHost());\n final Timer.Context timerDownload = this.registry.timer(baseMetricName).time();\n try (ClientHttpResponse httpResponse = request.execute()) {\n if (httpResponse.getStatusCode() != HttpStatus.OK) {\n final String message = String.format(\n \"Invalid status code for %s (%d!=%d). The response was: '%s'\",\n request.getURI(), httpResponse.getStatusCode().value(),\n HttpStatus.OK.value(), httpResponse.getStatusText());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(message);\n } else {\n LOGGER.info(message);\n return createErrorImage(transformer.getPaintArea());\n }\n }\n\n final List<String> contentType = httpResponse.getHeaders().get(\"Content-Type\");\n if (contentType == null || contentType.size() != 1) {\n LOGGER.debug(\"The image {} didn't return a valid content type header.\",\n request.getURI());\n } else if (!contentType.get(0).startsWith(\"image/\")) {\n final byte[] data;\n try (InputStream body = httpResponse.getBody()) {\n data = IOUtils.toByteArray(body);\n }\n LOGGER.debug(\"We get a wrong image for {}, content type: {}\\nresult:\\n{}\",\n request.getURI(), contentType.get(0),\n new String(data, StandardCharsets.UTF_8));\n this.registry.counter(baseMetricName + \".error\").inc();\n return createErrorImage(transformer.getPaintArea());\n }\n\n final BufferedImage image = ImageIO.read(httpResponse.getBody());\n if (image == null) {\n LOGGER.warn(\"Cannot read image from %a\", request.getURI());\n this.registry.counter(baseMetricName + \".error\").inc();\n if (getFailOnError()) {\n throw new RuntimeException(\"Cannot read image from \" + request.getURI());\n } else {\n return createErrorImage(transformer.getPaintArea());\n }\n }\n timerDownload.stop();\n return image;\n } catch (Throwable e) {\n this.registry.counter(baseMetricName + \".error\").inc();\n throw e;\n }\n }",
"protected synchronized void handleCompleted() {\n latch.countDown();\n for (final ShutdownListener listener : listeners) {\n listener.handleCompleted();\n }\n listeners.clear();\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }",
"public List<List<IN>> classifyRaw(String str,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, readerAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }",
"public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }",
"public void setSiteRoot(String siteRoot) {\n\n if (siteRoot != null) {\n siteRoot = siteRoot.replaceFirst(\"/$\", \"\");\n }\n m_siteRoot = siteRoot;\n }",
"void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }"
] |
Filters attributes from the HTML string.
@param html The HTML to filter.
@return The filtered HTML string. | [
"private String filterAttributes(String html) {\n\t\tString filteredHtml = html;\n\t\tfor (String attribute : this.filterAttributes) {\n\t\t\tString regex = \"\\\\s\" + attribute + \"=\\\"[^\\\"]*\\\"\";\n\t\t\tPattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n\t\t\tMatcher m = p.matcher(html);\n\t\t\tfilteredHtml = m.replaceAll(\"\");\n\t\t}\n\t\treturn filteredHtml;\n\t}"
] | [
"public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }",
"public 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 Indexable taskResult(String taskId) {\n TaskGroupEntry<TaskItem> taskGroupEntry = super.getNode(taskId);\n if (taskGroupEntry != null) {\n return taskGroupEntry.taskResult();\n }\n if (!this.proxyTaskGroupWrapper.isActive()) {\n throw new IllegalArgumentException(\"A dependency task with id '\" + taskId + \"' is not found\");\n }\n taskGroupEntry = this.proxyTaskGroupWrapper.proxyTaskGroup.getNode(taskId);\n if (taskGroupEntry != null) {\n return taskGroupEntry.taskResult();\n }\n throw new IllegalArgumentException(\"A dependency task or 'post-run' dependent task with with id '\" + taskId + \"' not found\");\n }",
"private Entry getEntry(Object key)\r\n {\r\n if (key == null) return null;\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n for (Entry entry = table[index]; entry != null; entry = entry.next)\r\n {\r\n if ((entry.hash == hash) && equals(key, entry.getKey()))\r\n {\r\n return entry;\r\n }\r\n }\r\n return null;\r\n }",
"public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }",
"private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }",
"public GVRShaderId getShaderType(Class<? extends GVRShader> shaderClass)\n {\n GVRShaderId shaderId = mShaderTemplates.get(shaderClass);\n\n if (shaderId == null)\n {\n GVRContext ctx = getGVRContext();\n shaderId = new GVRShaderId(shaderClass);\n mShaderTemplates.put(shaderClass, shaderId);\n shaderId.getTemplate(ctx);\n }\n return shaderId;\n }",
"private void processUpdate(DeviceUpdate update) {\n updates.put(update.getAddress(), update);\n\n // Keep track of the largest sync number we see.\n if (update instanceof CdjStatus) {\n int syncNumber = ((CdjStatus)update).getSyncNumber();\n if (syncNumber > this.largestSyncCounter.get()) {\n this.largestSyncCounter.set(syncNumber);\n }\n }\n\n // Deal with the tempo master complexities, including handoff to/from us.\n if (update.isTempoMaster()) {\n final Integer packetYieldingTo = update.getDeviceMasterIsBeingYieldedTo();\n if (packetYieldingTo == null) {\n // This is a normal, non-yielding master packet. Update our notion of the current master, and,\n // if we were yielding, finish that process, updating our sync number appropriately.\n if (master.get()) {\n if (nextMaster.get() == update.deviceNumber) {\n syncCounter.set(largestSyncCounter.get() + 1);\n } else {\n if (nextMaster.get() == 0xff) {\n logger.warn(\"Saw master asserted by player \" + update.deviceNumber +\n \" when we were not yielding it.\");\n } else {\n logger.warn(\"Expected to yield master role to player \" + nextMaster.get() +\n \" but saw master asserted by player \" + update.deviceNumber);\n }\n }\n }\n master.set(false);\n nextMaster.set(0xff);\n setTempoMaster(update);\n setMasterTempo(update.getEffectiveTempo());\n } else {\n // This is a yielding master packet. If it is us that is being yielded to, take over master.\n // Log a message if it was unsolicited, and a warning if it's coming from a different player than\n // we asked.\n if (packetYieldingTo == getDeviceNumber()) {\n if (update.deviceNumber != masterYieldedFrom.get()) {\n if (masterYieldedFrom.get() == 0) {\n logger.info(\"Accepting unsolicited Master yield; we must be the only synced device playing.\");\n } else {\n logger.warn(\"Expected player \" + masterYieldedFrom.get() + \" to yield master to us, but player \" +\n update.deviceNumber + \" did.\");\n }\n }\n master.set(true);\n masterYieldedFrom.set(0);\n setTempoMaster(null);\n setMasterTempo(getTempo());\n }\n }\n } else {\n // This update was not acting as a tempo master; if we thought it should be, update our records.\n DeviceUpdate oldMaster = getTempoMaster();\n if (oldMaster != null && oldMaster.getAddress().equals(update.getAddress())) {\n // This device has resigned master status, and nobody else has claimed it so far\n setTempoMaster(null);\n }\n }\n deliverDeviceUpdate(update);\n }",
"public String putDocument(Document document) {\n\t\tString key = UUID.randomUUID().toString();\n\t\tdocumentMap.put(key, document);\n\t\treturn key;\n\t}"
] |
Returns all resources that belong to the bundle
This includes the descriptor if one exists.
@return List of the bundle resources, including the descriptor. | [
"List<CmsResource> getBundleResources() {\n\n List<CmsResource> resources = new ArrayList<>(m_bundleFiles.values());\n if (m_desc != null) {\n resources.add(m_desc);\n }\n return resources;\n\n }"
] | [
"public static base_responses update(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\tupdateresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void calculateSize(PdfContext context) {\n\t\tfloat width = 0;\n\t\tfloat height = 0;\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.calculateSize(context);\n\t\t\tfloat cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX();\n\t\t\tfloat ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY();\n\t\t\tswitch (getConstraint().getFlowDirection()) {\n\t\t\t\tcase LayoutConstraint.FLOW_NONE:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_X:\n\t\t\t\t\twidth += cw;\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_Y:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight += ch;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unknown flow direction \" + getConstraint().getFlowDirection());\n\t\t\t}\n\t\t}\n\t\tif (getConstraint().getWidth() != 0) {\n\t\t\twidth = getConstraint().getWidth();\n\t\t}\n\t\tif (getConstraint().getHeight() != 0) {\n\t\t\theight = getConstraint().getHeight();\n\t\t}\n\t\tsetBounds(new Rectangle(0, 0, width, height));\n\t}",
"public void checkConnection() {\n long start = Time.currentTimeMillis();\n\n while (clientChannel == null) {\n\n tcpSocketConsumer.checkNotShutdown();\n\n if (start + timeoutMs > Time.currentTimeMillis())\n try {\n condition.await(1, TimeUnit.MILLISECONDS);\n\n } catch (InterruptedException e) {\n throw new IORuntimeException(\"Interrupted\");\n }\n else\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }\n\n if (clientChannel == null)\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }",
"public static base_response add(nitro_service client, linkset resource) throws Exception {\n\t\tlinkset addresource = new linkset();\n\t\taddresource.id = resource.id;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }",
"public static ProtocolConnectionManager create(final Connection connection, final ConnectionOpenHandler openHandler) {\n return create(new EstablishedConnection(connection, openHandler));\n }",
"@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }",
"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 enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }"
] |
Analyzes the source code of an interface. The specified interface must not contain methods, that changes the
state of the corresponding object itself.
@param code
source code of an interface which describes how to generate the <i>immutable</i>
@return analysis result | [
"@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}"
] | [
"public Collection<Group> getPublicGroups(String userId) throws FlickrException {\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_GROUPS);\r\n\r\n parameters.put(\"user_id\", userId);\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 groupsElement = response.getPayload();\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"nsid\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setEighteenPlus(groupElement.getAttribute(\"eighteenplus\").equals(\"0\") ? false : true);\r\n groups.add(group);\r\n }\r\n return groups;\r\n }",
"protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public static double JaccardDistance(double[] p, double[] q) {\n double distance = 0;\n int intersection = 0, union = 0;\n\n for (int x = 0; x < p.length; x++) {\n if ((p[x] != 0) || (q[x] != 0)) {\n if (p[x] == q[x]) {\n intersection++;\n }\n\n union++;\n }\n }\n\n if (union != 0)\n distance = 1.0 - ((double) intersection / (double) union);\n else\n distance = 0;\n\n return distance;\n }",
"public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {\n final TestSpecification testSpecification = new TestSpecification();\n // Sort buckets by value ascending\n final Map<String,Integer> buckets = Maps.newLinkedHashMap();\n final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {\n @Override\n public int compare(final TestBucket lhs, final TestBucket rhs) {\n return Ints.compare(lhs.getValue(), rhs.getValue());\n }\n }).immutableSortedCopy(testDefinition.getBuckets());\n int fallbackValue = -1;\n if(testDefinitionBuckets.size() > 0) {\n final TestBucket firstBucket = testDefinitionBuckets.get(0);\n fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value\n\n final PayloadSpecification payloadSpecification = new PayloadSpecification();\n if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {\n final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());\n payloadSpecification.setType(payloadType.payloadTypeName);\n if (payloadType == PayloadType.MAP) {\n final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();\n for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {\n payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);\n }\n payloadSpecification.setSchema(payloadSpecificationSchema);\n }\n testSpecification.setPayload(payloadSpecification);\n }\n\n for (int i = 0; i < testDefinitionBuckets.size(); i++) {\n final TestBucket bucket = testDefinitionBuckets.get(i);\n buckets.put(bucket.getName(), bucket.getValue());\n }\n }\n testSpecification.setBuckets(buckets);\n testSpecification.setDescription(testDefinition.getDescription());\n testSpecification.setFallbackValue(fallbackValue);\n return testSpecification;\n }",
"public static String join(int[] array, String separator) {\n if (array != null) {\n StringBuilder buf = new StringBuilder(Math.max(16, (separator.length() + 1) * array.length));\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n for (int i = 0; i < array.length; i++) {\n if (i != 0) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n buf.append(array[i]);\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }",
"private static Map<String, String> mapCustomInfo(CustomInfoType ciType){\n Map<String, String> customInfo = new HashMap<String, String>();\n if (ciType != null){\n for (CustomInfoType.Item item : ciType.getItem()) {\n customInfo.put(item.getKey(), item.getValue());\n }\n }\n return customInfo;\n }",
"public static String getRelativePathName(Path root, Path path) {\n Path relative = root.relativize(path);\n return Files.isDirectory(path) && !relative.toString().endsWith(\"/\") ? String.format(\"%s/\", relative.toString()) : relative.toString();\n }",
"public static String fromClassPath() {\n Set<String> versions = new HashSet<>();\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> manifests = classLoader.getResources(\"META-INF/MANIFEST.MF\");\n\n while (manifests.hasMoreElements()) {\n URL manifestURL = manifests.nextElement();\n try (InputStream is = manifestURL.openStream()) {\n Manifest manifest = new Manifest();\n manifest.read(is);\n\n Attributes buildInfo = manifest.getAttributes(\"Build-Info\");\n if (buildInfo != null) {\n if (buildInfo.getValue(\"Selenium-Version\") != null) {\n versions.add(buildInfo.getValue(\"Selenium-Version\"));\n } else {\n // might be in build-info part\n if (manifest.getEntries() != null) {\n if (manifest.getEntries().containsKey(\"Build-Info\")) {\n final Attributes attributes = manifest.getEntries().get(\"Build-Info\");\n\n if (attributes.getValue(\"Selenium-Version\") != null) {\n versions.add(attributes.getValue(\"Selenium-Version\"));\n }\n }\n }\n }\n }\n }\n }\n } catch (Exception e) {\n logger.log(Level.WARNING,\n \"Exception {0} occurred while resolving selenium version and latest image is going to be used.\",\n e.getMessage());\n return SELENIUM_VERSION;\n }\n\n if (versions.isEmpty()) {\n logger.log(Level.INFO, \"No version of Selenium found in classpath. Using latest image.\");\n return SELENIUM_VERSION;\n }\n\n String foundVersion = versions.iterator().next();\n if (versions.size() > 1) {\n logger.log(Level.WARNING, \"Multiple versions of Selenium found in classpath. Using the first one found {0}.\",\n foundVersion);\n }\n\n return foundVersion;\n }",
"public ServerRedirect getRedirect(int id) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n\n return curServer;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }"
] |
Adds the specified list of users as followers to the project. Followers are a subset of members, therefore if
the users are not already members of the project they will also become members as a result of this operation.
Returns the updated project record.
@param project The project to add followers to.
@return Request object | [
"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 static synchronized void unregister(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n l.remove( factory );\n }\n }\n }",
"public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }",
"public static Optional<Field> getField(Class<?> type, final String fieldName) {\n Optional<Field> field = Iterables.tryFind(newArrayList(type.getDeclaredFields()), havingFieldName(fieldName));\n\n if (!field.isPresent() && type.getSuperclass() != null){\n field = getField(type.getSuperclass(), fieldName);\n }\n\n return field;\n }",
"public static base_responses delete(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 deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"@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 }",
"public void parseRawValue(String value)\n {\n int valueIndex = 0;\n int elementIndex = 0;\n m_elements.clear();\n while (valueIndex < value.length() && elementIndex < m_elements.size())\n {\n int elementLength = m_lengths.get(elementIndex).intValue();\n if (elementIndex > 0)\n {\n m_elements.add(m_separators.get(elementIndex - 1));\n }\n int endIndex = valueIndex + elementLength;\n if (endIndex > value.length())\n {\n endIndex = value.length();\n }\n String element = value.substring(valueIndex, endIndex);\n m_elements.add(element);\n valueIndex += elementLength;\n elementIndex++;\n }\n }",
"public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }",
"public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static synchronized void resetAndSetNewConfig(Context ctx, Config config) {\n GLOBAL_CONFIG = config;\n\n if (DISK_CACHE_MANAGER != null) {\n DISK_CACHE_MANAGER.clear();\n DISK_CACHE_MANAGER = null;\n createCache(ctx);\n }\n\n if (EXECUTOR_MANAGER != null) {\n EXECUTOR_MANAGER.shutDown();\n EXECUTOR_MANAGER = null;\n }\n Log.i(TAG, \"New config set\");\n }"
] |
Similar to masking, checks that the range resulting from the bitwise or is contiguous.
@param maskValue
@param segmentPrefixLength
@return
@throws PrefixLenException | [
"public boolean isBitwiseOrCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\treturn super.isBitwiseOrCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}"
] | [
"public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }",
"private void addEdgesForVertex(Vertex vertex)\r\n {\r\n ClassDescriptor cld = vertex.getEnvelope().getClassDescriptor();\r\n Iterator rdsIter = cld.getObjectReferenceDescriptors(true).iterator();\r\n while (rdsIter.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) rdsIter.next();\r\n addObjectReferenceEdges(vertex, rds);\r\n }\r\n Iterator cdsIter = cld.getCollectionDescriptors(true).iterator();\r\n while (cdsIter.hasNext())\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) cdsIter.next();\r\n addCollectionEdges(vertex, cds);\r\n }\r\n }",
"@Override\n public void populateObject(ProcessedCommand<Command<CI>, CI> processedCommand, InvocationProviders invocationProviders,\n AeshContext aeshContext, CommandLineParser.Mode mode)\n throws CommandLineParserException, OptionValidatorException {\n if(processedCommand.parserExceptions().size() > 0 && mode == CommandLineParser.Mode.VALIDATE)\n throw processedCommand.parserExceptions().get(0);\n for(ProcessedOption option : processedCommand.getOptions()) {\n if(option.getValues() != null && option.getValues().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE );\n else if(option.getDefaultValues().size() > 0) {\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n }\n else if(option.getOptionType().equals(OptionType.GROUP) && option.getProperties().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else\n resetField(getObject(), option.getFieldName(), option.hasValue());\n }\n //arguments\n if(processedCommand.getArguments() != null &&\n (processedCommand.getArguments().getValues().size() > 0 || processedCommand.getArguments().getDefaultValues().size() > 0))\n processedCommand.getArguments().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArguments() != null)\n resetField(getObject(), processedCommand.getArguments().getFieldName(), true);\n //argument\n if(processedCommand.getArgument() != null &&\n (processedCommand.getArgument().getValues().size() > 0 || processedCommand.getArgument().getDefaultValues().size() > 0))\n processedCommand.getArgument().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArgument() != null)\n resetField(getObject(), processedCommand.getArgument().getFieldName(), true);\n }",
"public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static String encodeHost(String host, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4);\n\t}",
"public void setShortAttribute(String name, Short value) {\n\t\tensureValue();\n\t\tAttribute attribute = new ShortAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"public static int getDayAsReadableInt(long time) {\n Calendar cal = calendarThreadLocal.get();\n cal.setTimeInMillis(time);\n return getDayAsReadableInt(cal);\n }",
"public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }",
"public static void munlock(Pointer addr, long len) {\n\n if(Delegate.munlock(addr, new NativeLong(len)) != 0) {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking failed with errno:\" + errno.strerror());\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking region\");\n }\n }"
] |
Returns the field with the specified value properly formatted. Multiline
values are automatically indented, and dots are added on the empty lines.
<pre>
Field-Name: value
</pre> | [
"public String format(String value) {\n StringBuilder s = new StringBuilder();\n\n if (value != null && value.trim().length() > 0) {\n boolean continuationLine = false;\n\n s.append(getName()).append(\":\");\n if (isFirstLineEmpty()) {\n s.append(\"\\n\");\n continuationLine = true;\n }\n\n try {\n BufferedReader reader = new BufferedReader(new StringReader(value));\n String line;\n while ((line = reader.readLine()) != null) {\n if (continuationLine && line.trim().length() == 0) {\n // put a dot on the empty continuation lines\n s.append(\" .\\n\");\n } else {\n s.append(\" \").append(line).append(\"\\n\");\n }\n\n continuationLine = true;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return s.toString();\n }"
] | [
"private void updateGhostStyle() {\n\n if (CmsStringUtil.isEmpty(m_realValue)) {\n if (CmsStringUtil.isEmpty(m_ghostValue)) {\n updateTextArea(m_realValue);\n return;\n }\n if (!m_focus) {\n setGhostStyleEnabled(true);\n updateTextArea(m_ghostValue);\n } else {\n // don't show ghost mode while focused\n setGhostStyleEnabled(false);\n }\n } else {\n setGhostStyleEnabled(false);\n updateTextArea(m_realValue);\n }\n }",
"public ProjectCalendar addDefaultDerivedCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n return (calendar);\n }",
"public boolean isIdentical(T a, double tol) {\n if( a.getType() != getType() )\n return false;\n return ops.isIdentical(mat,a.mat,tol);\n }",
"public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"public static lbvserver_stats[] get(nitro_service service) throws Exception{\n\t\tlbvserver_stats obj = new lbvserver_stats();\n\t\tlbvserver_stats[] response = (lbvserver_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }",
"public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}",
"public void addIn(Object attribute, Query subQuery)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }"
] |
Fancy print without a space added to positive numbers | [
"public String p(double value ) {\n return UtilEjml.fancyString(value,format,false,length,significant);\n }"
] | [
"@Deprecated\n @Override\n public File fetch(String source, String dest, long diskQuotaSizeInKB) throws Exception {\n return fetchFromSource(source, dest, null, null, -1, diskQuotaSizeInKB, null);\n }",
"public void setStartTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getStart(), date)) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setStart(date);\r\n setPatternDefaultValues(date);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }",
"private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }",
"public void fillFromToWith(int from, int to, Object val) {\r\n\tcheckRangeFromTo(from,to,this.size);\r\n\tfor (int i=from; i<=to;) setQuick(i++,val); \r\n}",
"private void refreshInstance(Object cachedInstance, Identity oid, ClassDescriptor cld)\n {\n // read in fresh copy from the db, but do not cache it\n Object freshInstance = getPlainDBObject(cld, oid);\n\n // update all primitive typed attributes\n FieldDescriptor[] fields = cld.getFieldDescriptions();\n FieldDescriptor fmd;\n PersistentField fld;\n for (int i = 0; i < fields.length; i++)\n {\n fmd = fields[i];\n fld = fmd.getPersistentField();\n fld.set(cachedInstance, fld.get(freshInstance));\n }\n }",
"public void addForeignKeyField(int newId)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(new Integer(newId));\r\n }",
"public void setVec3(String key, float x, float y, float z)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec3(getNative(), key, x, y, z);\n }",
"public static cacheobject[] get(nitro_service service, cacheobject_args args) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private boolean isForGerritHost(HttpRequest request) {\n if (!(request instanceof HttpRequestWrapper)) return false;\n HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();\n if (!(originalRequest instanceof HttpRequestBase)) return false;\n URI uri = ((HttpRequestBase) originalRequest).getURI();\n URI authDataUri = URI.create(authData.getHost());\n if (uri == null || uri.getHost() == null) return false;\n boolean hostEquals = uri.getHost().equals(authDataUri.getHost());\n boolean portEquals = uri.getPort() == authDataUri.getPort();\n return hostEquals && portEquals;\n }"
] |
Find out the scrollable child view from a ViewGroup.
@param viewGroup | [
"private void findScrollView(ViewGroup viewGroup) {\n scrollChild = viewGroup;\n if (viewGroup.getChildCount() > 0) {\n int count = viewGroup.getChildCount();\n View child;\n for (int i = 0; i < count; i++) {\n child = viewGroup.getChildAt(i);\n if (child instanceof AbsListView || child instanceof ScrollView || child instanceof ViewPager || child instanceof WebView) {\n scrollChild = child;\n return;\n }\n }\n }\n }"
] | [
"public static void launchPermissionSettings(Activity activity) {\n Intent intent = new Intent();\n intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n intent.setData(Uri.fromParts(\"package\", activity.getPackageName(), null));\n activity.startActivity(intent);\n }",
"public final void setExceptions(SortedSet<Date> dates) {\n\n m_exceptions.clear();\n if (null != dates) {\n m_exceptions.addAll(dates);\n }\n\n }",
"public static Span prefix(Bytes rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n Bytes fp = followingPrefix(rowPrefix);\n return new Span(rowPrefix, true, fp == null ? Bytes.EMPTY : fp, false);\n }",
"public static lbvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_appflowpolicy_binding obj = new lbvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_appflowpolicy_binding response[] = (lbvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }",
"public final void setValue(String value) {\n\n if ((null == value) || value.isEmpty()) {\n setDefaultValue();\n } else {\n try {\n tryToSetParsedValue(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n CmsDebugLog.consoleLog(\"Could not set invalid serial date value: \" + value);\n setDefaultValue();\n }\n }\n notifyOnValueChange();\n }",
"public List<CmsUser> getVisibleUser() {\n\n if (!m_fullyLoaded) {\n return m_users;\n }\n if (size() == m_users.size()) {\n return m_users;\n }\n List<CmsUser> directs = new ArrayList<CmsUser>();\n for (CmsUser user : m_users) {\n if (!m_indirects.contains(user)) {\n directs.add(user);\n }\n }\n return directs;\n }",
"public ServerRedirect updateServerRedirectHost(int serverMappingId, String hostHeader) {\n ServerRedirect redirect = new ServerRedirect();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"hostHeader\", hostHeader),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVER + \"/\" + serverMappingId + \"/host\", params));\n redirect = getServerRedirectFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return redirect;\n }",
"public static double Sinc(double x) {\r\n return Math.sin(Math.PI * x) / (Math.PI * x);\r\n }"
] |
Private helper method which decodes the Stitch error from the body of an HTTP `Response`
object. If the error is successfully decoded, this function will throw the error for the end
user to eventually consume. If the error cannot be decoded, this is likely not an error from
the Stitch server, and this function will return an error message that the calling function
should use as the message of a StitchServiceException with an unknown code. | [
"private static String handleRichError(final Response response, final String body) {\n if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)\n || !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {\n return body;\n }\n\n final Document doc;\n try {\n doc = BsonUtils.parseValue(body, Document.class);\n } catch (Exception e) {\n return body;\n }\n\n if (!doc.containsKey(Fields.ERROR)) {\n return body;\n }\n final String errorMsg = doc.getString(Fields.ERROR);\n if (!doc.containsKey(Fields.ERROR_CODE)) {\n return errorMsg;\n }\n\n final String errorCode = doc.getString(Fields.ERROR_CODE);\n throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));\n }"
] | [
"private void checkLocking(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);\r\n\r\n if (!\"TIMESTAMP\".equals(jdbcType) && !\"INTEGER\".equals(jdbcType))\r\n {\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_LOCKING, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has locking set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UPDATE_LOCK, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has update-lock set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n }\r\n }",
"public static String toJson(Date date) {\n if (date == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(date, buffer);\n\n return buffer.toString();\n }",
"private List<DomainControllerData> readFromFile(String directoryName) {\n List<DomainControllerData> data = new ArrayList<DomainControllerData>();\n if (directoryName == null) {\n return data;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n directoryName = parsedPut.getPrefix();\n }\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n GetResponse val = conn.get(location, key, null);\n if (val.object != null) {\n byte[] buf = val.object.data;\n if (buf != null && buf.length > 0) {\n try {\n data = S3Util.domainControllerDataFromByteBuffer(buf);\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData();\n }\n }\n }\n return data;\n } catch (IOException e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3File(e.getLocalizedMessage());\n }\n }",
"public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }",
"public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\taddDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);\n\t}",
"public static List<CompiledAutomaton> createAutomata(String prefix,\n String regexp, Map<String, Automaton> automatonMap) throws IOException {\n List<CompiledAutomaton> list = new ArrayList<>();\n Automaton automatonRegexp = null;\n if (regexp != null) {\n RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + \"\\u0000*\");\n automatonRegexp = re.toAutomaton();\n }\n int step = 500;\n List<String> keyList = new ArrayList<>(automatonMap.keySet());\n for (int i = 0; i < keyList.size(); i += step) {\n int localStep = step;\n boolean success = false;\n CompiledAutomaton compiledAutomaton = null;\n while (!success) {\n success = true;\n int next = Math.min(keyList.size(), i + localStep);\n List<Automaton> listAutomaton = new ArrayList<>();\n for (int j = i; j < next; j++) {\n listAutomaton.add(automatonMap.get(keyList.get(j)));\n }\n Automaton automatonList = Operations.union(listAutomaton);\n Automaton automaton;\n if (automatonRegexp != null) {\n automaton = Operations.intersection(automatonList, automatonRegexp);\n } else {\n automaton = automatonList;\n }\n try {\n compiledAutomaton = new CompiledAutomaton(automaton);\n } catch (TooComplexToDeterminizeException e) {\n log.debug(e);\n success = false;\n if (localStep > 1) {\n localStep /= 2;\n } else {\n throw new IOException(\"TooComplexToDeterminizeException\");\n }\n }\n }\n list.add(compiledAutomaton);\n }\n return list;\n }",
"public static base_response update(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy updateresource = new dospolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.qdepth = resource.qdepth;\n\t\tupdateresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn updateresource.update_resource(client);\n\t}",
"@Override\n public boolean visit(VariableDeclarationStatement node)\n {\n for (int i = 0; i < node.fragments().size(); ++i)\n {\n String nodeType = node.getType().toString();\n VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i);\n state.getNames().add(frag.getName().getIdentifier());\n state.getNameInstance().put(frag.getName().toString(), nodeType.toString());\n }\n\n processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION,\n compilationUnit.getLineNumber(node.getStartPosition()),\n compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString());\n return super.visit(node);\n }",
"private Point parsePoint(String point) {\n int comma = point.indexOf(',');\n if (comma == -1)\n return null;\n\n float lat = Float.valueOf(point.substring(0, comma));\n float lng = Float.valueOf(point.substring(comma + 1));\n return spatialctx.makePoint(lng, lat);\n }"
] |
Returns the "short rate" from timeIndex to timeIndex+1.
@param timeIndex The time index (corresponding to {@link getTime()).
@return The "short rate" from timeIndex to timeIndex+1.
@throws CalculationException Thrown if simulation failed. | [
"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}"
] | [
"private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}",
"public static Properties loadProperties(String[] filesToLoad)\n {\n Properties p = new Properties();\n InputStream fis = null;\n for (String path : filesToLoad)\n {\n try\n {\n fis = Db.class.getClassLoader().getResourceAsStream(path);\n if (fis != null)\n {\n p.load(fis);\n jqmlogger.info(\"A jqm.properties file was found at {}\", path);\n }\n }\n catch (IOException e)\n {\n // We allow no configuration files, but not an unreadable configuration file.\n throw new DatabaseException(\"META-INF/jqm.properties file is invalid\", e);\n }\n finally\n {\n closeQuietly(fis);\n }\n }\n\n // Overload the datasource name from environment variable if any (tests only).\n String dbName = System.getenv(\"DB\");\n if (dbName != null)\n {\n p.put(\"com.enioka.jqm.jdbc.datasource\", \"jdbc/\" + dbName);\n }\n\n // Done\n return p;\n }",
"public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }",
"public ResourceAssignment addResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = getExistingResourceAssignment(resource);\n\n if (assignment == null)\n {\n assignment = new ResourceAssignment(getParentFile(), this);\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n assignment.setTaskUniqueID(getUniqueID());\n assignment.setWork(getDuration());\n assignment.setUnits(ResourceAssignment.DEFAULT_UNITS);\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n }\n\n return (assignment);\n }",
"public static sslservicegroup_sslcertkey_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tsslservicegroup_sslcertkey_binding obj = new sslservicegroup_sslcertkey_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tsslservicegroup_sslcertkey_binding response[] = (sslservicegroup_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private MapRow getRow(int index)\n {\n MapRow result;\n\n if (index == m_rows.size())\n {\n result = new MapRow(this, new HashMap<FastTrackField, Object>());\n m_rows.add(result);\n }\n else\n {\n result = m_rows.get(index);\n }\n\n return result;\n }",
"protected void print(String text) {\n String tableStart = format(PARAMETER_TABLE_START, PARAMETER_TABLE_START);\n String tableEnd = format(PARAMETER_TABLE_END, PARAMETER_TABLE_END);\n boolean containsTable = text.contains(tableStart) && text.contains(tableEnd);\n String textToPrint = containsTable ? transformPrintingTable(text, tableStart, tableEnd) : text;\n print(output, textToPrint\n .replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format(\"parameterValueStart\", EMPTY))\n .replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format(\"parameterValueEnd\", EMPTY))\n .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format(\"parameterValueNewline\", NL)));\n }",
"public DateRange getRange(int index)\n {\n DateRange result;\n\n if (index >= 0 && index < m_ranges.size())\n {\n result = m_ranges.get(index);\n }\n else\n {\n result = DateRange.EMPTY_RANGE;\n }\n\n return (result);\n }",
"public void add( int row , int col , double value ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds\");\n }\n\n data[ row * numCols + col ] += value;\n }"
] |
Collect the total times measured by all known named timers of the given
name. This is useful to add up times that were collected across separate
threads.
@param timerName
@return timer | [
"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 addNotBetween(Object attribute, Object value1, Object value2)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }",
"public static void writeErrorResponse(MessageEvent messageEvent,\n HttpResponseStatus status,\n String message) {\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);\n response.setHeader(CONTENT_TYPE, \"text/plain; charset=UTF-8\");\n response.setContent(ChannelBuffers.copiedBuffer(\"Failure: \" + status.toString() + \". \"\n + message + \"\\r\\n\", CharsetUtil.UTF_8));\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n messageEvent.getChannel().write(response);\n }",
"private PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>\n getMatchedDestination(List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations,\n HttpMethod targetHttpMethod, String requestUri) {\n\n LOG.trace(\"Routable destinations for request {}: {}\", requestUri, routableDestinations);\n Iterable<String> requestUriParts = splitAndOmitEmpty(requestUri, '/');\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = new ArrayList<>();\n long maxScore = 0;\n\n for (PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> destination : routableDestinations) {\n HttpResourceModel resourceModel = destination.getDestination();\n\n for (HttpMethod httpMethod : resourceModel.getHttpMethod()) {\n if (targetHttpMethod.equals(httpMethod)) {\n long score = getWeightedMatchScore(requestUriParts, splitAndOmitEmpty(resourceModel.getPath(), '/'));\n LOG.trace(\"Max score = {}. Weighted score for {} is {}. \", maxScore, destination, score);\n if (score > maxScore) {\n maxScore = score;\n matchedDestinations.clear();\n matchedDestinations.add(destination);\n } else if (score == maxScore) {\n matchedDestinations.add(destination);\n }\n }\n }\n }\n\n if (matchedDestinations.size() > 1) {\n throw new IllegalStateException(String.format(\"Multiple matched handlers found for request uri %s: %s\",\n requestUri, matchedDestinations));\n } else if (matchedDestinations.size() == 1) {\n return matchedDestinations.get(0);\n }\n return null;\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {\n d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());\n\n if (start == null || end == null) {\n return false;\n }\n\n if (start.before(end) && (!(d.after(start) && d.before(end)))) {\n return false;\n }\n\n if (end.before(start) && (!(d.after(end) || d.before(start)))) {\n return false;\n }\n return true;\n }",
"@Override\n public void solve(DMatrixRBlock B, DMatrixRBlock X) {\n if( B.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in B.\");\n\n DSubmatrixD1 L = new DSubmatrixD1(decomposer.getT(null));\n\n if( X != null ) {\n if( X.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in X.\");\n if( X.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in X\");\n }\n \n if( B.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in B\");\n\n // L * L^T*X = B\n\n // Solve for Y: L*Y = B\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),false);\n\n // L^T * X = Y\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),true);\n\n if( X != null ) {\n // copy the solution from B into X\n MatrixOps_DDRB.extractAligned(B,X);\n }\n\n }",
"public static void checkFloatNotNaNOrInfinity(String parameterName,\n float data) {\n if (Float.isNaN(data) || Float.isInfinite(data)) {\n throw Exceptions.IllegalArgument(\n \"%s should never be NaN or Infinite.\", parameterName);\n }\n }",
"private void addTransformInterceptors(List<Interceptor<?>> inInterceptors,\n List<Interceptor<?>> outInterceptors,\n boolean newClient) {\n \n // The old service expects the Customer data be qualified with\n // the 'http://customer/v1' namespace.\n \n // The new service expects the Customer data be qualified with\n // the 'http://customer/v2' namespace.\n \n // If it is an old client talking to the new service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v1' qualified data be transformed into\n // 'http://customer/v2' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v2' qualified response data be transformed into\n // 'http://customer/v1' qualified data.\n \n // If it is a new client talking to the old service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v2' qualified data be transformed into\n // 'http://customer/v1' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v1' qualified response data be transformed into\n // 'http://customer/v2' qualified data.\n // - new Customer type also introduces a briefDescription property\n // which needs to be dropped for the old service validation to succeed\n \n \n // this configuration can be provided externally\n \n Map<String, String> newToOldTransformMap = new HashMap<String, String>();\n newToOldTransformMap.put(\"{http://customer/v2}*\", \"{http://customer/v1}*\");\n Map<String, String> oldToNewTransformMap = \n Collections.singletonMap(\"{http://customer/v1}*\", \"{http://customer/v2}*\");\n \n TransformOutInterceptor outTransform = new TransformOutInterceptor();\n outTransform.setOutTransformElements(newClient ? newToOldTransformMap \n : oldToNewTransformMap);\n \n if (newClient) {\n newToOldTransformMap.put(\"{http://customer/v2}briefDescription\", \"\");\n //outTransform.setOutDropElements(\n // Collections.singletonList(\"{http://customer/v2}briefDescription\")); \n }\n \n TransformInInterceptor inTransform = new TransformInInterceptor();\n inTransform.setInTransformElements(newClient ? oldToNewTransformMap \n : newToOldTransformMap);\n\n inInterceptors.add(inTransform);\n outInterceptors.add(outTransform);\n \n \n }",
"private boolean isInInnerCircle(float x, float y) {\n return GearWearableUtility.isInCircle(x, y, CENTER_X, CENTER_Y, INNER_RADIUS);\n }",
"public static PersistenceStrategy<?, ?, ?> getInstance(\n\t\t\tCacheMappingType cacheMapping,\n\t\t\tEmbeddedCacheManager externalCacheManager,\n\t\t\tURL configurationUrl,\n\t\t\tJtaPlatform jtaPlatform,\n\t\t\tSet<EntityKeyMetadata> entityTypes,\n\t\t\tSet<AssociationKeyMetadata> associationTypes,\n\t\t\tSet<IdSourceKeyMetadata> idSourceTypes ) {\n\n\t\tif ( cacheMapping == CacheMappingType.CACHE_PER_KIND ) {\n\t\t\treturn getPerKindStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\treturn getPerTableStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform,\n\t\t\t\t\tentityTypes,\n\t\t\t\t\tassociationTypes,\n\t\t\t\t\tidSourceTypes\n\t\t\t);\n\t\t}\n\t}"
] |
Find and unmarshal all test suite files in given directories.
@throws IOException if any occurs.
@see #unmarshal(File) | [
"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 }"
] | [
"public static base_response add(nitro_service client, vpnclientlessaccesspolicy resource) throws Exception {\n\t\tvpnclientlessaccesspolicy addresource = new vpnclientlessaccesspolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\treturn addresource.add_resource(client);\n\t}",
"private static Clique valueOfHelper(int[] relativeIndices) {\r\n // if clique already exists, return that one\r\n Clique c = new Clique();\r\n c.relativeIndices = relativeIndices;\r\n return intern(c);\r\n }",
"public static DoubleMatrix expm(DoubleMatrix A) {\n // constants for pade approximation\n final double c0 = 1.0;\n final double c1 = 0.5;\n final double c2 = 0.12;\n final double c3 = 0.01833333333333333;\n final double c4 = 0.0019927536231884053;\n final double c5 = 1.630434782608695E-4;\n final double c6 = 1.0351966873706E-5;\n final double c7 = 5.175983436853E-7;\n final double c8 = 2.0431513566525E-8;\n final double c9 = 6.306022705717593E-10;\n final double c10 = 1.4837700484041396E-11;\n final double c11 = 2.5291534915979653E-13;\n final double c12 = 2.8101705462199615E-15;\n final double c13 = 1.5440497506703084E-17;\n\n int j = Math.max(0, 1 + (int) Math.floor(Math.log(A.normmax()) / Math.log(2)));\n DoubleMatrix As = A.div((double) Math.pow(2, j)); // scaled version of A\n int n = A.getRows();\n\n // calculate D and N using special Horner techniques\n DoubleMatrix As_2 = As.mmul(As);\n DoubleMatrix As_4 = As_2.mmul(As_2);\n DoubleMatrix As_6 = As_4.mmul(As_2);\n // U = c0*I + c2*A^2 + c4*A^4 + (c6*I + c8*A^2 + c10*A^4 + c12*A^6)*A^6\n DoubleMatrix U = DoubleMatrix.eye(n).muli(c0).addi(As_2.mul(c2)).addi(As_4.mul(c4)).addi(\n DoubleMatrix.eye(n).muli(c6).addi(As_2.mul(c8)).addi(As_4.mul(c10)).addi(As_6.mul(c12)).mmuli(As_6));\n // V = c1*I + c3*A^2 + c5*A^4 + (c7*I + c9*A^2 + c11*A^4 + c13*A^6)*A^6\n DoubleMatrix V = DoubleMatrix.eye(n).muli(c1).addi(As_2.mul(c3)).addi(As_4.mul(c5)).addi(\n DoubleMatrix.eye(n).muli(c7).addi(As_2.mul(c9)).addi(As_4.mul(c11)).addi(As_6.mul(c13)).mmuli(As_6));\n\n DoubleMatrix AV = As.mmuli(V);\n DoubleMatrix N = U.add(AV);\n DoubleMatrix D = U.subi(AV);\n\n // solve DF = N for F\n DoubleMatrix F = Solve.solve(D, N);\n\n // now square j times\n for (int k = 0; k < j; k++) {\n F.mmuli(F);\n }\n\n return F;\n }",
"public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }",
"protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }",
"public static authenticationldappolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationldappolicy_authenticationvserver_binding obj = new authenticationldappolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationldappolicy_authenticationvserver_binding response[] = (authenticationldappolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static appfwlearningsettings[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public synchronized void setSendingStatus(boolean send) throws IOException {\n if (isSendingStatus() == send) {\n return;\n }\n\n if (send) { // Start sending status packets.\n ensureRunning();\n if ((getDeviceNumber() < 1) || (getDeviceNumber() > 4)) {\n throw new IllegalStateException(\"Can only send status when using a standard player number, 1 through 4.\");\n }\n\n BeatFinder.getInstance().start();\n BeatFinder.getInstance().addLifecycleListener(beatFinderLifecycleListener);\n\n final AtomicBoolean stillRunning = new AtomicBoolean(true);\n sendingStatus = stillRunning; // Allow other threads to stop us when necessary.\n\n Thread sender = new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (stillRunning.get()) {\n sendStatus();\n try {\n Thread.sleep(getStatusInterval());\n } catch (InterruptedException e) {\n logger.warn(\"beat-link VirtualCDJ status sender thread was interrupted; continuing\");\n }\n }\n }\n }, \"beat-link VirtualCdj status sender\");\n sender.setDaemon(true);\n sender.start();\n\n if (isSynced()) { // If we are supposed to be synced, we need to respond to master beats and tempo changes.\n addMasterListener(ourSyncMasterListener);\n }\n\n if (isPlaying()) { // Start the beat sender too, if we are supposed to be playing.\n beatSender.set(new BeatSender(metronome));\n }\n } else { // Stop sending status packets, and responding to master beats and tempo changes if we were synced.\n BeatFinder.getInstance().removeLifecycleListener(beatFinderLifecycleListener);\n removeMasterListener(ourSyncMasterListener);\n\n sendingStatus.set(false); // Stop the status sending thread.\n sendingStatus = null; // Indicate that we are no longer sending status.\n final BeatSender activeSender = beatSender.get(); // And stop the beat sender if we have one.\n if (activeSender != null) {\n activeSender.shutDown();\n beatSender.set(null);\n }\n }\n }",
"public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) {\n\n\t\t// Extract factors corresponding to the largest eigenvalues\n\t\tdouble[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors);\n\n\t\t// Renormalize rows\n\t\tfor (int row = 0; row < correlationMatrix.length; row++) {\n\t\t\tdouble sumSquared = 0;\n\t\t\tfor (int factor = 0; factor < numberOfFactors; factor++) {\n\t\t\t\tsumSquared += factorMatrix[row][factor] * factorMatrix[row][factor];\n\t\t\t}\n\t\t\tif(sumSquared != 0) {\n\t\t\t\tfor (int factor = 0; factor < numberOfFactors; factor++) {\n\t\t\t\t\tfactorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// This is a rare case: The factor reduction of a completely decorrelated system to 1 factor\n\t\t\t\tfor (int factor = 0; factor < numberOfFactors; factor++) {\n\t\t\t\t\tfactorMatrix[row][factor] = 1.0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Orthogonalized again\n\t\tdouble[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData();\n\n\t\treturn getFactorMatrix(reducedCorrelationMatrix, numberOfFactors);\n\t}"
] |
Returns the effective batch size. If the dialect is multiget capable and a batch size has been configured, use
that one, otherwise the default. | [
"private static int determineBatchSize(boolean canGridDialectDoMultiget, int classBatchSize, int configuredDefaultBatchSize) {\n\t\t// if the dialect does not support it, don't batch so that we can avoid skewing the ORM fetch statistics\n\t\tif ( !canGridDialectDoMultiget ) {\n\t\t\treturn -1;\n\t\t}\n\t\telse if ( classBatchSize != -1 ) {\n\t\t\treturn classBatchSize;\n\t\t}\n\t\telse if ( configuredDefaultBatchSize != -1 ) {\n\t\t\treturn configuredDefaultBatchSize;\n\t\t}\n\t\telse {\n\t\t\treturn DEFAULT_MULTIGET_BATCH_SIZE;\n\t\t}\n\t}"
] | [
"private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }",
"public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }",
"private void createResults(List<ISuite> suites,\n File outputDirectory,\n boolean onlyShowFailures) throws Exception\n {\n int index = 1;\n for (ISuite suite : suites)\n {\n int index2 = 1;\n for (ISuiteResult result : suite.getResults().values())\n {\n boolean failuresExist = result.getTestContext().getFailedTests().size() > 0\n || result.getTestContext().getFailedConfigurations().size() > 0;\n if (!onlyShowFailures || failuresExist)\n {\n VelocityContext context = createContext();\n context.put(RESULT_KEY, result);\n context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));\n context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));\n context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));\n context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));\n context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));\n String fileName = String.format(\"suite%d_test%d_%s\", index, index2, RESULTS_FILE);\n generateFile(new File(outputDirectory, fileName),\n RESULTS_FILE + TEMPLATE_EXTENSION,\n context);\n }\n ++index2;\n }\n ++index;\n }\n }",
"public Duration getDuration(Date startDate, Date endDate)\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n int days = getDaysInRange(startDate, endDate);\n int duration = 0;\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n\n while (days > 0)\n {\n if (isWorkingDate(cal.getTime(), day) == true)\n {\n ++duration;\n }\n\n --days;\n day = day.getNextDay();\n cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);\n }\n DateHelper.pushCalendar(cal);\n \n return (Duration.getInstance(duration, TimeUnit.DAYS));\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 }",
"@UiThread\n public int getChildAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getChildPosition(flatPosition);\n }",
"public <T> T convert(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\ttry {\r\n\t\t\treturn (T) multiConverter.convert(context, source, destinationType);\r\n\t\t} catch (ConverterException e) {\r\n\t\t\tthrow e;\r\n\t\t} catch (Exception e) {\r\n\t\t\t// There is a problem with one converter. This should not happen.\r\n\t\t\t// Either there is a bug in this converter or it is not properly\r\n\t\t\t// configured\r\n\t\t\tthrow new ConverterException(\r\n\t\t\t\t\tMessageFormat\r\n\t\t\t\t\t\t\t.format(\r\n\t\t\t\t\t\t\t\t\t\"Could not convert given object with class ''{0}'' to object with type signature ''{1}''\",\r\n\t\t\t\t\t\t\t\t\tsource == null ? \"null\" : source.getClass()\r\n\t\t\t\t\t\t\t\t\t\t\t.getName(), destinationType), e);\r\n\t\t}\r\n\t}",
"public static void logLong(String TAG, String longString) {\n InputStream is = new ByteArrayInputStream( longString.getBytes() );\n @SuppressWarnings(\"resource\")\n Scanner scan = new Scanner(is);\n while (scan.hasNextLine()) {\n Log.v(TAG, scan.nextLine());\n }\n }",
"public static String readTextFile(Context context, String asset) {\n try {\n InputStream inputStream = context.getAssets().open(asset);\n return org.gearvrf.utility.TextFile.readTextFile(inputStream);\n } catch (FileNotFoundException f) {\n Log.w(TAG, \"readTextFile(): asset file '%s' doesn't exist\", asset);\n } catch (IOException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"readTextFile()\");\n }\n return null;\n }"
] |
Returns the title according to the given locale.
@param locale the locale for which the title should be read.
@return the title according to the given locale | [
"protected String getLocaleSpecificTitle(Locale locale) {\n\n String result = null;\n\n try {\n\n if (isDetailRequest()) {\n // this is a request to a detail page\n CmsResource res = getDetailContent();\n CmsFile file = m_cms.readFile(res);\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale());\n if (result == null) {\n // title not found, maybe no mapping OR not available in the current locale\n // read the title of the detail resource as fall back (may contain mapping from another locale)\n result = m_cms.readPropertyObject(\n res,\n CmsPropertyDefinition.PROPERTY_TITLE,\n false,\n locale).getValue();\n }\n }\n if (result == null) {\n // read the title of the requested resource as fall back\n result = m_cms.readPropertyObject(\n m_cms.getRequestContext().getUri(),\n CmsPropertyDefinition.PROPERTY_TITLE,\n true,\n locale).getValue();\n }\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {\n result = \"\";\n }\n\n return result;\n }"
] | [
"public RuntimeParameter addParameter(String key, String value)\n {\n RuntimeParameter jp = new RuntimeParameter();\n jp.setJi(this.getId());\n jp.setKey(key);\n jp.setValue(value);\n return jp;\n }",
"private IndexedContainer createContainerForBundleWithDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(Descriptor.N_MESSAGE, Descriptor.LOCALE);\n String descValue;\n boolean hasDescription = false;\n String defaultValue;\n boolean hasDefault = false;\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n String translation = localization.getProperty(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n descValue = m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(descValue);\n hasDescription = hasDescription || !descValue.isEmpty();\n defaultValue = m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DEFAULT).setValue(defaultValue);\n hasDefault = hasDefault || !defaultValue.isEmpty();\n }\n\n m_hasDefault = hasDefault;\n m_hasDescription = hasDescription;\n return container;\n\n }",
"protected Boolean getEscapeQueryChars() {\n\n Boolean isEscape = parseOptionalBooleanValue(m_configObject, JSON_KEY_ESCAPE_QUERY_CHARACTERS);\n return (null == isEscape) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getEscapeQueryChars())\n : isEscape;\n }",
"public static Class getClass(String className, boolean initialize) throws ClassNotFoundException\r\n {\r\n return Class.forName(className, initialize, getClassLoader());\r\n }",
"public static void append(File file, Writer writer, String charset) throws IOException {\n appendBuffered(file, writer, charset);\n }",
"protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public B importContext(AbstractContext context, boolean overwriteDuplicates){\n for (Map.Entry<String, Object> en : context.data.entrySet()) {\n if (overwriteDuplicates) {\n this.data.put(en.getKey(), en.getValue());\n }else{\n this.data.putIfAbsent(en.getKey(), en.getValue());\n }\n }\n return (B) this;\n }",
"static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }",
"protected void parseSequencesWithColons(TokenList tokens , Sequence sequence ) {\n\n TokenList.Token t = tokens.getFirst();\n if( t == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token middle = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) && (t.next != null && t.next.getSymbol() == Symbol.COLON) ) {\n start = t;\n state = 1;\n t = t.next;\n } else if( t != null && t.getSymbol() == Symbol.COLON ) {\n // If it starts with a colon then it must be 'all' or a type-o\n IntegerSequence range = new IntegerSequence.Range(null,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n TokenList.Token n = new TokenList.Token(varSequence);\n tokens.insert(t.previous, n);\n tokens.remove(t);\n t = n;\n }\n } else if( state == 1 ) {\n // var : ?\n if (isVariableInteger(t)) {\n state = 2;\n } else {\n // array range\n IntegerSequence range = new IntegerSequence.Range(start,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n } else if ( state == 2 ) {\n // var:var ?\n if( t != null && t.getSymbol() == Symbol.COLON ) {\n middle = prev;\n state = 3;\n } else {\n // create for sequence with start and stop elements only\n IntegerSequence numbers = new IntegerSequence.For(start,null,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev );\n if( t != null )\n t = t.previous;\n state = 0;\n }\n } else if ( state == 3 ) {\n // var:var: ?\n if( isVariableInteger(t) ) {\n // create 'for' sequence with three variables\n IntegerSequence numbers = new IntegerSequence.For(start,middle,t);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n t = replaceSequence(tokens, varSequence, start, t);\n } else {\n // array range with 2 elements\n IntegerSequence numbers = new IntegerSequence.Range(start,middle);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev);\n }\n state = 0;\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }"
] |
The Baseline Start field shows the planned beginning date for a task at
the time you saved a baseline. Information in this field becomes available
when you set a baseline.
@return Date | [
"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 }"
] | [
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"@Override\n public final Double optDouble(final String key, final Double defaultValue) {\n Double result = optDouble(key);\n return result == null ? defaultValue : result;\n }",
"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 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 History[] filterHistory(String... filters) throws Exception {\n BasicNameValuePair[] params;\n if (filters.length > 0) {\n params = new BasicNameValuePair[filters.length];\n for (int i = 0; i < filters.length; i++) {\n params[i] = new BasicNameValuePair(\"source_uri[]\", filters[i]);\n }\n } else {\n return refreshHistory();\n }\n\n return constructHistory(params);\n }",
"public static void compress(File dir, File zipFile) throws IOException {\n\n FileOutputStream fos = new FileOutputStream(zipFile);\n ZipOutputStream zos = new ZipOutputStream(fos);\n\n recursiveAddZip(dir, zos, dir);\n\n zos.finish();\n zos.close();\n\n }",
"public DocumentReaderAndWriter<IN> makePlainTextReaderAndWriter() {\r\n String readerClassName = flags.plainTextDocumentReaderAndWriter;\r\n // We set this default here if needed because there may be models\r\n // which don't have the reader flag set\r\n if (readerClassName == null) {\r\n readerClassName = SeqClassifierFlags.DEFAULT_PLAIN_TEXT_READER;\r\n }\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>) Class.forName(readerClassName).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.plainTextDocumentReaderAndWriter: '%s'\", flags.plainTextDocumentReaderAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }",
"public void setFieldByAlias(String alias, Object value)\n {\n set(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias), value);\n }",
"protected Object checkUndefined(Object val) {\n if (val instanceof String && ((String) val).equals(\"undefined\")) {\n return null;\n }\n return val;\n }"
] |
This method removes line breaks from a piece of text, and replaces
them with the supplied text.
@param text source text
@param replacement line break replacement text
@return text with line breaks removed. | [
"private String stripLineBreaks(String text, String replacement)\n {\n if (text.indexOf('\\r') != -1 || text.indexOf('\\n') != -1)\n {\n StringBuilder sb = new StringBuilder(text);\n\n int index;\n\n while ((index = sb.indexOf(\"\\r\\n\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\\r\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\r\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n text = sb.toString();\n }\n\n return (text);\n }"
] | [
"@SuppressWarnings(\"unchecked\") public final List<MapRow> getRows(String name)\n {\n return (List<MapRow>) getObject(name);\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 }",
"private String quoteFormatCharacters(String literal)\n {\n StringBuilder sb = new StringBuilder();\n int length = literal.length();\n char c;\n\n for (int loop = 0; loop < length; loop++)\n {\n c = literal.charAt(loop);\n switch (c)\n {\n case '0':\n case '#':\n case '.':\n case '-':\n case ',':\n case 'E':\n case ';':\n case '%':\n {\n sb.append(\"'\");\n sb.append(c);\n sb.append(\"'\");\n break;\n }\n\n default:\n {\n sb.append(c);\n break;\n }\n }\n }\n\n return (sb.toString());\n }",
"public static String getDefaultJdbcTypeFor(String javaType)\r\n {\r\n return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE;\r\n }",
"public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"@Override\n\tpublic void addExtraState(EntityEntryExtraState extraState) {\n\t\tif ( next == null ) {\n\t\t\tnext = extraState;\n\t\t}\n\t\telse {\n\t\t\tnext.addExtraState( extraState );\n\t\t}\n\t}",
"public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException {\n try (DataOutputStream dataStream = new DataOutputStream(stream)) {\n int len = str.length();\n if (len < SINGLE_UTF_CHUNK_SIZE) {\n dataStream.writeUTF(str);\n } else {\n int startIndex = 0;\n int endIndex;\n do {\n endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE;\n if (endIndex > len) {\n endIndex = len;\n }\n dataStream.writeUTF(str.substring(startIndex, endIndex));\n startIndex += SINGLE_UTF_CHUNK_SIZE;\n } while (endIndex < len);\n }\n }\n }",
"public static File createDir(String dir) {\n // create outdir\n File directory = null;\n if(dir != null) {\n directory = new File(dir);\n if(!(directory.exists() || directory.mkdir())) {\n Utils.croak(\"Can't find or create directory \" + dir);\n }\n }\n return directory;\n }",
"public String getURN() throws InvalidRegistrationContentException {\n if (parsedConfig==null || parsedConfig.urn==null || parsedConfig.urn.trim().isEmpty()) {\n throw new InvalidRegistrationContentException(\"Invalid registration config - failed to read mediator URN\");\n }\n return parsedConfig.urn;\n }"
] |
Create an error image.
@param area The size of the image | [
"protected BufferedImage createErrorImage(final Rectangle area) {\n final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);\n final Graphics2D graphics = bufferedImage.createGraphics();\n try {\n graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));\n graphics.clearRect(0, 0, area.width, area.height);\n return bufferedImage;\n } finally {\n graphics.dispose();\n }\n }"
] | [
"public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }",
"public AsciiTable setPaddingTop(int paddingTop) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void decreaseIndent() throws IOException\n {\n if (m_pretty)\n {\n m_writer.write('\\n');\n m_indent = m_indent.substring(0, m_indent.length() - INDENT.length());\n m_writer.write(m_indent);\n }\n m_firstNameValuePair.pop();\n }",
"public static ProjectReader getProjectReader(String name) throws MPXJException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectReader> fileClass = READER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot read files of type: \" + extension);\n }\n\n try\n {\n ProjectReader file = fileClass.newInstance();\n return (file);\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to load project reader\", ex);\n }\n }",
"public static final BigDecimal printDurationInDecimalThousandthsOfMinutes(Duration duration)\n {\n BigDecimal result = null;\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigDecimal.valueOf(printDurationFractionsOfMinutes(duration, 1000));\n }\n return result;\n }",
"private Renderer createRenderer(T content, ViewGroup parent) {\n int prototypeIndex = getPrototypeIndex(content);\n Renderer renderer = getPrototypeByIndex(prototypeIndex).copy();\n renderer.onCreate(content, layoutInflater, parent);\n return renderer;\n }",
"public static Object invoke(Object object, String methodName, Object[] parameters) {\n try {\n Class[] classTypes = new Class[parameters.length];\n for (int i = 0; i < classTypes.length; i++) {\n classTypes[i] = parameters[i].getClass();\n }\n Method method = object.getClass().getMethod(methodName, classTypes);\n return method.invoke(object, parameters);\n } catch (Throwable t) {\n return InvokerHelper.invokeMethod(object, methodName, parameters);\n }\n }",
"public static void startTrack(final Object... args){\r\n if(isClosed){ return; }\r\n //--Create Record\r\n final int len = args.length == 0 ? 0 : args.length-1;\r\n final Object content = args.length == 0 ? \"\" : args[len];\r\n final Object[] tags = new Object[len];\r\n final StackTraceElement ste = getStackTrace();\r\n final long timestamp = System.currentTimeMillis();\r\n System.arraycopy(args,0,tags,0,len);\r\n //--Create Task\r\n final long threadID = Thread.currentThread().getId();\r\n final Runnable startTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n Record toPass = new Record(content,tags,depth,ste,timestamp);\r\n depth += 1;\r\n titleStack.push(args.length == 0 ? \"\" : args[len].toString());\r\n handlers.process(toPass, MessageType.START_TRACK, depth, toPass.timesstamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, startTrack );\r\n } else {\r\n //(case: no threading)\r\n startTrack.run();\r\n }\r\n }",
"public void shutdown() {\n final Connection connection;\n synchronized (this) {\n if(shutdown) return;\n shutdown = true;\n connection = this.connection;\n if(connectTask != null) {\n connectTask.shutdown();\n }\n }\n if (connection != null) {\n connection.closeAsync();\n }\n }"
] |
Ranks a map based on integer values
@param inputMap Input
@return The ranked map | [
"public static <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) {\n Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap));\n newMap.putAll(inputMap);\n\n Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap);\n return linkedMap;\n }"
] | [
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}",
"public static sslcertkey[] get(nitro_service service, String certkey[]) throws Exception{\n\t\tif (certkey !=null && certkey.length>0) {\n\t\t\tsslcertkey response[] = new sslcertkey[certkey.length];\n\t\t\tsslcertkey obj[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++) {\n\t\t\t\tobj[i] = new sslcertkey();\n\t\t\t\tobj[i].set_certkey(certkey[i]);\n\t\t\t\tresponse[i] = (sslcertkey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"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 static byte[] getContentBytes(String stringUrl) throws IOException {\n URL url = new URL(stringUrl);\n byte[] data = MyStreamUtils.readContentBytes(url.openStream());\n return data;\n }",
"public static String workDays(ProjectCalendar input)\n {\n StringBuilder result = new StringBuilder();\n DayType[] test = input.getDays(); // get the array from MPXJ ProjectCalendar\n for (DayType i : test)\n { // go through every day in the given array\n if (i == DayType.NON_WORKING)\n {\n result.append(\"N\"); // only put N for non-working day of the week\n }\n else\n {\n result.append(\"Y\"); // Assume WORKING day unless NON_WORKING\n }\n }\n return result.toString(); // According to USACE specs., exceptions will be specified in HOLI records\n }",
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n for ( int i = 0; i < mEmitRate * 2; i +=2 )\n {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n return timeStamps;\n }",
"public static <T> Set<T> asImmutable(Set<? extends T> self) {\n return Collections.unmodifiableSet(self);\n }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\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 }"
] |
Checks the given field descriptor.
@param fieldDef The field descriptor
@param checkLevel The amount of checks to perform
@exception ConstraintException If a constraint has been violated | [
"public void check(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureColumn(fieldDef, checkLevel);\r\n ensureJdbcType(fieldDef, checkLevel);\r\n ensureConversion(fieldDef, checkLevel);\r\n ensureLength(fieldDef, checkLevel);\r\n ensurePrecisionAndScale(fieldDef, checkLevel);\r\n checkLocking(fieldDef, checkLevel);\r\n checkSequenceName(fieldDef, checkLevel);\r\n checkId(fieldDef, checkLevel);\r\n if (fieldDef.isAnonymous())\r\n {\r\n checkAnonymous(fieldDef, checkLevel);\r\n }\r\n else\r\n {\r\n checkReadonlyAccessForNativePKs(fieldDef, checkLevel);\r\n }\r\n }"
] | [
"public boolean matches(String uri) {\n\t\tif (uri == null) {\n\t\t\treturn false;\n\t\t}\n\t\tMatcher matcher = this.matchPattern.matcher(uri);\n\t\treturn matcher.matches();\n\t}",
"public void postPhoto(Photo photo, String blogId, String blogPassword) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_POST_PHOTO);\r\n\r\n parameters.put(\"blog_id\", blogId);\r\n parameters.put(\"photo_id\", photo.getId());\r\n parameters.put(\"title\", photo.getTitle());\r\n parameters.put(\"description\", photo.getDescription());\r\n if (blogPassword != null) {\r\n parameters.put(\"blog_password\", blogPassword);\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 }",
"static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\n }",
"public static appfwprofile_excluderescontenttype_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_excluderescontenttype_binding obj = new appfwprofile_excluderescontenttype_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_excluderescontenttype_binding response[] = (appfwprofile_excluderescontenttype_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void addOperation(final OperationContext context) {\n RbacSanityCheckOperation added = context.getAttachment(KEY);\n if (added == null) {\n // TODO support managed domain\n if (!context.isNormalServer()) return;\n context.addStep(createOperation(), INSTANCE, Stage.MODEL);\n context.attach(KEY, INSTANCE);\n }\n }",
"public static boolean setCustomResponseForDefaultProfile(String pathName, String customData) {\n try {\n return setCustomForDefaultProfile(pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"@UiHandler(\"m_seriesCheckBox\")\n void onSeriesChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setIsSeries(event.getValue());\n }\n }",
"public Collection<EmailAlias> getEmailAliases() {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject emailAliasJSON = value.asObject();\n emailAliases.add(new EmailAlias(emailAliasJSON));\n }\n\n return emailAliases;\n }",
"protected <C> C convert(Object object, Class<C> targetClass) {\n return this.mapper.convertValue(object, targetClass);\n }"
] |
Use this API to delete appfwlearningdata. | [
"public static base_response delete(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata deleteresource = new appfwlearningdata();\n\t\tdeleteresource.profilename = resource.profilename;\n\t\tdeleteresource.starturl = resource.starturl;\n\t\tdeleteresource.cookieconsistency = resource.cookieconsistency;\n\t\tdeleteresource.fieldconsistency = resource.fieldconsistency;\n\t\tdeleteresource.formactionurl_ffc = resource.formactionurl_ffc;\n\t\tdeleteresource.crosssitescripting = resource.crosssitescripting;\n\t\tdeleteresource.formactionurl_xss = resource.formactionurl_xss;\n\t\tdeleteresource.sqlinjection = resource.sqlinjection;\n\t\tdeleteresource.formactionurl_sql = resource.formactionurl_sql;\n\t\tdeleteresource.fieldformat = resource.fieldformat;\n\t\tdeleteresource.formactionurl_ff = resource.formactionurl_ff;\n\t\tdeleteresource.csrftag = resource.csrftag;\n\t\tdeleteresource.csrfformoriginurl = resource.csrfformoriginurl;\n\t\tdeleteresource.xmldoscheck = resource.xmldoscheck;\n\t\tdeleteresource.xmlwsicheck = resource.xmlwsicheck;\n\t\tdeleteresource.xmlattachmentcheck = resource.xmlattachmentcheck;\n\t\tdeleteresource.totalxmlrequests = resource.totalxmlrequests;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }",
"private void addFoldersToSearchIn(final List<String> folders) {\n\n if (null == folders) {\n return;\n }\n\n for (String folder : folders) {\n if (!CmsResource.isFolder(folder)) {\n folder += \"/\";\n }\n\n m_foldersToSearchIn.add(folder);\n }\n }",
"private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }",
"public static void handleDomainOperationResponseStreams(final OperationContext context,\n final ModelNode responseNode,\n final List<OperationResponse.StreamEntry> streams) {\n\n if (responseNode.hasDefined(RESPONSE_HEADERS)) {\n ModelNode responseHeaders = responseNode.get(RESPONSE_HEADERS);\n // Strip out any stream header as the header created by this process is what counts\n responseHeaders.remove(ATTACHED_STREAMS);\n if (responseHeaders.asInt() == 0) {\n responseNode.remove(RESPONSE_HEADERS);\n }\n }\n\n for (OperationResponse.StreamEntry streamEntry : streams) {\n context.attachResultStream(streamEntry.getUUID(), streamEntry.getMimeType(), streamEntry.getStream());\n }\n }",
"public void check(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureColumn(fieldDef, checkLevel);\r\n ensureJdbcType(fieldDef, checkLevel);\r\n ensureConversion(fieldDef, checkLevel);\r\n ensureLength(fieldDef, checkLevel);\r\n ensurePrecisionAndScale(fieldDef, checkLevel);\r\n checkLocking(fieldDef, checkLevel);\r\n checkSequenceName(fieldDef, checkLevel);\r\n checkId(fieldDef, checkLevel);\r\n if (fieldDef.isAnonymous())\r\n {\r\n checkAnonymous(fieldDef, checkLevel);\r\n }\r\n else\r\n {\r\n checkReadonlyAccessForNativePKs(fieldDef, checkLevel);\r\n }\r\n }",
"private void createAndAddButton(PatternType pattern, String messageKey) {\n\n CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));\n btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());\n btn.setGroup(m_groupPattern);\n m_patternButtons.put(pattern, btn);\n m_patternRadioButtonsPanel.add(btn);\n\n }",
"private <T> void deferNotification(T event, final EventMetadata metadata, final ObserverMethod<? super T> observer,\n final List<DeferredEventNotification<?>> notifications) {\n TransactionPhase transactionPhase = observer.getTransactionPhase();\n boolean before = transactionPhase.equals(TransactionPhase.BEFORE_COMPLETION);\n Status status = Status.valueOf(transactionPhase);\n notifications.add(new DeferredEventNotification<T>(contextId, event, metadata, observer, currentEventMetadata, status, before));\n }",
"public final void configureAccess(final Template template, final ApplicationContext context) {\n final Configuration configuration = template.getConfiguration();\n\n AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);\n accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());\n this.access = accessAssertion;\n }",
"public static base_response add(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy addresource = new spilloverpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.comment = resource.comment;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Checks if class package match provided list of action packages
@param classPackageName
name of class package
@return true if class package is on the {@link #actionPackages} list | [
"protected boolean checkActionPackages(String classPackageName) {\n\t\tif (actionPackages != null) {\n\t\t\tfor (String packageName : actionPackages) {\n\t\t\t\tString strictPackageName = packageName + \".\";\n\t\t\t\tif (classPackageName.equals(packageName) || classPackageName.startsWith(strictPackageName))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}"
] | [
"@AsParameterConverter\n\tpublic Trader retrieveTrader(String name) {\n\t\tfor (Trader trader : traders) {\n\t\t\tif (trader.getName().equals(name)) {\n\t\t\t\treturn trader;\n\t\t\t}\n\t\t}\n\t\treturn mockTradePersister().retrieveTrader(name);\n\t}",
"public static final String printResourceUID(Integer value)\n {\n ProjectFile file = PARENT_FILE.get();\n if (file != null)\n {\n file.getEventManager().fireResourceWrittenEvent(file.getResourceByUniqueID(value));\n }\n return (value.toString());\n }",
"public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }",
"public static boolean promoteAndCheckResponse(Promotion promotion, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber) throws IOException {\n // If failFast is true, perform dry run first\n if (promotion.isFailFast()) {\n promotion.setDryRun(true);\n listener.getLogger().println(\"Performing dry run promotion (no changes are made during dry run) ...\");\n HttpResponse dryResponse = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(dryResponse, true, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully.\\nPerforming promotion ...\");\n }\n\n // Perform promotion\n promotion.setDryRun(false);\n HttpResponse response = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(response, false, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Promotion completed successfully!\");\n\n return true;\n }",
"public void setFullscreen(boolean fullscreen) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setTintStatusBar(!fullscreen);\n mBuilder.mScrimInsetsLayout.setTintNavigationBar(!fullscreen);\n }\n }",
"public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }",
"private void addEdgesForVertex(Vertex vertex)\r\n {\r\n ClassDescriptor cld = vertex.getEnvelope().getClassDescriptor();\r\n Iterator rdsIter = cld.getObjectReferenceDescriptors(true).iterator();\r\n while (rdsIter.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) rdsIter.next();\r\n addObjectReferenceEdges(vertex, rds);\r\n }\r\n Iterator cdsIter = cld.getCollectionDescriptors(true).iterator();\r\n while (cdsIter.hasNext())\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) cdsIter.next();\r\n addCollectionEdges(vertex, cds);\r\n }\r\n }",
"protected List<I_CmsFacetQueryItem> parseFacetQueryItems(final String path) throws Exception {\n\n final List<I_CmsXmlContentValue> values = m_xml.getValues(path, m_locale);\n if (values == null) {\n return null;\n } else {\n List<I_CmsFacetQueryItem> parsedItems = new ArrayList<I_CmsFacetQueryItem>(values.size());\n for (I_CmsXmlContentValue value : values) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(value.getPath() + \"/\");\n if (null != item) {\n parsedItems.add(item);\n } else {\n // TODO: log\n }\n }\n return parsedItems;\n }\n }"
] |
Join a group as a public member.
Note: if a group has rules - the client must display the rules to the user and the user must accept them prior to joining the group. The acceptRules
parameter indicates that the user has accepted those rules.
@param groupId
- the id of the group to join
@param acceptRules
- if a group has rules, true indicates the user has accepted the rules
@see <a href="http://www.flickr.com/services/api/flickr.groups.join.html">flickr.groups.join</a> | [
"public void join(String groupId, Boolean acceptRules) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_JOIN);\r\n parameters.put(\"group_id\", groupId);\r\n if (acceptRules != null) {\r\n parameters.put(\"accept_rules\", acceptRules);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }"
] | [
"private String checkinScriptCommand() {\n\n String exportModules = \"\";\n if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {\n StringBuffer exportModulesParam = new StringBuffer();\n for (String moduleName : m_modulesToExport) {\n exportModulesParam.append(\" \").append(moduleName);\n }\n exportModulesParam.replace(0, 1, \" \\\"\");\n exportModulesParam.append(\"\\\" \");\n exportModules = \" --modules \" + exportModulesParam.toString();\n\n }\n String commitMessage = \"\";\n if (m_commitMessage != null) {\n commitMessage = \" -msg \\\"\" + m_commitMessage.replace(\"\\\"\", \"\\\\\\\"\") + \"\\\"\";\n }\n String gitUserName = \"\";\n if (m_gitUserName != null) {\n if (m_gitUserName.trim().isEmpty()) {\n gitUserName = \" --ignore-default-git-user-name\";\n } else {\n gitUserName = \" --git-user-name \\\"\" + m_gitUserName + \"\\\"\";\n }\n }\n String gitUserEmail = \"\";\n if (m_gitUserEmail != null) {\n if (m_gitUserEmail.trim().isEmpty()) {\n gitUserEmail = \" --ignore-default-git-user-email\";\n } else {\n gitUserEmail = \" --git-user-email \\\"\" + m_gitUserEmail + \"\\\"\";\n }\n }\n String autoPullBefore = \"\";\n if (m_autoPullBefore != null) {\n autoPullBefore = m_autoPullBefore.booleanValue() ? \" --pull-before \" : \" --no-pull-before\";\n }\n String autoPullAfter = \"\";\n if (m_autoPullAfter != null) {\n autoPullAfter = m_autoPullAfter.booleanValue() ? \" --pull-after \" : \" --no-pull-after\";\n }\n String autoPush = \"\";\n if (m_autoPush != null) {\n autoPush = m_autoPush.booleanValue() ? \" --push \" : \" --no-push\";\n }\n String exportFolder = \" --export-folder \\\"\" + m_currentConfiguration.getModuleExportPath() + \"\\\"\";\n String exportMode = \" --export-mode \" + m_currentConfiguration.getExportMode();\n String excludeLibs = \"\";\n if (m_excludeLibs != null) {\n excludeLibs = m_excludeLibs.booleanValue() ? \" --exclude-libs\" : \" --no-exclude-libs\";\n }\n String commitMode = \"\";\n if (m_commitMode != null) {\n commitMode = m_commitMode.booleanValue() ? \" --commit\" : \" --no-commit\";\n }\n String ignoreUncleanMode = \"\";\n if (m_ignoreUnclean != null) {\n ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? \" --ignore-unclean\" : \" --no-ignore-unclean\";\n }\n String copyAndUnzip = \"\";\n if (m_copyAndUnzip != null) {\n copyAndUnzip = m_copyAndUnzip.booleanValue() ? \" --copy-and-unzip\" : \" --no-copy-and-unzip\";\n }\n\n String configFilePath = m_currentConfiguration.getFilePath();\n\n return \"\\\"\"\n + DEFAULT_SCRIPT_FILE\n + \"\\\"\"\n + exportModules\n + commitMessage\n + gitUserName\n + gitUserEmail\n + autoPullBefore\n + autoPullAfter\n + autoPush\n + exportFolder\n + exportMode\n + excludeLibs\n + commitMode\n + ignoreUncleanMode\n + copyAndUnzip\n + \" \\\"\"\n + configFilePath\n + \"\\\"\";\n }",
"public void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }",
"public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\n }",
"private void closeClient(Client client) {\n logger.debug(\"Closing client {}\", client);\n client.close();\n openClients.remove(client.targetPlayer);\n useCounts.remove(client);\n timestamps.remove(client);\n }",
"@Override\n public SuggestAccountsRequest suggestAccounts() throws RestApiException {\n return new SuggestAccountsRequest() {\n @Override\n public List<AccountInfo> get() throws RestApiException {\n return AccountsRestClient.this.suggestAccounts(this);\n }\n };\n }",
"public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(final BoxAPIConnection api,\n final String externalAppUserId, final String... fields) {\n return getUsersInfoForType(api, null, null, externalAppUserId, fields);\n }",
"@UiHandler(\"m_seriesCheckBox\")\n void onSeriesChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setIsSeries(event.getValue());\n }\n }",
"public void setBorderWidth(int borderWidth) {\n\t\tthis.borderWidth = borderWidth;\n\t\tif(paintBorder != null)\n\t\t\tpaintBorder.setStrokeWidth(borderWidth);\n\t\trequestLayout();\n\t\tinvalidate();\n\t}",
"private synchronized void setInitializationMethod(Method newMethod)\r\n {\r\n if (newMethod != null)\r\n {\r\n // make sure it's a no argument method\r\n if (newMethod.getParameterTypes().length > 0)\r\n {\r\n throw new MetadataException(\r\n \"Initialization methods must be zero argument methods: \"\r\n + newMethod.getClass().getName()\r\n + \".\"\r\n + newMethod.getName());\r\n }\r\n\r\n // make it accessible if it's not already\r\n if (!newMethod.isAccessible())\r\n {\r\n newMethod.setAccessible(true);\r\n }\r\n }\r\n this.initializationMethod = newMethod;\r\n }"
] |
Starts this EventStream and begins long polling the API.
@throws IllegalStateException if the EventStream is already started. | [
"public void start() {\n if (this.started) {\n throw new IllegalStateException(\"Cannot start the EventStream because it isn't stopped.\");\n }\n\n final long initialPosition;\n\n if (this.startingPosition == STREAM_POSITION_NOW) {\n BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), \"now\"), \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n initialPosition = jsonObject.get(\"next_stream_position\").asLong();\n } else {\n assert this.startingPosition >= 0 : \"Starting position must be non-negative\";\n initialPosition = this.startingPosition;\n }\n\n this.poller = new Poller(initialPosition);\n\n this.pollerThread = new Thread(this.poller);\n this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n EventStream.this.notifyException(e);\n }\n });\n this.pollerThread.start();\n\n this.started = true;\n }"
] | [
"private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }",
"public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }",
"public boolean measureAll(List<Widget> measuredChildren) {\n boolean changed = false;\n for (int i = 0; i < mContainer.size(); ++i) {\n\n if (!isChildMeasured(i)) {\n Widget child = measureChild(i, false);\n if (child != null) {\n if (measuredChildren != null) {\n measuredChildren.add(child);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n postMeasurement();\n }\n return changed;\n }",
"private DecompilerSettings getDefaultSettings(File outputDir)\n {\n DecompilerSettings settings = new DecompilerSettings();\n procyonConf.setDecompilerSettings(settings);\n settings.setOutputDirectory(outputDir.getPath());\n settings.setShowSyntheticMembers(false);\n settings.setForceExplicitImports(true);\n\n if (settings.getTypeLoader() == null)\n settings.setTypeLoader(new ClasspathTypeLoader());\n return settings;\n }",
"public int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedRefresh == null) {\n\t\t\tmappedRefresh = MappedRefresh.build(dao, tableInfo);\n\t\t}\n\t\treturn mappedRefresh.executeRefresh(databaseConnection, data, objectCache);\n\t}",
"private void validatePermissions(final File dirPath, final File file) {\n\n // Check execute and read permissions for parent dirPath\n if( !dirPath.canExecute() || !dirPath.canRead() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n return;\n }\n\n // Check read and write permissions for properties file\n if( !file.canRead() || !file.canWrite() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n }\n\n }",
"public static base_response create(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey createresource = new sslfipskey();\n\t\tcreateresource.fipskeyname = resource.fipskeyname;\n\t\tcreateresource.modulus = resource.modulus;\n\t\tcreateresource.exponent = resource.exponent;\n\t\treturn createresource.perform_operation(client,\"create\");\n\t}",
"public void setSeriesEndDate(Date date) {\r\n\r\n if (!Objects.equals(m_model.getSeriesEndDate(), date)) {\r\n m_model.setSeriesEndDate(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"public BsonDocument toUpdateDocument() {\n final List<BsonElement> unsets = new ArrayList<>();\n for (final String removedField : this.removedFields) {\n unsets.add(new BsonElement(removedField, new BsonBoolean(true)));\n }\n final BsonDocument updateDocument = new BsonDocument();\n\n if (this.updatedFields.size() > 0) {\n updateDocument.append(\"$set\", this.updatedFields);\n }\n\n if (unsets.size() > 0) {\n updateDocument.append(\"$unset\", new BsonDocument(unsets));\n }\n\n return updateDocument;\n }"
] |
Use this API to fetch all the dnstxtrec resources that are configured on netscaler.
This uses dnstxtrec_args which is a way to provide additional arguments while fetching the resources. | [
"public static dnstxtrec[] get(nitro_service service, dnstxtrec_args args) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] | [
"public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }",
"public void loadObject(Object object, Set<String> excludedMethods)\n {\n m_model.setTableModel(createTableModel(object, excludedMethods));\n }",
"public static String getParameter(DbConn cnx, String key, String defaultValue)\n {\n try\n {\n return cnx.runSelectSingle(\"globalprm_select_by_key\", 3, String.class, key);\n }\n catch (NoResultException e)\n {\n return defaultValue;\n }\n }",
"public 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 }",
"protected ClassDescriptor getClassDescriptor()\r\n {\r\n ClassDescriptor cld = (ClassDescriptor) m_classDescriptor.get();\r\n if(cld == null)\r\n {\r\n throw new OJBRuntimeException(\"Requested ClassDescriptor instance was already GC by JVM\");\r\n }\r\n return cld;\r\n }",
"public static float distance(final float ax, final float ay,\n final float bx, final float by) {\n return (float) Math.sqrt(\n (ax - bx) * (ax - bx) +\n (ay - by) * (ay - by)\n );\n }",
"private void readProjectProperties(Document cdp)\n {\n WorkspaceProperties props = cdp.getWorkspaceProperties();\n ProjectProperties mpxjProps = m_projectFile.getProjectProperties();\n mpxjProps.setSymbolPosition(props.getCurrencyPosition());\n mpxjProps.setCurrencyDigits(props.getCurrencyDigits());\n mpxjProps.setCurrencySymbol(props.getCurrencySymbol());\n mpxjProps.setDaysPerMonth(props.getDaysPerMonth());\n mpxjProps.setMinutesPerDay(props.getHoursPerDay());\n mpxjProps.setMinutesPerWeek(props.getHoursPerWeek());\n\n m_workHoursPerDay = mpxjProps.getMinutesPerDay().doubleValue() / 60.0;\n }",
"static ChangeEvent<BsonDocument> changeEventForLocalDelete(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.DELETE,\n null,\n namespace,\n new BsonDocument(\"_id\", documentId),\n null,\n writePending);\n }",
"public static List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths,\n Path sourceFile)\n {\n ASTParser parser = ASTParser.newParser(AST.JLS11);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n String fileName = sourceFile.getFileName().toString();\n parser.setUnitName(fileName);\n try\n {\n parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray());\n }\n catch (IOException e)\n {\n throw new ASTException(\"Failed to get source for file: \" + sourceFile.toString() + \" due to: \" + e.getMessage(), e);\n }\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n CompilationUnit cu = (CompilationUnit) parser.createAST(null);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString());\n cu.accept(visitor);\n return visitor.getJavaClassReferences();\n }"
] |
Creates a Resque backtrace from a Throwable's stack trace. Includes
causes.
@param t
the Exception to use
@return a list of strings that represent how the exception's stacktrace
appears. | [
"public static List<String> createBacktrace(final Throwable t) {\n final List<String> bTrace = new LinkedList<String>();\n for (final StackTraceElement ste : t.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (t.getCause() != null) {\n addCauseToBacktrace(t.getCause(), bTrace);\n }\n return bTrace;\n }"
] | [
"private int findAvailablePortNumber( Integer portNumberStartingPoint, List<Integer> reservedPorts )\n {\n assert portNumberStartingPoint != null;\n int candidate = portNumberStartingPoint;\n while ( reservedPorts.contains( candidate ) )\n {\n candidate++;\n }\n return candidate;\n }",
"public static void deleteSilentlyRecursively(final Path path) {\n if (path != null) {\n try {\n deleteRecursively(path);\n } catch (IOException ioex) {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(ioex, path);\n }\n }\n }",
"public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }",
"private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\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 }",
"@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 void renumberUniqueIDs()\n {\n int uid = firstUniqueID();\n for (T entity : this)\n {\n entity.setUniqueID(Integer.valueOf(uid++));\n }\n }",
"public void deleteModule(final String name, final String version, 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.getModulePath(name, version));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"to delete module\", name, version);\n\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 }",
"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 }"
] |
Request metadata for a specific track ID, given a dbserver connection to a player that has already been set up.
Separated into its own method so it could be used multiple times with the same connection when gathering
all track metadata.
@param track uniquely identifies the track whose metadata is desired
@param trackType identifies the type of track being requested, which affects the type of metadata request
message that must be used
@param client the dbserver client that is communicating with the appropriate player
@return the retrieved metadata, or {@code null} if there is no such track
@throws IOException if there is a communication problem
@throws InterruptedException if the thread is interrupted while trying to lock the client for menu operations
@throws TimeoutException if we are unable to lock the client for menu operations | [
"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 ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\n }",
"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 void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}",
"public void setProjectionMatrix(float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4) {\n NativeCustomCamera.setProjectionMatrix(getNative(), x1, y1, z1, w1, x2,\n y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }",
"public static Map<String, Map<String, Metadata>> parseAndPopulateMetadataMap(JsonObject jsonObject) {\n Map<String, Map<String, Metadata>> metadataMap = new HashMap<String, Map<String, Metadata>>();\n //Parse all templates\n for (JsonObject.Member templateMember : jsonObject) {\n if (templateMember.getValue().isNull()) {\n continue;\n } else {\n String templateName = templateMember.getName();\n Map<String, Metadata> scopeMap = metadataMap.get(templateName);\n //If templateName doesn't yet exist then create an entry with empty scope map\n if (scopeMap == null) {\n scopeMap = new HashMap<String, Metadata>();\n metadataMap.put(templateName, scopeMap);\n }\n //Parse all scopes in a template\n for (JsonObject.Member scopeMember : templateMember.getValue().asObject()) {\n String scope = scopeMember.getName();\n Metadata metadataObject = new Metadata(scopeMember.getValue().asObject());\n scopeMap.put(scope, metadataObject);\n }\n }\n\n }\n return metadataMap;\n }",
"public Iterator getAllBaseTypes()\r\n {\r\n ArrayList baseTypes = new ArrayList();\r\n\r\n baseTypes.addAll(_directBaseTypes.values());\r\n\r\n for (int idx = baseTypes.size() - 1; idx >= 0; idx--)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)baseTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getDirectBaseTypes(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curBaseTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!baseTypes.contains(curBaseTypeDef))\r\n {\r\n baseTypes.add(0, curBaseTypeDef);\r\n idx++;\r\n }\r\n }\r\n }\r\n return baseTypes.iterator();\r\n }",
"public static Envelope getTileBounds(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble[] layerSize = getTileLayerSize(code, maxExtent, scale);\n\t\tif (layerSize[0] == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tdouble cX = maxExtent.getMinX() + code.getX() * layerSize[0];\n\t\tdouble cY = maxExtent.getMinY() + code.getY() * layerSize[1];\n\t\treturn new Envelope(cX, cX + layerSize[0], cY, cY + layerSize[1]);\n\t}",
"public static base_response update(nitro_service client, nsspparams resource) throws Exception {\n\t\tnsspparams updateresource = new nsspparams();\n\t\tupdateresource.basethreshold = resource.basethreshold;\n\t\tupdateresource.throttle = resource.throttle;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static sslcertkey_sslocspresponder_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslocspresponder_binding response[] = (sslcertkey_sslocspresponder_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Returns the accrued interest of the bond for a given time.
@param time The time of interest as double.
@param model The model under which the product is valued.
@return The accrued interest. | [
"public double getAccruedInterest(double time, AnalyticModel model) {\n\t\tLocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time);\n\t\treturn getAccruedInterest(date, model);\n\t}"
] | [
"public static sslcertkey_sslvserver_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslvserver_binding obj = new sslcertkey_sslvserver_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslvserver_binding response[] = (sslcertkey_sslvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }",
"@Deprecated\n public void validateOperation(final ModelNode operation) throws OperationFailedException {\n if (operation.hasDefined(ModelDescriptionConstants.OPERATION_NAME) && deprecationData != null && deprecationData.isNotificationUseful()) {\n ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(getName(),\n PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString());\n }\n for (AttributeDefinition ad : this.parameters) {\n ad.validateOperation(operation);\n }\n }",
"@Override\n public ResourceStorageLoadable getOrCreateResourceStorageLoadable(final StorageAwareResource resource) {\n try {\n final ResourceStorageProviderAdapter stateProvider = IterableExtensions.<ResourceStorageProviderAdapter>head(Iterables.<ResourceStorageProviderAdapter>filter(resource.getResourceSet().eAdapters(), ResourceStorageProviderAdapter.class));\n if ((stateProvider != null)) {\n final ResourceStorageLoadable inputStream = stateProvider.getResourceStorageLoadable(resource);\n if ((inputStream != null)) {\n return inputStream;\n }\n }\n InputStream _xifexpression = null;\n boolean _exists = resource.getResourceSet().getURIConverter().exists(this.getBinaryStorageURI(resource.getURI()), CollectionLiterals.<Object, Object>emptyMap());\n if (_exists) {\n _xifexpression = resource.getResourceSet().getURIConverter().createInputStream(this.getBinaryStorageURI(resource.getURI()));\n } else {\n InputStream _xblockexpression = null;\n {\n final AbstractFileSystemAccess2 fsa = this.getFileSystemAccess(resource);\n final String outputRelativePath = this.computeOutputPath(resource);\n _xblockexpression = fsa.readBinaryFile(outputRelativePath);\n }\n _xifexpression = _xblockexpression;\n }\n final InputStream inputStream_1 = _xifexpression;\n return this.createResourceStorageLoadable(inputStream_1);\n } catch (Throwable _e) {\n throw Exceptions.sneakyThrow(_e);\n }\n }",
"private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\n }",
"@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 final PrintJobResultExtImpl getResult(final URI reportURI) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<PrintJobResultExtImpl> criteria =\n builder.createQuery(PrintJobResultExtImpl.class);\n final Root<PrintJobResultExtImpl> root = criteria.from(PrintJobResultExtImpl.class);\n criteria.where(builder.equal(root.get(\"reportURI\"), reportURI.toString()));\n return getSession().createQuery(criteria).uniqueResult();\n }",
"protected FluentModelTImpl find(String key) {\n for (Map.Entry<String, FluentModelTImpl> entry : this.childCollection.entrySet()) {\n if (entry.getKey().equalsIgnoreCase(key)) {\n return entry.getValue();\n }\n }\n return null;\n }",
"public static nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] |
This filter permit to return an image sized exactly as requested wherever is its ratio by
filling with chosen color the missing parts. Usually used with "fit-in" or "adaptive-fit-in"
@param color integer representation of color. | [
"public static String fill(int color) {\n final String colorCode = Integer.toHexString(color & 0xFFFFFF); // Strip alpha\n return FILTER_FILL + \"(\" + colorCode + \")\";\n }"
] | [
"public int getFixedDataOffset(FieldType type)\n {\n int result;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFixedDataOffset();\n }\n else\n {\n result = -1;\n }\n return result;\n }",
"protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }",
"public static void extract( DMatrixRMaj src,\n int rows[] , int rowsSize ,\n int cols[] , int colsSize , DMatrixRMaj dst ) {\n if( rowsSize != dst.numRows || colsSize != dst.numCols )\n throw new MatrixDimensionException(\"Unexpected number of rows and/or columns in dst matrix\");\n\n int indexDst = 0;\n for (int i = 0; i < rowsSize; i++) {\n int indexSrcRow = src.numCols*rows[i];\n for (int j = 0; j < colsSize; j++) {\n dst.data[indexDst++] = src.data[indexSrcRow + cols[j]];\n }\n }\n }",
"public ChannelInfo getChannel(String name) {\n final URI uri = uriWithPath(\"./channels/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ChannelInfo.class);\n }",
"public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@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 }",
"public static String getMemberName() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getName();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n return MethodTagsHandler.getPropertyNameFor(getCurrentMethod());\r\n }\r\n else {\r\n return null;\r\n }\r\n }",
"public void setHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n ODO_HOST = hostName;\n BASE_URL = \"http://\" + ODO_HOST + \":\" + API_PORT + \"/\" + API_BASE + \"/\";\n }",
"@RequestMapping(value = \"/scripts\", method = RequestMethod.GET)\n public String scriptView(Model model) throws Exception {\n return \"script\";\n }"
] |
Execute blocking for a prepared result.
@param operation the operation to execute
@param client the protocol client
@return the prepared operation
@throws IOException
@throws InterruptedException | [
"public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }"
] | [
"public void setPattern(String patternType) {\r\n\r\n final PatternType type = PatternType.valueOf(patternType);\r\n if (type != m_model.getPatternType()) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n EndType oldEndType = m_model.getEndType();\r\n m_model.setPatternType(type);\r\n m_model.setIndividualDates(null);\r\n m_model.setInterval(getPatternDefaultValues().getInterval());\r\n m_model.setEveryWorkingDay(Boolean.FALSE);\r\n m_model.clearWeekDays();\r\n m_model.clearIndividualDates();\r\n m_model.clearWeeksOfMonth();\r\n m_model.clearExceptions();\r\n if (type.equals(PatternType.NONE) || type.equals(PatternType.INDIVIDUAL)) {\r\n m_model.setEndType(EndType.SINGLE);\r\n } else if (oldEndType.equals(EndType.SINGLE)) {\r\n m_model.setEndType(EndType.TIMES);\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n }\r\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\r\n m_model.setMonth(getPatternDefaultValues().getMonth());\r\n if (type.equals(PatternType.WEEKLY)) {\r\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\r\n }\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }",
"public 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 }",
"private static JSONArray parseOutgoings(ArrayList<Shape> outgoings) throws JSONException {\n if (outgoings != null) {\n JSONArray outgoingsArray = new JSONArray();\n\n for (Shape outgoing : outgoings) {\n JSONObject outgoingObject = new JSONObject();\n\n outgoingObject.put(\"resourceId\",\n outgoing.getResourceId().toString());\n outgoingsArray.put(outgoingObject);\n }\n\n return outgoingsArray;\n }\n\n return new JSONArray();\n }",
"public JSONObject getJsonFormatted(Map<String, String> dataMap) {\r\n JSONObject oneRowJson = new JSONObject();\n\r\n for (int i = 0; i < outTemplate.length; i++) {\r\n oneRowJson.put(outTemplate[i], dataMap.get(outTemplate[i]));\r\n }\n\n\r\n return oneRowJson;\r\n }",
"static void createMessage(String textMessage, JobInstance jobInstance, DbConn cnx)\n {\n cnx.runUpdate(\"message_insert\", jobInstance.getId(), textMessage);\n }",
"public static base_responses update(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice updateresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbservice();\n\t\t\t\tupdateresources[i].servicename = resources[i].servicename;\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].publicip = resources[i].publicip;\n\t\t\t\tupdateresources[i].publicport = resources[i].publicport;\n\t\t\t\tupdateresources[i].cip = resources[i].cip;\n\t\t\t\tupdateresources[i].cipheader = resources[i].cipheader;\n\t\t\t\tupdateresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\tupdateresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\tupdateresources[i].maxclient = resources[i].maxclient;\n\t\t\t\tupdateresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\tupdateresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\tupdateresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\tupdateresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\tupdateresources[i].viewname = resources[i].viewname;\n\t\t\t\tupdateresources[i].viewip = resources[i].viewip;\n\t\t\t\tupdateresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].monitor_name_svc = resources[i].monitor_name_svc;\n\t\t\t\tupdateresources[i].hashid = resources[i].hashid;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"void register(long mjDay, int leapAdjustment) {\n if (leapAdjustment != -1 && leapAdjustment != 1) {\n throw new IllegalArgumentException(\"Leap adjustment must be -1 or 1\");\n }\n Data data = dataRef.get();\n int pos = Arrays.binarySearch(data.dates, mjDay);\n int currentAdj = pos > 0 ? data.offsets[pos] - data.offsets[pos - 1] : 0;\n if (currentAdj == leapAdjustment) {\n return; // matches previous definition\n }\n if (mjDay <= data.dates[data.dates.length - 1]) {\n throw new IllegalArgumentException(\"Date must be after the last configured leap second date\");\n }\n long[] dates = Arrays.copyOf(data.dates, data.dates.length + 1);\n int[] offsets = Arrays.copyOf(data.offsets, data.offsets.length + 1);\n long[] taiSeconds = Arrays.copyOf(data.taiSeconds, data.taiSeconds.length + 1);\n int offset = offsets[offsets.length - 2] + leapAdjustment;\n dates[dates.length - 1] = mjDay;\n offsets[offsets.length - 1] = offset;\n taiSeconds[taiSeconds.length - 1] = tai(mjDay, offset);\n Data newData = new Data(dates, offsets, taiSeconds);\n if (dataRef.compareAndSet(data, newData) == false) {\n throw new ConcurrentModificationException(\"Unable to update leap second rules as they have already been updated\");\n }\n }",
"public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }"
] |
Add new control at the end of control bar with specified touch listener.
Size of control bar is updated based on new number of controls.
@param name name of the control to remove
@param properties JSON control specific properties
@param listener touch listener | [
"public void addControl(String name, JSONObject properties, Widget.OnTouchListener listener) {\n final JSONObject allowedProperties = new JSONObject();\n put(allowedProperties, Widget.Properties.name, optString(properties, Widget.Properties.name));\n put(allowedProperties, Widget.Properties.size, new PointF(mControlDimensions.x, mControlDimensions.y));\n put(allowedProperties, Widget.Properties.states, optJSONObject(properties, Widget.Properties.states));\n\n Widget control = new Widget(getGVRContext(), allowedProperties);\n setupControl(name, control, listener, -1);\n }"
] | [
"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 static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"@UiHandler({\"m_atMonth\", \"m_everyMonth\"})\r\n void onMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setMonth(event.getValue());\r\n }\r\n }",
"public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedInsert == null) {\n\t\t\tmappedInsert = MappedCreate.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}",
"public List<FailedEventInvocation> getFailedInvocations() {\n synchronized (this.mutex) {\n if (this.failedEvents == null) {\n return Collections.emptyList();\n }\n return Collections.unmodifiableList(this.failedEvents);\n }\n }",
"public final Object getRealObject(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n return getIndirectionHandler(objectOrProxy).getRealSubject();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n return ((VirtualProxy) objectOrProxy).getRealSubject();\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }",
"public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }",
"public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld)\r\n {\r\n SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger);\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n return sql;\r\n }",
"public boolean getBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n return (data[word] & (1 << offset)) != 0;\n }"
] |
Utility function that fetches user defined store definitions
@param adminClient An instance of AdminClient points to given cluster
@param nodeId Node id to fetch store definitions from
@return The map container that maps store names to store definitions | [
"public static Map<String, StoreDefinition> getUserStoreDefMapOnNode(AdminClient adminClient,\n Integer nodeId) {\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, StoreDefinition> storeDefinitionMap = Maps.newHashMap();\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeDefinitionMap.put(storeDefinition.getName(), storeDefinition);\n }\n return storeDefinitionMap;\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 }",
"@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }",
"public static void validate(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n try {\n validateEmpty(bic);\n validateLength(bic);\n validateCase(bic);\n validateBankCode(bic);\n validateCountryCode(bic);\n validateLocationCode(bic);\n\n if(hasBranchCode(bic)) {\n validateBranchCode(bic);\n }\n } catch (UnsupportedCountryException e) {\n throw e;\n } catch (RuntimeException e) {\n throw new BicFormatException(UNKNOWN, e.getMessage());\n }\n }",
"void onPatternChange() {\n\n PatternType patternType = m_model.getPatternType();\n boolean isSeries = !patternType.equals(PatternType.NONE);\n setSerialOptionsVisible(isSeries);\n m_seriesCheckBox.setChecked(isSeries);\n if (isSeries) {\n m_groupPattern.selectButton(m_patternButtons.get(patternType));\n m_controller.getPatternView().onValueChange();\n m_patternOptions.setWidget(m_controller.getPatternView());\n onEndTypeChange();\n }\n m_controller.sizeChanged();\n }",
"public void perform() {\n for (int i = 0; i < operations.size(); i++) {\n operations.get(i).process();\n }\n }",
"private String alterPrefix(String word, String oldPrefix, String newPrefix) {\n\n if (word.startsWith(oldPrefix)) {\n return word.replaceFirst(oldPrefix, newPrefix);\n }\n return (newPrefix + word);\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 }",
"public void updateSchema(String migrationPath) {\n try {\n logger.info(\"Updating schema... \");\n int current_version = 0;\n\n // first check the current schema version\n HashMap<String, Object> configuration = getFirstResult(\"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION +\n \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \" = \\'\" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"\\'\");\n\n if (configuration == null) {\n logger.info(\"Creating configuration table..\");\n // create configuration table\n executeUpdate(\"CREATE TABLE \"\n + Constants.DB_TABLE_CONFIGURATION\n + \" (\" + Constants.GENERIC_ID + \" INTEGER IDENTITY,\"\n + Constants.DB_TABLE_CONFIGURATION_NAME + \" VARCHAR(256),\"\n + Constants.DB_TABLE_CONFIGURATION_VALUE + \" VARCHAR(1024));\");\n\n executeUpdate(\"INSERT INTO \" + Constants.DB_TABLE_CONFIGURATION\n + \"(\" + Constants.DB_TABLE_CONFIGURATION_NAME + \",\" + Constants.DB_TABLE_CONFIGURATION_VALUE + \")\"\n + \" VALUES (\\'\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION\n + \"\\', '0');\");\n } else {\n logger.info(\"Getting current schema version..\");\n // get current version\n current_version = new Integer(configuration.get(\"VALUE\").toString());\n logger.info(\"Current schema version is {}\", current_version);\n }\n\n // loop through until we get up to the right schema version\n while (current_version < Constants.DB_CURRENT_SCHEMA_VERSION) {\n current_version++;\n\n // look for a schema file for this version\n logger.info(\"Updating to schema version {}\", current_version);\n String currentFile = migrationPath + \"/schema.\"\n + current_version;\n Resource migFile = new ClassPathResource(currentFile);\n BufferedReader in = new BufferedReader(new InputStreamReader(\n migFile.getInputStream()));\n\n String str;\n while ((str = in.readLine()) != null) {\n // execute each line\n if (str.length() > 0) {\n executeUpdate(str);\n }\n }\n in.close();\n }\n\n // update the configuration table with the correct version\n executeUpdate(\"UPDATE \" + Constants.DB_TABLE_CONFIGURATION\n + \" SET \" + Constants.DB_TABLE_CONFIGURATION_VALUE + \"='\" + current_version\n + \"' WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"='\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"';\");\n } catch (Exception e) {\n logger.info(\"Error in executeUpdate\");\n e.printStackTrace();\n }\n }",
"public static base_response add(nitro_service client, inat resource) throws Exception {\n\t\tinat addresource = new inat();\n\t\taddresource.name = resource.name;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.privateip = resource.privateip;\n\t\taddresource.tcpproxy = resource.tcpproxy;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.tftp = resource.tftp;\n\t\taddresource.usip = resource.usip;\n\t\taddresource.usnip = resource.usnip;\n\t\taddresource.proxyip = resource.proxyip;\n\t\taddresource.mode = resource.mode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Associate the specified value with the specified key in this map.
If the map previously contained a mapping for this key, the old
value is replaced and returned.
@param key the key with which the value is to be associated
@param value the value to be associated with this key
@return the value previously mapped to the key, or null | [
"@Override\r\n public V put(K key, V value) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.put(key, value);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.put(key, value));\r\n }\r\n }\r\n }"
] | [
"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 boolean checkVersionDirName(File versionDir) {\n return (versionDir.isDirectory() && versionDir.getName().contains(\"version-\") && !versionDir.getName()\n .endsWith(\".bak\"));\n }",
"@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n blockB.reshape(B.numRows,B.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n // since overwrite B is true X does not need to be passed in\n alg.solve(blockB,null);\n\n MatrixOps_DDRB.convert(blockB,X);\n }",
"@Override\n public EthiopicDate date(int prolepticYear, int month, int dayOfMonth) {\n return EthiopicDate.of(prolepticYear, month, dayOfMonth);\n }",
"public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }",
"@Override\n public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) {\n return minimize(function, point, null);\n }",
"protected void copyStream(File outputDirectory,\n InputStream stream,\n String targetFileName) throws IOException\n {\n File resourceFile = new File(outputDirectory, targetFileName);\n BufferedReader reader = null;\n Writer writer = null;\n try\n {\n reader = new BufferedReader(new InputStreamReader(stream, ENCODING));\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));\n\n String line = reader.readLine();\n while (line != null)\n {\n writer.write(line);\n writer.write('\\n');\n line = reader.readLine();\n }\n writer.flush();\n }\n finally\n {\n if (reader != null)\n {\n reader.close();\n }\n if (writer != null)\n {\n writer.close();\n }\n }\n }",
"public static dnsnsecrec[] get(nitro_service service) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\tdnsnsecrec[] response = (dnsnsecrec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }"
] |
Write a boolean field to the JSON file.
@param fieldName field name
@param value field value | [
"private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }"
] | [
"public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}",
"public static void writeFully(ByteBuffer buffer, WritableByteChannel channel) throws IOException {\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n }",
"public Eval<UploadResult> putAsync(String key, Object value) {\n return Eval.later(() -> put(key, value))\n .map(t -> t.orElse(null))\n .map(FluentFunctions.ofChecked(up -> up.waitForUploadResult()));\n\n }",
"public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject,\n\t\t\tObjectCache objectCache) throws SQLException {\n\n\t\tif (logger.isLevelEnabled(Level.TRACE)) {\n\t\t\tlogger.trace(\"assiging from data {}, val {}: {}\", (data == null ? \"null\" : data.getClass()),\n\t\t\t\t\t(val == null ? \"null\" : val.getClass()), val);\n\t\t}\n\t\t// if this is a foreign object then val is the foreign object's id val\n\t\tif (foreignRefField != null && val != null) {\n\t\t\t// get the current field value which is the foreign-id\n\t\t\tObject foreignRef = extractJavaFieldValue(data);\n\t\t\t/*\n\t\t\t * See if we don't need to create a new foreign object. If we are refreshing and the id field has not\n\t\t\t * changed then there is no need to create a new foreign object and maybe lose previously refreshed field\n\t\t\t * information.\n\t\t\t */\n\t\t\tif (foreignRef != null && foreignRef.equals(val)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// awhitlock: raised as OrmLite issue: bug #122\n\t\t\tObject cachedVal;\n\t\t\tObjectCache foreignCache = foreignDao.getObjectCache();\n\t\t\tif (foreignCache == null) {\n\t\t\t\tcachedVal = null;\n\t\t\t} else {\n\t\t\t\tcachedVal = foreignCache.get(getType(), val);\n\t\t\t}\n\t\t\tif (cachedVal != null) {\n\t\t\t\tval = cachedVal;\n\t\t\t} else if (!parentObject) {\n\t\t\t\t// the value we are to assign to our field is now the foreign object itself\n\t\t\t\tval = createForeignObject(connectionSource, val, objectCache);\n\t\t\t}\n\t\t}\n\n\t\tif (fieldSetMethod == null) {\n\t\t\ttry {\n\t\t\t\tfield.set(data, val);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tif (val == null) {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\"Could not assign object '\" + val + \"' to field \" + this, e);\n\t\t\t\t} else {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \" to field \" + this, e);\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \"' to field \" + this, e);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tfieldSetMethod.invoke(data, val);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil\n\t\t\t\t\t\t.create(\"Could not call \" + fieldSetMethod + \" on object with '\" + val + \"' for \" + this, e);\n\t\t\t}\n\t\t}\n\t}",
"public void setTexture(GVRRenderTexture texture)\n {\n mTexture = texture;\n NativeRenderTarget.setTexture(getNative(), texture.getNative());\n }",
"public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }",
"public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }",
"public static boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }",
"public static boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }"
] |
Use this API to fetch all the dnstxtrec resources that are configured on netscaler. | [
"public static dnstxtrec[] get(nitro_service service) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static base_response delete(nitro_service client, String viewname) throws Exception {\n\t\tdnsview deleteresource = new dnsview();\n\t\tdeleteresource.viewname = viewname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private void writeCalendars(Project project)\n {\n //\n // Create the new MSPDI calendar list\n //\n Project.Calendars calendars = m_factory.createProjectCalendars();\n project.setCalendars(calendars);\n List<Project.Calendars.Calendar> calendar = calendars.getCalendar();\n\n //\n // Process each calendar in turn\n //\n for (ProjectCalendar cal : m_projectFile.getCalendars())\n {\n calendar.add(writeCalendar(cal));\n }\n }",
"@Nonnull\n public static XMLDSigValidationResult createReferenceErrors (@Nonnull @Nonempty final List <Integer> aInvalidReferences)\n {\n return new XMLDSigValidationResult (aInvalidReferences);\n }",
"protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }",
"private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }",
"@SuppressWarnings(\"unused\")\n public void selectItem(int position, boolean invokeListeners) {\n IOperationItem item = mOuterAdapter.getItem(position);\n IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition);\n\n int realPosition = mOuterAdapter.normalizePosition(position);\n //do nothing if position not changed\n if (realPosition == mCurrentItemPosition) {\n return;\n }\n int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition;\n\n item.setVisible(false);\n\n startSelectedViewOutAnimation(position);\n\n mOuterAdapter.notifyRealItemChanged(position);\n mRealHidedPosition = realPosition;\n\n oldHidedItem.setVisible(true);\n mFlContainerSelected.requestLayout();\n mOuterAdapter.notifyRealItemChanged(itemToShowAdapterPosition);\n mCurrentItemPosition = realPosition;\n\n if (invokeListeners) {\n notifyItemClickListeners(realPosition);\n }\n\n if (BuildConfig.DEBUG) {\n Log.i(TAG, \"clicked on position =\" + position);\n }\n\n }",
"private int bindStatementValue(PreparedStatement stmt, int index, Object attributeOrQuery, Object value, ClassDescriptor cld)\r\n throws SQLException\r\n {\r\n FieldDescriptor fld = null;\r\n // if value is a subQuery bind it\r\n if (value instanceof Query)\r\n {\r\n Query subQuery = (Query) value;\r\n return bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n\r\n // if attribute is a subQuery bind it\r\n if (attributeOrQuery instanceof Query)\r\n {\r\n Query subQuery = (Query) attributeOrQuery;\r\n bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n else\r\n {\r\n fld = cld.getFieldDescriptorForPath((String) attributeOrQuery);\r\n }\r\n\r\n if (fld != null)\r\n {\r\n // BRJ: use field conversions and platform\r\n if (value != null)\r\n {\r\n m_platform.setObjectForStatement(stmt, index, fld.getFieldConversion().javaToSql(value), fld.getJdbcType().getType());\r\n }\r\n else\r\n {\r\n m_platform.setNullForStatement(stmt, index, fld.getJdbcType().getType());\r\n }\r\n }\r\n else\r\n {\r\n if (value != null)\r\n {\r\n stmt.setObject(index, value);\r\n }\r\n else\r\n {\r\n stmt.setNull(index, Types.NULL);\r\n }\r\n }\r\n\r\n return ++index; // increment before return\r\n }",
"protected Map<String, String> getGalleryOpenParams(\n CmsObject cms,\n CmsMessages messages,\n I_CmsWidgetParameter param,\n String resource,\n long hashId) {\n\n Map<String, String> result = new HashMap<String, String>();\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, A_CmsAjaxGallery.MODE_WIDGET);\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_STORAGE_PREFIX, getGalleryStoragePrefix());\n result.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, getGalleryTypes());\n if (param.getId() != null) {\n result.put(I_CmsGalleryProviderConstants.KEY_FIELD_ID, param.getId());\n // use javascript to read the current field value\n result.put(\n I_CmsGalleryProviderConstants.CONFIG_CURRENT_ELEMENT,\n \"'+document.getElementById('\" + param.getId() + \"').getAttribute('value')+'\");\n }\n result.put(I_CmsGalleryProviderConstants.KEY_HASH_ID, \"\" + hashId);\n // the edited resource\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, resource);\n }\n // the start up gallery path\n CmsGalleryWidgetConfiguration configuration = getWidgetConfiguration(cms, messages, param);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getStartup())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_PATH, configuration.getStartup());\n }\n // set gallery types if available\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getGalleryTypes())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_TYPES, configuration.getGalleryTypes());\n }\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_NAME, getGalleryName());\n return result;\n }",
"public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){\n\t\tList<Integer> intList = new ArrayList<Integer>();\n\t\tfor(String str : strList){\n\t\t\ttry{\n\t\t\t\tintList.add(Integer.parseInt(str));\n\t\t\t}\n\t\t\tcatch(NumberFormatException nfe){\n\t\t\t\tif(failOnException){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tintList.add(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn intList;\n\t}"
] |
Tries to guess location of the user secure keyring using various
heuristics.
@return path to the keyring file
@throws FileNotFoundException if no keyring file found | [
"public static File guessKeyRingFile() throws FileNotFoundException {\n final Collection<String> possibleLocations = getKnownPGPSecureRingLocations();\n for (final String location : possibleLocations) {\n final File candidate = new File(location);\n if (candidate.exists()) {\n return candidate;\n }\n }\n final StringBuilder message = new StringBuilder(\"Could not locate secure keyring, locations tried: \");\n final Iterator<String> it = possibleLocations.iterator();\n while (it.hasNext()) {\n message.append(it.next());\n if (it.hasNext()) {\n message.append(\", \");\n }\n }\n throw new FileNotFoundException(message.toString());\n }"
] | [
"public synchronized int skip(int count) {\n if (count > available) {\n count = available;\n }\n idxGet = (idxGet + count) % capacity;\n available -= count;\n return count;\n }",
"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 }",
"private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }",
"private JSONArray toJsonStringArray(Collection<? extends Object> collection) {\n\n if (null != collection) {\n JSONArray array = new JSONArray();\n for (Object o : collection) {\n array.put(\"\" + o);\n }\n return array;\n } else {\n return null;\n }\n }",
"public static <T> DatabaseTableConfig<T> fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseTableConfig<T> config = new DatabaseTableConfig<T>();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseTableConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_FIELDS_START)) {\n\t\t\t\treadFields(reader, config);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseTableConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadTableField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}",
"private String getCachedETag(HttpHost host, String file) {\n Map<String, Object> cachedETags = readCachedETags();\n\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> hostMap =\n (Map<String, Object>)cachedETags.get(host.toURI());\n if (hostMap == null) {\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n Map<String, String> etagMap = (Map<String, String>)hostMap.get(file);\n if (etagMap == null) {\n return null;\n }\n\n return etagMap.get(\"ETag\");\n }",
"protected boolean checkvalue(String colorvalue) {\n\n boolean valid = validateColorValue(colorvalue);\n if (valid) {\n if (colorvalue.length() == 4) {\n char[] chr = colorvalue.toCharArray();\n for (int i = 1; i < 4; i++) {\n String foo = String.valueOf(chr[i]);\n colorvalue = colorvalue.replaceFirst(foo, foo + foo);\n }\n }\n m_textboxColorValue.setValue(colorvalue, true);\n m_colorField.getElement().getStyle().setBackgroundColor(colorvalue);\n m_colorValue = colorvalue;\n }\n return valid;\n }",
"public static authenticationvserver_authenticationlocalpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationlocalpolicy_binding obj = new authenticationvserver_authenticationlocalpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationlocalpolicy_binding response[] = (authenticationvserver_authenticationlocalpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void processProperties() {\n state = true;\n try {\n importerServiceFilter = getFilter(importerServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n importDeclarationFilter = getFilter(importDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }"
] |
Generates a schedule based on some meta data. The schedule generation
considers short periods. Date rolling is ignored.
@param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0.
@param startDate The start date of the first period.
@param frequency The frequency.
@param maturity The end date of the last period.
@param daycountConvention The daycount convention.
@param shortPeriodConvention If short period exists, have it first or last.
@return The corresponding schedule
@deprecated Will be removed in version 2.3 | [
"@Deprecated\n\tpublic static ScheduleInterface createScheduleFromConventions(\n\t\t\tLocalDate referenceDate,\n\t\t\tLocalDate startDate,\n\t\t\tString frequency,\n\t\t\tdouble maturity,\n\t\t\tString daycountConvention,\n\t\t\tString shortPeriodConvention\n\t\t\t)\n\t{\n\t\treturn createScheduleFromConventions(\n\t\t\t\treferenceDate,\n\t\t\t\tstartDate,\n\t\t\t\tfrequency,\n\t\t\t\tmaturity,\n\t\t\t\tdaycountConvention,\n\t\t\t\tshortPeriodConvention,\n\t\t\t\t\"UNADJUSTED\",\n\t\t\t\tnew BusinessdayCalendarAny(),\n\t\t\t\t0, 0);\n\t}"
] | [
"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 }",
"@Deprecated\n public static <T> T buildJsonResponse(Response response, Class<T> clazz) throws IOException, SlackApiException {\n if (response.code() == 200) {\n String body = response.body().string();\n DETAILED_LOGGER.accept(new HttpResponseListener.State(SlackConfig.DEFAULT, response, body));\n return GsonFactory.createSnakeCase().fromJson(body, clazz);\n } else {\n String body = response.body().string();\n throw new SlackApiException(response, body);\n }\n }",
"public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}",
"public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }",
"private Map<Integer, List<Row>> createExceptionAssignmentMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String exceptions = row.getString(\"EXCEPTIONS\");\n map.put(calendarID, createExceptionAssignmentRowList(exceptions));\n }\n return map;\n }",
"private static I_CmsResourceBundle tryBundle(String localizedName) {\n\n I_CmsResourceBundle result = null;\n\n try {\n\n String resourceName = localizedName.replace('.', '/') + \".properties\";\n URL url = CmsResourceBundleLoader.class.getClassLoader().getResource(resourceName);\n\n I_CmsResourceBundle additionalBundle = m_permanentCache.get(localizedName);\n if (additionalBundle != null) {\n result = additionalBundle.getClone();\n } else if (url != null) {\n // the resource was found on the file system\n InputStream is = null;\n String path = CmsFileUtil.normalizePath(url);\n File file = new File(path);\n try {\n // try to load the resource bundle from a file, NOT with the resource loader first\n // this is important since using #getResourceAsStream() may return cached results,\n // for example Tomcat by default does cache all resources loaded by the class loader\n // this means a changed resource bundle file is not loaded\n is = new FileInputStream(file);\n } catch (IOException ex) {\n // this will happen if the resource is contained for example in a .jar file\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n } catch (AccessControlException acex) {\n // fixed bug #1550\n // this will happen if the resource is contained for example in a .jar file\n // and security manager is turned on.\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n }\n if (is != null) {\n result = new CmsPropertyResourceBundle(is);\n }\n }\n } catch (IOException ex) {\n // can't localized these message since this may lead to a chicken-egg problem\n MissingResourceException mre = new MissingResourceException(\n \"Failed to load bundle '\" + localizedName + \"'\",\n localizedName,\n \"\");\n mre.initCause(ex);\n throw mre;\n }\n\n return result;\n }",
"public int readFrom(ByteBuffer src, long destOffset) {\n if (src.remaining() + destOffset >= size())\n throw new BufferOverflowException();\n int readLen = src.remaining();\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src);\n return readLen;\n }",
"protected void buildSuperJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)\r\n {\r\n ClassDescriptor superCld = cld.getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n SuperReferenceDescriptor superRef = cld.getSuperReference();\r\n FieldDescriptor[] leftFields = superRef.getForeignKeyFieldDescriptors(cld);\r\n TableAlias base_alias = getTableAliasForPath(name, null, null);\r\n String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;\r\n TableAlias right = new TableAlias(superCld, aliasName, useOuterJoin, null);\r\n\r\n Join join1to1 = new Join(left, leftFields, right, superCld.getPkFields(), useOuterJoin, \"superClass\");\r\n base_alias.addJoin(join1to1);\r\n\r\n buildSuperJoinTree(right, superCld, name, useOuterJoin);\r\n }\r\n }",
"public void addWatcher(final MongoNamespace namespace,\n final Callback<ChangeEvent<BsonDocument>, Object> watcher) {\n instanceChangeStreamListener.addWatcher(namespace, watcher);\n }"
] |
Marshal the assertion as a JSON object.
@param assertion the assertion to marshal | [
"public JSONObject marshal(final AccessAssertion assertion) {\n final JSONObject jsonObject = assertion.marshal();\n if (jsonObject.has(JSON_CLASS_NAME)) {\n throw new AssertionError(\"The toJson method in AccessAssertion: '\" + assertion.getClass() +\n \"' defined a JSON field \" + JSON_CLASS_NAME +\n \" which is a reserved keyword and is not permitted to be used \" +\n \"in toJSON method\");\n }\n try {\n jsonObject.put(JSON_CLASS_NAME, assertion.getClass().getName());\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n\n return jsonObject;\n }"
] | [
"public void strokeRectangle(Rectangle rect, Color color, float linewidth) {\n\t\tstrokeRectangle(rect, color, linewidth, null);\n\t}",
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }",
"public static final <T> T getSingle( Iterable<T> it ) {\n if( ! it.iterator().hasNext() )\n return null;\n\n final Iterator<T> iterator = it.iterator();\n T o = iterator.next();\n if(iterator.hasNext())\n throw new IllegalStateException(\"Found multiple items in iterator over \" + o.getClass().getName() );\n\n return o;\n }",
"@SuppressWarnings(\"unused\")\n public void setError(CharSequence error, Drawable icon) {\n mPhoneEdit.setError(error, icon);\n }",
"public static void addInterceptors(InterceptorProvider provider) {\n PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);\n for (Phase p : phases.getInPhases()) {\n provider.getInInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n for (Phase p : phases.getOutPhases()) {\n provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n }",
"public synchronized void shutdown(){\r\n\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tlogger.info(\"Shutting down connection pool...\");\r\n\t\t\tthis.poolShuttingDown = true;\r\n\t\t\tthis.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE);\r\n\t\t\tthis.keepAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.maxAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.connectionsScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.asyncExecutor.shutdownNow();\r\n\r\n\t\t\ttry {\r\n\t\t\t\tthis.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\r\n\t\t\t\tthis.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t\r\n\t\t\t\tif (this.closeConnectionExecutor != null){\r\n\t\t\t\t\tthis.closeConnectionExecutor.shutdownNow();\r\n\t\t\t\t\tthis.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t// do nothing\r\n\t\t\t}\r\n\t\t\tthis.connectionStrategy.terminateAllConnections();\r\n\t\t\tunregisterDriver();\r\n\t\t\tregisterUnregisterJMX(false);\r\n\t\t\tif (finalizableRefQueue != null) {\r\n\t\t\t\tfinalizableRefQueue.close();\r\n\t\t\t}\r\n\t\t\t logger.info(\"Connection pool has been shutdown.\");\r\n\t\t}\r\n\t}",
"public void addForeignKeyField(String newField)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(newField);\r\n }",
"private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {\n if (!node.isDefined()) {\n return node;\n }\n\n ModelType type = node.getType();\n ModelNode resolved;\n if (type == ModelType.EXPRESSION) {\n resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);\n } else if (type == ModelType.OBJECT) {\n resolved = node.clone();\n for (Property prop : resolved.asPropertyList()) {\n resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));\n }\n } else if (type == ModelType.LIST) {\n resolved = node.clone();\n ModelNode list = new ModelNode();\n list.setEmptyList();\n for (ModelNode current : resolved.asList()) {\n list.add(resolveExpressionsRecursively(current));\n }\n resolved = list;\n } else if (type == ModelType.PROPERTY) {\n resolved = node.clone();\n resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));\n } else {\n resolved = node;\n }\n\n return resolved;\n }",
"public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }"
] |
If any of the given list of properties are not found, returns the
name of that property. Otherwise, returns null. | [
"public static String checkRequiredProperties(Properties props,\r\n String ... requiredProps) {\r\n for (String required : requiredProps) {\r\n if (props.getProperty(required) == null) {\r\n return required;\r\n }\r\n }\r\n return null;\r\n }"
] | [
"public Collection<Contact> getList() throws FlickrException {\r\n \t ContactList<Contact> contacts = new ContactList<Contact>();\r\n \r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n contacts.setPage(contactsElement.getAttribute(\"page\"));\r\n contacts.setPages(contactsElement.getAttribute(\"pages\"));\r\n contacts.setPerPage(contactsElement.getAttribute(\"perpage\"));\r\n contacts.setTotal(contactsElement.getAttribute(\"total\"));\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n String lPathAlias = contactElement.getAttribute(\"path_alias\");\r\n contact.setPathAlias(lPathAlias == null || \"\".equals(lPathAlias) ? null : lPathAlias);\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }",
"public static DMatrixRMaj nullspaceSVD( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpace<DMatrixRMaj> solver = new SolveNullSpaceSvd_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }",
"public static final boolean isInside(int x, int y, Rect box) {\n return (box.x < x && x < box.x + box.w && box.y < y && y < box.y + box.h);\n }",
"public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }",
"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 void enqueue(SerialMessage serialMessage) {\n\t\tthis.sendQueue.add(serialMessage);\n\t\tlogger.debug(\"Enqueueing message. Queue length = {}\", this.sendQueue.size());\n\t}",
"public void updateLinks(ServiceReference<S> serviceReference) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);\n boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);\n if (isAlreadyLinked && !canBeLinked) {\n linkerManagement.unlink(declaration, serviceReference);\n } else if (!isAlreadyLinked && canBeLinked) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }",
"public String getRemoteUrl(String defaultRemoteUrl) {\n if (StringUtils.isBlank(defaultRemoteUrl)) {\n RemoteConfig remoteConfig = getJenkinsScm().getRepositories().get(0);\n URIish uri = remoteConfig.getURIs().get(0);\n return uri.toPrivateString();\n }\n\n return defaultRemoteUrl;\n }",
"public void createInsertionSql(Database model, Platform platform, Writer writer) throws IOException\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n writer.write(platform.getInsertSql(model, (DynaBean)it.next()));\r\n if (it.hasNext())\r\n {\r\n writer.write(\"\\n\");\r\n }\r\n }\r\n }"
] |
Parse a macro defintion.
"macro NAME( var0 , var1 ) = 5+var0+var1' | [
"private void parseMacro( TokenList tokens , Sequence sequence ) {\n Macro macro = new Macro();\n\n TokenList.Token t = tokens.getFirst().next;\n\n if( t.word == null ) {\n throw new ParseError(\"Expected the macro's name after \"+tokens.getFirst().word);\n }\n List<TokenList.Token> variableTokens = new ArrayList<TokenList.Token>();\n\n macro.name = t.word;\n t = t.next;\n t = parseMacroInput(variableTokens, t);\n for( TokenList.Token a : variableTokens ) {\n if( a.word == null) throw new ParseError(\"expected word in macro header\");\n macro.inputs.add(a.word);\n }\n t = t.next;\n if( t == null || t.getSymbol() != Symbol.ASSIGN)\n throw new ParseError(\"Expected assignment\");\n t = t.next;\n macro.tokens = new TokenList(t,tokens.last);\n\n sequence.addOperation(macro.createOperation(macros));\n }"
] | [
"void writeNoValueRestriction(RdfWriter rdfWriter, String propertyUri,\n\t\t\tString rangeUri, String subject) throws RDFHandlerException {\n\n\t\tResource bnodeSome = rdfWriter.getFreshBNode();\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_CLASS);\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.OWL_COMPLEMENT_OF,\n\t\t\t\tbnodeSome);\n\t\trdfWriter.writeTripleValueObject(bnodeSome, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\trdfWriter.writeTripleUriObject(bnodeSome, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\trdfWriter.writeTripleUriObject(bnodeSome,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}",
"public void setRegularExpression(String regularExpression) {\n\t\tif (regularExpression != null)\n\t\t\tthis.regularExpression = Pattern.compile(regularExpression);\n\t\telse\n\t\t\tthis.regularExpression = null;\n\t}",
"public static void main(String[] args) {\n if(args.length != 2) {\n System.out.println(\"Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema\");\n return;\n }\n\n Schema oldSchema;\n Schema newSchema;\n\n try {\n oldSchema = Schema.parse(new File(args[0]));\n } catch(Exception ex) {\n oldSchema = null;\n System.out.println(\"Could not open or parse the old schema (\" + args[0] + \") due to \"\n + ex);\n }\n\n try {\n newSchema = Schema.parse(new File(args[1]));\n } catch(Exception ex) {\n newSchema = null;\n System.out.println(\"Could not open or parse the new schema (\" + args[1] + \") due to \"\n + ex);\n }\n\n if(oldSchema == null || newSchema == null) {\n return;\n }\n\n System.out.println(\"Comparing: \");\n System.out.println(\"\\t\" + args[0]);\n System.out.println(\"\\t\" + args[1]);\n\n List<Message> messages = SchemaEvolutionValidator.checkBackwardCompatibility(oldSchema,\n newSchema,\n oldSchema.getName());\n Level maxLevel = Level.ALL;\n for(Message message: messages) {\n System.out.println(message.getLevel() + \": \" + message.getMessage());\n if(message.getLevel().isGreaterOrEqual(maxLevel)) {\n maxLevel = message.getLevel();\n }\n }\n\n if(maxLevel.isGreaterOrEqual(Level.ERROR)) {\n System.out.println(Level.ERROR\n + \": The schema is not backward compatible. New clients will not be able to read existing data.\");\n } else if(maxLevel.isGreaterOrEqual(Level.WARN)) {\n System.out.println(Level.WARN\n + \": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format.\");\n } else {\n System.out.println(Level.INFO\n + \": The schema is backward compatible. Old and new clients will be able to read records serialized by one another.\");\n }\n }",
"public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }",
"public static base_response delete(nitro_service client, String username) throws Exception {\n\t\tsystemuser deleteresource = new systemuser();\n\t\tdeleteresource.username = username;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) {\n this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY));\n }\n\n if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) {\n List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY);\n if(urls.size() > 0) {\n setHttpBootstrapURL(urls.get(0));\n }\n }\n\n if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) {\n setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY,\n maxR2ConnectionPoolSize));\n }\n\n if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY))\n this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs),\n TimeUnit.MILLISECONDS);\n\n // By default, make all the timeouts equal to routing timeout\n timeoutConfig = new TimeoutConfig(timeoutMs, false);\n\n if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE,\n props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE,\n props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) {\n long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY);\n timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs);\n // By default, use the same thing for getVersions() also\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs);\n }\n\n // of course, if someone overrides it, we will respect that\n if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE,\n props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE,\n props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY))\n timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY));\n\n }",
"private static boolean isDpiSet(final Multimap<String, String> extraParams) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n for (String value: extraParams.get(key)) {\n if (value.toLowerCase().contains(\"dpi:\")) {\n return true;\n }\n }\n }\n }\n return false;\n }",
"private int countCharsStart(final char ch, final boolean allowSpaces)\n {\n int count = 0;\n for (int i = 0; i < this.value.length(); i++)\n {\n final char c = this.value.charAt(i);\n if (c == ' ' && allowSpaces)\n {\n continue;\n }\n if (c == ch)\n {\n count++;\n }\n else\n {\n break;\n }\n }\n return count;\n }",
"public static final Bytes of(ByteBuffer bb) {\n Objects.requireNonNull(bb);\n if (bb.remaining() == 0) {\n return EMPTY;\n }\n byte[] data;\n if (bb.hasArray()) {\n data = Arrays.copyOfRange(bb.array(), bb.position() + bb.arrayOffset(),\n bb.limit() + bb.arrayOffset());\n } else {\n data = new byte[bb.remaining()];\n // duplicate so that it does not change position\n bb.duplicate().get(data);\n }\n return new Bytes(data);\n }"
] |
Curries a function that takes three arguments.
@param function
the original function. May not be <code>null</code>.
@param argument
the fixed first argument of {@code function}.
@return a function that takes two arguments. Never <code>null</code>. | [
"@Pure\n\tpublic static <P1, P2, P3, RESULT> Function2<P2, P3, RESULT> curry(final Function3<? super P1, ? super P2, ? super P3, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function2<P2, P3, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3) {\n\t\t\t\treturn function.apply(argument, p2, p3);\n\t\t\t}\n\t\t};\n\t}"
] | [
"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 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 acceptsPartition(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_P, OPT_PARTITION), \"partition id list\")\n .withRequiredArg()\n .describedAs(\"partition-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }",
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }",
"public static appflowpolicylabel[] get(nitro_service service) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tappflowpolicylabel[] response = (appflowpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {\n\n context.init();\n\n HiveConf hiveConf = context.getHiveConf();\n\n // merge test case properties with hive conf before HiveServer is started.\n for (Map.Entry<String, String> property : testConfig.entrySet()) {\n hiveConf.set(property.getKey(), property.getValue());\n }\n\n try {\n hiveServer2 = new HiveServer2();\n hiveServer2.init(hiveConf);\n\n // Locate the ClIService in the HiveServer2\n for (Service service : hiveServer2.getServices()) {\n if (service instanceof CLIService) {\n client = (CLIService) service;\n }\n }\n\n Preconditions.checkNotNull(client, \"ClIService was not initialized by HiveServer2\");\n\n sessionHandle = client.openSession(\"noUser\", \"noPassword\", null);\n\n SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();\n currentSessionState = sessionState;\n currentSessionState.setHiveVariables(hiveVars);\n } catch (Exception e) {\n throw new IllegalStateException(\"Failed to create HiveServer :\" + e.getMessage(), e);\n }\n\n // Ping hive server before we do anything more with it! If validation\n // is switched on, this will fail if metastorage is not set up properly\n pingHiveServer();\n }",
"public void joinRequest(String groupId, String message, boolean acceptRules) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_JOIN_REQUEST);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"message\", message);\r\n parameters.put(\"accept_rules\", acceptRules);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private boolean runQueuedTask(boolean hasPermit) {\n if (!hasPermit && beginRequest(paused) == RunResult.REJECTED) {\n return false;\n }\n QueuedTask task = null;\n if (!paused) {\n task = taskQueue.poll();\n } else {\n //the container is suspended, but we still need to run any force queued tasks\n task = findForcedTask();\n }\n if (task != null) {\n if(!task.runRequest()) {\n decrementRequestCount();\n }\n return true;\n } else {\n decrementRequestCount();\n return false;\n }\n }",
"public List<GetLocationResult> search(String q, int maxRows, Locale locale)\n\t\t\tthrows Exception {\n\t\tList<GetLocationResult> searchResult = new ArrayList<GetLocationResult>();\n\n\t\tString url = URLEncoder.encode(q, \"UTF8\");\n\t\turl = \"q=select%20*%20from%20geo.placefinder%20where%20text%3D%22\"\n\t\t\t\t+ url + \"%22\";\n\t\tif (maxRows > 0) {\n\t\t\turl = url + \"&count=\" + maxRows;\n\t\t}\n\t\turl = url + \"&flags=GX\";\n\t\tif (null != locale) {\n\t\t\turl = url + \"&locale=\" + locale;\n\t\t}\n\t\tif (appId != null) {\n\t\t\turl = url + \"&appid=\" + appId;\n\t\t}\n\n\t\tInputStream inputStream = connect(url);\n\t\tif (null != inputStream) {\n\t\t\tSAXBuilder parser = new SAXBuilder();\n\t\t\tDocument doc = parser.build(inputStream);\n\n\t\t\tElement root = doc.getRootElement();\n\n\t\t\t// check code for exception\n\t\t\tString message = root.getChildText(\"Error\");\n\t\t\t// Integer errorCode = Integer.parseInt(message);\n\t\t\tif (message != null && Integer.parseInt(message) != 0) {\n\t\t\t\tthrow new Exception(root.getChildText(\"ErrorMessage\"));\n\t\t\t}\n\t\t\tElement results = root.getChild(\"results\");\n\t\t\tfor (Object obj : results.getChildren(\"Result\")) {\n\t\t\t\tElement toponymElement = (Element) obj;\n\t\t\t\tGetLocationResult location = getLocationFromElement(toponymElement);\n\t\t\t\tsearchResult.add(location);\n\t\t\t}\n\t\t}\n\t\treturn searchResult;\n\t}"
] |
Roll the java.util.Time forward or backward.
@param startDate - The start date
@param period Calendar.YEAR etc
@param amount - Negative to rollbackwards. | [
"public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\n }"
] | [
"private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }",
"private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\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 }",
"@Inline(value = \"$1.remove($2)\", statementExpression = true)\n\tpublic static <K, V> V operator_remove(Map<K, V> map, K key) {\n\t\treturn map.remove(key);\n\t}",
"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 Where<T, ID> ge(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"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 }",
"private void createAndAddButton(PatternType pattern, String messageKey) {\n\n CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));\n btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());\n btn.setGroup(m_groupPattern);\n m_patternButtons.put(pattern, btn);\n m_patternRadioButtonsPanel.add(btn);\n\n }",
"public void writeOutput(DataPipe cr) {\n try {\n context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate)));\n } catch (Exception e) {\n throw new RuntimeException(\"Exception occurred while writing to Context\", e);\n }\n }"
] |
Sets the max.
@param n the new max | [
"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 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 static void putUnsignedInt(ByteBuffer buffer, int index, long value) {\n buffer.putInt(index, (int) (value & 0xffffffffL));\n }",
"public void reset() {\n state = BreakerState.CLOSED;\n isHardTrip = false;\n byPass = false;\n isAttemptLive = false;\n\n notifyBreakerStateChange(getStatus());\n }",
"private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }",
"public void setFrustum(float[] frustum)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.setFrustum(frustum[0], frustum[3], frustum[1], frustum[4], frustum[2], frustum[5]);\n setFrustum(projMatrix);\n }",
"public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}",
"public final void notifyContentItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount, itemCount);\n }",
"private static void listTaskNotes(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n String notes = task.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + task.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }",
"private void clearDeckPreview(TrackMetadataUpdate update) {\n if (previewHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformPreviewUpdate(update.player, null);\n }\n }"
] |
Gets the top of thread-local shell stack, or null if it is empty.
@return the top of the shell stack | [
"public static CmsShell getTopShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.isEmpty()) {\n return null;\n }\n return shells.get(shells.size() - 1);\n\n }"
] | [
"public static Map<String, IDiagramPlugin>\n getLocalPluginsRegistry(ServletContext context) {\n if (LOCAL == null) {\n LOCAL = initializeLocalPlugins(context);\n }\n return LOCAL;\n }",
"private void updateImageInfo() {\n\n String crop = getCrop();\n String point = getPoint();\n m_imageInfoDisplay.fillContent(m_info, crop, point);\n }",
"public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata(BoxAPIConnection api,\r\n String policyID,\r\n String templateID,\r\n MetadataFieldFilter... filter) {\r\n JsonObject assignTo = new JsonObject().add(\"type\", TYPE_METADATA).add(\"id\", templateID);\r\n JsonArray filters = null;\r\n if (filter.length > 0) {\r\n filters = new JsonArray();\r\n for (MetadataFieldFilter f : filter) {\r\n filters.add(f.getJsonObject());\r\n }\r\n }\r\n return createAssignment(api, policyID, assignTo, filters);\r\n }",
"protected String getLocaleSpecificTitle(Locale locale) {\n\n String result = null;\n\n try {\n\n if (isDetailRequest()) {\n // this is a request to a detail page\n CmsResource res = getDetailContent();\n CmsFile file = m_cms.readFile(res);\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale());\n if (result == null) {\n // title not found, maybe no mapping OR not available in the current locale\n // read the title of the detail resource as fall back (may contain mapping from another locale)\n result = m_cms.readPropertyObject(\n res,\n CmsPropertyDefinition.PROPERTY_TITLE,\n false,\n locale).getValue();\n }\n }\n if (result == null) {\n // read the title of the requested resource as fall back\n result = m_cms.readPropertyObject(\n m_cms.getRequestContext().getUri(),\n CmsPropertyDefinition.PROPERTY_TITLE,\n true,\n locale).getValue();\n }\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {\n result = \"\";\n }\n\n return result;\n }",
"ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }",
"private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getMessageUniqueID()));\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getConfirmed() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getResponsePending() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getScheduleID()));\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }",
"protected boolean isFiltered(Param param) {\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\twhile (elementToParse != null) {\n\t\t\tif (isFiltered(elementToParse, param)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telementToParse = getEnclosingSingleElementGroup(elementToParse);\n\t\t}\n\t\treturn false;\n\t}",
"public static ComponentsMultiThread getComponentsMultiThread() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.componentsMultiThread;\n }",
"public InternalTile paint(InternalTile tile) throws RenderException {\n\t\tif (tile.getContentType().equals(VectorTileContentType.URL_CONTENT)) {\n\t\t\tif (urlBuilder != null) {\n\t\t\t\tif (paintGeometries) {\n\t\t\t\t\turlBuilder.paintGeometries(paintGeometries);\n\t\t\t\t\turlBuilder.paintLabels(false);\n\t\t\t\t\ttile.setFeatureContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\tif (paintLabels) {\n\t\t\t\t\turlBuilder.paintGeometries(false);\n\t\t\t\t\turlBuilder.paintLabels(paintLabels);\n\t\t\t\t\ttile.setLabelContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\treturn tile;\n\t\t\t}\n\t\t}\n\t\treturn tile;\n\t}"
] |
Adds a logical operator block.
@param list parent criteria list
@param block current block
@param operator logical operator represented by this block | [
"private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator)\n {\n GenericCriteria result = new GenericCriteria(m_properties);\n result.setOperator(operator);\n list.add(result);\n processBlock(result.getCriteriaList(), getChildBlock(block));\n processBlock(list, getListNextBlock(block));\n }"
] | [
"@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }",
"public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }",
"public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }",
"@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }",
"public void store(Object obj) throws PersistenceBrokerException\n {\n obj = extractObjectToStore(obj);\n // only do something if obj != null\n if(obj == null) return;\n\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n /*\n if one of the PK fields was null, we assume the objects\n was new and needs insert\n */\n boolean insert = serviceBrokerHelper().hasNullPKField(cld, obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n /*\n if PK values are set, lookup cache or db to see whether object\n needs insert or update\n */\n if (!insert)\n {\n insert = objectCache.lookup(oid) == null\n && !serviceBrokerHelper().doesExist(cld, oid, obj);\n }\n store(obj, oid, cld, insert);\n }",
"private <T> InternalProviderImpl installInternalProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider,\n boolean isBound, boolean isTestProvider) {\n if (bindingName == null) {\n if (isBound) {\n return installUnNamedProvider(mapClassesToUnNamedBoundProviders, clazz, internalProvider, isTestProvider);\n } else {\n return installUnNamedProvider(mapClassesToUnNamedUnBoundProviders, clazz, internalProvider, isTestProvider);\n }\n } else {\n return installNamedProvider(mapClassesToNamedBoundProviders, clazz, bindingName, internalProvider, isTestProvider);\n }\n }",
"public void rename(String newName) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n response.getJSON();\n }",
"public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }",
"public void wipeInMemorySettings() {\n this.waitUntilInitialized();\n\n syncLock.lock();\n try {\n this.instanceChangeStreamListener.stop();\n if (instancesColl.find().first() == null) {\n throw new IllegalStateException(\"expected to find instance configuration\");\n }\n this.syncConfig = new InstanceSynchronizationConfig(configDb);\n this.instanceChangeStreamListener = new InstanceChangeStreamListenerImpl(\n syncConfig,\n service,\n networkMonitor,\n authMonitor\n );\n this.isConfigured = false;\n this.stop();\n } finally {\n syncLock.unlock();\n }\n }"
] |
Determine which field the Activity ID has been mapped to.
@param map field map
@return field | [
"private FieldType getActivityIDField(Map<FieldType, String> map)\n {\n FieldType result = null;\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n if (entry.getValue().equals(\"task_code\"))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }"
] | [
"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 void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData)\n {\n String notes = taskExtData.getString(TASK_NOTES);\n if (notes == null && data.length == 366)\n {\n byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362));\n if (offsetData != null && offsetData.length >= 12)\n {\n notes = taskVarData.getString(getOffset(offsetData, 8));\n \n // We do pick up some random stuff with this approach, and \n // we don't know enough about the file format to know when to ignore it\n // so we'll use a heuristic here to ignore anything that\n // doesn't look like RTF.\n if (notes != null && notes.indexOf('{') == -1)\n {\n notes = null;\n }\n }\n }\n \n if (notes != null)\n {\n if (m_reader.getPreserveNoteFormatting() == false)\n {\n notes = RtfHelper.strip(notes);\n }\n\n task.setNotes(notes);\n }\n }",
"private String getValueFromProp(final String propValue) {\n\n String value = propValue;\n // remove quotes\n value = value.trim();\n if ((value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.substring(1, value.length() - 1);\n }\n return value;\n }",
"List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) {\n\t\tList<String> dumpFileDates = findDumpDatesOnline(dumpContentType);\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String dateStamp : dumpFileDates) {\n\t\t\tif (dumpContentType == DumpContentType.DAILY) {\n\t\t\t\tresult.add(new WmfOnlineDailyDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager));\n\t\t\t} else if (dumpContentType == DumpContentType.JSON) {\n\t\t\t\tresult.add(new JsonOnlineDumpFile(dateStamp, this.projectName,\n\t\t\t\t\t\tthis.webResourceFetcher, this.dumpfileDirectoryManager));\n\t\t\t} else {\n\t\t\t\tresult.add(new WmfOnlineStandardDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager, dumpContentType));\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(\"Found \" + result.size() + \" online dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}",
"private void processUDF(UDFTypeType udf)\n {\n FieldTypeClass fieldType = FIELD_TYPE_MAP.get(udf.getSubjectArea());\n if (fieldType != null)\n {\n UserFieldDataType dataType = UserFieldDataType.getInstanceFromXmlName(udf.getDataType());\n String name = udf.getTitle();\n FieldType field = addUserDefinedField(fieldType, dataType, name);\n if (field != null)\n {\n m_fieldTypeMap.put(udf.getObjectId(), field);\n }\n }\n }",
"public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }",
"protected List<String> splitLinesAndNewLines(String text) {\n\t\tif (text == null)\n\t\t\treturn Collections.emptyList();\n\t\tint idx = initialSegmentSize(text);\n\t\tif (idx == text.length()) {\n\t\t\treturn Collections.singletonList(text);\n\t\t}\n\n\t\treturn continueSplitting(text, idx);\n\t}",
"public static base_responses add(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 addresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsacl6();\n\t\t\t\taddresources[i].acl6name = resources[i].acl6name;\n\t\t\t\taddresources[i].acl6action = resources[i].acl6action;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].established = resources[i].established;\n\t\t\t\taddresources[i].icmptype = resources[i].icmptype;\n\t\t\t\taddresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // If the API level is less than 11, we can't rely on the view animation system to\n // do the scrolling animation. Need to tick it here and call postInvalidate() until the scrolling is done.\n if (Build.VERSION.SDK_INT < 11) {\n tickScrollAnimation();\n if (!mScroller.isFinished()) {\n mGraph.postInvalidate();\n }\n }\n }"
] |
Sets the number of ms to wait before attempting to obtain a connection again after a failure.
@param acquireRetryDelay the acquireRetryDelay to set
@param timeUnit time granularity | [
"public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) {\n\t\tthis.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit);\n\t}"
] | [
"@Override\n public InstalledIdentity getInstalledIdentity(String productName, String productVersion) throws PatchingException {\n final String defaultIdentityName = defaultIdentity.getIdentity().getName();\n if(productName == null) {\n productName = defaultIdentityName;\n }\n\n final File productConf = new File(installedImage.getInstallationMetadata(), productName + Constants.DOT_CONF);\n final String recordedProductVersion;\n if(!productConf.exists()) {\n recordedProductVersion = null;\n } else {\n final Properties props = loadProductConf(productConf);\n recordedProductVersion = props.getProperty(Constants.CURRENT_VERSION);\n }\n\n if(defaultIdentityName.equals(productName)) {\n if(recordedProductVersion != null && !recordedProductVersion.equals(defaultIdentity.getIdentity().getVersion())) {\n // this means the patching history indicates that the current version is different from the one specified in the server's version module,\n // which could happen in case:\n // - the last applied CP didn't include the new version module or\n // - the version module version included in the last CP didn't match the version specified in the CP's metadata, or\n // - the version module was updated from a one-off, or\n // - the patching history was edited somehow\n // In any case, here I decided to rely on the patching history.\n defaultIdentity = loadIdentity(productName, recordedProductVersion);\n }\n if(productVersion != null && !defaultIdentity.getIdentity().getVersion().equals(productVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(\n productName, productVersion, defaultIdentity.getIdentity().getVersion()));\n }\n return defaultIdentity;\n }\n\n if(recordedProductVersion != null && !Constants.UNKNOWN.equals(recordedProductVersion)) {\n if(productVersion != null) {\n if (!productVersion.equals(recordedProductVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(productName, productVersion, recordedProductVersion));\n }\n } else {\n productVersion = recordedProductVersion;\n }\n }\n\n return loadIdentity(productName, productVersion);\n }",
"private D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\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 static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (PreparedStatement) Proxy.newProxyInstance(\n\t\t\t\tPreparedStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {PreparedStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public synchronized void reset() {\n this.authorizerDescription = StandardRBACAuthorizer.AUTHORIZER_DESCRIPTION;\n this.useIdentityRoles = this.nonFacadeMBeansSensitive = false;\n this.roleMappings = new HashMap<String, RoleMappingImpl>();\n RoleMaps oldRoleMaps = this.roleMaps;\n this.roleMaps = new RoleMaps(authorizerDescription.getStandardRoles(), Collections.<String, ScopedRole>emptyMap());\n for (ScopedRole role : oldRoleMaps.scopedRoles.values()) {\n for (ScopedRoleListener listener : scopedRoleListeners) {\n try {\n listener.scopedRoleRemoved(role);\n } catch (Exception ignored) {\n // TODO log an ERROR\n }\n }\n }\n }",
"private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgTileWriter());\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}",
"public static int cudnnConvolutionForward(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n cudnnFilterDescriptor wDesc, \n Pointer w, \n cudnnConvolutionDescriptor convDesc, \n int algo, \n Pointer workSpace, \n long workSpaceSizeInBytes, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnConvolutionForwardNative(handle, alpha, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, beta, yDesc, y));\n }",
"public static Cluster\n balanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster,\n final int maxContiguousPartitionsPerZone) {\n System.out.println(\"Balance number of contiguous partitions within a zone.\");\n System.out.println(\"numPartitionsPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \"\n + nextCandidateCluster.getNumberOfPartitionsInZone(zoneId));\n }\n System.out.println(\"numNodesPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \" + nextCandidateCluster.getNumberOfNodesInZone(zoneId));\n }\n\n // Break up contiguous partitions within each zone\n HashMap<Integer, List<Integer>> partitionsToRemoveFromZone = Maps.newHashMap();\n System.out.println(\"Contiguous partitions\");\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(\"\\tZone: \" + zoneId);\n Map<Integer, Integer> partitionToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(nextCandidateCluster,\n zoneId);\n\n List<Integer> partitionsToRemoveFromThisZone = new ArrayList<Integer>();\n for(Map.Entry<Integer, Integer> entry: partitionToRunLength.entrySet()) {\n if(entry.getValue() > maxContiguousPartitionsPerZone) {\n List<Integer> contiguousPartitions = new ArrayList<Integer>(entry.getValue());\n for(int partitionId = entry.getKey(); partitionId < entry.getKey()\n + entry.getValue(); partitionId++) {\n contiguousPartitions.add(partitionId\n % nextCandidateCluster.getNumberOfPartitions());\n }\n System.out.println(\"Contiguous partitions: \" + contiguousPartitions);\n partitionsToRemoveFromThisZone.addAll(Utils.removeItemsToSplitListEvenly(contiguousPartitions,\n maxContiguousPartitionsPerZone));\n }\n }\n\n partitionsToRemoveFromZone.put(zoneId, partitionsToRemoveFromThisZone);\n System.out.println(\"\\t\\tPartitions to remove: \" + partitionsToRemoveFromThisZone);\n }\n\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n Random r = new Random();\n for(int zoneId: returnCluster.getZoneIds()) {\n for(int partitionId: partitionsToRemoveFromZone.get(zoneId)) {\n // Pick a random other zone Id\n List<Integer> otherZoneIds = new ArrayList<Integer>();\n for(int otherZoneId: returnCluster.getZoneIds()) {\n if(otherZoneId != zoneId) {\n otherZoneIds.add(otherZoneId);\n }\n }\n int whichOtherZoneId = otherZoneIds.get(r.nextInt(otherZoneIds.size()));\n\n // Pick a random node from other zone ID\n int whichNodeOffset = r.nextInt(returnCluster.getNumberOfNodesInZone(whichOtherZoneId));\n int whichNodeId = new ArrayList<Integer>(returnCluster.getNodeIdsInZone(whichOtherZoneId)).get(whichNodeOffset);\n\n // Steal partition from one zone to another!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n whichNodeId,\n Lists.newArrayList(partitionId));\n }\n }\n\n return returnCluster;\n\n }",
"public static Date getDateFromConciseStr(String str) {\n\n Date d = null;\n if (str == null || str.isEmpty())\n return null;\n\n try {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMddHHmmssSSSZ\");\n\n d = sdf.parse(str);\n } catch (Exception ex) {\n logger.error(ex + \"Exception while converting string to date : \"\n + str);\n }\n\n return d;\n }"
] |
Adds a perspective camera constructed from the designated
perspective camera to describe the shadow projection.
This type of camera is used for shadows generated by spot lights.
@param centerCam GVRPerspectiveCamera to derive shadow projection from
@param coneAngle spot light cone angle
@return Perspective camera to use for shadow casting
@see GVRSpotLight | [
"static GVRPerspectiveCamera makePerspShadowCamera(GVRPerspectiveCamera centerCam, float coneAngle)\n {\n GVRPerspectiveCamera camera = new GVRPerspectiveCamera(centerCam.getGVRContext());\n float near = centerCam.getNearClippingDistance();\n float far = centerCam.getFarClippingDistance();\n\n camera.setNearClippingDistance(near);\n camera.setFarClippingDistance(far);\n camera.setFovY((float) Math.toDegrees(coneAngle));\n camera.setAspectRatio(1.0f);\n return camera;\n }"
] | [
"public static lbvserver_filterpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_filterpolicy_binding obj = new lbvserver_filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_filterpolicy_binding response[] = (lbvserver_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"void setDayOfMonth(String day) {\n\n final int i = CmsSerialDateUtil.toIntWithDefault(day, -1);\n if (m_model.getDayOfMonth() != i) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setDayOfMonth(i);\n onValueChange();\n }\n });\n }\n }",
"public boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }",
"@SuppressWarnings(\"unchecked\")\n public T[] nextPermutationAsArray()\n {\n T[] permutation = (T[]) Array.newInstance(elements.getClass().getComponentType(),\n permutationIndices.length);\n return nextPermutationAsArray(permutation);\n }",
"public static void addItemsHandled(String handledItemsType, int handledItemsNumber) {\n \tJobLogger jobLogger = (JobLogger) getInstance();\n if (jobLogger == null) {\n return;\n }\n\n jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber);\n }",
"public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}",
"@Override\n public void setCursorDepth(float depth)\n {\n super.setCursorDepth(depth);\n if (mRayModel != null)\n {\n mRayModel.getTransform().setScaleZ(mCursorDepth);\n }\n }",
"public static String plus(CharSequence left, Object value) {\n return left + DefaultGroovyMethods.toString(value);\n }",
"public ArrayList<Duration> segmentWork(ProjectCalendar projectCalendar, List<TimephasedWork> work, TimescaleUnits rangeUnits, List<DateRange> dateList)\n {\n ArrayList<Duration> result = new ArrayList<Duration>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, work, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(Duration.getInstance(0, TimeUnit.HOURS));\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeDuration(projectCalendar, rangeUnits, range, work, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }"
] |
Create a new collaboration object.
@param api the API connection used to make the request.
@param accessibleBy the JSON object describing who should be collaborated.
@param item the JSON object describing which item to collaborate.
@param role the role to give the collaborators.
@param notify the user/group should receive email notification of the collaboration or not.
@param canViewPath the view path collaboration feature is enabled or not.
@return info about the new collaboration. | [
"protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item,\n BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) {\n\n\n String queryString = \"\";\n if (notify != null) {\n queryString = new QueryStringBuilder().appendParam(\"notify\", notify.toString()).toString();\n }\n URL url;\n if (queryString.length() > 0) {\n url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString);\n } else {\n url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL());\n }\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", item);\n requestJSON.add(\"accessible_by\", accessibleBy);\n requestJSON.add(\"role\", role.toJSONString());\n if (canViewPath != null) {\n requestJSON.add(\"can_view_path\", canViewPath.booleanValue());\n }\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get(\"id\").asString());\n return newCollaboration.new Info(responseJSON);\n }"
] | [
"public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {\n if (artifactsProps == null) {\n artifactsProps = ArrayListMultimap.create();\n }\n artifactsProps.put(\"build.name\", buildName);\n artifactsProps.put(\"build.number\", buildNumber);\n artifactsProps.put(\"build.timestamp\", timestamp);\n String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);\n\n Properties buildInfoItemsProps = new Properties();\n buildInfoItemsProps.setProperty(\"build.name\", buildName);\n buildInfoItemsProps.setProperty(\"build.number\", buildNumber);\n buildInfoItemsProps.setProperty(\"build.timestamp\", timestamp);\n\n ArtifactoryServer server = config.getArtifactoryServer();\n CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();\n ArtifactoryDependenciesClient dependenciesClient = null;\n ArtifactoryBuildInfoClient propertyChangeClient = null;\n\n try {\n dependenciesClient = server.createArtifactoryDependenciesClient(\n preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);\n\n CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);\n propertyChangeClient = server.createArtifactoryClient(\n preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy));\n\n Module buildInfoModule = new Module();\n buildInfoModule.setId(imageTag.substring(imageTag.indexOf(\"/\") + 1));\n\n // If manifest and imagePath not found, return.\n if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {\n return buildInfoModule;\n }\n\n listener.getLogger().println(\"Fetching details of published docker layers from Artifactory...\");\n boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);\n DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);\n\n listener.getLogger().println(\"Tagging published docker layers with build properties in Artifactory...\");\n setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,\n dependenciesClient, propertyChangeClient, server);\n setBuildInfoModuleProps(buildInfoModule);\n return buildInfoModule;\n } finally {\n if (dependenciesClient != null) {\n dependenciesClient.close();\n }\n if (propertyChangeClient != null) {\n propertyChangeClient.close();\n }\n }\n }",
"public static String removeOpenCmsContext(final String path) {\n\n String context = OpenCms.getSystemInfo().getOpenCmsContext();\n if (path.startsWith(context + \"/\")) {\n return path.substring(context.length());\n }\n String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix();\n if (path.startsWith(renderPrefix + \"/\")) {\n return path.substring(renderPrefix.length());\n }\n return path;\n }",
"public List<WbSearchEntitiesResult> wbSearchEntities(String search, String language,\n Boolean strictLanguage, String type, Long limit, Long offset)\n throws MediaWikiApiErrorException {\n\n Map<String, String> parameters = new HashMap<String, String>();\n parameters.put(ApiConnection.PARAM_ACTION, \"wbsearchentities\");\n\n if (search != null) {\n parameters.put(\"search\", search);\n } else {\n throw new IllegalArgumentException(\n \"Search parameter must be specified for this action.\");\n }\n\n if (language != null) {\n parameters.put(\"language\", language);\n } else {\n throw new IllegalArgumentException(\n \"Language parameter must be specified for this action.\");\n }\n if (strictLanguage != null) {\n parameters.put(\"strictlanguage\", Boolean.toString(strictLanguage));\n }\n\n if (type != null) {\n parameters.put(\"type\", type);\n }\n\n if (limit != null) {\n parameters.put(\"limit\", Long.toString(limit));\n }\n\n if (offset != null) {\n parameters.put(\"continue\", Long.toString(offset));\n }\n\n List<WbSearchEntitiesResult> results = new ArrayList<>();\n\n try {\n JsonNode root = this.connection.sendJsonRequest(\"POST\", parameters);\n JsonNode entities = root.path(\"search\");\n for (JsonNode entityNode : entities) {\n try {\n JacksonWbSearchEntitiesResult ed = mapper.treeToValue(entityNode,\n JacksonWbSearchEntitiesResult.class);\n results.add(ed);\n } catch (JsonProcessingException e) {\n LOGGER.error(\"Error when reading JSON for entity \"\n + entityNode.path(\"id\").asText(\"UNKNOWN\") + \": \"\n + e.toString());\n }\n }\n } catch (IOException e) {\n LOGGER.error(\"Could not retrive data: \" + e.toString());\n }\n\n return results;\n }",
"public void bootstrap() throws Exception {\n final HostRunningModeControl runningModeControl = environment.getRunningModeControl();\n final ControlledProcessState processState = new ControlledProcessState(true);\n shutdownHook.setControlledProcessState(processState);\n ServiceTarget target = serviceContainer.subTarget();\n ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService.addService(target, processState).getValue();\n RunningStateJmx.registerMBean(controlledProcessStateService, null, runningModeControl, false);\n final HostControllerService hcs = new HostControllerService(environment, runningModeControl, authCode, processState);\n target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install();\n }",
"public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }",
"@SuppressWarnings(\"unused\")\n public void selectItem(int position, boolean invokeListeners) {\n IOperationItem item = mOuterAdapter.getItem(position);\n IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition);\n\n int realPosition = mOuterAdapter.normalizePosition(position);\n //do nothing if position not changed\n if (realPosition == mCurrentItemPosition) {\n return;\n }\n int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition;\n\n item.setVisible(false);\n\n startSelectedViewOutAnimation(position);\n\n mOuterAdapter.notifyRealItemChanged(position);\n mRealHidedPosition = realPosition;\n\n oldHidedItem.setVisible(true);\n mFlContainerSelected.requestLayout();\n mOuterAdapter.notifyRealItemChanged(itemToShowAdapterPosition);\n mCurrentItemPosition = realPosition;\n\n if (invokeListeners) {\n notifyItemClickListeners(realPosition);\n }\n\n if (BuildConfig.DEBUG) {\n Log.i(TAG, \"clicked on position =\" + position);\n }\n\n }",
"public void moveUp(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index > 0) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index - 1);\n }\n updateButtonBars();\n }",
"final protected char next(final ByteBuffer buffer, boolean allow8859) throws BaseExceptions.BadMessage {\n\n if (!buffer.hasRemaining()) return HttpTokens.EMPTY_BUFF;\n\n if (_segmentByteLimit <= _segmentBytePosition) {\n shutdownParser();\n throw new BaseExceptions.BadMessage(\"Request length limit exceeded: \" + _segmentByteLimit);\n }\n\n final byte b = buffer.get();\n _segmentBytePosition++;\n\n // If we ended on a CR, make sure we are\n if (_cr) {\n if (b != HttpTokens.LF) {\n throw new BadCharacter(\"Invalid sequence: LF didn't follow CR: \" + b);\n }\n _cr = false;\n return (char)b; // must be LF\n }\n\n // Make sure its a valid character\n if (b < HttpTokens.SPACE) {\n if (b == HttpTokens.CR) { // Set the flag to check for _cr and just run again\n _cr = true;\n return next(buffer, allow8859);\n }\n else if (b == HttpTokens.TAB || allow8859 && b < 0) {\n return (char)(b & 0xff);\n }\n else if (b == HttpTokens.LF) {\n return (char)b; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3\n }\n else if (isLenient()) {\n return HttpTokens.REPLACEMENT;\n }\n else {\n shutdownParser();\n throw new BadCharacter(\"Invalid char: '\" + (char)(b & 0xff) + \"', 0x\" + Integer.toHexString(b));\n }\n }\n\n // valid ascii char\n return (char)b;\n }",
"public static final Double parseCurrency(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() / 100));\n }"
] |
Determines the median value of the data set.
@return If the number of elements is odd, returns the middle element.
If the number of elements is even, returns the midpoint of the two
middle elements.
@since 1.0.1 | [
"public final double getMedian()\n {\n assertNotEmpty();\n // Sort the data (take a copy to do this).\n double[] dataCopy = new double[getSize()];\n System.arraycopy(dataSet, 0, dataCopy, 0, dataCopy.length);\n Arrays.sort(dataCopy);\n int midPoint = dataCopy.length / 2;\n if (dataCopy.length % 2 != 0)\n {\n return dataCopy[midPoint];\n }\n else\n {\n return dataCopy[midPoint - 1] + (dataCopy[midPoint] - dataCopy[midPoint - 1]) / 2;\n }\n }"
] | [
"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 T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}",
"public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }",
"public static boolean isDouble(CharSequence self) {\n try {\n Double.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"private void logOriginalRequestHistory(String requestType,\n HttpServletRequest request, History history) {\n logger.info(\"Storing original request history\");\n history.setRequestType(requestType);\n history.setOriginalRequestHeaders(HttpUtilities.getHeaders(request));\n history.setOriginalRequestURL(request.getRequestURL().toString());\n history.setOriginalRequestParams(request.getQueryString() == null ? \"\" : request.getQueryString());\n logger.info(\"Done storing\");\n }",
"private void processConstraints(Row row, Task task)\n {\n ConstraintType constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n Date constraintDate = null;\n\n switch (row.getInt(\"CONSTRAINU\"))\n {\n case 0:\n {\n if (row.getInt(\"PLACEMENT\") == 0)\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n }\n else\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n }\n break;\n }\n\n case 1:\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 2:\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 3:\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = row.getDate(\"START_CONSTRAINT_DATE\");\n break;\n }\n\n case 4:\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 5:\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 6:\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = row.getDate(\"END_CONSTRAINT_DATE\");\n break;\n }\n\n case 8:\n {\n task.setDeadline(row.getDate(\"END_CONSTRAINT_DATE\"));\n break;\n }\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"protected Container findContainer(ContainerContext ctx, StringBuilder dump) {\n Container container = null;\n // 1. Custom container class\n String containerClassName = ctx.getServletContext().getInitParameter(Container.CONTEXT_PARAM_CONTAINER_CLASS);\n if (containerClassName != null) {\n try {\n Class<Container> containerClass = Reflections.classForName(resourceLoader, containerClassName);\n container = SecurityActions.newInstance(containerClass);\n WeldServletLogger.LOG.containerDetectionSkipped(containerClassName);\n } catch (Exception e) {\n WeldServletLogger.LOG.unableToInstantiateCustomContainerClass(containerClassName);\n WeldServletLogger.LOG.catchingDebug(e);\n }\n }\n if (container == null) {\n // 2. Service providers\n Iterable<Container> extContainers = ServiceLoader.load(Container.class, getClass().getClassLoader());\n container = checkContainers(ctx, dump, extContainers);\n if (container == null) {\n // 3. Built-in containers in predefined order\n container = checkContainers(ctx, dump,\n Arrays.asList(TomcatContainer.INSTANCE, JettyContainer.INSTANCE, UndertowContainer.INSTANCE, GwtDevHostedModeContainer.INSTANCE));\n }\n }\n return container;\n }",
"public static void Shuffle(double[] array, long seed) {\n Random random = new Random();\n if (seed != 0) random.setSeed(seed);\n\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n double temp = array[index];\n array[index] = array[i];\n array[i] = temp;\n }\n }",
"private static RemoteWebDriver buildRemoteWebDriver(String hubUrl) {\n\t\tDesiredCapabilities capabilities = new DesiredCapabilities();\n\t\tcapabilities.setPlatform(Platform.ANY);\n\t\tURL url;\n\t\ttry {\n\t\t\turl = new URL(hubUrl);\n\t\t} catch (MalformedURLException e) {\n\t\t\tLOGGER.error(\"The given hub url of the remote server is malformed can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\tHttpCommandExecutor executor = null;\n\t\ttry {\n\t\t\texecutor = new HttpCommandExecutor(url);\n\t\t} catch (Exception e) {\n\t\t\t// TODO Stefan; refactor this catch, this will definitely result in\n\t\t\t// NullPointers, why\n\t\t\t// not throw RuntimeException direct?\n\t\t\tLOGGER.error(\n\t\t\t\t\t\"Received unknown exception while creating the \"\n\t\t\t\t\t\t\t+ \"HttpCommandExecutor, can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\treturn new RemoteWebDriver(executor, capabilities);\n\t}"
] |
Disassociate a name with an object
@param name The name of an object.
@exception ObjectNameNotFoundException No object exists in the database with that name. | [
"public void unbind(String name) throws ObjectNameNotFoundException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call unbind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call unbind\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call lookup.\");\r\n }\r\n\r\n tx.getNamedRootsMap().unbind(name);\r\n }"
] | [
"@Override\n public void preStateCrawling(CrawlerContext context,\n ImmutableList<CandidateElement> candidateElements, StateVertex state) {\n LOG.debug(\"preStateCrawling\");\n List<CandidateElementPosition> newElements = Lists.newLinkedList();\n LOG.info(\"Prestate found new state {} with {} candidates\", state.getName(),\n candidateElements.size());\n for (CandidateElement element : candidateElements) {\n try {\n WebElement webElement = getWebElement(context.getBrowser(), element);\n if (webElement != null) {\n newElements.add(findElement(webElement, element));\n }\n } catch (WebDriverException e) {\n LOG.info(\"Could not get position for {}\", element, e);\n }\n }\n\n StateBuilder stateOut = outModelCache.addStateIfAbsent(state);\n stateOut.addCandidates(newElements);\n LOG.trace(\"preState finished, elements added to state\");\n }",
"public int count() {\n int n = 0;\n for (ConcurrentMap<?, ?> bag : registry.values()) {\n n += bag.size();\n }\n return n;\n }",
"void init( DMatrixSparseCSC A ) {\n this.A = A;\n this.m = A.numRows;\n this.n = A.numCols;\n\n this.next = 0;\n this.head = m;\n this.tail = m + n;\n this.nque = m + 2*n;\n\n if( parent.length < n || leftmost.length < m) {\n parent = new int[n];\n post = new int[n];\n pinv = new int[m+n];\n countsR = new int[n];\n leftmost = new int[m];\n }\n gwork.reshape(m+3*n);\n }",
"public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) {\n int shift = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n bytes[i] = (byte) (0xFF & (value >> shift));\n shift += 8;\n }\n }",
"public static base_response add(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy addresource = new dospolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.qdepth = resource.qdepth;\n\t\taddresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void writeAssignments()\n {\n Allocations allocations = m_factory.createAllocations();\n m_plannerProject.setAllocations(allocations);\n\n List<Allocation> allocationList = allocations.getAllocation();\n for (ResourceAssignment mpxjAssignment : m_projectFile.getResourceAssignments())\n {\n Allocation plannerAllocation = m_factory.createAllocation();\n allocationList.add(plannerAllocation);\n\n plannerAllocation.setTaskId(getIntegerString(mpxjAssignment.getTask().getUniqueID()));\n plannerAllocation.setResourceId(getIntegerString(mpxjAssignment.getResourceUniqueID()));\n plannerAllocation.setUnits(getIntegerString(mpxjAssignment.getUnits()));\n\n m_eventManager.fireAssignmentWrittenEvent(mpxjAssignment);\n }\n }",
"public static PathAddress pathAddress(final ModelNode node) {\n if (node.isDefined()) {\n\n// final List<Property> props = node.asPropertyList();\n // Following bit is crap TODO; uncomment above and delete below\n // when bug is fixed\n final List<Property> props = new ArrayList<Property>();\n String key = null;\n for (ModelNode element : node.asList()) {\n Property prop = null;\n if (element.getType() == ModelType.PROPERTY || element.getType() == ModelType.OBJECT) {\n prop = element.asProperty();\n } else if (key == null) {\n key = element.asString();\n } else {\n prop = new Property(key, element);\n }\n if (prop != null) {\n props.add(prop);\n key = null;\n }\n\n }\n if (props.size() == 0) {\n return EMPTY_ADDRESS;\n } else {\n final Set<String> seen = new HashSet<String>();\n final List<PathElement> values = new ArrayList<PathElement>();\n int index = 0;\n for (final Property prop : props) {\n final String name = prop.getName();\n if (seen.add(name)) {\n values.add(new PathElement(name, prop.getValue().asString()));\n } else {\n throw duplicateElement(name);\n }\n if (index == 1 && name.equals(SERVER) && seen.contains(HOST)) {\n seen.clear();\n }\n index++;\n }\n return new PathAddress(Collections.unmodifiableList(values));\n }\n } else {\n return EMPTY_ADDRESS;\n }\n }",
"public static base_responses update(nitro_service client, appfwlearningsettings resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningsettings updateresources[] = new appfwlearningsettings[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new appfwlearningsettings();\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].starturlminthreshold = resources[i].starturlminthreshold;\n\t\t\t\tupdateresources[i].starturlpercentthreshold = resources[i].starturlpercentthreshold;\n\t\t\t\tupdateresources[i].cookieconsistencyminthreshold = resources[i].cookieconsistencyminthreshold;\n\t\t\t\tupdateresources[i].cookieconsistencypercentthreshold = resources[i].cookieconsistencypercentthreshold;\n\t\t\t\tupdateresources[i].csrftagminthreshold = resources[i].csrftagminthreshold;\n\t\t\t\tupdateresources[i].csrftagpercentthreshold = resources[i].csrftagpercentthreshold;\n\t\t\t\tupdateresources[i].fieldconsistencyminthreshold = resources[i].fieldconsistencyminthreshold;\n\t\t\t\tupdateresources[i].fieldconsistencypercentthreshold = resources[i].fieldconsistencypercentthreshold;\n\t\t\t\tupdateresources[i].crosssitescriptingminthreshold = resources[i].crosssitescriptingminthreshold;\n\t\t\t\tupdateresources[i].crosssitescriptingpercentthreshold = resources[i].crosssitescriptingpercentthreshold;\n\t\t\t\tupdateresources[i].sqlinjectionminthreshold = resources[i].sqlinjectionminthreshold;\n\t\t\t\tupdateresources[i].sqlinjectionpercentthreshold = resources[i].sqlinjectionpercentthreshold;\n\t\t\t\tupdateresources[i].fieldformatminthreshold = resources[i].fieldformatminthreshold;\n\t\t\t\tupdateresources[i].fieldformatpercentthreshold = resources[i].fieldformatpercentthreshold;\n\t\t\t\tupdateresources[i].xmlwsiminthreshold = resources[i].xmlwsiminthreshold;\n\t\t\t\tupdateresources[i].xmlwsipercentthreshold = resources[i].xmlwsipercentthreshold;\n\t\t\t\tupdateresources[i].xmlattachmentminthreshold = resources[i].xmlattachmentminthreshold;\n\t\t\t\tupdateresources[i].xmlattachmentpercentthreshold = resources[i].xmlattachmentpercentthreshold;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static List<Node> getSiblings(Node parent, Node element) {\n\t\tList<Node> result = new ArrayList<>();\n\t\tNodeList list = parent.getChildNodes();\n\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\tNode el = list.item(i);\n\n\t\t\tif (el.getNodeName().equals(element.getNodeName())) {\n\t\t\t\tresult.add(el);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}"
] |
Returns true if required properties for FluoAdmin are set | [
"public boolean hasRequiredAdminProps() {\n boolean valid = true;\n valid &= hasRequiredClientProps();\n valid &= verifyStringPropSet(ACCUMULO_TABLE_PROP, ADMIN_ACCUMULO_TABLE_PROP);\n return valid;\n }"
] | [
"public void fatal(String msg) {\n\t\tlogIfEnabled(Level.FATAL, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}",
"private void buildTransformers_3_0(ResourceTransformationDescriptionBuilder builder) {\n /*\n ====== Resource root address: [\"subsystem\" => \"remoting\"] - Current version: 4.0.0; legacy version: 3.0.0 =======\n --- Problems for relative address to root [\"configuration\" => \"endpoint\"]:\n Different 'default' for attribute 'sasl-protocol'. Current: \"remote\"; legacy: \"remoting\" ## both are valid also for legacy servers\n --- Problems for relative address to root [\"connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n --- Problems for relative address to root [\"http-connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory]\n --- Problems for relative address to root [\"remote-outbound-connection\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for attribute 'protocol'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'security-realm'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'username'. Current: [\"authentication-context\"]; legacy: undefined\n Missing parameters for operation 'add' in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for parameter 'protocol' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'security-realm' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'username' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n */\n\n builder.addChildResource(ConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT);\n\n builder.addChildResource(RemotingEndpointResource.ENDPOINT_PATH).getAttributeBuilder()\n .setValueConverter(new AttributeConverter.DefaultAttributeConverter() {\n @Override\n protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {\n if (!attributeValue.isDefined()) {\n attributeValue.set(\"remoting\"); //if value is not defined, set it to EAP 7.0 default valueRemotingSubsystemTransformersTestCase\n }\n }\n }, RemotingSubsystemRootResource.SASL_PROTOCOL);\n\n builder.addChildResource(HttpConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY);\n\n builder.addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, RemoteOutboundConnectionResourceDefinition.AUTHENTICATION_CONTEXT);\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 ResourceAssignmentWorkgroupFields addWorkgroupAssignment() throws MPXJException\n {\n if (m_workgroup != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n m_workgroup = new ResourceAssignmentWorkgroupFields();\n\n return (m_workgroup);\n }",
"private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}",
"public PartialCollection<BoxItem.Info> getItemsRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"offset\", offset)\n .appendParam(\"limit\", limit);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_COLLECTION_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> items = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n BoxItem.Info entryInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject());\n if (entryInfo != null) {\n items.add(entryInfo);\n }\n }\n return items;\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }",
"public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) {\r\n\r\n\t\tif(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tthrow new IllegalArgumentException(\"SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL.\");\r\n\t\t}\r\n\r\n\t\t//Reverse sign of moneyness, if switching between payer and receiver convention.\r\n\t\tint reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1;\r\n\r\n\t\tList<Integer> maturities\t= new ArrayList<>();\r\n\t\tList<Integer> tenors\t\t= new ArrayList<>();\r\n\t\tList<Integer> moneynesss\t= new ArrayList<>();\r\n\t\tList<Double> values\t\t= new ArrayList<>();\r\n\r\n\t\tfor(DataKey key : entryMap.keySet()) {\r\n\t\t\tmaturities.add(key.maturity);\r\n\t\t\ttenors.add(key.tenor);\r\n\t\t\tmoneynesss.add(key.moneyness * reverse);\r\n\t\t\tvalues.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model));\r\n\t\t}\r\n\r\n\t\treturn new SwaptionDataLattice(referenceDate, targetConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule,\r\n\t\t\t\tmaturities.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\ttenors.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\tmoneynesss.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\tvalues.stream().mapToDouble(Double::doubleValue).toArray());\r\n\t}",
"public static <V> V doWorkInPool(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) throws Exception {\n if (pool == null) {\n throw new IllegalArgumentException(\"pool must not be null\");\n }\n if (work == null) {\n throw new IllegalArgumentException(\"work must not be null\");\n }\n final V result;\n final Jedis poolResource = pool.getResource();\n try {\n result = work.doWork(poolResource);\n } finally {\n poolResource.close();\n }\n return result;\n }"
] |
Get all registration points associated with this registration.
@return all registration points. Will not be {@code null} but may be empty | [
"public synchronized Set<RegistrationPoint> getRegistrationPoints() {\n Set<RegistrationPoint> result = new HashSet<>();\n for (List<RegistrationPoint> registrationPoints : registrationPoints.values()) {\n result.addAll(registrationPoints);\n }\n return Collections.unmodifiableSet(result);\n }"
] | [
"public Node findEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getFindEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}",
"public static double elementMin( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a minimum.\n // Otherwise zero needs to be considered\n double min = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val < min ) {\n min = val;\n }\n }\n\n return min;\n }",
"public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }",
"public static BoxCollaborationWhitelistExemptTarget.Info create(final BoxAPIConnection api, String userID) {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"user\", new JsonObject()\n .add(\"type\", \"user\")\n .add(\"id\", userID));\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelistExemptTarget userWhitelist = new BoxCollaborationWhitelistExemptTarget(api,\n responseJSON.get(\"id\").asString());\n\n return userWhitelist.new Info(responseJSON);\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\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 static int lengthOfCodePoint(int codePoint)\n {\n if (codePoint < 0) {\n throw new InvalidCodePointException(codePoint);\n }\n if (codePoint < 0x80) {\n // normal ASCII\n // 0xxx_xxxx\n return 1;\n }\n if (codePoint < 0x800) {\n return 2;\n }\n if (codePoint < 0x1_0000) {\n return 3;\n }\n if (codePoint < 0x11_0000) {\n return 4;\n }\n // Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal\n throw new InvalidCodePointException(codePoint);\n }",
"public void emitEvent(\n final NamespaceSynchronizationConfig nsConfig,\n final ChangeEvent<BsonDocument> event) {\n listenersLock.lock();\n try {\n if (nsConfig.getNamespaceListenerConfig() == null) {\n return;\n }\n final NamespaceListenerConfig namespaceListener =\n nsConfig.getNamespaceListenerConfig();\n eventDispatcher.dispatch(() -> {\n try {\n if (namespaceListener.getEventListener() != null) {\n namespaceListener.getEventListener().onEvent(\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ChangeEvents.transformChangeEventForUser(\n event, namespaceListener.getDocumentCodec()));\n }\n } catch (final Exception ex) {\n logger.error(String.format(\n Locale.US,\n \"emitEvent ns=%s documentId=%s emit exception: %s\",\n event.getNamespace(),\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ex), ex);\n }\n return null;\n });\n } finally {\n listenersLock.unlock();\n }\n }",
"protected void checkJobType(final String jobName, final Class<?> jobType) {\n if (jobName == null) {\n throw new IllegalArgumentException(\"jobName must not be null\");\n }\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n if (!(Runnable.class.isAssignableFrom(jobType)) \n && !(Callable.class.isAssignableFrom(jobType))) {\n throw new IllegalArgumentException(\n \"jobType must implement either Runnable or Callable: \" + jobType);\n }\n }"
] |
Main method to start reading the plain text given by the client
@param args
, where arg[0] is Beast configuration file (beast.properties)
and arg[1] is Logger configuration file (logger.properties)
@throws Exception | [
"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 }"
] | [
"public List<Object> stepsInstances(List<CandidateSteps> candidateSteps) {\n List<Object> instances = new ArrayList<>();\n for (CandidateSteps steps : candidateSteps) {\n if (steps instanceof Steps) {\n instances.add(((Steps) steps).instance());\n }\n }\n return instances;\n }",
"public static Collection<CurrencyUnit> getCurrencies(String... providers) {\n return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryCurrenciesSingletonSpi loaded, check your system setup.\"))\n .getCurrencies(providers);\n }",
"public static String asTime(long time) {\n if (time > HOUR) {\n return String.format(\"%.1f h\", (time / HOUR));\n } else if (time > MINUTE) {\n return String.format(\"%.1f m\", (time / MINUTE));\n } else if (time > SECOND) {\n return String.format(\"%.1f s\", (time / SECOND));\n } else {\n return String.format(\"%d ms\", time);\n }\n }",
"public static List<int[]> createList( int N )\n {\n int data[] = new int[ N ];\n for( int i = 0; i < data.length; i++ ) {\n data[i] = -1;\n }\n\n List<int[]> ret = new ArrayList<int[]>();\n\n createList(data,0,-1,ret);\n\n return ret;\n }",
"static void tryAutoAttaching(final SlotReference slot) {\n if (!MetadataFinder.getInstance().getMountedMediaSlots().contains(slot)) {\n logger.error(\"Unable to auto-attach cache to empty slot {}\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getMetadataCache(slot) != null) {\n logger.info(\"Not auto-attaching to slot {}; already has a cache attached.\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getAutoAttachCacheFiles().isEmpty()) {\n logger.debug(\"No auto-attach files configured.\");\n return;\n }\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5); // Give us a chance to find out what type of media is in the new mount.\n final MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null && details.mediaType == CdjStatus.TrackType.REKORDBOX) {\n // First stage attempt: See if we can match based on stored media details, which is both more reliable and\n // less disruptive than trying to sample the player database to compare entries.\n boolean attached = false;\n for (File file : MetadataFinder.getInstance().getAutoAttachCacheFiles()) {\n final MetadataCache cache = new MetadataCache(file);\n try {\n if (cache.sourceMedia != null && cache.sourceMedia.hashKey().equals(details.hashKey())) {\n // We found a solid match, no need to probe tracks.\n final boolean changed = cache.sourceMedia.hasChanged(details);\n logger.info(\"Auto-attaching metadata cache \" + cache.getName() + \" to slot \" + slot +\n \" based on media details \" + (changed? \"(changed since created)!\" : \"(unchanged).\"));\n MetadataFinder.getInstance().attachMetadataCacheInternal(slot, cache);\n attached = true;\n return;\n }\n } finally {\n if (!attached) {\n cache.close();\n }\n }\n }\n\n // Could not match based on media details; fall back to older method based on probing track metadata.\n ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {\n @Override\n public Object useClient(Client client) throws Exception {\n tryAutoAttachingWithConnection(slot, client);\n return null;\n }\n };\n ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, \"trying to auto-attach metadata cache\");\n }\n } catch (Exception e) {\n logger.error(\"Problem trying to auto-attach metadata cache for slot \" + slot, e);\n }\n\n }\n }, \"Metadata cache file auto-attachment attempt\").start();\n }",
"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 }",
"public int rebalanceNode(final RebalanceTaskInfo stealInfo) {\n\n final RebalanceTaskInfo info = metadataStore.getRebalancerState()\n .find(stealInfo.getDonorId());\n\n // Do we have the plan in the state?\n if(info == null) {\n throw new VoldemortException(\"Could not find plan \" + stealInfo\n + \" in the server state on \" + metadataStore.getNodeId());\n } else if(!info.equals(stealInfo)) {\n // If we do have the plan, is it the same\n throw new VoldemortException(\"The plan in server state \" + info\n + \" is not the same as the process passed \" + stealInfo);\n } else if(!acquireRebalancingPermit(stealInfo.getDonorId())) {\n // Both are same, now try to acquire a lock for the donor node\n throw new AlreadyRebalancingException(\"Node \" + metadataStore.getNodeId()\n + \" is already rebalancing from donor \"\n + info.getDonorId() + \" with info \" + info);\n }\n\n // Acquired lock successfully, start rebalancing...\n int requestId = asyncService.getUniqueRequestId();\n\n // Why do we pass 'info' instead of 'stealInfo'? So that we can change\n // the state as the stores finish rebalance\n asyncService.submitOperation(requestId,\n new StealerBasedRebalanceAsyncOperation(this,\n voldemortConfig,\n metadataStore,\n requestId,\n info));\n\n return requestId;\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 }",
"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 }"
] |
List all the environment variables for an app.
@param appName App name. See {@link #listApps} for a list of apps that can be used.
@return map of config vars | [
"public Map<String, String> listConfig(String appName) {\n return connection.execute(new ConfigList(appName), apiKey);\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 }",
"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 decreaseIndent() throws IOException\n {\n if (m_pretty)\n {\n m_writer.write('\\n');\n m_indent = m_indent.substring(0, m_indent.length() - INDENT.length());\n m_writer.write(m_indent);\n }\n m_firstNameValuePair.pop();\n }",
"private String FCMGetFreshToken(final String senderID) {\n String token = null;\n try {\n if(senderID != null){\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token with Sender Id - \"+senderID);\n token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);\n }else {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token\");\n token = FirebaseInstanceId.getInstance().getToken();\n }\n getConfigLogger().info(getAccountId(),\"FCM token: \"+token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Error requesting FCM token\", t);\n }\n return token;\n }",
"private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) {\n MenuDrawer drawer;\n\n if (type == Type.STATIC) {\n drawer = new StaticDrawer(activity);\n\n } else if (type == Type.OVERLAY) {\n drawer = new OverlayDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n\n } else {\n drawer = new SlidingDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n }\n\n drawer.mDragMode = dragMode;\n drawer.setPosition(position);\n\n return drawer;\n }",
"public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }",
"protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\n }",
"public static String getBuildString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.build\");\n\t\t}\n\t\treturn versionString;\n\t}",
"public void setChildren(List<PrintComponent<?>> children) {\n\t\tthis.children = children;\n\t\t// needed for Json unmarshall !!!!\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.setParent(this);\n\t\t}\n\t}"
] |
Build a valid datastore URL. | [
"String buildProjectEndpoint(DatastoreOptions options) {\n if (options.getProjectEndpoint() != null) {\n return options.getProjectEndpoint();\n }\n // DatastoreOptions ensures either project endpoint or project ID is set.\n String projectId = checkNotNull(options.getProjectId());\n if (options.getHost() != null) {\n return validateUrl(String.format(\"https://%s/%s/projects/%s\",\n options.getHost(), VERSION, projectId));\n } else if (options.getLocalHost() != null) {\n return validateUrl(String.format(\"http://%s/%s/projects/%s\",\n options.getLocalHost(), VERSION, projectId));\n }\n return validateUrl(String.format(\"%s/%s/projects/%s\",\n DEFAULT_HOST, VERSION, projectId));\n }"
] | [
"private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\n }",
"public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}",
"private static String getAttribute(String name, Element firstElement, Element secondElement) {\r\n String val = firstElement.getAttribute(name);\r\n if (val.length() == 0 && secondElement != null) {\r\n val = secondElement.getAttribute(name);\r\n }\r\n return val;\r\n }",
"public static String md5sum(InputStream input) throws IOException {\r\n InputStream in = new BufferedInputStream(input);\r\n try {\r\n MessageDigest digest = java.security.MessageDigest.getInstance(\"MD5\");\r\n DigestInputStream digestInputStream = new DigestInputStream(in, digest);\r\n while(digestInputStream.read() >= 0) {\r\n }\r\n OutputStream md5out = new ByteArrayOutputStream();\r\n md5out.write(digest.digest());\r\n return md5out.toString();\r\n }\r\n catch(NoSuchAlgorithmException e) {\r\n throw new IllegalStateException(\"MD5 algorithm is not available: \" + e.getMessage());\r\n }\r\n finally {\r\n in.close();\r\n }\r\n }",
"public static void Forward(double[][] data) {\n int rows = data.length;\n int cols = data[0].length;\n\n double[] row = new double[cols];\n double[] col = new double[rows];\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < row.length; j++)\n row[j] = data[i][j];\n\n Forward(row);\n\n for (int j = 0; j < row.length; j++)\n data[i][j] = row[j];\n }\n\n for (int j = 0; j < cols; j++) {\n for (int i = 0; i < col.length; i++)\n col[i] = data[i][j];\n\n Forward(col);\n\n for (int i = 0; i < col.length; i++)\n data[i][j] = col[i];\n }\n }",
"public static String truncate(int n, int smallestDigit, int biggestDigit) {\r\n int numDigits = biggestDigit - smallestDigit + 1;\r\n char[] result = new char[numDigits];\r\n for (int j = 1; j < smallestDigit; j++) {\r\n n = n / 10;\r\n }\r\n for (int j = numDigits - 1; j >= 0; j--) {\r\n result[j] = Character.forDigit(n % 10, 10);\r\n n = n / 10;\r\n }\r\n return new String(result);\r\n }",
"protected void registerValueFormatter(DJGroupVariable djVariable, String variableName) {\n\t\tif ( djVariable.getValueFormatter() == null){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tJRDesignParameter dparam = new JRDesignParameter();\n\t\tdparam.setName(variableName + \"_vf\"); //value formater suffix\n\t\tdparam.setValueClassName(DJValueFormatter.class.getName());\n\t\tlog.debug(\"Registering value formatter parameter for property \" + dparam.getName() );\n\t\ttry {\n\t\t\tgetDjd().addParameter(dparam);\n\t\t} catch (JRException e) {\n\t\t\tthrow new EntitiesRegistrationException(e.getMessage(),e);\n\t\t}\n\t\tgetDjd().getParametersWithValues().put(dparam.getName(), djVariable.getValueFormatter());\t\t\n\t\t\n\t}",
"public static synchronized List<Class< ? >> locateAll(final String serviceName) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n List<Class< ? >> classes = new ArrayList<Class< ? >>();\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n for ( Callable<Class< ? >> c : l ) {\n try {\n classes.add( c.call() );\n } catch ( Exception e ) {\n }\n }\n }\n }\n return classes;\n }"
] |
Checks if a key already exists.
@param newKey the key to check for.
@return <code>true</code> if the key already exists, <code>false</code> otherwise. | [
"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 }"
] | [
"private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }",
"public static int colorSpline(int x, int numKnots, int[] xknots, int[] yknots) {\n\t\tint span;\n\t\tint numSpans = numKnots - 3;\n\t\tfloat k0, k1, k2, k3;\n\t\tfloat c0, c1, c2, c3;\n\t\t\n\t\tif (numSpans < 1)\n\t\t\tthrow new IllegalArgumentException(\"Too few knots in spline\");\n\t\t\n\t\tfor (span = 0; span < numSpans; span++)\n\t\t\tif (xknots[span+1] > x)\n\t\t\t\tbreak;\n\t\tif (span > numKnots-3)\n\t\t\tspan = numKnots-3;\n\t\tfloat t = (float)(x-xknots[span]) / (xknots[span+1]-xknots[span]);\n\t\tspan--;\n\t\tif (span < 0) {\n\t\t\tspan = 0;\n\t\t\tt = 0;\n\t\t}\n\n\t\tint v = 0;\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint shift = i * 8;\n\t\t\t\n\t\t\tk0 = (yknots[span] >> shift) & 0xff;\n\t\t\tk1 = (yknots[span+1] >> shift) & 0xff;\n\t\t\tk2 = (yknots[span+2] >> shift) & 0xff;\n\t\t\tk3 = (yknots[span+3] >> shift) & 0xff;\n\t\t\t\n\t\t\tc3 = m00*k0 + m01*k1 + m02*k2 + m03*k3;\n\t\t\tc2 = m10*k0 + m11*k1 + m12*k2 + m13*k3;\n\t\t\tc1 = m20*k0 + m21*k1 + m22*k2 + m23*k3;\n\t\t\tc0 = m30*k0 + m31*k1 + m32*k2 + m33*k3;\n\t\t\tint n = (int)(((c3*t + c2)*t + c1)*t + c0);\n\t\t\tif (n < 0)\n\t\t\t\tn = 0;\n\t\t\telse if (n > 255)\n\t\t\t\tn = 255;\n\t\t\tv |= n << shift;\n\t\t}\n\t\t\n\t\treturn v;\n\t}",
"public static void transformChar(Reader self, Writer writer, @ClosureParams(value=SimpleType.class, options=\"java.lang.String\") Closure closure) throws IOException {\n int c;\n try {\n char[] chars = new char[1];\n while ((c = self.read()) != -1) {\n chars[0] = (char) c;\n writer.write((String) closure.call(new String(chars)));\n }\n writer.flush();\n\n Writer temp2 = writer;\n writer = null;\n temp2.close();\n Reader temp1 = self;\n self = null;\n temp1.close();\n } finally {\n closeWithWarning(self);\n closeWithWarning(writer);\n }\n }",
"public static final int getInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n is.read(data);\n return getInt(data, 0);\n }",
"public Collection<BoxGroupMembership.Info> getMemberships() {\n final BoxAPIConnection api = this.getAPI();\n final String groupID = this.getID();\n\n Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID);\n return new BoxGroupMembershipIterator(api, url);\n }\n };\n\n // We need to iterate all results because this method must return a Collection. This logic should be removed in\n // the next major version, and instead return the Iterable directly.\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>();\n for (BoxGroupMembership.Info membership : iter) {\n memberships.add(membership);\n }\n return memberships;\n }",
"protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(ADDITIONAL_BDA_ID, Collections.synchronizedSet(new HashSet<String>()), null);\n additionalBda.getServices().addAll(getServices().entrySet());\n beanDeploymentArchives.add(additionalBda);\n setBeanDeploymentArchivesAccessibility();\n return additionalBda;\n }",
"private static boolean isValidPropertyClass(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n return Number.class.isAssignableFrom(type) || type == String.class || Date.class.isAssignableFrom(type) || type == Boolean.class;\n }",
"private String quoteFormatCharacters(String literal)\n {\n StringBuilder sb = new StringBuilder();\n int length = literal.length();\n char c;\n\n for (int loop = 0; loop < length; loop++)\n {\n c = literal.charAt(loop);\n switch (c)\n {\n case '0':\n case '#':\n case '.':\n case '-':\n case ',':\n case 'E':\n case ';':\n case '%':\n {\n sb.append(\"'\");\n sb.append(c);\n sb.append(\"'\");\n break;\n }\n\n default:\n {\n sb.append(c);\n break;\n }\n }\n }\n\n return (sb.toString());\n }",
"public static void objectToXML(Object object, String fileName) throws FileNotFoundException {\r\n\t\tFileOutputStream fo = new FileOutputStream(fileName);\r\n\t\tXMLEncoder encoder = new XMLEncoder(fo);\r\n\t\tencoder.writeObject(object);\r\n\t\tencoder.close();\r\n\t}"
] |
Log a warning for the given operation at the provided address for the given attributes, using the provided detail
message.
@param address where warning occurred
@param operation where which problem occurred
@param message custom error message to append
@param attributes attributes we that have problems about | [
"public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }"
] | [
"public static void mlock(Pointer addr, long len) {\n\n int res = Delegate.mlock(addr, new NativeLong(len));\n if(res != 0) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Mlock failed probably because of insufficient privileges, errno:\"\n + errno.strerror() + \", return value:\" + res);\n }\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"Mlock successfull\");\n\n }\n\n }",
"public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}",
"public static nsfeature get(nitro_service service) throws Exception{\n\t\tnsfeature obj = new nsfeature();\n\t\tnsfeature[] response = (nsfeature[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }",
"public static auditsyslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_systemglobal_binding obj = new auditsyslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_systemglobal_binding response[] = (auditsyslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public AsciiTable setPaddingTopChar(Character paddingTopChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private <T> ServiceResponse<T> getPutOrPatchResult(Observable<Response<ResponseBody>> observable, Type resourceType) throws CloudException, InterruptedException, IOException {\n Observable<ServiceResponse<T>> asyncObservable = getPutOrPatchResultAsync(observable, resourceType);\n return asyncObservable.toBlocking().last();\n }",
"public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}",
"public AT_Context setFrameTopBottomMargin(int frameTop, int frameBottom){\r\n\t\tif(frameTop>-1 && frameBottom>-1){\r\n\t\t\tthis.frameTopMargin = frameTop;\r\n\t\t\tthis.frameBottomMargin = frameBottom;\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] |
Map the given region of the given file descriptor into memory.
Returns a Pointer to the newly mapped memory throws an
IOException on error. | [
"public static Pointer mmap(long len, int prot, int flags, int fildes, long off)\n throws IOException {\n\n // we don't really have a need to change the recommended pointer.\n Pointer addr = new Pointer(0);\n\n Pointer result = Delegate.mmap(addr,\n new NativeLong(len),\n prot,\n flags,\n fildes,\n new NativeLong(off));\n\n if(Pointer.nativeValue(result) == -1) {\n if(logger.isDebugEnabled())\n logger.debug(errno.strerror());\n\t throw new IOException(\"mmap failed: \" + errno.strerror());\n }\n\n return result;\n\n }"
] | [
"private OperationEntry getInheritableOperationEntryLocked(final String operationName) {\n final OperationEntry entry = operations == null ? null : operations.get(operationName);\n if (entry != null && entry.isInherited()) {\n return entry;\n }\n return null;\n }",
"private String searchForPersistentSubType(XClass type)\r\n {\r\n ArrayList queue = new ArrayList();\r\n XClass subType;\r\n\r\n queue.add(type);\r\n while (!queue.isEmpty())\r\n {\r\n subType = (XClass)queue.get(0);\r\n queue.remove(0);\r\n if (_model.hasClass(subType.getQualifiedName()))\r\n {\r\n return subType.getQualifiedName();\r\n }\r\n addDirectSubTypes(subType, queue);\r\n }\r\n return null;\r\n }",
"@RequestMapping(value = \"/api/scripts\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getScripts(Model model,\n @RequestParam(required = false) Integer type) throws Exception {\n Script[] scripts = ScriptService.getInstance().getScripts(type);\n return Utils.getJQGridJSON(scripts, \"scripts\");\n }",
"@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }",
"public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }",
"public static double huntKennedyCMSFloorValue(\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 huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}",
"public double convert(double value, double temperatur, double viscosity){\n\t\treturn temperatur*kB / (Math.PI*viscosity*value);\n\t}",
"private void countCoordinateStatement(Statement statement,\n\t\t\tItemDocument itemDocument) {\n\t\tValue value = statement.getValue();\n\t\tif (!(value instanceof GlobeCoordinatesValue)) {\n\t\t\treturn;\n\t\t}\n\n\t\tGlobeCoordinatesValue coordsValue = (GlobeCoordinatesValue) value;\n\t\tif (!this.globe.equals((coordsValue.getGlobe()))) {\n\t\t\treturn;\n\t\t}\n\n\t\tint xCoord = (int) (((coordsValue.getLongitude() + 180.0) / 360.0) * this.width)\n\t\t\t\t% this.width;\n\t\tint yCoord = (int) (((coordsValue.getLatitude() + 90.0) / 180.0) * this.height)\n\t\t\t\t% this.height;\n\n\t\tif (xCoord < 0 || yCoord < 0 || xCoord >= this.width\n\t\t\t\t|| yCoord >= this.height) {\n\t\t\tSystem.out.println(\"Dropping out-of-range coordinate: \"\n\t\t\t\t\t+ coordsValue);\n\t\t\treturn;\n\t\t}\n\n\t\tcountCoordinates(xCoord, yCoord, itemDocument);\n\t\tthis.count += 1;\n\n\t\tif (this.count % 100000 == 0) {\n\t\t\treportProgress();\n\t\t\twriteImages();\n\t\t}\n\t}",
"public static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\n }"
] |
A modified version of abs that always returns a non-negative value.
Math.abs returns Integer.MIN_VALUE if a == Integer.MIN_VALUE and this
method returns Integer.MAX_VALUE in that case. | [
"private static int abs(int a) {\n if(a >= 0)\n return a;\n else if(a != Integer.MIN_VALUE)\n return -a;\n return Integer.MAX_VALUE;\n }"
] | [
"public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) {\n if (imageHolder != null && imageView != null) {\n Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint);\n if (drawable != null) {\n imageView.setImageDrawable(drawable);\n imageView.setVisibility(View.VISIBLE);\n } else if (imageHolder.getBitmap() != null) {\n imageView.setImageBitmap(imageHolder.getBitmap());\n imageView.setVisibility(View.VISIBLE);\n } else {\n imageView.setVisibility(View.GONE);\n }\n } else if (imageView != null) {\n imageView.setVisibility(View.GONE);\n }\n }",
"public static base_response Import(nitro_service client, appfwsignatures resource) throws Exception {\n\t\tappfwsignatures Importresource = new appfwsignatures();\n\t\tImportresource.src = resource.src;\n\t\tImportresource.name = resource.name;\n\t\tImportresource.xslt = resource.xslt;\n\t\tImportresource.comment = resource.comment;\n\t\tImportresource.overwrite = resource.overwrite;\n\t\tImportresource.merge = resource.merge;\n\t\tImportresource.sha1 = resource.sha1;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }",
"private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }",
"public IdRange[] parseIdRange(ImapRequestLineReader request)\n throws ProtocolException {\n CharacterValidator validator = new MessageSetCharValidator();\n String nextWord = consumeWord(request, validator);\n\n int commaPos = nextWord.indexOf(',');\n if (commaPos == -1) {\n return new IdRange[]{IdRange.parseRange(nextWord)};\n }\n\n List<IdRange> rangeList = new ArrayList<>();\n int pos = 0;\n while (commaPos != -1) {\n String range = nextWord.substring(pos, commaPos);\n IdRange set = IdRange.parseRange(range);\n rangeList.add(set);\n\n pos = commaPos + 1;\n commaPos = nextWord.indexOf(',', pos);\n }\n String range = nextWord.substring(pos);\n rangeList.add(IdRange.parseRange(range));\n return rangeList.toArray(new IdRange[rangeList.size()]);\n }",
"public void readFrom(IIMReader reader, int recover) throws IOException, InvalidDataSetException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (;;) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSet ds = reader.read();\r\n\t\t\t\tif (ds == null) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (doLog) {\r\n\t\t\t\t\tlog.debug(\"Read data set \" + ds);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\t\tSerializer s = info.getSerializer();\r\n\t\t\t\tif (s != null) {\r\n\t\t\t\t\tif (info.getDataSetNumber() == IIM.DS(1, 90)) {\r\n\t\t\t\t\t\tsetCharacterSet((String) s.deserialize(ds.getData(), activeSerializationContext));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tdataSets.add(ds);\r\n\r\n\t\t\t\tif (stopAfter9_10 && info.getDataSetNumber() == IIM.DS(9, 10))\r\n\t\t\t\t\tbreak;\r\n\t\t\t} catch (IIMFormatException e) {\r\n\t\t\t\tif (recoverFromIIMFormat && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (UnsupportedDataSetException e) {\r\n\t\t\t\tif (recoverFromUnsupportedDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (InvalidDataSetException e) {\r\n\t\t\t\tif (recoverFromInvalidDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tif (recover-- > 0 && !dataSets.isEmpty()) {\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.error(\"IOException while reading, however some data sets where recovered, \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"private PoolingHttpClientConnectionManager createConnectionMgr() {\n PoolingHttpClientConnectionManager connectionMgr;\n\n // prepare SSLContext\n SSLContext sslContext = buildSslContext();\n ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();\n // we allow to disable host name verification against CA certificate,\n // notice: in general this is insecure and should be avoided in production,\n // (this type of configuration is useful for development purposes)\n boolean noHostVerification = false;\n LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(\n sslContext,\n noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()\n );\n Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()\n .register(\"http\", plainsf)\n .register(\"https\", sslsf)\n .build();\n connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,\n null, connectionPoolTimeToLive, TimeUnit.SECONDS);\n\n connectionMgr.setMaxTotal(maxConnectionsTotal);\n connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);\n HttpHost localhost = new HttpHost(\"localhost\", 80);\n connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);\n return connectionMgr;\n }",
"public final void setWeeksOfMonth(SortedSet<WeekOfMonth> weeksOfMonth) {\n\n m_weeksOfMonth.clear();\n if (null != weeksOfMonth) {\n m_weeksOfMonth.addAll(weeksOfMonth);\n }\n\n }"
] |
All the attributes needed either by the processors for each datasource row or by the jasper template.
@param attributes the attributes. | [
"public void setAttributes(final Map<String, Attribute> attributes) {\n this.internalAttributes = attributes;\n this.allAttributes.putAll(attributes);\n }"
] | [
"public DomainList getPhotoDomains(Date date, String photoId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTO_DOMAINS, \"photo_id\", photoId, date, perPage, page);\n }",
"public static Integer getDay(Day day)\n {\n Integer result = null;\n if (day != null)\n {\n result = DAY_MAP.get(day);\n }\n return (result);\n }",
"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 static void addInterceptors(InterceptorProvider provider) {\n PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);\n for (Phase p : phases.getInPhases()) {\n provider.getInInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n for (Phase p : phases.getOutPhases()) {\n provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n }",
"protected void appendWhereClause(FieldDescriptor[] fields, StringBuffer stmt) throws PersistenceBrokerException\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n\r\n stmt.append(fmd.getColumnName());\r\n stmt.append(\" = ? \");\r\n if(i < fields.length - 1)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n }\r\n }",
"private void addDateWithCheckState(Date date, boolean checkState) {\n\n addCheckBox(date, checkState);\n if (!m_dates.contains(date)) {\n m_dates.add(date);\n fireValueChange();\n }\n }",
"public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.count();\n } else {\n getConfigLogger().debug(getAccountId(),\"Notification Inbox not initialized\");\n return -1;\n }\n }\n }",
"public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {\n return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);\n }"
] |
Given a String the method uses Regex to check if the String only contains punctuation characters
@param s a String to check using regex
@return true if the String is valid | [
"public static boolean isPunct(String s){\r\n Pattern p = Pattern.compile(\"^[\\\\p{Punct}]+$\");\r\n Matcher m = p.matcher(s);\r\n return m.matches();\r\n }"
] | [
"public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) {\n return getObjectFromJSONPath(record, path);\n }",
"@Deprecated\r\n private BufferedImage getImage(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }",
"public final void draw() {\n AffineTransform transform = new AffineTransform(this.transform);\n transform.concatenate(getAlignmentTransform());\n\n // draw the background box\n this.graphics2d.setTransform(transform);\n this.graphics2d.setColor(this.params.getBackgroundColor());\n this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);\n\n //draw the labels\n this.graphics2d.setColor(this.params.getFontColor());\n drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());\n\n //sets the transformation for drawing the bar and do it\n final AffineTransform lineTransform = new AffineTransform(transform);\n setLineTranslate(lineTransform);\n\n if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||\n this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {\n final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);\n lineTransform.concatenate(rotate);\n }\n\n this.graphics2d.setTransform(lineTransform);\n this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));\n this.graphics2d.setColor(this.params.getColor());\n drawBar();\n }",
"@NonNull\n public static String placeholders(final int numberOfPlaceholders) {\n if (numberOfPlaceholders == 1) {\n return \"?\"; // fffast\n } else if (numberOfPlaceholders == 0) {\n return \"\";\n } else if (numberOfPlaceholders < 0) {\n throw new IllegalArgumentException(\"numberOfPlaceholders must be >= 0, but was = \" + numberOfPlaceholders);\n }\n\n final StringBuilder stringBuilder = new StringBuilder((numberOfPlaceholders * 2) - 1);\n\n for (int i = 0; i < numberOfPlaceholders; i++) {\n stringBuilder.append('?');\n\n if (i != numberOfPlaceholders - 1) {\n stringBuilder.append(',');\n }\n }\n\n return stringBuilder.toString();\n }",
"public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}",
"protected void registerValueFormatter(DJGroupVariable djVariable, String variableName) {\n\t\tif ( djVariable.getValueFormatter() == null){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tJRDesignParameter dparam = new JRDesignParameter();\n\t\tdparam.setName(variableName + \"_vf\"); //value formater suffix\n\t\tdparam.setValueClassName(DJValueFormatter.class.getName());\n\t\tlog.debug(\"Registering value formatter parameter for property \" + dparam.getName() );\n\t\ttry {\n\t\t\tgetDjd().addParameter(dparam);\n\t\t} catch (JRException e) {\n\t\t\tthrow new EntitiesRegistrationException(e.getMessage(),e);\n\t\t}\n\t\tgetDjd().getParametersWithValues().put(dparam.getName(), djVariable.getValueFormatter());\t\t\n\t\t\n\t}",
"protected void importUserFromFile() {\n\n CmsImportUserThread thread = new CmsImportUserThread(\n m_cms,\n m_ou,\n m_userImportList,\n getGroupsList(m_importGroups, true),\n getRolesList(m_importRoles, true),\n m_sendMail.getValue().booleanValue());\n thread.start();\n CmsShowReportDialog dialog = new CmsShowReportDialog(thread, new Runnable() {\n\n public void run() {\n\n m_window.close();\n }\n });\n m_window.setContent(dialog);\n\n }",
"public PhotoList<Photo> search(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.putAll(params.getAsParameters());\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 = 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 photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }",
"@Override\n\tpublic boolean isPrefixBlock() {\n\t\tInteger networkPrefixLength = getNetworkPrefixLength();\n\t\tif(networkPrefixLength == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif(getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn containsPrefixBlock(networkPrefixLength);\n\t}"
] |
Click no children of the specified parent element.
@param tagName The tag name of which no children should be clicked.
@return The builder to append more options. | [
"public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {\r\n\t\tcheckNotRead();\r\n\t\tPreconditions.checkNotNull(tagName);\r\n\t\tExcludeByParentBuilder exclude = new ExcludeByParentBuilder(\r\n\t\t\t\ttagName.toUpperCase());\r\n\t\tcrawlParentsExcluded.add(exclude);\r\n\t\treturn exclude;\r\n\t}"
] | [
"public void fire(TestCaseFinishedEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n Step root = stepStorage.pollLast();\n\n if (Status.PASSED.equals(testCase.getStatus())) {\n new RemoveAttachmentsEvent(AllureConfig.newInstance().getRemoveAttachments()).process(root);\n }\n\n testCase.getSteps().addAll(root.getSteps());\n testCase.getAttachments().addAll(root.getAttachments());\n\n stepStorage.remove();\n testCaseStorage.remove();\n\n notifier.fire(event);\n }",
"public void setWeekDay(String dayString) {\n\n final WeekDay day = WeekDay.valueOf(dayString);\n if (m_model.getWeekDay() != day) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(day);\n onValueChange();\n }\n });\n }\n\n }",
"public void setMesh(GVRMesh mesh) {\n mMesh = mesh;\n NativeMeshCollider.setMesh(getNative(), mesh.getNative());\n }",
"private void readZookeeperConfig() {\n\n try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {\n curator.start();\n\n accumuloInstance =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),\n StandardCharsets.UTF_8);\n accumuloInstanceID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),\n StandardCharsets.UTF_8);\n fluoApplicationID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),\n StandardCharsets.UTF_8);\n\n table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),\n StandardCharsets.UTF_8);\n\n observers = ObserverUtil.load(curator);\n\n config = FluoAdminImpl.mergeZookeeperConfig(config);\n\n // make sure not to include config passed to env, only want config from zookeeper\n appConfig = config.getAppConfiguration();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }",
"public Set<DbLicense> resolveLicenses(List<String> licStrings) {\n Set<DbLicense> result = new HashSet<>();\n\n licStrings\n .stream()\n .map(this::getMatchingLicenses)\n .forEach(result::addAll);\n\n return result;\n }",
"public void drawText(String text, Font font, Rectangle box, Color fontColor) {\n\t\ttemplate.saveState();\n\t\t// get the font\n\t\tDefaultFontMapper mapper = new DefaultFontMapper();\n\t\tBaseFont bf = mapper.awtToPdf(font);\n\t\ttemplate.setFontAndSize(bf, font.getSize());\n\n\t\t// calculate descent\n\t\tfloat descent = 0;\n\t\tif (text != null) {\n\t\t\tdescent = bf.getDescentPoint(text, font.getSize());\n\t\t}\n\n\t\t// calculate the fitting size\n\t\tRectangle fit = getTextSize(text, font);\n\n\t\t// draw text if necessary\n\t\ttemplate.setColorFill(fontColor);\n\t\ttemplate.beginText();\n\t\ttemplate.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f\n\t\t\t\t* (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f\n\t\t\t\t* (box.getHeight() - fit.getHeight()) - descent, 0);\n\t\ttemplate.endText();\n\t\ttemplate.restoreState();\n\t}",
"private void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData)\n {\n String notes = taskExtData.getString(TASK_NOTES);\n if (notes == null && data.length == 366)\n {\n byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362));\n if (offsetData != null && offsetData.length >= 12)\n {\n notes = taskVarData.getString(getOffset(offsetData, 8));\n \n // We do pick up some random stuff with this approach, and \n // we don't know enough about the file format to know when to ignore it\n // so we'll use a heuristic here to ignore anything that\n // doesn't look like RTF.\n if (notes != null && notes.indexOf('{') == -1)\n {\n notes = null;\n }\n }\n }\n \n if (notes != null)\n {\n if (m_reader.getPreserveNoteFormatting() == false)\n {\n notes = RtfHelper.strip(notes);\n }\n\n task.setNotes(notes);\n }\n }",
"public static tmsessionpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\ttmsessionpolicy_binding obj = new tmsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\ttmsessionpolicy_binding response = (tmsessionpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }"
] |
Gets the metrics as a map whose keys are the metric name and whose values are the metric values.
@return map | [
"public static SortedMap<String, Object> asMap() {\n SortedMap<String, Object> metrics = Maps.newTreeMap();\n METRICS_SOURCE.applyMetrics(metrics);\n return metrics;\n }"
] | [
"public static void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }",
"private static Bitmap crop(Bitmap srcBmp, View canvasView, int downsampling) {\n float scale = 1f / downsampling;\n return Bitmap.createBitmap(\n srcBmp,\n (int) Math.floor((ViewCompat.getX(canvasView)) * scale),\n (int) Math.floor((ViewCompat.getY(canvasView)) * scale),\n (int) Math.floor((canvasView.getWidth()) * scale),\n (int) Math.floor((canvasView.getHeight()) * scale)\n );\n }",
"public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }",
"public static String getContent(String stringUrl) throws IOException {\n InputStream stream = getContentStream(stringUrl);\n return MyStreamUtils.readContent(stream);\n }",
"public void updateSequenceElement(int[] sequence, int pos, int oldVal) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].updateSequenceElement(sequence, pos, oldVal);\r\n return; \r\n }\r\n model1.updateSequenceElement(sequence, pos, 0);\r\n model2.updateSequenceElement(sequence, pos, 0);\r\n }",
"public final void notifyHeaderItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart, itemCount);\n }",
"public CmsContextMenu getContextMenuForItem(Object itemId) {\n\n CmsContextMenu result = null;\n try {\n final Item item = m_container.getItem(itemId);\n Property<?> keyProp = item.getItemProperty(TableProperty.KEY);\n String key = (String)keyProp.getValue();\n if ((null != key) && !key.isEmpty()) {\n loadAllRemainingLocalizations();\n final Map<Locale, String> localesWithEntries = new HashMap<Locale, String>();\n for (Locale l : m_localizations.keySet()) {\n if (l != m_locale) {\n String value = m_localizations.get(l).getProperty(key);\n if ((null != value) && !value.isEmpty()) {\n localesWithEntries.put(l, value);\n }\n }\n }\n if (!localesWithEntries.isEmpty()) {\n result = new CmsContextMenu();\n ContextMenuItem mainItem = result.addItem(\n Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n Messages.GUI_BUNDLE_EDITOR_CONTEXT_COPY_LOCALE_0));\n for (final Locale l : localesWithEntries.keySet()) {\n\n ContextMenuItem menuItem = mainItem.addItem(l.getDisplayName(UI.getCurrent().getLocale()));\n menuItem.addItemClickListener(new ContextMenuItemClickListener() {\n\n public void contextMenuItemClicked(ContextMenuItemClickEvent event) {\n\n item.getItemProperty(TableProperty.TRANSLATION).setValue(localesWithEntries.get(l));\n\n }\n });\n }\n }\n }\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n //TODO: Improve\n }\n return result;\n }",
"public static<Z> Function0<Z> lift(Func0<Z> f) {\n\treturn bridge.lift(f);\n }",
"ServerStatus getState() {\n final InternalState requiredState = this.requiredState;\n final InternalState state = internalState;\n if(requiredState == InternalState.FAILED) {\n return ServerStatus.FAILED;\n }\n switch (state) {\n case STOPPED:\n return ServerStatus.STOPPED;\n case SERVER_STARTED:\n return ServerStatus.STARTED;\n default: {\n if(requiredState == InternalState.SERVER_STARTED) {\n return ServerStatus.STARTING;\n } else {\n return ServerStatus.STOPPING;\n }\n }\n }\n }"
] |
Load the installation state based on the identity
@param installedIdentity the installed identity
@return the installation state
@throws IOException | [
"protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }"
] | [
"public VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }",
"public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}",
"public static base_response rename(nitro_service client, cmppolicylabel resource, String new_labelname) throws Exception {\n\t\tcmppolicylabel renameresource = new cmppolicylabel();\n\t\trenameresource.labelname = resource.labelname;\n\t\treturn renameresource.rename_resource(client,new_labelname);\n\t}",
"private final String getHeader(Map /* String, String */ headers, String name) {\n return (String) headers.get(name.toLowerCase());\n }",
"private void writeNewLineIndent() throws IOException\n {\n if (m_pretty)\n {\n if (!m_indent.isEmpty())\n {\n m_writer.write('\\n');\n m_writer.write(m_indent);\n }\n }\n }",
"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 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 final void notifyFooterItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount + contentItemCount, itemCount);\n }",
"public void writeAuxiliaryTriples() throws RDFHandlerException {\n\t\tfor (PropertyRestriction pr : this.someValuesQueue) {\n\t\t\twriteSomeValueRestriction(pr.propertyUri, pr.rangeUri, pr.subject);\n\t\t}\n\t\tthis.someValuesQueue.clear();\n\n\t\tthis.valueRdfConverter.writeAuxiliaryTriples();\n\t}"
] |
Load the available layers.
@param image the installed image
@param productConfig the product config to establish the identity
@param moduleRoots the module roots
@param bundleRoots the bundle roots
@return the layers
@throws IOException | [
"static InstalledIdentity load(final InstalledImage image, final ProductConfig productConfig, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n\n // build the identity information\n final String productVersion = productConfig.resolveVersion();\n final String productName = productConfig.resolveName();\n final Identity identity = new AbstractLazyIdentity() {\n @Override\n public String getName() {\n return productName;\n }\n\n @Override\n public String getVersion() {\n return productVersion;\n }\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n };\n\n final Properties properties = PatchUtils.loadProperties(identity.getDirectoryStructure().getInstallationInfo());\n final List<String> allPatches = PatchUtils.readRefs(properties, Constants.ALL_PATCHES);\n\n // Step 1 - gather the installed layers data\n final InstalledConfiguration conf = createInstalledConfig(image);\n // Step 2 - process the actual module and bundle roots\n final ProcessedLayers processedLayers = process(conf, moduleRoots, bundleRoots);\n final InstalledConfiguration config = processedLayers.getConf();\n\n // Step 3 - create the actual config objects\n // Process layers\n final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl(identity, allPatches, image);\n for (final LayerPathConfig layer : processedLayers.getLayers().values()) {\n final String name = layer.name;\n installedIdentity.putLayer(name, createPatchableTarget(name, layer, config.getLayerMetadataDir(name), image));\n }\n // Process add-ons\n for (final LayerPathConfig addOn : processedLayers.getAddOns().values()) {\n final String name = addOn.name;\n installedIdentity.putAddOn(name, createPatchableTarget(name, addOn, config.getAddOnMetadataDir(name), image));\n }\n return installedIdentity;\n }"
] | [
"public static ContainerDescription getContainerDescription(final ModelControllerClient client) throws IOException, OperationExecutionException {\n return DefaultContainerDescription.lookup(Assert.checkNotNullParam(\"client\", client));\n }",
"public static RgbaColor fromHex(String hex) {\n if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor();\n\n // #rgb\n if (hex.length() == 4) {\n\n return new RgbaColor(parseHex(hex, 1, 2),\n parseHex(hex, 2, 3),\n parseHex(hex, 3, 4));\n\n }\n // #rrggbb\n else if (hex.length() == 7) {\n\n return new RgbaColor(parseHex(hex, 1, 3),\n parseHex(hex, 3, 5),\n parseHex(hex, 5, 7));\n\n }\n else {\n return getDefaultColor();\n }\n }",
"public List<RoutableDestination<T>> getDestinations(String path) {\n\n String cleanPath = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n List<RoutableDestination<T>> result = new ArrayList<>();\n\n for (ImmutablePair<Pattern, RouteDestinationWithGroups> patternRoute : patternRouteList) {\n Map<String, String> groupNameValuesBuilder = new HashMap<>();\n Matcher matcher = patternRoute.getFirst().matcher(cleanPath);\n if (matcher.matches()) {\n int matchIndex = 1;\n for (String name : patternRoute.getSecond().getGroupNames()) {\n String value = matcher.group(matchIndex);\n groupNameValuesBuilder.put(name, value);\n matchIndex++;\n }\n result.add(new RoutableDestination<>(patternRoute.getSecond().getDestination(), groupNameValuesBuilder));\n }\n }\n return result;\n }",
"public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }",
"public static void scale(GVRMesh mesh, float x, float y, float z) {\n final float [] vertices = mesh.getVertices();\n final int vsize = vertices.length;\n\n for (int i = 0; i < vsize; i += 3) {\n vertices[i] *= x;\n vertices[i + 1] *= y;\n vertices[i + 2] *= z;\n }\n\n mesh.setVertices(vertices);\n }",
"public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static final Duration parseDurationInThousanthsOfMinutes(ProjectProperties properties, Number value, TimeUnit targetTimeUnit)\n {\n return parseDurationInFractionsOfMinutes(properties, value, targetTimeUnit, 1000);\n }",
"Object readResolve() throws ObjectStreamException {\n Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);\n if (bean == null) {\n throw BeanLogger.LOG.proxyDeserializationFailure(beanId);\n }\n return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);\n }",
"public boolean hasUniqueLongOption(String optionName) {\n if(hasLongOption(optionName)) {\n for(ProcessedOption o : getOptions()) {\n if(o.name().startsWith(optionName) && !o.name().equals(optionName))\n return false;\n }\n return true;\n }\n return false;\n }"
] |
Get a property as an int or default value.
@param key the property name
@param defaultValue the default value | [
"@Override\n public final Integer optInt(final String key, final Integer defaultValue) {\n Integer result = optInt(key);\n return result == null ? defaultValue : result;\n }"
] | [
"protected void capture3DScreenShot(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshot3DCallback == null) {\n return;\n }\n final Bitmap[] bitmaps = new Bitmap[6];\n renderSixCamerasAndReadback(mMainScene.getMainCameraRig(), bitmaps, renderTarget, isMultiview);\n returnScreenshot3DToCaller(mScreenshot3DCallback, bitmaps, mReadbackBufferWidth, mReadbackBufferHeight);\n\n mScreenshot3DCallback = null;\n }",
"private 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 void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }",
"protected void addLabelForNumbers(ItemIdValue itemIdValue) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if we still have exactly one numeric value:\n\t\t\tQuantityValue number = currentItemDocument\n\t\t\t\t\t.findStatementQuantityValue(\"P1181\");\n\t\t\tif (number == null) {\n\t\t\t\tSystem.out.println(\"*** No unique numeric value for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the item is in a known numeric class:\n\t\t\tif (!currentItemDocument.hasStatementValue(\"P31\", numberClasses)) {\n\t\t\t\tSystem.out\n\t\t\t\t\t\t.println(\"*** \"\n\t\t\t\t\t\t\t\t+ qid\n\t\t\t\t\t\t\t\t+ \" is not in a known class of integer numbers. Skipping.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if the value is integer and build label string:\n\t\t\tString numberString;\n\t\t\ttry {\n\t\t\t\tBigInteger intValue = number.getNumericValue()\n\t\t\t\t\t\t.toBigIntegerExact();\n\t\t\t\tnumberString = intValue.toString();\n\t\t\t} catch (ArithmeticException e) {\n\t\t\t\tSystem.out.println(\"*** Numeric value for \" + qid\n\t\t\t\t\t\t+ \" is not an integer: \" + number.getNumericValue());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Construct data to write:\n\t\t\tItemDocumentBuilder itemDocumentBuilder = ItemDocumentBuilder\n\t\t\t\t\t.forItemId(itemIdValue).withRevisionId(\n\t\t\t\t\t\t\tcurrentItemDocument.getRevisionId());\n\t\t\tArrayList<String> languages = new ArrayList<>(\n\t\t\t\t\tarabicNumeralLanguages.length);\n\t\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\t\tif (!currentItemDocument.getLabels().containsKey(\n\t\t\t\t\t\tarabicNumeralLanguages[i])) {\n\t\t\t\t\titemDocumentBuilder.withLabel(numberString,\n\t\t\t\t\t\t\tarabicNumeralLanguages[i]);\n\t\t\t\t\tlanguages.add(arabicNumeralLanguages[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (languages.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** Labels already complete for \" + qid);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tnumberString, languages);\n\n\t\t\tdataEditor.editItemDocument(itemDocumentBuilder.build(), false,\n\t\t\t\t\t\"Set labels to numeric value (Task MB1)\");\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public static base_response unset(nitro_service client, Interface resource, String[] args) throws Exception{\n\t\tInterface unsetresource = new Interface();\n\t\tunsetresource.id = resource.id;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"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 }",
"public static JRDesignGroup getJRDesignGroup(DynamicJasperDesign jd, LayoutManager layoutManager, DJGroup group) {\n\t\tMap references = layoutManager.getReferencesMap();\n\t\tfor (Object o : references.keySet()) {\n\t\t\tString groupName = (String) o;\n\t\t\tDJGroup djGroup = (DJGroup) references.get(groupName);\n\t\t\tif (group == djGroup) {\n\t\t\t\treturn (JRDesignGroup) jd.getGroupsMap().get(groupName);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}",
"@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }"
] |
Convert a layer type to a geometry class.
@param layerType
layer type
@return JTS class | [
"public Class<? extends com.vividsolutions.jts.geom.Geometry> toInternal(LayerType layerType) {\n\t\tswitch (layerType) {\n\t\t\tcase GEOMETRY:\n\t\t\t\treturn com.vividsolutions.jts.geom.Geometry.class;\n\t\t\tcase LINESTRING:\n\t\t\t\treturn LineString.class;\n\t\t\tcase MULTILINESTRING:\n\t\t\t\treturn MultiLineString.class;\n\t\t\tcase POINT:\n\t\t\t\treturn Point.class;\n\t\t\tcase MULTIPOINT:\n\t\t\t\treturn MultiPoint.class;\n\t\t\tcase POLYGON:\n\t\t\t\treturn Polygon.class;\n\t\t\tcase MULTIPOLYGON:\n\t\t\t\treturn MultiPolygon.class;\n\t\t\tcase RASTER:\n\t\t\t\treturn null;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalStateException(\"Don't know how to handle layer type \" + layerType);\n\t\t}\n\t}"
] | [
"protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}",
"private static boolean isConjWithNoPrep(TreeGraphNode node, Collection<TypedDependency> list) {\r\n for (TypedDependency td : list) {\r\n if (td.gov() == node && td.reln() == CONJUNCT) {\r\n // we have a conjunct\r\n // check the POS of the dependent\r\n String tdDepPOS = td.dep().parent().value();\r\n if (!(tdDepPOS.equals(\"IN\") || tdDepPOS.equals(\"TO\"))) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"protected void handleParentheses( TokenList tokens, Sequence sequence ) {\n // have a list to handle embedded parentheses, e.g. (((((a)))))\n List<TokenList.Token> left = new ArrayList<TokenList.Token>();\n\n // find all of them\n TokenList.Token t = tokens.first;\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getType() == Type.SYMBOL ) {\n if( t.getSymbol() == Symbol.PAREN_LEFT )\n left.add(t);\n else if( t.getSymbol() == Symbol.PAREN_RIGHT ) {\n if( left.isEmpty() )\n throw new ParseError(\") found with no matching (\");\n\n TokenList.Token a = left.remove(left.size()-1);\n\n // remember the element before so the new one can be inserted afterwards\n TokenList.Token before = a.previous;\n\n TokenList sublist = tokens.extractSubList(a,t);\n // remove parentheses\n sublist.remove(sublist.first);\n sublist.remove(sublist.last);\n\n // if its a function before () then the () indicates its an input to a function\n if( before != null && before.getType() == Type.FUNCTION ) {\n List<TokenList.Token> inputs = parseParameterCommaBlock(sublist, sequence);\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n else {\n createFunction(before, inputs, tokens, sequence);\n }\n } else if( before != null && before.getType() == Type.VARIABLE &&\n before.getVariable().getType() == VariableType.MATRIX ) {\n // if it's a variable then that says it's a sub-matrix\n TokenList.Token extract = parseSubmatrixToExtract(before,sublist, sequence);\n // put in the extract operation\n tokens.insert(before,extract);\n tokens.remove(before);\n } else {\n // if null then it was empty inside\n TokenList.Token output = parseBlockNoParentheses(sublist,sequence, false);\n if (output != null)\n tokens.insert(before, output);\n }\n }\n }\n t = next;\n }\n\n if( !left.isEmpty())\n throw new ParseError(\"Dangling ( parentheses\");\n }",
"public static AT_Row createContentRow(Object[] content, TableRowStyle style){\r\n\t\tValidate.notNull(content);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\tLinkedList<AT_Cell> cells = new LinkedList<AT_Cell>();\r\n\t\tfor(Object o : content){\r\n\t\t\tcells.add(new AT_Cell(o));\r\n\t\t}\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn TableRowType.CONTENT;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic LinkedList<AT_Cell> getCells(){\r\n\t\t\t\treturn cells;\r\n\t\t\t}\r\n\t\t};\r\n\t}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal);\n }",
"public void updateRequestByAddingReplaceVarPair(\n ParallelTask task, String replaceVarKey, String replaceVarValue) {\n\n Map<String, NodeReqResponse> taskResult = task.getParallelTaskResult();\n\n for (Entry<String, NodeReqResponse> entry : taskResult.entrySet()) {\n NodeReqResponse nodeReqResponse = entry.getValue();\n\n nodeReqResponse.getRequestParameters()\n .put(PcConstants.NODE_REQUEST_PREFIX_REPLACE_VAR\n + replaceVarKey, replaceVarValue);\n nodeReqResponse.getRequestParameters().put(\n PcConstants.NODE_REQUEST_WILL_EXECUTE,\n Boolean.toString(true));\n\n }// end for loop\n\n }",
"public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }",
"private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n DayTypes dayTypes = gpCalendar.getDayTypes();\n DefaultWeek defaultWeek = dayTypes.getDefaultWeek();\n if (defaultWeek == null)\n {\n mpxjCalendar.setWorkingDay(Day.SUNDAY, false);\n mpxjCalendar.setWorkingDay(Day.MONDAY, true);\n mpxjCalendar.setWorkingDay(Day.TUESDAY, true);\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true);\n mpxjCalendar.setWorkingDay(Day.THURSDAY, true);\n mpxjCalendar.setWorkingDay(Day.FRIDAY, true);\n mpxjCalendar.setWorkingDay(Day.SATURDAY, false);\n }\n else\n {\n mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon()));\n mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue()));\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed()));\n mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu()));\n mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri()));\n mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat()));\n mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun()));\n }\n\n for (Day day : Day.values())\n {\n if (mpxjCalendar.isWorkingDay(day))\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }",
"private void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) {\r\n String getterName = \"get\" + MetaClassHelper.capitalize(propertyName);\r\n MethodNode setter = classNode.getSetterMethod(\"set\" + MetaClassHelper.capitalize(propertyName));\r\n\r\n if (setter != null) {\r\n // Get the existing code block\r\n Statement code = setter.getCode();\r\n\r\n Expression oldValue = varX(\"$oldValue\");\r\n Expression newValue = varX(\"$newValue\");\r\n Expression proposedValue = varX(setter.getParameters()[0].getName());\r\n BlockStatement block = new BlockStatement();\r\n\r\n // create a local variable to hold the old value from the getter\r\n block.addStatement(declS(oldValue, callThisX(getterName)));\r\n\r\n // add the fireVetoableChange method call\r\n block.addStatement(stmt(callThisX(\"fireVetoableChange\", args(\r\n constX(propertyName), oldValue, proposedValue))));\r\n\r\n // call the existing block, which will presumably set the value properly\r\n block.addStatement(code);\r\n\r\n if (bindable) {\r\n // get the new value to emit in the event\r\n block.addStatement(declS(newValue, callThisX(getterName)));\r\n\r\n // add the firePropertyChange method call\r\n block.addStatement(stmt(callThisX(\"firePropertyChange\", args(constX(propertyName), oldValue, newValue))));\r\n }\r\n\r\n // replace the existing code block with our new one\r\n setter.setCode(block);\r\n }\r\n }"
] |
Use this API to fetch filtered set of appqoepolicy resources.
set the filter parameter values in filtervalue object. | [
"public static appqoepolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}"
] | [
"@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\n }\n }",
"public boolean decompose(DMatrixRMaj mat , int indexStart , int n ) {\n double m[] = mat.data;\n\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = m[indexStart+i*mat.numCols+j];\n\n int iEl = i*n;\n int jEl = j*n;\n int end = iEl+i;\n // k = 0:i-1\n for( ; iEl<end; iEl++,jEl++ ) {\n// sum -= el[i*n+k]*el[j*n+k];\n sum -= el[iEl]*el[jEl];\n }\n\n if( i == j ) {\n // is it positive-definate?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n el[i*n+i] = el_ii;\n m[indexStart+i*mat.numCols+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n double v = sum*div_el_ii;\n el[j*n+i] = v;\n m[indexStart+j*mat.numCols+i] = v;\n }\n }\n }\n\n return true;\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 }",
"public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher deleteFacet(String... attributes) {\n for (String attribute : attributes) {\n facetRequestCount.put(attribute, 0);\n facets.remove(attribute);\n }\n rebuildQueryFacets();\n return this;\n }",
"public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }",
"public static spilloverpolicy[] get(nitro_service service, options option) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tspilloverpolicy[] response = (spilloverpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public T addModule(final String moduleName, final String slot, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.ADD, NO_CONTENT));\n return returnThis();\n }"
] |
Retrieves the amount of working time represented by
a calendar exception.
@param exception calendar exception
@return length of time in milliseconds | [
"private long getTotalTime(ProjectCalendarDateRanges exception)\n {\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd());\n }\n return (total);\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 synchronized Message simpleRequest(Message.KnownType requestType, Message.KnownType responseType,\n Field... arguments)\n throws IOException {\n final NumberField transaction = assignTransactionNumber();\n final Message request = new Message(transaction, new NumberField(requestType.protocolValue, 2), arguments);\n sendMessage(request);\n final Message response = Message.read(is);\n if (response.transaction.getValue() != transaction.getValue()) {\n throw new IOException(\"Received response with wrong transaction ID. Expected: \" + transaction.getValue() +\n \", got: \" + response);\n }\n if (responseType != null && response.knownType != responseType) {\n throw new IOException(\"Received response with wrong type. Expected: \" + responseType +\n \", got: \" + response);\n }\n return response;\n }",
"public static String readFlowId(Message message) {\n String flowId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> flowIds = headers.get(FLOWID_HTTP_HEADER_NAME);\n if (flowIds != null && flowIds.size() > 0) {\n flowId = flowIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' found: \" + flowId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' found\");\n }\n }\n\n return flowId;\n }",
"void nextExecuted(String sql) throws SQLException\r\n {\r\n count++;\r\n\r\n if (_order.contains(sql))\r\n {\r\n return;\r\n }\r\n\r\n String sqlCmd = sql.substring(0, 7);\r\n String rest = sql.substring(sqlCmd.equals(\"UPDATE \") ? 7 // \"UPDATE \"\r\n : 12); // \"INSERT INTO \" or \"DELETE FROM \"\r\n String tableName = rest.substring(0, rest.indexOf(' '));\r\n HashSet fkTables = (HashSet) _fkInfo.get(tableName);\r\n\r\n // we should not change order of INSERT/DELETE/UPDATE\r\n // statements for the same table\r\n if (_touched.contains(tableName))\r\n {\r\n executeBatch();\r\n }\r\n if (sqlCmd.equals(\"INSERT \"))\r\n {\r\n if (_dontInsert != null && _dontInsert.contains(tableName))\r\n {\r\n // one of the previous INSERTs contained a table\r\n // that references this table.\r\n // Let's execute that previous INSERT right now so that\r\n // in the future INSERTs into this table will go first\r\n // in the _order array.\r\n executeBatch();\r\n }\r\n }\r\n else\r\n //if (sqlCmd.equals(\"DELETE \") || sqlCmd.equals(\"UPDATE \"))\r\n {\r\n // We process UPDATEs in the same way as DELETEs\r\n // because setting FK to NULL in UPDATE is equivalent\r\n // to DELETE from the referential integrity point of view.\r\n\r\n if (_deleted != null && fkTables != null)\r\n {\r\n HashSet intersection = (HashSet) _deleted.clone();\r\n\r\n intersection.retainAll(fkTables);\r\n if (!intersection.isEmpty())\r\n {\r\n // one of the previous DELETEs contained a table\r\n // that is referenced from this table.\r\n // Let's execute that previous DELETE right now so that\r\n // in the future DELETEs into this table will go first\r\n // in the _order array.\r\n executeBatch();\r\n }\r\n }\r\n }\r\n\r\n _order.add(sql);\r\n\r\n _touched.add(tableName);\r\n if (sqlCmd.equals(\"INSERT \"))\r\n {\r\n if (fkTables != null)\r\n {\r\n if (_dontInsert == null)\r\n {\r\n _dontInsert = new HashSet();\r\n }\r\n _dontInsert.addAll(fkTables);\r\n }\r\n }\r\n else if (sqlCmd.equals(\"DELETE \"))\r\n {\r\n if (_deleted == null)\r\n {\r\n _deleted = new HashSet();\r\n }\r\n _deleted.add(tableName);\r\n }\r\n }",
"public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }",
"public String getScopes() {\n final StringBuilder sb = new StringBuilder();\n for (final Scope scope : Scope.values()) {\n sb.append(scope);\n sb.append(\", \");\n }\n final String scopes = sb.toString().trim();\n return scopes.substring(0, scopes.length() - 1);\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 void end() {\n if (TransitionConfig.isPrintDebug()) {\n getTransitionStateHolder().end();\n getTransitionStateHolder().print();\n }\n\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).end();\n }\n }",
"public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }"
] |
Deletes the device pin. | [
"public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }"
] | [
"public static void ensureNotSingular( DMatrixSparseCSC A , Random rand ) {\n// if( A.numRows < A.numCols ) {\n// throw new IllegalArgumentException(\"Fewer equations than variables\");\n// }\n\n int []s = UtilEjml.shuffled(A.numRows,rand);\n Arrays.sort(s);\n\n int N = Math.min(A.numCols,A.numRows);\n for (int col = 0; col < N; col++) {\n A.set(s[col],col,rand.nextDouble()+0.5);\n }\n }",
"public void value2x2( double a11 , double a12, double a21 , double a22 )\n {\n // apply a rotators such that th a11 and a22 elements are the same\n double c,s;\n\n if( a12 + a21 == 0 ) { // is this pointless since\n c = s = 1.0 / Math.sqrt(2);\n } else {\n double aa = (a11-a22);\n double bb = (a12+a21);\n\n double t_hat = aa/bb;\n double t = t_hat/(1.0 + Math.sqrt(1.0+t_hat*t_hat));\n\n c = 1.0/ Math.sqrt(1.0+t*t);\n s = c*t;\n }\n\n double c2 = c*c;\n double s2 = s*s;\n double cs = c*s;\n\n double b11 = c2*a11 + s2*a22 - cs*(a12+a21);\n double b12 = c2*a12 - s2*a21 + cs*(a11-a22);\n double b21 = c2*a21 - s2*a12 + cs*(a11-a22);\n// double b22 = c2*a22 + s2*a11 + cs*(a12+a21);\n\n // apply second rotator to make A upper triangular if real eigenvalues\n if( b21*b12 >= 0 ) {\n if( b12 == 0 ) {\n c = 0;\n s = 1;\n } else {\n s = Math.sqrt(b21/(b12+b21));\n c = Math.sqrt(b12/(b12+b21));\n }\n\n// c2 = b12;//c*c;\n// s2 = b21;//s*s;\n cs = c*s;\n\n a11 = b11 - cs*(b12 + b21);\n// a12 = c2*b12 - s2*b21;\n// a21 = c2*b21 - s2*b12;\n a22 = b11 + cs*(b12 + b21);\n\n value0.real = a11;\n value1.real = a22;\n\n value0.imaginary = value1.imaginary = 0;\n\n } else {\n value0.real = value1.real = b11;\n value0.imaginary = Math.sqrt(-b21*b12);\n value1.imaginary = -value0.imaginary;\n }\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our previews, on the proper thread, and outside our lock.\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(hotCache.keySet());\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(deck.player, null);\n }\n }\n }\n });\n hotCache.clear();\n deliverLifecycleAnnouncement(logger, false);\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}",
"private boolean isForGerritHost(HttpRequest request) {\n if (!(request instanceof HttpRequestWrapper)) return false;\n HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();\n if (!(originalRequest instanceof HttpRequestBase)) return false;\n URI uri = ((HttpRequestBase) originalRequest).getURI();\n URI authDataUri = URI.create(authData.getHost());\n if (uri == null || uri.getHost() == null) return false;\n boolean hostEquals = uri.getHost().equals(authDataUri.getHost());\n boolean portEquals = uri.getPort() == authDataUri.getPort();\n return hostEquals && portEquals;\n }",
"public void start() {\n syncLock.lock();\n try {\n if (!this.isConfigured) {\n return;\n }\n instanceChangeStreamListener.stop();\n if (listenersEnabled) {\n instanceChangeStreamListener.start();\n }\n\n if (syncThread == null) {\n syncThread = new Thread(\n new DataSynchronizerRunner(\n new WeakReference<>(this),\n networkMonitor,\n logger\n ),\n \"dataSynchronizerRunnerThread\"\n );\n }\n if (syncThreadEnabled && !isRunning) {\n syncThread.start();\n isRunning = true;\n }\n } finally {\n syncLock.unlock();\n }\n }",
"public static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }",
"public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\n }",
"public void addProcedure(ProcedureDef procDef)\r\n {\r\n procDef.setOwner(this);\r\n _procedures.put(procDef.getName(), procDef);\r\n }"
] |
Write an error response.
@param channel the channel
@param header the request
@param error the error
@throws IOException | [
"protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException {\n final ManagementResponseHeader response = ManagementResponseHeader.create(header, error);\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }"
] | [
"public void addExportedPackages(Set<String> exportedPackages) {\n\t\taddExportedPackages(exportedPackages.toArray(new String[exportedPackages.size()]));\n\t}",
"public ItemRequest<Task> dependencies(String task) {\n \n String path = String.format(\"/tasks/%s/dependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return servers;\n }",
"public void copy(ProjectCalendar cal)\n {\n setName(cal.getName());\n setParent(cal.getParent());\n System.arraycopy(cal.getDays(), 0, getDays(), 0, getDays().length);\n for (ProjectCalendarException ex : cal.m_exceptions)\n {\n addCalendarException(ex.getFromDate(), ex.getToDate());\n for (DateRange range : ex)\n {\n ex.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n\n for (ProjectCalendarHours hours : getHours())\n {\n if (hours != null)\n {\n ProjectCalendarHours copyHours = cal.addCalendarHours(hours.getDay());\n for (DateRange range : hours)\n {\n copyHours.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n }\n }",
"public <T> T with( Closure<T> closure ) {\n return DefaultGroovyMethods.with( null, closure ) ;\n }",
"public static SortedMap<String, Object> asMap() {\n SortedMap<String, Object> metrics = Maps.newTreeMap();\n METRICS_SOURCE.applyMetrics(metrics);\n return metrics;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry010Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry010Date>) super.localDateTime(temporal);\n }",
"public Map<Integer, String> getSignatures() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<Integer, String>(signatures));\n }",
"protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(violationMessage);\n return violation;\n }"
] |
Search one prototype using the prototype index which is equals to the view type. This method
has to be implemented because prototypes member is declared with Collection and that interface
doesn't allow the client code to get one element by index.
@param prototypeIndex used to search.
@return prototype renderer. | [
"private Renderer getPrototypeByIndex(final int prototypeIndex) {\n Renderer prototypeSelected = null;\n int i = 0;\n for (Renderer prototype : prototypes) {\n if (i == prototypeIndex) {\n prototypeSelected = prototype;\n }\n i++;\n }\n return prototypeSelected;\n }"
] | [
"public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tAssert.notNull(methodName, \"Method name must not be null\");\n\t\ttry {\n\t\t\tMethod method = clazz.getMethod(methodName, args);\n\t\t\treturn Modifier.isStatic(method.getModifiers()) ? method : null;\n\t\t}\n\t\tcatch (NoSuchMethodException ex) {\n\t\t\treturn null;\n\t\t}\n\t}",
"public static double[][] toDouble(int[][] array) {\n double[][] n = new double[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (double) array[i][j];\n }\n }\n return n;\n }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {\n return getResponseHeaders(stringUrl, true);\n }",
"private void readResourceAssignments(Project gpProject)\n {\n Allocations allocations = gpProject.getAllocations();\n if (allocations != null)\n {\n for (Allocation allocation : allocations.getAllocation())\n {\n readResourceAssignment(allocation);\n }\n }\n }",
"public static boolean containsAtLeastOneNonBlank(List<String> list){\n\t\tfor(String str : list){\n\t\t\tif(StringUtils.isNotBlank(str)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public String validationErrors() {\n\n List<String> errors = new ArrayList<>();\n for (File config : getConfigFiles()) {\n String filename = config.getName();\n try (FileInputStream stream = new FileInputStream(config)) {\n CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true);\n } catch (CmsXmlException e) {\n errors.add(filename + \":\" + e.getCause().getMessage());\n } catch (Exception e) {\n errors.add(filename + \":\" + e.getMessage());\n }\n }\n if (errors.size() == 0) {\n return null;\n }\n String errString = CmsStringUtil.listAsString(errors, \"\\n\");\n JSONObject obj = new JSONObject();\n try {\n obj.put(\"err\", errString);\n } catch (JSONException e) {\n\n }\n return obj.toString();\n }",
"public String calculateCacheKey(String sql, int autoGeneratedKeys) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\ttmp.append(autoGeneratedKeys);\r\n\t\treturn tmp.toString();\r\n\t}",
"public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }",
"private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }"
] |
Execute a HTTP request
@param stringUrl URL
@param method Method to use
@param parameters Params
@param input Input / Payload
@param charset Input Charset
@return response
@throws IOException | [
"public static String httpRequest(String stringUrl, String method, Map<String, String> parameters,\n String input, String charset) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setDoOutput(true);\n conn.setRequestMethod(method);\n\n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n if (input != null) {\n OutputStream output = null;\n try {\n output = conn.getOutputStream();\n output.write(input.getBytes(charset));\n } finally {\n if (output != null) {\n output.close();\n }\n }\n }\n\n return MyStreamUtils.readContent(conn.getInputStream());\n }"
] | [
"private void prefetchRelationships(Query query)\r\n {\r\n List prefetchedRel;\r\n Collection owners;\r\n String relName;\r\n RelationshipPrefetcher[] prefetchers;\r\n\r\n if (query == null || query.getPrefetchedRelationships() == null || query.getPrefetchedRelationships().isEmpty())\r\n {\r\n return;\r\n }\r\n\r\n if (!supportsAdvancedJDBCCursorControl())\r\n {\r\n logger.info(\"prefetching relationships requires JDBC level 2.0\");\r\n return;\r\n }\r\n\r\n // prevent releasing of DBResources\r\n setInBatchedMode(true);\r\n\r\n prefetchedRel = query.getPrefetchedRelationships();\r\n prefetchers = new RelationshipPrefetcher[prefetchedRel.size()];\r\n\r\n // disable auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n relName = (String) prefetchedRel.get(i);\r\n prefetchers[i] = getBroker().getRelationshipPrefetcherFactory()\r\n .createRelationshipPrefetcher(getQueryObject().getClassDescriptor(), relName);\r\n prefetchers[i].prepareRelationshipSettings();\r\n }\r\n\r\n // materialize ALL owners of this Iterator\r\n owners = getOwnerObjects();\r\n\r\n // prefetch relationships and associate with owners\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].prefetchRelationship(owners);\r\n }\r\n\r\n // reset auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].restoreRelationshipSettings();\r\n }\r\n\r\n try\r\n {\r\n getRsAndStmt().m_rs.beforeFirst(); // reposition resultset jdbc 2.0\r\n }\r\n catch (SQLException e)\r\n {\r\n logger.error(\"beforeFirst failed !\", e);\r\n }\r\n\r\n setInBatchedMode(false);\r\n setHasCalledCheck(false);\r\n }",
"public void deleteFolder(String folderID) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }",
"void updateFromResponseOnPutPatch(Response<ResponseBody> response) throws CloudException, IOException {\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n\n if (responseContent == null || responseContent.isEmpty()) {\n throw new CloudException(\"polling response does not contain a valid body\", response);\n }\n\n PollingResource resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n final int statusCode = response.code();\n if (resource != null && resource.properties != null && resource.properties.provisioningState != null) {\n this.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n this.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n }\n\n CloudError error = new CloudError();\n this.withErrorBody(error);\n error.withCode(this.status());\n error.withMessage(\"Long running operation failed\");\n this.withResponse(response);\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n }",
"protected void fixIntegerPrecisions(ItemIdValue itemIdValue,\n\t\t\tString propertyId) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Get the current statements for the property we want to fix:\n\t\t\tStatementGroup editPropertyStatements = currentItemDocument\n\t\t\t\t\t.findStatementGroup(propertyId);\n\t\t\tif (editPropertyStatements == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" no longer has any statements for \" + propertyId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tPropertyIdValue property = Datamodel\n\t\t\t\t\t.makeWikidataPropertyIdValue(propertyId);\n\t\t\tList<Statement> updateStatements = new ArrayList<>();\n\t\t\tfor (Statement s : editPropertyStatements) {\n\t\t\t\tQuantityValue qv = (QuantityValue) s.getValue();\n\t\t\t\tif (qv != null && isPlusMinusOneValue(qv)) {\n\t\t\t\t\tQuantityValue exactValue = Datamodel.makeQuantityValue(\n\t\t\t\t\t\t\tqv.getNumericValue(), qv.getNumericValue(),\n\t\t\t\t\t\t\tqv.getNumericValue());\n\t\t\t\t\tStatement exactStatement = StatementBuilder\n\t\t\t\t\t\t\t.forSubjectAndProperty(itemIdValue, property)\n\t\t\t\t\t\t\t.withValue(exactValue).withId(s.getStatementId())\n\t\t\t\t\t\t\t.withQualifiers(s.getQualifiers())\n\t\t\t\t\t\t\t.withReferences(s.getReferences())\n\t\t\t\t\t\t\t.withRank(s.getRank()).build();\n\t\t\t\t\tupdateStatements.add(exactStatement);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (updateStatements.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** \" + qid + \" quantity values for \"\n\t\t\t\t\t\t+ propertyId + \" already fixed\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tupdateStatements, propertyId);\n\n\t\t\tdataEditor.updateStatements(currentItemDocument, updateStatements,\n\t\t\t\t\tCollections.<Statement> emptyList(),\n\t\t\t\t\t\"Set exact values for [[Property:\" + propertyId + \"|\"\n\t\t\t\t\t\t\t+ propertyId + \"]] integer quantities (Task MB2)\");\n\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"public MessageSet read(long offset, int length) throws IOException {\n List<LogSegment> views = segments.getView();\n LogSegment found = findRange(views, offset, views.size());\n if (found == null) {\n if (logger.isTraceEnabled()) {\n logger.trace(format(\"NOT FOUND MessageSet from Log[%s], offset=%d, length=%d\", name, offset, length));\n }\n return MessageSet.Empty;\n }\n return found.getMessageSet().read(offset - found.start(), length);\n }",
"public static final int getInt(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Integer.parseInt(value));\n }",
"public String getHostAddress() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostAddress();\n }\n return ((InetAddress)addr).getHostAddress();\n }",
"private boolean hidden(ProgramElementDoc c) {\n\tif (c.tags(\"hidden\").length > 0 || c.tags(\"view\").length > 0)\n\t return true;\n\tOptions opt = optionProvider.getOptionsFor(c instanceof ClassDoc ? (ClassDoc) c : c.containingClass());\n\treturn opt.matchesHideExpression(c.toString()) //\n\t\t|| (opt.hidePrivateInner && c instanceof ClassDoc && c.isPrivate() && ((ClassDoc) c).containingClass() != null);\n }"
] |
Adds a new step to the list of steps.
@param name Name of the step to add.
@param robot The name of the robot ot use with the step.
@param options extra options required for the step. | [
"public void addStep(String name, String robot, Map<String, Object> options) {\n all.put(name, new Step(name, robot, options));\n }"
] | [
"private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }",
"private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}",
"public static base_responses delete(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 deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"public static Object formatL(final String template, final Object... args) {\n return new Object() {\n @Override\n public String toString() {\n return format(template, args);\n }\n };\n }",
"public Where<T, ID> ge(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"public <Ex extends Throwable> Try<R,Ex> execute(T input,Class<Ex> classes){\n\t\t\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)),classes);\n\t\t \n\t}",
"public static int[] getTileScreenSize(double[] worldSize, double scale) {\n\t\tint screenWidth = (int) Math.round(scale * worldSize[0]);\n\t\tint screenHeight = (int) Math.round(scale * worldSize[1]);\n\t\treturn new int[] { screenWidth, screenHeight };\n\t}",
"void gc() {\n if (stopped) {\n return;\n }\n long expirationTime = System.currentTimeMillis() - timeout;\n for (Iterator<Map.Entry<InputStreamKey, TimedStreamEntry>> iter = streamMap.entrySet().iterator(); iter.hasNext();) {\n if (stopped) {\n return;\n }\n Map.Entry<InputStreamKey, TimedStreamEntry> entry = iter.next();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n if (timedStreamEntry.timestamp.get() <= expirationTime) {\n iter.remove();\n InputStreamKey key = entry.getKey();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }\n }"
] |
Performs a null edit on a property. This has some effects on Wikibase,
such as refreshing the labels of the referred items in the UI.
@param propertyId
the document to perform a null edit on
@throws MediaWikiApiErrorException
if the API returns errors
@throws IOException
if there are any IO errors, such as missing network connection | [
"public <T extends StatementDocument> void nullEdit(PropertyIdValue propertyId)\n\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tPropertyDocument currentDocument = (PropertyDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(propertyId.getId());\n\t\t\n\t\tnullEdit(currentDocument);\n\t}"
] | [
"public ItemRequest<Task> removeDependents(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public int deleteTopic(String topic, String password) throws IOException {\n KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }",
"public static Class getClass(String className, boolean initialize) throws ClassNotFoundException\r\n {\r\n return Class.forName(className, initialize, getClassLoader());\r\n }",
"private static Map<String, Object> processConf(Map<String, ?> conf) {\n Map<String, Object> m = new HashMap<String, Object>(conf.size());\n for (String s : conf.keySet()) {\n Object o = conf.get(s);\n if (s.startsWith(\"act.\")) s = s.substring(4);\n m.put(s, o);\n m.put(Config.canonical(s), o);\n }\n return m;\n }",
"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 }",
"private void setAnimationProgress(float progress) {\n if (isAlphaUsedForScale()) {\n setColorViewAlpha((int) (progress * MAX_ALPHA));\n } else {\n ViewCompat.setScaleX(mCircleView, progress);\n ViewCompat.setScaleY(mCircleView, progress);\n }\n }",
"private void flush(final boolean propagate) throws IOException {\n final int avail = baseNCodec.available(context);\n if (avail > 0) {\n final byte[] buf = new byte[avail];\n final int c = baseNCodec.readResults(buf, 0, avail, context);\n if (c > 0) {\n out.write(buf, 0, c);\n }\n }\n if (propagate) {\n out.flush();\n }\n }",
"public static Diagram parseJson(JSONObject json,\n Boolean keepGlossaryLink) throws JSONException {\n ArrayList<Shape> shapes = new ArrayList<Shape>();\n HashMap<String, JSONObject> flatJSON = flatRessources(json);\n for (String resourceId : flatJSON.keySet()) {\n parseRessource(shapes,\n flatJSON,\n resourceId,\n keepGlossaryLink);\n }\n String id = \"canvas\";\n\n if (json.has(\"resourceId\")) {\n id = json.getString(\"resourceId\");\n shapes.remove(new Shape(id));\n }\n ;\n Diagram diagram = new Diagram(id);\n\n // remove Diagram\n // (Diagram)getShapeWithId(json.getString(\"resourceId\"), shapes);\n parseStencilSet(json,\n diagram);\n parseSsextensions(json,\n diagram);\n parseStencil(json,\n diagram);\n parseProperties(json,\n diagram,\n keepGlossaryLink);\n parseChildShapes(shapes,\n json,\n diagram);\n parseBounds(json,\n diagram);\n diagram.setShapes(shapes);\n return diagram;\n }",
"public Where<T, ID> raw(String rawStatement, ArgumentHolder... args) {\n\t\tfor (ArgumentHolder arg : args) {\n\t\t\tString columnName = arg.getColumnName();\n\t\t\tif (columnName == null) {\n\t\t\t\tif (arg.getSqlType() == null) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Either the column name or SqlType must be set on each argument\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\targ.setMetaInfo(findColumnFieldType(columnName));\n\t\t\t}\n\t\t}\n\t\taddClause(new Raw(rawStatement, args));\n\t\treturn this;\n\t}"
] |
Parses coordinates into a Spatial4j point shape. | [
"private Point parsePoint(String point) {\n int comma = point.indexOf(',');\n if (comma == -1)\n return null;\n\n float lat = Float.valueOf(point.substring(0, comma));\n float lng = Float.valueOf(point.substring(comma + 1));\n return spatialctx.makePoint(lng, lat);\n }"
] | [
"private static JSONArray parseChildShapesRecursive(ArrayList<Shape> childShapes) throws JSONException {\n if (childShapes != null) {\n JSONArray childShapesArray = new JSONArray();\n\n for (Shape childShape : childShapes) {\n JSONObject childShapeObject = new JSONObject();\n\n childShapeObject.put(\"resourceId\",\n childShape.getResourceId().toString());\n childShapeObject.put(\"properties\",\n parseProperties(childShape.getProperties()));\n childShapeObject.put(\"stencil\",\n parseStencil(childShape.getStencilId()));\n childShapeObject.put(\"childShapes\",\n parseChildShapesRecursive(childShape.getChildShapes()));\n childShapeObject.put(\"outgoing\",\n parseOutgoings(childShape.getOutgoings()));\n childShapeObject.put(\"bounds\",\n parseBounds(childShape.getBounds()));\n childShapeObject.put(\"dockers\",\n parseDockers(childShape.getDockers()));\n\n if (childShape.getTarget() != null) {\n childShapeObject.put(\"target\",\n parseTarget(childShape.getTarget()));\n }\n\n childShapesArray.put(childShapeObject);\n }\n\n return childShapesArray;\n }\n\n return new JSONArray();\n }",
"public void setModelByInputFileStream(InputStream inputFileStream) {\r\n try {\r\n this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\n }",
"public boolean detectMobileQuick() {\r\n\r\n //Let's exclude tablets\r\n if (isTierTablet) {\r\n return false;\r\n }\r\n //Most mobile browsing is done on smartphones\r\n if (detectSmartphone()) {\r\n return true;\r\n }\r\n\r\n //Catch-all for many mobile devices\r\n if (userAgent.indexOf(mobile) != -1) {\r\n return true;\r\n }\r\n\r\n if (detectOperaMobile()) {\r\n return true;\r\n }\r\n\r\n //We also look for Kindle devices\r\n if (detectKindle() || detectAmazonSilk()) {\r\n return true;\r\n }\r\n\r\n if (detectWapWml() || detectMidpCapable() || detectBrewDevice()) {\r\n return true;\r\n }\r\n\r\n if ((userAgent.indexOf(engineNetfront) != -1) || (userAgent.indexOf(engineUpBrowser) != -1)) {\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"private void initManagementPart() {\n\n m_manageExceptionsButton.setText(Messages.get().key(Messages.GUI_SERIALDATE_BUTTON_MANAGE_EXCEPTIONS_0));\n m_manageExceptionsButton.getElement().getStyle().setFloat(Style.Float.RIGHT);\n }",
"private void setRawDirection(SwipyRefreshLayoutDirection direction) {\n if (mDirection == direction) {\n return;\n }\n\n mDirection = direction;\n switch (mDirection) {\n case BOTTOM:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();\n break;\n case TOP:\n default:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();\n break;\n }\n }",
"public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }",
"public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }",
"public static base_response update(nitro_service client, nsspparams resource) throws Exception {\n\t\tnsspparams updateresource = new nsspparams();\n\t\tupdateresource.basethreshold = resource.basethreshold;\n\t\tupdateresource.throttle = resource.throttle;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public ItemRequest<Project> removeCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/removeCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }"
] |
Retrieves a ProjectWriter instance which can write a file of the
type specified by the supplied file name.
@param name file name
@return ProjectWriter instance | [
"public static ProjectWriter getProjectWriter(String name) throws InstantiationException, IllegalAccessException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectWriter> fileClass = WRITER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot write files of type: \" + name);\n }\n\n ProjectWriter file = fileClass.newInstance();\n\n return (file);\n }"
] | [
"public static boolean isClassClassNodeWrappingConcreteType(ClassNode classNode) {\n GenericsType[] genericsTypes = classNode.getGenericsTypes();\n return ClassHelper.CLASS_Type.equals(classNode)\n && classNode.isUsingGenerics()\n && genericsTypes!=null\n && !genericsTypes[0].isPlaceholder()\n && !genericsTypes[0].isWildcard();\n }",
"public static void withInstance(String url, Closure c) throws SQLException {\n Sql sql = null;\n try {\n sql = newInstance(url);\n c.call(sql);\n } finally {\n if (sql != null) sql.close();\n }\n }",
"public void bind(Object object, String name)\r\n throws ObjectNameNotUniqueException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call bind.\");\r\n }\r\n /**\r\n * Is Tx open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call bind.\");\r\n }\r\n\r\n tx.getNamedRootsMap().bind(object, name);\r\n }",
"public void setBackgroundColor(int color) {\n colorUnpressed = color;\n\n if(!isSelected()) {\n if (rippleAnimationSupport()) {\n ripple.setRippleBackground(colorUnpressed);\n }\n else {\n view.setBackgroundColor(colorUnpressed);\n }\n }\n }",
"public void rememberAndDisableQuota() {\n for(Integer nodeId: nodeIds) {\n boolean quotaEnforcement = Boolean.parseBoolean(adminClient.metadataMgmtOps.getRemoteMetadata(nodeId,\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY)\n .getValue());\n mapNodeToQuotaEnforcingEnabled.put(nodeId, quotaEnforcement);\n }\n adminClient.metadataMgmtOps.updateRemoteMetadata(nodeIds,\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY,\n Boolean.toString(false));\n }",
"private void writeAttributeTypes(String name, FieldType[] types) throws IOException\n {\n m_writer.writeStartObject(name);\n for (FieldType field : types)\n {\n m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue());\n }\n m_writer.writeEndObject();\n }",
"public static String getParentId(String digest, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(digest).exec().getParent();\n } finally {\n closeQuietly(dockerClient);\n }\n }",
"public static final void deleteQuietly(File file)\n {\n if (file != null)\n {\n if (file.isDirectory())\n {\n File[] children = file.listFiles();\n if (children != null)\n {\n for (File child : children)\n {\n deleteQuietly(child);\n }\n }\n }\n file.delete();\n }\n }",
"public String putDocument(Document document) {\n\t\tString key = UUID.randomUUID().toString();\n\t\tdocumentMap.put(key, document);\n\t\treturn key;\n\t}"
] |
Was this beat sent by the current tempo master?
@return {@code true} if the device that sent this beat is the master
@throws IllegalStateException if the {@link VirtualCdj} is not running | [
"@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }"
] | [
"public void setVelocityRange( final Vector3f minV, final Vector3f maxV )\n {\n if (null != mGVRContext) {\n mGVRContext.runOnGlThread(new Runnable() {\n\n @Override\n public void run() {\n minVelocity = minV;\n maxVelocity = maxV;\n }\n });\n }\n }",
"public 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}",
"public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }",
"public void enableClipRegion() {\n if (mClippingEnabled) {\n Log.w(TAG, \"Clipping has been enabled already for %s!\", getName());\n return;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"enableClipping for %s [%f, %f, %f]\",\n getName(), getViewPortWidth(), getViewPortHeight(), getViewPortDepth());\n\n mClippingEnabled = true;\n\n GVRTexture texture = WidgetLib.getTextureHelper().getSolidColorTexture(Color.YELLOW);\n\n GVRSceneObject clippingObj = new GVRSceneObject(mContext, getViewPortWidth(), getViewPortHeight(), texture);\n clippingObj.setName(\"clippingObj\");\n clippingObj.getRenderData()\n .setRenderingOrder(GVRRenderData.GVRRenderingOrder.STENCIL)\n .setStencilTest(true)\n .setStencilFunc(GLES30.GL_ALWAYS, 1, 0xFF)\n .setStencilOp(GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_REPLACE)\n .setStencilMask(0xFF);\n\n mSceneObject.addChildObject(clippingObj);\n\n for (Widget child : getChildren()) {\n setObjectClipped(child);\n }\n }",
"public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) {\n unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size);\n }",
"private void processClientId(HttpServletRequest httpServletRequest, History history) {\n // get the client id from the request header if applicable.. otherwise set to default\n // also set the client uuid in the history object\n if (httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME) != null &&\n !httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME).equals(\"\")) {\n history.setClientUUID(httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME));\n } else {\n history.setClientUUID(Constants.PROFILE_CLIENT_DEFAULT_ID);\n }\n logger.info(\"Client UUID is: {}\", history.getClientUUID());\n }",
"private void readResource(net.sf.mpxj.planner.schema.Resource plannerResource) throws MPXJException\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n //mpxjResource.setResourceCalendar(m_projectFile.getBaseCalendarByUniqueID(getInteger(plannerResource.getCalendar())));\n mpxjResource.setEmailAddress(plannerResource.getEmail());\n mpxjResource.setUniqueID(getInteger(plannerResource.getId()));\n mpxjResource.setName(plannerResource.getName());\n mpxjResource.setNotes(plannerResource.getNote());\n mpxjResource.setInitials(plannerResource.getShortName());\n mpxjResource.setType(getInt(plannerResource.getType()) == 2 ? ResourceType.MATERIAL : ResourceType.WORK);\n //plannerResource.getStdRate();\n //plannerResource.getOvtRate();\n //plannerResource.getUnits();\n //plannerResource.getProperties();\n\n ProjectCalendar calendar = mpxjResource.addResourceCalendar();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n ProjectCalendar baseCalendar = m_projectFile.getCalendarByUniqueID(getInteger(plannerResource.getCalendar()));\n if (baseCalendar == null)\n {\n baseCalendar = m_defaultCalendar;\n }\n calendar.setParent(baseCalendar);\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"Map<String, String> packageNameMap() {\n if (packageNames == null) {\n return emptyMap();\n }\n\n Map<String, String> names = new LinkedHashMap<String, String>();\n for (PackageName name : packageNames) {\n names.put(name.getUri(), name.getPackage());\n }\n return names;\n }",
"public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Add a LIKE clause so the column must mach the value using '%' patterns. | [
"public Where<T, ID> like(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LIKE_OPERATION));\n\t\treturn this;\n\t}"
] | [
"public void subscriptionRequestReceived(SubscriptionRequest sr) throws SubscriptionException {\n\n LOG.info(\"Subscriber -> (Hub), new subscription request received.\", sr.getCallback());\n\n try {\n\n verifySubscriberRequestedSubscription(sr);\n\n if (\"subscribe\".equals(sr.getMode())) {\n LOG.info(\"Adding callback {} to the topic {}\", sr.getCallback(), sr.getTopic());\n addCallbackToTopic(sr.getCallback(), sr.getTopic());\n } else if (\"unsubscribe\".equals(sr.getMode())) {\n LOG.info(\"Removing callback {} from the topic {}\", sr.getCallback(), sr.getTopic());\n removeCallbackToTopic(sr.getCallback(), sr.getTopic());\n }\n\n } catch (Exception e) {\n throw new SubscriptionException(e);\n }\n\n }",
"private String safeToString(Object obj)\r\n\t{\r\n\t\tString toString = null;\r\n\t\tif (obj != null)\r\n\t\t{\r\n\t\t try\r\n\t\t {\r\n\t\t toString = obj.toString();\r\n\t\t }\r\n\t\t catch (Throwable ex)\r\n\t\t {\r\n\t\t toString = \"BAD toString() impl for \" + obj.getClass().getName();\r\n\t\t }\r\n\t\t}\r\n\t\treturn toString;\r\n\t}",
"public String calculateCacheKey(String sql, int[] columnIndexes) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\tfor (int i=0; i < columnIndexes.length; i++){\r\n\t\t\ttmp.append(columnIndexes[i]);\r\n\t\t\ttmp.append(\"CI,\");\r\n\t\t}\r\n\t\treturn tmp.toString();\r\n\t}",
"public String getURN() throws InvalidRegistrationContentException {\n if (parsedConfig==null || parsedConfig.urn==null || parsedConfig.urn.trim().isEmpty()) {\n throw new InvalidRegistrationContentException(\"Invalid registration config - failed to read mediator URN\");\n }\n return parsedConfig.urn;\n }",
"@Override\n public <T> Producer<T> createProducer(final Bean<X> declaringBean, final Bean<T> bean, DisposalMethod<X, T> disposalMethod) {\n EnhancedAnnotatedField<T, X> enhancedField = getManager().getServices().get(MemberTransformer.class).loadEnhancedMember(field, getManager().getId());\n return new ProducerFieldProducer<X, T>(enhancedField, disposalMethod) {\n\n @Override\n public AnnotatedField<X> getAnnotated() {\n return field;\n }\n\n @Override\n public BeanManagerImpl getBeanManager() {\n return getManager();\n }\n\n @Override\n public Bean<X> getDeclaringBean() {\n return declaringBean;\n }\n\n @Override\n public Bean<T> getBean() {\n return bean;\n }\n };\n }",
"private void ensureColumn(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN))\r\n {\r\n String javaname = fieldDef.getName();\r\n\r\n if (fieldDef.isNested())\r\n { \r\n int pos = javaname.indexOf(\"::\");\r\n\r\n // we convert nested names ('_' for '::')\r\n if (pos > 0)\r\n {\r\n StringBuffer newJavaname = new StringBuffer(javaname.substring(0, pos));\r\n int lastPos = pos + 2;\r\n\r\n do\r\n {\r\n pos = javaname.indexOf(\"::\", lastPos);\r\n newJavaname.append(\"_\");\r\n if (pos > 0)\r\n { \r\n newJavaname.append(javaname.substring(lastPos, pos));\r\n lastPos = pos + 2;\r\n }\r\n else\r\n {\r\n newJavaname.append(javaname.substring(lastPos));\r\n }\r\n }\r\n while (pos > 0);\r\n javaname = newJavaname.toString();\r\n }\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN, javaname);\r\n }\r\n }",
"public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}",
"@PostConstruct\n public void initDatabase() {\n MongoDBInit.LOGGER.info(\"initializing MongoDB\");\n String dbName = System.getProperty(\"mongodb.name\");\n if (dbName == null) {\n throw new RuntimeException(\"Missing database name; Set system property 'mongodb.name'\");\n }\n MongoDatabase db = this.mongo.getDatabase(dbName);\n\n try {\n PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();\n Resource[] resources = resolver.getResources(\"classpath*:mongodb/*.ndjson\");\n MongoDBInit.LOGGER.info(\"Scanning for collection data\");\n for (Resource res : resources) {\n String filename = res.getFilename();\n String collection = filename.substring(0, filename.length() - 7);\n MongoDBInit.LOGGER.info(\"Found collection file: {}\", collection);\n MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);\n try (Scanner scan = new Scanner(res.getInputStream(), \"UTF-8\")) {\n int lines = 0;\n while (scan.hasNextLine()) {\n String json = scan.nextLine();\n Object parse = JSON.parse(json);\n if (parse instanceof DBObject) {\n DBObject dbObject = (DBObject) parse;\n dbCollection.insertOne(dbObject);\n } else {\n MongoDBInit.LOGGER.error(\"Invalid object found: {}\", parse);\n throw new RuntimeException(\"Invalid object\");\n }\n lines++;\n }\n MongoDBInit.LOGGER.info(\"Imported {} objects into collection {}\", lines, collection);\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error importing objects\", e);\n }\n }",
"public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth)\n {\n int currentDepth = 0;\n Iterable<? extends WindupVertexFrame> result = null;\n for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque)\n {\n result = frame.get(name);\n if (result != null)\n {\n break;\n }\n currentDepth++;\n if (currentDepth >= maxDepth)\n break;\n }\n return result;\n }"
] |
returns IsolationLevel literal as matching
to the corresponding id
@return the IsolationLevel literal | [
"protected String getIsolationLevelAsString()\r\n {\r\n if (defaultIsolationLevel == IL_READ_UNCOMMITTED)\r\n {\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_READ_COMMITTED)\r\n {\r\n return LITERAL_IL_READ_COMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_REPEATABLE_READ)\r\n {\r\n return LITERAL_IL_REPEATABLE_READ;\r\n }\r\n else if (defaultIsolationLevel == IL_SERIALIZABLE)\r\n {\r\n return LITERAL_IL_SERIALIZABLE;\r\n }\r\n else if (defaultIsolationLevel == IL_OPTIMISTIC)\r\n {\r\n return LITERAL_IL_OPTIMISTIC;\r\n }\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }"
] | [
"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 }",
"public int readFrom(ByteBuffer src, long destOffset) {\n if (src.remaining() + destOffset >= size())\n throw new BufferOverflowException();\n int readLen = src.remaining();\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src);\n return readLen;\n }",
"public RedwoodConfiguration loggingClass(final String classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces); } });\r\n return this;\r\n }",
"public boolean destroyDependentInstance(T instance) {\n synchronized (dependentInstances) {\n for (Iterator<ContextualInstance<?>> iterator = dependentInstances.iterator(); iterator.hasNext();) {\n ContextualInstance<?> contextualInstance = iterator.next();\n if (contextualInstance.getInstance() == instance) {\n iterator.remove();\n destroy(contextualInstance);\n return true;\n }\n }\n }\n return false;\n }",
"public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }",
"public VideoCollection generate(final int videoCount) {\n List<Video> videos = new LinkedList<Video>();\n for (int i = 0; i < videoCount; i++) {\n Video video = generateRandomVideo();\n videos.add(video);\n }\n return new VideoCollection(videos);\n }",
"@Override\n public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener,\n Throwable error) {\n //listener.getLogger().println(\"[MavenDependenciesRecorder] mojo: \" + mojo.getClass() + \":\" + mojo.getGoal());\n //listener.getLogger().println(\"[MavenDependenciesRecorder] dependencies: \" + pom.getArtifacts());\n recordMavenDependencies(pom.getArtifacts());\n return true;\n }",
"public boolean detectBlackBerryTouch() {\r\n\r\n if (detectBlackBerry()\r\n && ((userAgent.indexOf(deviceBBStorm) != -1)\r\n || (userAgent.indexOf(deviceBBTorch) != -1)\r\n || (userAgent.indexOf(deviceBBBoldTouch) != -1)\r\n || (userAgent.indexOf(deviceBBCurveTouch) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }",
"private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }"
] |
If task completed success or failure from response.
@param myResponse
the my response
@return true, if successful | [
"public boolean ifTaskCompletedSuccessOrFailureFromResponse(\n ResponseOnSingeRequest myResponse) {\n\n boolean isCompleted = false;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return isCompleted;\n }\n\n String responseBody = myResponse.getResponseBody();\n if (responseBody.matches(successRegex)\n || responseBody.matches(failureRegex)) {\n isCompleted = true;\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n return isCompleted;\n }"
] | [
"public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }",
"public static void munlock(Pointer addr, long len) {\n\n if(Delegate.munlock(addr, new NativeLong(len)) != 0) {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking failed with errno:\" + errno.strerror());\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking region\");\n }\n }",
"public void process(String inputFile, String outputFile) throws Exception\n {\n System.out.println(\"Reading input file started.\");\n long start = System.currentTimeMillis();\n ProjectFile projectFile = readFile(inputFile);\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading input file completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }",
"private static double pointsDistance(Point a, Point b) {\n int dx = b.x - a.x;\n int dy = b.y - a.y;\n return Math.sqrt(dx * dx + dy * dy);\n }",
"static String md5(String input) {\n if (input == null || input.length() == 0) {\n throw new IllegalArgumentException(\"Input string must not be blank.\");\n }\n try {\n MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n algorithm.reset();\n algorithm.update(input.getBytes());\n byte[] messageDigest = algorithm.digest();\n\n StringBuilder hexString = new StringBuilder();\n for (byte messageByte : messageDigest) {\n hexString.append(Integer.toHexString((messageByte & 0xFF) | 0x100).substring(1, 3));\n }\n return hexString.toString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"private License getLicense(final String licenseId) {\n License result = null;\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);\n\n if (matchingLicenses.isEmpty()) {\n result = DataModelFactory.createLicense(\"#\" + licenseId + \"# (to be identified)\", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);\n result.setUnknown(true);\n } else {\n if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"%s matches multiple licenses %s. \" +\n \"Please run the report showing multiple matching on licenses\",\n licenseId, matchingLicenses.toString()));\n }\n result = mapper.getLicense(matchingLicenses.iterator().next());\n\n }\n\n return result;\n }",
"public static wisite_binding[] get(nitro_service service, String sitepath[]) throws Exception{\n\t\tif (sitepath !=null && sitepath.length>0) {\n\t\t\twisite_binding response[] = new wisite_binding[sitepath.length];\n\t\t\twisite_binding obj[] = new wisite_binding[sitepath.length];\n\t\t\tfor (int i=0;i<sitepath.length;i++) {\n\t\t\t\tobj[i] = new wisite_binding();\n\t\t\t\tobj[i].set_sitepath(sitepath[i]);\n\t\t\t\tresponse[i] = (wisite_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }",
"public void setVariable(String name, Object value) {\n if (variables == null)\n variables = new LinkedHashMap();\n variables.put(name, value);\n }"
] |
Add all headers in a header map.
@param headers a map of headers.
@return the interceptor instance itself. | [
"public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }"
] | [
"private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }",
"private void writeAssignments() throws IOException\n {\n writeAttributeTypes(\"assignment_types\", AssignmentField.values());\n\n m_writer.writeStartList(\"assignments\");\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n writeFields(null, assignment, AssignmentField.values());\n }\n m_writer.writeEndList();\n\n }",
"private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }",
"public void setConnectTimeout(int millis) {\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t}",
"public int scrollToPage(int pageNumber) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToPage pageNumber = %d mPageCount = %d\",\n pageNumber, mPageCount);\n\n if (mSupportScrollByPage &&\n (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) {\n scrollToItem(getFirstItemIndexOnPage(pageNumber));\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n return mCurrentItemIndex;\n\t}",
"@Nullable\n public static String readUTF(@NotNull final InputStream stream) throws IOException {\n final DataInputStream dataInput = new DataInputStream(stream);\n if (stream instanceof ByteArraySizedInputStream) {\n final ByteArraySizedInputStream sizedStream = (ByteArraySizedInputStream) stream;\n final int streamSize = sizedStream.size();\n if (streamSize >= 2) {\n sizedStream.mark(Integer.MAX_VALUE);\n final int utfLen = dataInput.readUnsignedShort();\n if (utfLen == streamSize - 2) {\n boolean isAscii = true;\n final byte[] bytes = sizedStream.toByteArray();\n for (int i = 0; i < utfLen; ++i) {\n if ((bytes[i + 2] & 0xff) > 127) {\n isAscii = false;\n break;\n }\n }\n if (isAscii) {\n return fromAsciiByteArray(bytes, 2, utfLen);\n }\n }\n sizedStream.reset();\n }\n }\n try {\n String result = null;\n StringBuilder builder = null;\n for (; ; ) {\n final String temp;\n try {\n temp = dataInput.readUTF();\n if (result != null && result.length() == 0 &&\n builder != null && builder.length() == 0 && temp.length() == 0) {\n break;\n }\n } catch (EOFException e) {\n break;\n }\n if (result == null) {\n result = temp;\n } else {\n if (builder == null) {\n builder = new StringBuilder();\n builder.append(result);\n }\n builder.append(temp);\n }\n }\n return (builder != null) ? builder.toString() : result;\n } finally {\n dataInput.close();\n }\n }",
"private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }",
"private ProjectFile handleXerFile(InputStream stream) throws Exception\n {\n PrimaveraXERFileReader reader = new PrimaveraXERFileReader();\n reader.setCharset(m_charset);\n List<ProjectFile> projects = reader.readAll(stream);\n ProjectFile project = null;\n for (ProjectFile file : projects)\n {\n if (file.getProjectProperties().getExportFlag())\n {\n project = file;\n break;\n }\n }\n if (project == null && !projects.isEmpty())\n {\n project = projects.get(0);\n }\n return project;\n }",
"public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Retrieve a Double from an input stream.
@param is input stream
@return Double instance | [
"public static final Double getDouble(InputStream is) throws IOException\n {\n double result = Double.longBitsToDouble(getLong(is));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return Double.valueOf(result);\n }"
] | [
"public String getAlias(String path)\r\n {\r\n if (m_allPathsAliased && m_attributePath.lastIndexOf(path) != -1)\r\n {\r\n return m_name;\r\n }\r\n Object retObj = m_mapping.get(path);\r\n if (retObj != null)\r\n {\r\n return (String) retObj;\r\n }\r\n return null;\r\n }",
"private Collection<TestClassResults> flattenResults(List<ISuite> suites)\n {\n Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();\n for (ISuite suite : suites)\n {\n for (ISuiteResult suiteResult : suite.getResults().values())\n {\n // Failed and skipped configuration methods are treated as test failures.\n organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);\n // Successful configuration methods are not included.\n \n organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);\n }\n }\n return flattenedResults.values();\n }",
"private static Map<String, ServerGroupDeploymentPlanResult> buildServerGroupResults(Map<UUID, DeploymentActionResult> deploymentActionResults) {\n Map<String, ServerGroupDeploymentPlanResult> serverGroupResults = new HashMap<String, ServerGroupDeploymentPlanResult>();\n\n for (Map.Entry<UUID, DeploymentActionResult> entry : deploymentActionResults.entrySet()) {\n\n UUID actionId = entry.getKey();\n DeploymentActionResult actionResult = entry.getValue();\n\n Map<String, ServerGroupDeploymentActionResult> actionResultsByServerGroup = actionResult.getResultsByServerGroup();\n for (ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup.values()) {\n String serverGroupName = serverGroupActionResult.getServerGroupName();\n\n ServerGroupDeploymentPlanResultImpl sgdpr = (ServerGroupDeploymentPlanResultImpl) serverGroupResults.get(serverGroupName);\n if (sgdpr == null) {\n sgdpr = new ServerGroupDeploymentPlanResultImpl(serverGroupName);\n serverGroupResults.put(serverGroupName, sgdpr);\n }\n\n for (Map.Entry<String, ServerUpdateResult> serverEntry : serverGroupActionResult.getResultByServer().entrySet()) {\n String serverName = serverEntry.getKey();\n ServerUpdateResult sud = serverEntry.getValue();\n ServerDeploymentPlanResultImpl sdpr = (ServerDeploymentPlanResultImpl) sgdpr.getServerResult(serverName);\n if (sdpr == null) {\n sdpr = new ServerDeploymentPlanResultImpl(serverName);\n sgdpr.storeServerResult(serverName, sdpr);\n }\n sdpr.storeServerUpdateResult(actionId, sud);\n }\n }\n }\n return serverGroupResults;\n }",
"private static Object checkComponentType(Object array, Class<?> expectedComponentType) {\n\t\tClass<?> actualComponentType = array.getClass().getComponentType();\n\t\tif (!expectedComponentType.isAssignableFrom(actualComponentType)) {\n\t\t\tthrow new ArrayStoreException(\n\t\t\t\t\tString.format(\"The expected component type %s is not assignable from the actual type %s\",\n\t\t\t\t\t\t\texpectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));\n\t\t}\n\t\treturn array;\n\t}",
"public void bind(Object object, String name)\r\n throws ObjectNameNotUniqueException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call bind.\");\r\n }\r\n /**\r\n * Is Tx open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call bind.\");\r\n }\r\n\r\n tx.getNamedRootsMap().bind(object, name);\r\n }",
"public static boolean isDouble(CharSequence self) {\n try {\n Double.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"protected int getRequestTypeFromString(String requestType) {\n if (\"GET\".equals(requestType)) {\n return REQUEST_TYPE_GET;\n }\n if (\"POST\".equals(requestType)) {\n return REQUEST_TYPE_POST;\n }\n if (\"PUT\".equals(requestType)) {\n return REQUEST_TYPE_PUT;\n }\n if (\"DELETE\".equals(requestType)) {\n return REQUEST_TYPE_DELETE;\n }\n return REQUEST_TYPE_ALL;\n }",
"public boolean detectTierIphone() {\r\n\r\n if (detectIphoneOrIpod()\r\n || detectAndroidPhone()\r\n || detectWindowsPhone()\r\n || detectBlackBerry10Phone()\r\n || (detectBlackBerryWebKit() && detectBlackBerryTouch())\r\n || detectPalmWebOS()\r\n || detectBada()\r\n || detectTizen()\r\n || detectFirefoxOSPhone()\r\n || detectSailfishPhone()\r\n || detectUbuntuPhone()\r\n || detectGamingHandheld()) {\r\n return true;\r\n }\r\n return false;\r\n }",
"public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() {\n if (bounds == null) {\n bounds = new ReadOnlyObjectWrapper<>(getBounds());\n addStateEventHandler(MapStateEventType.idle, () -> {\n bounds.set(getBounds());\n });\n }\n return bounds.getReadOnlyProperty();\n }"
] |
Writes an activity to a PM XML file.
@param mpxj MPXJ Task instance | [
"private void writeActivity(Task mpxj)\n {\n ActivityType xml = m_factory.createActivityType();\n m_project.getActivity().add(xml);\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setAtCompletionDuration(getDuration(mpxj.getDuration()));\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getCalendar()));\n xml.setDurationPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setDurationType(DURATION_TYPE_MAP.get(mpxj.getType()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(getActivityID(mpxj));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setPercentCompleteType(\"Duration\");\n xml.setPrimaryConstraintType(CONSTRAINT_TYPE_MAP.get(mpxj.getConstraintType()));\n xml.setPrimaryConstraintDate(mpxj.getConstraintDate());\n xml.setPlannedDuration(getDuration(mpxj.getDuration()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRemainingDuration(getDuration(mpxj.getRemainingDuration()));\n xml.setRemainingEarlyFinishDate(mpxj.getEarlyFinish());\n xml.setRemainingEarlyStartDate(mpxj.getResume());\n xml.setRemainingLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setStartDate(mpxj.getStart());\n xml.setStatus(getActivityStatus(mpxj));\n xml.setType(extractAndConvertTaskType(mpxj));\n xml.setWBSObjectId(parentObjectID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.TASK, mpxj));\n\n writePredecessors(mpxj);\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 boolean mapsCell(String cell) {\n return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell));\n }",
"public static final Date parseExtendedAttributeDate(String value)\n {\n Date result = null;\n\n if (value != null)\n {\n try\n {\n result = DATE_FORMAT.get().parse(value);\n }\n\n catch (ParseException ex)\n {\n // ignore exceptions\n }\n }\n\n return (result);\n }",
"@Override\n public SuggestAccountsRequest suggestAccounts() throws RestApiException {\n return new SuggestAccountsRequest() {\n @Override\n public List<AccountInfo> get() throws RestApiException {\n return AccountsRestClient.this.suggestAccounts(this);\n }\n };\n }",
"public static base_response add(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute addresource = new lbroute();\n\t\taddresource.network = resource.network;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.gatewayname = resource.gatewayname;\n\t\treturn addresource.add_resource(client);\n\t}",
"static String expandUriComponent(String source, UriTemplateVariables uriVariables) {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (source.indexOf('{') == -1) {\n\t\t\treturn source;\n\t\t}\n\t\tMatcher matcher = NAMES_PATTERN.matcher(source);\n\t\tStringBuffer sb = new StringBuffer();\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group(1);\n\t\t\tString variableName = getVariableName(match);\n\t\t\tObject variableValue = uriVariables.getValue(variableName);\n\t\t\tif (UriTemplateVariables.SKIP_VALUE.equals(variableValue)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString variableValueString = getVariableValueAsString(variableValue);\n\t\t\tString replacement = Matcher.quoteReplacement(variableValueString);\n\t\t\tmatcher.appendReplacement(sb, replacement);\n\t\t}\n\t\tmatcher.appendTail(sb);\n\t\treturn sb.toString();\n\t}",
"public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }",
"public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }",
"private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n Task mpxjTask = mpxjParent.addTask();\n mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n mpxjTask.setName(gpTask.getName());\n mpxjTask.setPercentageComplete(gpTask.getComplete());\n mpxjTask.setPriority(getPriority(gpTask.getPriority()));\n mpxjTask.setHyperlink(gpTask.getWebLink());\n\n Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS);\n mpxjTask.setDuration(duration);\n\n if (duration.getDuration() == 0)\n {\n mpxjTask.setMilestone(true);\n }\n else\n {\n mpxjTask.setStart(gpTask.getStart());\n mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false));\n }\n\n mpxjTask.setConstraintDate(gpTask.getThirdDate());\n if (mpxjTask.getConstraintDate() != null)\n {\n // TODO: you don't appear to be able to change this setting in GanttProject\n // task.getThirdDateConstraint()\n mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN);\n }\n\n readTaskCustomFields(gpTask, mpxjTask);\n\n m_eventManager.fireTaskReadEvent(mpxjTask);\n\n // TODO: read custom values\n\n //\n // Process child tasks\n //\n for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask())\n {\n readTask(mpxjTask, childTask);\n }\n }"
] |
Use this API to clear gslbldnsentries. | [
"public static base_response clear(nitro_service client) throws Exception {\n\t\tgslbldnsentries clearresource = new gslbldnsentries();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}"
] | [
"private void handleIncomingRequestMessage(SerialMessage incomingMessage) {\n\t\tlogger.debug(\"Message type = REQUEST\");\n\t\tswitch (incomingMessage.getMessageClass()) {\n\t\t\tcase ApplicationCommandHandler:\n\t\t\t\thandleApplicationCommandRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase SendData:\n\t\t\t\thandleSendDataRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase ApplicationUpdate:\n\t\t\t\thandleApplicationUpdateRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tlogger.warn(String.format(\"TODO: Implement processing of Request Message = %s (0x%02X)\",\n\t\t\t\t\tincomingMessage.getMessageClass().getLabel(),\n\t\t\t\t\tincomingMessage.getMessageClass().getKey()));\n\t\t\tbreak;\t\n\t\t}\n\t}",
"protected void writeBody(HttpURLConnection connection, ProgressListener listener) {\n if (this.body == null) {\n return;\n }\n\n connection.setDoOutput(true);\n try {\n OutputStream output = connection.getOutputStream();\n if (listener != null) {\n output = new ProgressOutputStream(output, listener, this.bodyLength);\n }\n int b = this.body.read();\n while (b != -1) {\n output.write(b);\n b = this.body.read();\n }\n output.close();\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n }",
"private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset)\n {\n if (previousItemOffset != null)\n {\n int itemSize = itemOffset.intValue() - previousItemOffset.intValue();\n byte[] itemData = new byte[itemSize];\n System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize);\n m_map.put(previousItemKey, itemData);\n }\n }",
"@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }",
"private Path getTempDir() {\n if (this.tempDir == null) {\n if (this.dir != null) {\n this.tempDir = dir;\n } else {\n this.tempDir = getProject().getBaseDir().toPath();\n }\n }\n return tempDir;\n }",
"public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\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 }",
"private String toPath(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, \"\" + name.hashCode()) + size.getSuffix();\n }",
"public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }"
] |
Scans all Forge addons for classes accepted by given filter.
TODO: Could be refactored - scan() is almost the same. | [
"public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }"
] | [
"private void clearBeatGrids(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 deliverBeatGridUpdate(player, null); // Inform listeners the beat grid is gone.\n }\n }\n }\n }",
"public static String encodeHost(String host, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4);\n\t}",
"protected org.apache.log4j.helpers.PatternParser createPatternParser(final String pattern) {\n\t\treturn new FoundationLoggingPatternParser(pattern);\n\t}",
"public TaskMode getTaskMode()\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;\n }",
"public static String fancyStringF(double value, DecimalFormat format, int length, int significant) {\n\n String formatted = fancyString(value, format, length, significant);\n\n int n = length-formatted.length();\n if( n > 0 ) {\n StringBuilder builder = new StringBuilder(n);\n for (int i = 0; i < n; i++) {\n builder.append(' ');\n }\n return formatted + builder.toString();\n } else {\n return formatted;\n }\n }",
"@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 }",
"private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }",
"void successfulBoot() throws ConfigurationPersistenceException {\n synchronized (this) {\n if (doneBootup.get()) {\n return;\n }\n final File copySource;\n if (!interactionPolicy.isReadOnly()) {\n copySource = mainFile;\n } else {\n\n if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) {\n copySource = new File(mainFile.getParentFile(), mainFile.getName() + \".boot\");\n } else{\n copySource = new File(configurationDir, mainFile.getName() + \".boot\");\n }\n\n FilePersistenceUtils.deleteFile(copySource);\n }\n\n try {\n if (!bootFile.equals(copySource)) {\n FilePersistenceUtils.copyFile(bootFile, copySource);\n }\n\n createHistoryDirectory();\n\n final File historyBase = new File(historyRoot, mainFile.getName());\n lastFile = addSuffixToFile(historyBase, LAST);\n final File boot = addSuffixToFile(historyBase, BOOT);\n final File initial = addSuffixToFile(historyBase, INITIAL);\n\n if (!initial.exists()) {\n FilePersistenceUtils.copyFile(copySource, initial);\n }\n\n FilePersistenceUtils.copyFile(copySource, lastFile);\n FilePersistenceUtils.copyFile(copySource, boot);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile);\n } finally {\n if (interactionPolicy.isReadOnly()) {\n //Delete the temporary file\n try {\n FilePersistenceUtils.deleteFile(copySource);\n } catch (Exception ignore) {\n }\n }\n }\n doneBootup.set(true);\n }\n }",
"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 }"
] |
Invalidate the item in layout
@param dataIndex data index | [
"public void invalidate(final int dataIndex) {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate [%d]\", dataIndex);\n mMeasuredChildren.remove(dataIndex);\n }\n }"
] | [
"@Override\n public List<Assignment> assign(Collection<String> suiteNames, int slaves, long seed) {\n // Read hints first.\n final Map<String,List<Long>> hints = ExecutionTimesReport.mergeHints(resources, suiteNames);\n\n // Preprocess and sort costs. Take the median for each suite's measurements as the \n // weight to avoid extreme measurements from screwing up the average.\n final List<SuiteHint> costs = new ArrayList<>();\n for (String suiteName : suiteNames) {\n final List<Long> suiteHint = hints.get(suiteName);\n if (suiteHint != null) {\n // Take the median for each suite's measurements as the weight\n // to avoid extreme measurements from screwing up the average.\n Collections.sort(suiteHint);\n final Long median = suiteHint.get(suiteHint.size() / 2);\n costs.add(new SuiteHint(suiteName, median));\n }\n }\n Collections.sort(costs, SuiteHint.DESCENDING_BY_WEIGHT);\n\n // Apply the assignment heuristic.\n final PriorityQueue<SlaveLoad> pq = new PriorityQueue<SlaveLoad>(\n slaves, SlaveLoad.ASCENDING_BY_ESTIMATED_FINISH);\n for (int i = 0; i < slaves; i++) {\n pq.add(new SlaveLoad(i));\n }\n\n final List<Assignment> assignments = new ArrayList<>();\n for (SuiteHint hint : costs) {\n SlaveLoad slave = pq.remove();\n slave.estimatedFinish += hint.cost;\n pq.add(slave);\n\n owner.log(\"Expected execution time for \" + hint.suiteName + \": \" +\n Duration.toHumanDuration(hint.cost),\n Project.MSG_DEBUG);\n\n assignments.add(new Assignment(hint.suiteName, slave.id, (int) hint.cost));\n }\n\n // Dump estimated execution times.\n TreeMap<Integer, SlaveLoad> ordered = new TreeMap<Integer, SlaveLoad>();\n while (!pq.isEmpty()) {\n SlaveLoad slave = pq.remove();\n ordered.put(slave.id, slave);\n }\n for (Integer id : ordered.keySet()) {\n final SlaveLoad slave = ordered.get(id);\n owner.log(String.format(Locale.ROOT, \n \"Expected execution time on JVM J%d: %8.2fs\",\n slave.id,\n slave.estimatedFinish / 1000.0f), \n verbose ? Project.MSG_INFO : Project.MSG_DEBUG);\n }\n\n return assignments;\n }",
"private int cleanupSegmentsToMaintainSize(final Log log) throws IOException {\n if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0;\n\n List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() {\n\n long diff = log.size() - logRetentionSize;\n\n public boolean filter(LogSegment segment) {\n diff -= segment.size();\n return diff >= 0;\n }\n });\n return deleteSegments(log, toBeDeleted);\n }",
"public static nstimeout get(nitro_service service) throws Exception{\n\t\tnstimeout obj = new nstimeout();\n\t\tnstimeout[] response = (nstimeout[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"@Deprecated\n\tpublic static Schedule createScheduleFromConventions(\n\t\t\tLocalDate referenceDate,\n\t\t\tLocalDate startDate,\n\t\t\tString frequency,\n\t\t\tdouble maturity,\n\t\t\tString daycountConvention,\n\t\t\tString shortPeriodConvention,\n\t\t\tString dateRollConvention,\n\t\t\tBusinessdayCalendar businessdayCalendar,\n\t\t\tint\tfixingOffsetDays,\n\t\t\tint\tpaymentOffsetDays\n\t\t\t)\n\t{\n\t\tLocalDate maturityDate = createDateFromDateAndOffset(startDate, maturity);\n\n\t\treturn createScheduleFromConventions(\n\t\t\t\treferenceDate,\n\t\t\t\tstartDate,\n\t\t\t\tmaturityDate,\n\t\t\t\tFrequency.valueOf(frequency.toUpperCase()),\n\t\t\t\tDaycountConvention.getEnum(daycountConvention),\n\t\t\t\tShortPeriodConvention.valueOf(shortPeriodConvention.toUpperCase()),\n\t\t\t\tDateRollConvention.getEnum(dateRollConvention),\n\t\t\t\tbusinessdayCalendar,\n\t\t\t\tfixingOffsetDays,\n\t\t\t\tpaymentOffsetDays\n\t\t\t\t);\n\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 }",
"protected void parseOperationsL(TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.SYMBOL && token.getSymbol() == Symbol.TRANSPOSE) {\n if( token.previous.getType() == Type.VARIABLE )\n token = insertTranspose(token.previous,tokens,sequence);\n else\n throw new ParseError(\"Expected variable before transpose\");\n }\n token = token.next;\n }\n }",
"DeleteResult deleteMany(final MongoNamespace namespace,\n final Bson filter) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();\n final DeleteResult result;\n final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n try {\n final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);\n final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);\n final Set<BsonValue> idsToDelete =\n localCollection\n .find(filter)\n .map(new Function<BsonDocument, BsonValue>() {\n @Override\n @NonNull\n public BsonValue apply(@NonNull final BsonDocument bsonDocument) {\n undoCollection.insertOne(bsonDocument);\n return BsonUtils.getDocumentId(bsonDocument);\n }\n }).into(new HashSet<>());\n\n result = localCollection.deleteMany(filter);\n\n for (final BsonValue documentId : idsToDelete) {\n final CoreDocumentSynchronizationConfig config =\n syncConfig.getSynchronizedDocument(namespace, documentId);\n\n if (config == null) {\n continue;\n }\n\n final ChangeEvent<BsonDocument> event =\n ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);\n\n // this block is to trigger coalescence for a delete after insert\n if (config.getLastUncommittedChangeEvent() != null\n && config.getLastUncommittedChangeEvent().getOperationType()\n == OperationType.INSERT) {\n desyncDocumentsFromRemote(nsConfig, config.getDocumentId())\n .commitAndClear();\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n continue;\n }\n\n config.setSomePendingWritesAndSave(logicalT, event);\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n eventsToEmit.add(event);\n }\n checkAndDeleteNamespaceListener(namespace);\n } finally {\n lock.unlock();\n }\n for (final ChangeEvent<BsonDocument> event : eventsToEmit) {\n eventDispatcher.emitEvent(nsConfig, event);\n }\n return result;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }",
"public void clearSelections() {\n for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {\n vh.checkbox.setChecked(false);\n }\n mCheckedVisibleViewHolders.clear();\n mCheckedItems.clear();\n }"
] |
Embeds the given SVG element into a new SVG element scaling the graphic to the given dimension and
applying the given rotation. | [
"private static void embedSvgGraphic(\n final SVGElement svgRoot,\n final SVGElement newSvgRoot, final Document newDocument,\n final Dimension targetSize, final Double rotation) {\n final String originalWidth = svgRoot.getAttributeNS(null, \"width\");\n final String originalHeight = svgRoot.getAttributeNS(null, \"height\");\n /*\n * To scale the SVG graphic and to apply the rotation, we distinguish two\n * cases: width and height is set on the original SVG or not.\n *\n * Case 1: Width and height is set\n * If width and height is set, we wrap the original SVG into 2 new SVG elements\n * and a container element.\n *\n * Example:\n * Original SVG:\n * <svg width=\"100\" height=\"100\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg width=\"100%\" height=\"100%\" viewBox=\"0 0 100 100\">\n * <svg width=\"100\" height=\"100\"></svg>\n * </svg>\n * </g>\n * </svg>\n *\n * The requested size is set on the outermost <svg>. Then, the rotation is applied to the\n * <g> container and the scaling is achieved with the viewBox parameter on the 2nd <svg>.\n *\n *\n * Case 2: Width and height is not set\n * In this case the original SVG is wrapped into just one container and one new SVG element.\n * The rotation is set on the container, and the scaling happens automatically.\n *\n * Example:\n * Original SVG:\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n *\n * New SVG (scaled to 300x300 and rotated by 90 degree):\n * <svg width=\"300\" height=\"300\">\n * <g transform=\"rotate(90.0 150 150)\">\n * <svg viewBox=\"0 0 61.06 91.83\"></svg>\n * </g>\n * </svg>\n */\n if (!StringUtils.isEmpty(originalWidth) && !StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Element wrapperSvg = newDocument.createElementNS(SVG_NS, \"svg\");\n wrapperSvg.setAttributeNS(null, \"width\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"height\", \"100%\");\n wrapperSvg.setAttributeNS(null, \"viewBox\", \"0 0 \" + originalWidth\n + \" \" + originalHeight);\n wrapperContainer.appendChild(wrapperSvg);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperSvg.appendChild(svgRootImported);\n } else if (StringUtils.isEmpty(originalWidth) && StringUtils.isEmpty(originalHeight)) {\n Element wrapperContainer = newDocument.createElementNS(SVG_NS, \"g\");\n wrapperContainer.setAttributeNS(\n null,\n SVGConstants.SVG_TRANSFORM_ATTRIBUTE,\n getRotateTransformation(targetSize, rotation));\n newSvgRoot.appendChild(wrapperContainer);\n\n Node svgRootImported = newDocument.importNode(svgRoot, true);\n wrapperContainer.appendChild(svgRootImported);\n } else {\n throw new IllegalArgumentException(\n \"Unsupported or invalid north-arrow SVG graphic: The same unit (px, em, %, ...) must be\" +\n \" \" +\n \"used for `width` and `height`.\");\n }\n }"
] | [
"private static EndpointReferenceType createEPR(String address, SLProperties props) {\n EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address);\n if (props != null) {\n addProperties(epr, props);\n }\n return epr;\n }",
"public static void addActionsTo(\n SourceBuilder code,\n Set<MergeAction> mergeActions,\n boolean forBuilder) {\n SetMultimap<String, String> nounsByVerb = TreeMultimap.create();\n mergeActions.forEach(mergeAction -> {\n if (forBuilder || !mergeAction.builderOnly) {\n nounsByVerb.put(mergeAction.verb, mergeAction.noun);\n }\n });\n List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet());\n String lastVerb = getLast(verbs, null);\n for (String verb : nounsByVerb.keySet()) {\n code.add(\", %s%s\", (verbs.size() > 1 && verb.equals(lastVerb)) ? \"and \" : \"\", verb);\n List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb));\n for (int i = 0; i < nouns.size(); ++i) {\n String separator = (i == 0) ? \"\" : (i == nouns.size() - 1) ? \" and\" : \",\";\n code.add(\"%s %s\", separator, nouns.get(i));\n }\n }\n }",
"private static void registerCommonClasses(Class<?>... commonClasses) {\n\t\tfor (Class<?> clazz : commonClasses) {\n\t\t\tcommonClassCache.put(clazz.getName(), clazz);\n\t\t}\n\t}",
"public final String getPath(final String key) {\n StringBuilder result = new StringBuilder();\n addPathTo(result);\n result.append(\".\");\n result.append(getPathElement(key));\n return result.toString();\n }",
"void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }",
"private void attachLocaleGroups(CmsResource copiedPage) throws CmsException {\n\n CmsLocaleGroupService localeGroupService = getRootCms().getLocaleGroupService();\n if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) {\n try {\n localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n }",
"public 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 }",
"public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }"
] |
Wrap an operation's parameters in a simple encapsulating object
@param operation the operation
@param messageHandler the message handler
@param attachments the attachments
@return the encapsulating object | [
"public static TransactionalProtocolClient.Operation wrap(final ModelNode operation, final OperationMessageHandler messageHandler, final OperationAttachments attachments) {\n return new TransactionalOperationImpl(operation, messageHandler, attachments);\n }"
] | [
"protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\n }",
"public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {\n if (artifactsProps == null) {\n artifactsProps = ArrayListMultimap.create();\n }\n artifactsProps.put(\"build.name\", buildName);\n artifactsProps.put(\"build.number\", buildNumber);\n artifactsProps.put(\"build.timestamp\", timestamp);\n String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);\n\n Properties buildInfoItemsProps = new Properties();\n buildInfoItemsProps.setProperty(\"build.name\", buildName);\n buildInfoItemsProps.setProperty(\"build.number\", buildNumber);\n buildInfoItemsProps.setProperty(\"build.timestamp\", timestamp);\n\n ArtifactoryServer server = config.getArtifactoryServer();\n CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();\n ArtifactoryDependenciesClient dependenciesClient = null;\n ArtifactoryBuildInfoClient propertyChangeClient = null;\n\n try {\n dependenciesClient = server.createArtifactoryDependenciesClient(\n preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);\n\n CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);\n propertyChangeClient = server.createArtifactoryClient(\n preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy));\n\n Module buildInfoModule = new Module();\n buildInfoModule.setId(imageTag.substring(imageTag.indexOf(\"/\") + 1));\n\n // If manifest and imagePath not found, return.\n if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {\n return buildInfoModule;\n }\n\n listener.getLogger().println(\"Fetching details of published docker layers from Artifactory...\");\n boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);\n DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);\n\n listener.getLogger().println(\"Tagging published docker layers with build properties in Artifactory...\");\n setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,\n dependenciesClient, propertyChangeClient, server);\n setBuildInfoModuleProps(buildInfoModule);\n return buildInfoModule;\n } finally {\n if (dependenciesClient != null) {\n dependenciesClient.close();\n }\n if (propertyChangeClient != null) {\n propertyChangeClient.close();\n }\n }\n }",
"public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }",
"public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) {\n this.content = content;\n this.rootView = inflate(layoutInflater, parent);\n if (rootView == null) {\n throw new NotInflateViewException(\n \"Renderer instances have to return a not null view in inflateView method\");\n }\n this.rootView.setTag(this);\n setUpView(rootView);\n hookListeners(rootView);\n }",
"public DateTimeZone getZone(String id) {\n if (id == null) {\n return null;\n }\n\n Object obj = iZoneInfoMap.get(id);\n if (obj == null) {\n return null;\n }\n\n if (id.equals(obj)) {\n // Load zone data for the first time.\n return loadZoneData(id);\n }\n\n if (obj instanceof SoftReference<?>) {\n @SuppressWarnings(\"unchecked\")\n SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;\n DateTimeZone tz = ref.get();\n if (tz != null) {\n return tz;\n }\n // Reference cleared; load data again.\n return loadZoneData(id);\n }\n\n // If this point is reached, mapping must link to another.\n return getZone((String) obj);\n }",
"public static base_response clear(nitro_service client) throws Exception {\n\t\tnssimpleacl clearresource = new nssimpleacl();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }",
"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 }",
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}"
] |
If the String argument defaultLocatorSelectionStrategy is as key in the map representing the locatorSelectionStrategies, the
corresponding strategy is selected and set as default strategy, else both the selected strategy and the default strategy remain
unchanged.
@param defaultLocatorSelectionStrategy | [
"@Value(\"${locator.strategy}\")\n public void setDefaultLocatorSelectionStrategy(String defaultLocatorSelectionStrategy) {\n this.defaultLocatorSelectionStrategy = defaultLocatorSelectionStrategy;\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Default strategy \" + defaultLocatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n }"
] | [
"public static void openLogFile() throws IOException\n {\n if (LOG_FILE != null)\n {\n System.out.println(\"SynchroLogger Configured\");\n LOG = new PrintWriter(new FileWriter(LOG_FILE));\n }\n }",
"public String getSafetyLevel() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SAFETY_LEVEL);\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 personElement = response.getPayload();\r\n return personElement.getAttribute(\"safety_level\");\r\n }",
"public static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }",
"public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }",
"protected long preConnection() throws SQLException{\r\n\t\tlong statsObtainTime = 0;\r\n\t\t\r\n\t\tif (this.pool.poolShuttingDown){\r\n\t\t\tthrow new SQLException(this.pool.shutdownStackTrace);\r\n\t\t}\r\n\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tstatsObtainTime = System.nanoTime();\r\n\t\t\tthis.pool.statistics.incrementConnectionsRequested();\r\n\t\t}\r\n\t\t\r\n\t\treturn statsObtainTime;\r\n\t}",
"private void readBlock(int blockIndex, int startIndex, int blockLength) throws Exception\n {\n logBlock(blockIndex, startIndex, blockLength);\n\n if (blockLength < 128)\n {\n readTableBlock(startIndex, blockLength);\n }\n else\n {\n readColumnBlock(startIndex, blockLength);\n }\n }",
"public void setDefaultCalendarName(String calendarName)\n {\n if (calendarName == null || calendarName.length() == 0)\n {\n calendarName = DEFAULT_CALENDAR_NAME;\n }\n\n set(ProjectField.DEFAULT_CALENDAR_NAME, calendarName);\n }",
"public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\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 }"
] |
Calculate power of a complex number.
@param z1 Complex Number.
@param n Power.
@return Returns a new complex number containing the power of a specified number. | [
"public static ComplexNumber Pow(ComplexNumber z1, double n) {\r\n\r\n double norm = Math.pow(z1.getMagnitude(), n);\r\n double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real)));\r\n\r\n double common = n * angle;\r\n\r\n double r = norm * Math.cos(Math.toRadians(common));\r\n double i = norm * Math.sin(Math.toRadians(common));\r\n\r\n return new ComplexNumber(r, i);\r\n\r\n }"
] | [
"public NRShape makeShape(Date from, Date to) {\n UnitNRShape fromShape = tree.toUnitShape(from);\n UnitNRShape toShape = tree.toUnitShape(to);\n return tree.toRangeShape(fromShape, toShape);\n }",
"public boolean ignoreOperation(final Resource domainResource, final Collection<ServerConfigInfo> serverConfigs, final PathAddress pathAddress) {\n if (pathAddress.size() == 0) {\n return false;\n }\n boolean ignore = ignoreResourceInternal(domainResource, serverConfigs, pathAddress);\n return ignore;\n }",
"public final void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n m_weekDays.clear();\n if (null != weekDays) {\n m_weekDays.addAll(weekDays);\n }\n }",
"protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }",
"private static void listResourceNotes(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n String notes = resource.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + resource.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }",
"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 static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\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 }",
"public List<PathAddressTransformer> getPathTransformations(final PathAddress address, PlaceholderResolver placeholderResolver) {\n final List<PathAddressTransformer> list = new ArrayList<PathAddressTransformer>();\n final Iterator<PathElement> iterator = address.iterator();\n resolvePathTransformers(iterator, list, placeholderResolver);\n if(iterator.hasNext()) {\n while(iterator.hasNext()) {\n iterator.next();\n list.add(PathAddressTransformer.DEFAULT);\n }\n }\n return list;\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.