query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Set the DPI value for GeoServer if there are already FORMAT_OPTIONS.
[ "private static void setDpiValue(final Multimap<String, String> extraParams, final int dpi) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n Collection<String> values = extraParams.removeAll(key);\n List<String> newValues = new ArrayList<>();\n for (String value: values) {\n if (!StringUtils.isEmpty(value)) {\n value += \";dpi:\" + Integer.toString(dpi);\n newValues.add(value);\n }\n }\n extraParams.putAll(key, newValues);\n return;\n }\n }\n }" ]
[ "public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }", "public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public List<Ticket> checkTickets(Set<String> tickets) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CHECK_TICKETS);\r\n\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = tickets.iterator();\r\n while (it.hasNext()) {\r\n if (sb.length() > 0) {\r\n sb.append(\",\");\r\n }\r\n Object obj = it.next();\r\n if (obj instanceof Ticket) {\r\n sb.append(((Ticket) obj).getTicketId());\r\n } else {\r\n sb.append(obj);\r\n }\r\n }\r\n parameters.put(\"tickets\", sb.toString());\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n // <uploader>\r\n // <ticket id=\"128\" complete=\"1\" photoid=\"2995\" />\r\n // <ticket id=\"129\" complete=\"0\" />\r\n // <ticket id=\"130\" complete=\"2\" />\r\n // <ticket id=\"131\" invalid=\"1\" />\r\n // </uploader>\r\n\r\n List<Ticket> list = new ArrayList<Ticket>();\r\n Element uploaderElement = response.getPayload();\r\n NodeList ticketNodes = uploaderElement.getElementsByTagName(\"ticket\");\r\n int n = ticketNodes.getLength();\r\n for (int i = 0; i < n; i++) {\r\n Element ticketElement = (Element) ticketNodes.item(i);\r\n String id = ticketElement.getAttribute(\"id\");\r\n String complete = ticketElement.getAttribute(\"complete\");\r\n boolean invalid = \"1\".equals(ticketElement.getAttribute(\"invalid\"));\r\n String photoId = ticketElement.getAttribute(\"photoid\");\r\n Ticket info = new Ticket();\r\n info.setTicketId(id);\r\n info.setInvalid(invalid);\r\n info.setStatus(Integer.parseInt(complete));\r\n info.setPhotoId(photoId);\r\n list.add(info);\r\n }\r\n return list;\r\n }", "private boolean isDebug(CmsObject cms, CmsSolrQuery query) {\r\n\r\n String[] debugSecretValues = query.remove(REQUEST_PARAM_DEBUG_SECRET);\r\n String debugSecret = (debugSecretValues == null) || (debugSecretValues.length < 1)\r\n ? null\r\n : debugSecretValues[0];\r\n if ((null != debugSecret) && !debugSecret.trim().isEmpty() && (null != m_handlerDebugSecretFile)) {\r\n try {\r\n CmsFile secretFile = cms.readFile(m_handlerDebugSecretFile);\r\n String secret = new String(secretFile.getContents(), CmsFileUtil.getEncoding(cms, secretFile));\r\n return secret.trim().equals(debugSecret.trim());\r\n } catch (Exception e) {\r\n LOG.info(\r\n \"Failed to read secret file for index \\\"\"\r\n + getName()\r\n + \"\\\" at path \\\"\"\r\n + m_handlerDebugSecretFile\r\n + \"\\\".\");\r\n }\r\n }\r\n return false;\r\n }", "@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "public void print() {\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n log.info(key + \" = \" + getRawString(key));\n }\n }", "public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}", "private void readVersion(InputStream is) throws IOException\n {\n BytesReadInputStream bytesReadStream = new BytesReadInputStream(is);\n String version = DatatypeConverter.getString(bytesReadStream);\n m_offset += bytesReadStream.getBytesRead();\n SynchroLogger.log(\"VERSION\", version);\n \n String[] versionArray = version.split(\"\\\\.\");\n m_majorVersion = Integer.parseInt(versionArray[0]);\n }", "public static base_responses add(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 addresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbservice();\n\t\t\t\taddresources[i].servicename = resources[i].servicename;\n\t\t\t\taddresources[i].cnameentry = resources[i].cnameentry;\n\t\t\t\taddresources[i].ip = resources[i].ip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].servicetype = resources[i].servicetype;\n\t\t\t\taddresources[i].port = resources[i].port;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].publicport = resources[i].publicport;\n\t\t\t\taddresources[i].maxclient = resources[i].maxclient;\n\t\t\t\taddresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].cip = resources[i].cip;\n\t\t\t\taddresources[i].cipheader = resources[i].cipheader;\n\t\t\t\taddresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\taddresources[i].cookietimeout = resources[i].cookietimeout;\n\t\t\t\taddresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\taddresources[i].clttimeout = resources[i].clttimeout;\n\t\t\t\taddresources[i].svrtimeout = resources[i].svrtimeout;\n\t\t\t\taddresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\taddresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\taddresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\taddresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\taddresources[i].hashid = resources[i].hashid;\n\t\t\t\taddresources[i].comment = resources[i].comment;\n\t\t\t\taddresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Record operation for async ops time @param dest Destination of the socket to connect to. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param opTimeUs The number of us for the op to finish
[ "public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs);\n recordAsyncOpTimeNs(null, opTimeNs);\n } else {\n this.asynOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }" ]
[ "@JsonProperty\n public String timestamp() {\n if (timestampAsText == null) {\n timestampAsText = DateTimeFormatter.ISO_INSTANT.format(timestamp);\n }\n return timestampAsText;\n }", "public void add(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n pi.add(photoId, userId, bounds);\r\n }", "private void postProcessTasks()\n {\n List<Task> allTasks = m_file.getTasks();\n if (allTasks.size() > 1)\n {\n Collections.sort(allTasks);\n\n int taskID = -1;\n int lastTaskID = -1;\n\n for (int i = 0; i < allTasks.size(); i++)\n {\n Task task = allTasks.get(i);\n taskID = NumberHelper.getInt(task.getID());\n // In Project the tasks IDs are always contiguous so we can spot invalid tasks by making sure all\n // IDs are represented.\n if (!task.getNull() && lastTaskID != -1 && taskID > lastTaskID + 1)\n {\n // This task looks to be invalid.\n task.setNull(true);\n }\n else\n {\n lastTaskID = taskID;\n }\n }\n }\n }", "@Api\n\tpublic void restoreSecurityContext(SavedAuthorization savedAuthorization) {\n\t\tList<Authentication> auths = new ArrayList<Authentication>();\n\t\tif (null != savedAuthorization) {\n\t\t\tfor (SavedAuthentication sa : savedAuthorization.getAuthentications()) {\n\t\t\t\tAuthentication auth = new Authentication();\n\t\t\t\tauth.setSecurityServiceId(sa.getSecurityServiceId());\n\t\t\t\tauth.setAuthorizations(sa.getAuthorizations());\n\t\t\t\tauths.add(auth);\n\t\t\t}\n\t\t}\n\t\tsetAuthentications(null, auths);\n\t\tuserInfoInit();\n\t}", "public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private ProctorContext getProctorContext(final HttpServletRequest request) throws IllegalAccessException, InstantiationException {\n final ProctorContext proctorContext = contextClass.newInstance();\n final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext);\n for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) {\n final String propertyName = descriptor.getName();\n if (!\"class\".equals(propertyName)) { // ignore class property which every object has\n final String parameterValue = request.getParameter(propertyName);\n if (parameterValue != null) {\n beanWrapper.setPropertyValue(propertyName, parameterValue);\n }\n }\n }\n return proctorContext;\n }", "public static boolean invertSPD(DMatrixRMaj mat, DMatrixRMaj result ) {\n if( mat.numRows != mat.numCols )\n throw new IllegalArgumentException(\"Must be a square matrix\");\n result.reshape(mat.numRows,mat.numRows);\n\n if( mat.numRows <= UnrolledCholesky_DDRM.MAX ) {\n // L*L' = A\n if( !UnrolledCholesky_DDRM.lower(mat,result) )\n return false;\n // L = inv(L)\n TriangularSolver_DDRM.invertLower(result.data,result.numCols);\n // inv(A) = inv(L')*inv(L)\n SpecializedOps_DDRM.multLowerTranA(result);\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.chol(mat.numCols);\n if( solver.modifiesA() )\n mat = mat.copy();\n\n if( !solver.setA(mat))\n return false;\n solver.invert(result);\n }\n\n return true;\n }", "public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }", "public Location getInfo(String placeId, String woeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\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 locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }" ]
Convert a floating point date to a LocalDateTime. Note: This method currently performs a rounding to the next second. If referenceDate is null, the method returns null. @param referenceDate The reference date associated with \( t=0 \). @param floatingPointDate The value to the time offset \( t \). @return The date resulting from adding Math.round(fixingTime*SECONDS_PER_DAY) seconds to referenceDate, where one day has SECONDS_PER_DAY seconds and SECONDS_PER_DAY is a constant 365*24*60*60
[ "public static LocalDateTime getDateFromFloatingPointDate(LocalDateTime referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tDuration duration = Duration.ofSeconds(Math.round(floatingPointDate * SECONDS_PER_DAY));\n\t\treturn referenceDate.plus(duration);\n\t}" ]
[ "public static Iterable<BoxRetentionPolicy.Info> getAll(final BoxAPIConnection api, String ... fields) {\r\n return getAll(null, null, null, DEFAULT_LIMIT, api, fields);\r\n }", "public void setPickingEnabled(boolean enabled) {\n if (enabled != getPickingEnabled()) {\n if (enabled) {\n attachComponent(new GVRSphereCollider(getGVRContext()));\n } else {\n detachComponent(GVRCollider.getComponentType());\n }\n }\n }", "public void setBooleanAttribute(String name, Boolean value) {\n\t\tensureValue();\n\t\tAttribute attribute = new BooleanAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}", "public static protocoludp_stats get(nitro_service service) throws Exception{\n\t\tprotocoludp_stats obj = new protocoludp_stats();\n\t\tprotocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\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 }", "public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }", "public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "public void removeMarker(Marker marker) {\n if (markers != null && markers.contains(marker)) {\n markers.remove(marker);\n }\n marker.setMap(null);\n }" ]
Creates the automata. @param prefix the prefix @param regexp the regexp @param automatonMap the automaton map @return the list @throws IOException Signals that an I/O exception has occurred.
[ "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 Document removeDocument(String key) throws PrintingException {\n\t\tif (documentMap.containsKey(key)) {\n\t\t\treturn documentMap.remove(key);\n\t\t} else {\n\t\t\tthrow new PrintingException(PrintingException.DOCUMENT_NOT_FOUND, key);\n\t\t}\n\t}", "public void reset() {\n\t\tCrawlSession session = context.getSession();\n\t\tif (crawlpath != null) {\n\t\t\tsession.addCrawlPath(crawlpath);\n\t\t}\n\t\tList<StateVertex> onURLSetTemp = new ArrayList<>();\n\t\tif (stateMachine != null)\n\t\t\tonURLSetTemp = stateMachine.getOnURLSet();\n\t\tstateMachine = new StateMachine(graphProvider.get(), crawlRules.getInvariants(), plugins,\n\t\t\t\tstateComparator, onURLSetTemp);\n\t\tcontext.setStateMachine(stateMachine);\n\t\tcrawlpath = new CrawlPath();\n\t\tcontext.setCrawlPath(crawlpath);\n\t\tbrowser.handlePopups();\n\t\tbrowser.goToUrl(url);\n\t\t// Checks the landing page for URL and sets the current page accordingly\n\t\tcheckOnURLState();\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tcrawlDepth.set(0);\n\t}", "private void getDailyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n while (moreDates(calendar, dates))\n {\n dates.add(calendar.getTime());\n calendar.add(Calendar.DAY_OF_YEAR, frequency);\n }\n }", "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 static cacheselector[] get(nitro_service service, String selectorname[]) throws Exception{\n\t\tif (selectorname !=null && selectorname.length>0) {\n\t\t\tcacheselector response[] = new cacheselector[selectorname.length];\n\t\t\tcacheselector obj[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++) {\n\t\t\t\tobj[i] = new cacheselector();\n\t\t\t\tobj[i].set_selectorname(selectorname[i]);\n\t\t\t\tresponse[i] = (cacheselector) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }", "public boolean hasUser(String userId) {\r\n String normalized = normalizerUserName(userId);\r\n return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized);\r\n }", "public List<Object> getAll(int dataSet) throws SerializationException {\r\n\t\tList<Object> result = new ArrayList<Object>();\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult.add(getData(ds));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }" ]
Get a timer of the given string name and todos for the current thread. If no such timer exists yet, then it will be newly created. @param timerName the name of the timer @param todoFlags @return timer
[ "public static Timer getNamedTimer(String timerName, int todoFlags) {\n\t\treturn getNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}" ]
[ "public Weld addExtension(Extension extension) {\n extensions.add(new MetadataImpl<Extension>(extension, SYNTHETIC_LOCATION_PREFIX + extension.getClass().getName()));\n return this;\n }", "private void addResources(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n final Resource r = resource;\n MpxjTreeNode childNode = new MpxjTreeNode(resource)\n {\n @Override public String toString()\n {\n return r.getName();\n }\n };\n parentNode.add(childNode);\n }\n }", "public void download(OutputStream output, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n long totalRead = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n totalRead += n;\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n totalRead += n;\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n\n response.disconnect();\n }", "public void addOrder(String columnName, boolean ascending) {\n if (columnName == null) {\n return;\n }\n for (int i = 0; i < columns.size(); i++) {\n if (!columnName.equals(columns.get(i).getData())) {\n continue;\n }\n order.add(new Order(i, ascending ? \"asc\" : \"desc\"));\n }\n }", "public void update(short number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_SHORT];\n ByteUtils.writeShort(numberInBytes, number, 0);\n update(numberInBytes);\n }", "public void setFinalTransformMatrix(Matrix4f finalTransform)\n {\n float[] mat = new float[16];\n finalTransform.get(mat);\n NativeBone.setFinalTransformMatrix(getNative(), mat);\n }", "public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {\n ModelNode readOps = null;\n try {\n readOps = cliGuiCtx.getExecutor().doCommand(\"/subsystem=logging:read-children-types\");\n } catch (CommandFormatException | IOException e) {\n return false;\n }\n if (!readOps.get(\"result\").isDefined()) return false;\n for (ModelNode op: readOps.get(\"result\").asList()) {\n if (\"log-file\".equals(op.asString())) return true;\n }\n return false;\n }", "public List<ServerGroup> getServerGroups() {\n ArrayList<ServerGroup> groups = new ArrayList<ServerGroup>();\n try {\n JSONObject response = new JSONObject(doGet(BASE_SERVERGROUP, null));\n JSONArray serverArray = response.getJSONArray(\"servergroups\");\n\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServerGroup = serverArray.getJSONObject(i);\n ServerGroup group = getServerGroupFromJSON(jsonServerGroup);\n groups.add(group);\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return groups;\n }", "public final File getJasperCompilation(final Configuration configuration) {\n File jasperCompilation = new File(getWorking(configuration), \"jasper-bin\");\n createIfMissing(jasperCompilation, \"Jasper Compilation\");\n return jasperCompilation;\n }" ]
Attachments are only structurally different if one step has an inline attachment and the other step either has no inline attachment or the inline attachment is different.
[ "boolean attachmentsAreStructurallyDifferent( List<AttachmentModel> firstAttachments, List<AttachmentModel> otherAttachments ) {\n if( firstAttachments.size() != otherAttachments.size() ) {\n return true;\n }\n\n for( int i = 0; i < firstAttachments.size(); i++ ) {\n if( attachmentIsStructurallyDifferent( firstAttachments.get( i ), otherAttachments.get( i ) ) ) {\n return true;\n }\n }\n return false;\n }" ]
[ "private boolean checkConfig(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n return \"true\".equalsIgnoreCase((String)config.getProperties().get(\"collector.lifecycleEvent\"));\n }", "private void writeCurrency()\n {\n ProjectProperties props = m_projectFile.getProjectProperties();\n CurrencyType currency = m_factory.createCurrencyType();\n m_apibo.getCurrency().add(currency);\n\n String positiveSymbol = getCurrencyFormat(props.getSymbolPosition());\n String negativeSymbol = \"(\" + positiveSymbol + \")\";\n\n currency.setDecimalPlaces(props.getCurrencyDigits());\n currency.setDecimalSymbol(getSymbolName(props.getDecimalSeparator()));\n currency.setDigitGroupingSymbol(getSymbolName(props.getThousandsSeparator()));\n currency.setExchangeRate(Double.valueOf(1.0));\n currency.setId(\"CUR\");\n currency.setName(\"Default Currency\");\n currency.setNegativeSymbol(negativeSymbol);\n currency.setObjectId(DEFAULT_CURRENCY_ID);\n currency.setPositiveSymbol(positiveSymbol);\n currency.setSymbol(props.getCurrencySymbol());\n }", "private void reorder()\r\n {\r\n if(getTransaction().isOrdering() && needsCommit && mhtObjectEnvelopes.size() > 1)\r\n {\r\n ObjectEnvelopeOrdering ordering = new ObjectEnvelopeOrdering(mvOrderOfIds, mhtObjectEnvelopes);\r\n ordering.reorder();\r\n Identity[] newOrder = ordering.getOrdering();\r\n\r\n mvOrderOfIds.clear();\r\n for(int i = 0; i < newOrder.length; i++)\r\n {\r\n mvOrderOfIds.add(newOrder[i]);\r\n }\r\n }\r\n }", "public static Diagram parseJson(String json,\n Boolean keepGlossaryLink) throws JSONException {\n JSONObject modelJSON = new JSONObject(json);\n return parseJson(modelJSON,\n keepGlossaryLink);\n }", "public AsciiTable setPaddingLeft(int paddingLeft) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeft(paddingLeft);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private void processActivity(Activity activity)\n {\n Task task = getParentTask(activity).addTask();\n task.setText(1, activity.getId());\n\n task.setActualDuration(activity.getActualDuration());\n task.setActualFinish(activity.getActualFinish());\n task.setActualStart(activity.getActualStart());\n //activity.getBaseunit()\n //activity.getBilled()\n //activity.getCalendar()\n //activity.getCostAccount()\n task.setCreateDate(activity.getCreationTime());\n task.setFinish(activity.getCurrentFinish());\n task.setStart(activity.getCurrentStart());\n task.setName(activity.getDescription());\n task.setDuration(activity.getDurationAtCompletion());\n task.setEarlyFinish(activity.getEarlyFinish());\n task.setEarlyStart(activity.getEarlyStart());\n task.setFreeSlack(activity.getFreeFloat());\n task.setLateFinish(activity.getLateFinish());\n task.setLateStart(activity.getLateStart());\n task.setNotes(activity.getNotes());\n task.setBaselineDuration(activity.getOriginalDuration());\n //activity.getPathFloat()\n task.setPhysicalPercentComplete(activity.getPhysicalPercentComplete());\n task.setRemainingDuration(activity.getRemainingDuration());\n task.setCost(activity.getTotalCost());\n task.setTotalSlack(activity.getTotalFloat());\n task.setMilestone(activityIsMilestone(activity));\n //activity.getUserDefined()\n task.setGUID(activity.getUuid());\n\n if (task.getMilestone())\n {\n if (activityIsStartMilestone(activity))\n {\n task.setFinish(task.getStart());\n }\n else\n {\n task.setStart(task.getFinish());\n }\n }\n\n if (task.getActualStart() == null)\n {\n task.setPercentageComplete(Integer.valueOf(0));\n }\n else\n {\n if (task.getActualFinish() != null)\n {\n task.setPercentageComplete(Integer.valueOf(100));\n }\n else\n {\n Duration remaining = activity.getRemainingDuration();\n Duration total = activity.getDurationAtCompletion();\n if (remaining != null && total != null && total.getDuration() != 0)\n {\n double percentComplete = ((total.getDuration() - remaining.getDuration()) * 100.0) / total.getDuration();\n task.setPercentageComplete(Double.valueOf(percentComplete));\n }\n }\n }\n\n m_activityMap.put(activity.getId(), task);\n }", "public static ModelNode getFailureDescription(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n throw ControllerClientLogger.ROOT_LOGGER.noFailureDescription();\n }\n if (result.hasDefined(FAILURE_DESCRIPTION)) {\n return result.get(FAILURE_DESCRIPTION);\n }\n return new ModelNode();\n }", "public static String transformXPath(String originalXPath)\n {\n // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the \"|\" operator)\n List<StringBuilder> compiledXPaths = new ArrayList<>(1);\n\n int frameIdx = -1;\n boolean inQuote = false;\n int conditionLevel = 0;\n char startQuoteChar = 0;\n StringBuilder currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n for (int i = 0; i < originalXPath.length(); i++)\n {\n char curChar = originalXPath.charAt(i);\n if (!inQuote && curChar == '[')\n {\n frameIdx++;\n conditionLevel++;\n currentXPath.append(\"[windup:startFrame(\").append(frameIdx).append(\") and windup:evaluate(\").append(frameIdx).append(\", \");\n }\n else if (!inQuote && curChar == ']')\n {\n conditionLevel--;\n currentXPath.append(\")]\");\n }\n else if (!inQuote && conditionLevel == 0 && curChar == '|')\n {\n // joining multiple xqueries\n currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n }\n else\n {\n if (inQuote && curChar == startQuoteChar)\n {\n inQuote = false;\n startQuoteChar = 0;\n }\n else if (curChar == '\"' || curChar == '\\'')\n {\n inQuote = true;\n startQuoteChar = curChar;\n }\n\n if (!inQuote && originalXPath.startsWith(WINDUP_MATCHES_FUNCTION_PREFIX, i))\n {\n i += (WINDUP_MATCHES_FUNCTION_PREFIX.length() - 1);\n currentXPath.append(\"windup:matches(\").append(frameIdx).append(\", \");\n }\n else\n {\n currentXPath.append(curChar);\n }\n }\n }\n\n Pattern leadingAndTrailingWhitespace = Pattern.compile(\"(\\\\s*)(.*?)(\\\\s*)\");\n StringBuilder finalResult = new StringBuilder();\n for (StringBuilder compiledXPath : compiledXPaths)\n {\n if (StringUtils.isNotBlank(compiledXPath))\n {\n Matcher whitespaceMatcher = leadingAndTrailingWhitespace.matcher(compiledXPath);\n if (!whitespaceMatcher.matches())\n continue;\n\n compiledXPath = new StringBuilder();\n compiledXPath.append(whitespaceMatcher.group(1));\n compiledXPath.append(whitespaceMatcher.group(2));\n compiledXPath.append(\"/self::node()[windup:persist(\").append(frameIdx).append(\", \").append(\".)]\");\n compiledXPath.append(whitespaceMatcher.group(3));\n\n if (StringUtils.isNotBlank(finalResult))\n finalResult.append(\"|\");\n finalResult.append(compiledXPath);\n }\n }\n return finalResult.toString();\n }", "private String getNotes(Row row)\n {\n String notes = row.getString(\"NOTET\");\n if (notes != null)\n {\n if (notes.isEmpty())\n {\n notes = null;\n }\n else\n {\n if (notes.indexOf(LINE_BREAK) != -1)\n {\n notes = notes.replace(LINE_BREAK, \"\\n\");\n }\n }\n }\n return notes;\n }" ]
Propagate onNoPick events to listeners @param picker GVRPicker which generated the event
[ "protected void propagateOnNoPick(GVRPicker picker)\n {\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, IPickEvents.class, \"onNoPick\", picker);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, IPickEvents.class, \"onNoPick\", picker);\n }\n }\n }" ]
[ "public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }", "public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>\n getDonorsAndStealersForBalance(final Cluster nextCandidateCluster,\n Map<Integer, List<Integer>> numPartitionsPerNodePerZone) {\n HashMap<Node, Integer> donorNodes = Maps.newHashMap();\n HashMap<Node, Integer> stealerNodes = Maps.newHashMap();\n\n HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n numNodesAssignedInZone.put(zoneId, 0);\n }\n for(Node node: nextCandidateCluster.getNodes()) {\n int zoneId = node.getZoneId();\n\n int offset = numNodesAssignedInZone.get(zoneId);\n numNodesAssignedInZone.put(zoneId, offset + 1);\n\n int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset);\n\n if(numPartitions < node.getNumberOfPartitions()) {\n donorNodes.put(node, numPartitions);\n } else if(numPartitions > node.getNumberOfPartitions()) {\n stealerNodes.put(node, numPartitions);\n }\n }\n\n // Print out donor/stealer information\n for(Node node: donorNodes.keySet()) {\n System.out.println(\"Donor Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + donorNodes.get(node));\n }\n for(Node node: stealerNodes.keySet()) {\n System.out.println(\"Stealer Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + stealerNodes.get(node));\n }\n\n return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes);\n }", "public static int cudnnLRNCrossChannelForward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y));\n }", "public static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}", "public static final BigInteger printConstraintType(ConstraintType value)\n {\n return (value == null ? null : BigInteger.valueOf(value.getValue()));\n }", "public ProjectCalendarWeek addWorkWeek()\n {\n ProjectCalendarWeek week = new ProjectCalendarWeek();\n week.setParent(this);\n m_workWeeks.add(week);\n m_weeksSorted = false;\n clearWorkingDateCache();\n return week;\n }", "public Column getColumn(String columnName) {\n if (columnName == null) {\n return null;\n }\n for (Column column : columns) {\n if (columnName.equals(column.getData())) {\n return column;\n }\n }\n return null;\n }", "public static void validate(final License license) {\n // A license should have a name\n if(license.getName() == null ||\n license.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License name should not be empty!\")\n .build());\n }\n\n // A license should have a long name\n if(license.getLongName() == null ||\n license.getLongName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License long name should not be empty!\")\n .build());\n }\n\n // If there is a regexp, it should compile\n if(license.getRegexp() != null &&\n !license.getRegexp().isEmpty()){\n try{\n Pattern.compile(license.getRegexp());\n }\n catch (PatternSyntaxException e){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n Pattern regex = Pattern.compile(\"[&%//]\");\n if(regex.matcher(license.getRegexp()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n }\n }", "public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler,\n MultiMap<String, Object> auxHandlers) {\n\n List<String> newPath = new ArrayList<String>(parent.getPath());\n newPath.add(pathElement);\n\n Shell subshell = new Shell(parent.getSettings().createWithAddedAuxHandlers(auxHandlers),\n new CommandTable(parent.getCommandTable().getNamer()), newPath);\n\n subshell.setAppName(appName);\n subshell.addMainHandler(subshell, \"!\");\n subshell.addMainHandler(new HelpCommandHandler(), \"?\");\n\n subshell.addMainHandler(mainHandler, \"\");\n return subshell;\n }" ]
Retrieves the column title for the given locale. @param locale required locale for the default column title @return column title
[ "public String getTitle(Locale locale)\n {\n String result = null;\n\n if (m_title != null)\n {\n result = m_title;\n }\n else\n {\n if (m_fieldType != null)\n {\n result = m_project.getCustomFields().getCustomField(m_fieldType).getAlias();\n if (result == null)\n {\n result = m_fieldType.getName(locale);\n }\n }\n }\n\n return (result);\n }" ]
[ "public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {\n\t\tdouble x = lognormalVolatiltiy * Math.sqrt(maturity / 8);\n\t\tdouble y = org.apache.commons.math3.special.Erf.erf(x);\n\t\tdouble normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;\n\n\t\treturn normalVol;\n\t}", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n protected void addStoreToSession(String store) {\n\n Exception initializationException = null;\n\n storeNames.add(store);\n\n for(Node node: nodesToStream) {\n\n SocketDestination destination = null;\n SocketAndStreams sands = null;\n\n try {\n destination = new SocketDestination(node.getHost(),\n node.getAdminPort(),\n RequestFormatType.ADMIN_PROTOCOL_BUFFERS);\n sands = streamingSocketPool.checkout(destination);\n DataOutputStream outputStream = sands.getOutputStream();\n DataInputStream inputStream = sands.getInputStream();\n\n nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination);\n nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream);\n nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream);\n nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands);\n nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);\n\n remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId())\n .getValue();\n\n } catch(Exception e) {\n logger.error(e);\n try {\n close(sands.getSocket());\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n\n if(!faultyNodes.contains(node.getId()))\n faultyNodes.add(node.getId());\n initializationException = e;\n }\n\n }\n\n if(initializationException != null)\n throw new VoldemortException(initializationException);\n\n if(store.equals(\"slop\"))\n return;\n\n boolean foundStore = false;\n\n for(StoreDefinition remoteStoreDef: remoteStoreDefs) {\n if(remoteStoreDef.getName().equals(store)) {\n RoutingStrategyFactory factory = new RoutingStrategyFactory();\n RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef,\n adminClient.getAdminClientCluster());\n\n storeToRoutingStrategy.put(store, storeRoutingStrategy);\n validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef);\n foundStore = true;\n break;\n }\n }\n if(!foundStore) {\n logger.error(\"Store Name not found on the cluster\");\n throw new VoldemortException(\"Store Name not found on the cluster\");\n\n }\n\n }", "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 }", "protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }", "public static ConstraintField getInstance(int value)\n {\n ConstraintField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n\n return (result);\n }", "private String fixApiDocRoot(String str) {\n\tif (str == null)\n\t return null;\n\tString fixed = str.trim();\n\tif (fixed.isEmpty())\n\t return \"\";\n\tif (File.separatorChar != '/')\n\t fixed = fixed.replace(File.separatorChar, '/');\n\tif (!fixed.endsWith(\"/\"))\n\t fixed = fixed + \"/\";\n\treturn fixed;\n }", "protected void processDescriptions(List<MonolingualTextValue> descriptions) {\n for(MonolingualTextValue description : descriptions) {\n \tNameWithUpdate currentValue = newDescriptions.get(description.getLanguageCode());\n \t// only mark the description as added if the value we are writing is different from the current one\n \tif (currentValue == null || !currentValue.value.equals(description)) {\n \t\tnewDescriptions.put(description.getLanguageCode(),\n new NameWithUpdate(description, true));\n \t}\n }\n }", "private void configureCustomFields()\n {\n CustomFieldContainer customFields = m_projectFile.getCustomFields();\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityIDField == null)\n {\n m_activityIDField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Code\");\n if (m_activityIDField == null)\n {\n m_activityIDField = TaskField.WBS;\n }\n }\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityTypeField == null)\n {\n m_activityTypeField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Activity Type\");\n }\n }", "public static KieRuntimeLogger newFileLogger(KieRuntimeEventManager session,\n String fileName) {\n return getKnowledgeRuntimeLoggerProvider().newFileLogger( session,\n fileName );\n }" ]
Shows the Loader component
[ "public void show() {\n if (!(container instanceof RootPanel)) {\n if (!(container instanceof MaterialDialog)) {\n container.getElement().getStyle().setPosition(Style.Position.RELATIVE);\n }\n div.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);\n }\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.HIDDEN);\n }\n if (type == LoaderType.CIRCULAR) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.LOADER_WRAPPER);\n div.add(preLoader);\n } else if (type == LoaderType.PROGRESS) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.PROGRESS_WRAPPER);\n progress.getElement().getStyle().setProperty(\"margin\", \"auto\");\n div.add(progress);\n }\n container.add(div);\n }" ]
[ "public static int cudnnBatchNormalizationBackward(\n cudnnHandle handle, \n int mode, \n Pointer alphaDataDiff, \n Pointer betaDataDiff, \n Pointer alphaParamDiff, \n Pointer betaParamDiff, \n cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */\n Pointer x, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor dxDesc, \n Pointer dx, \n /** Shared tensor desc for the 4 tensors below */\n cudnnTensorDescriptor dBnScaleBiasDesc, \n Pointer bnScale, /** bnBias doesn't affect backpropagation */\n /** scale and bias diff are not backpropagated below this layer */\n Pointer dBnScaleResult, \n Pointer dBnBiasResult, \n /** Same epsilon as forward pass */\n double epsilon, \n /** Optionally cached intermediate results from\n forward pass */\n Pointer savedMean, \n Pointer savedInvVariance)\n {\n return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));\n }", "public static base_responses update(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable updateresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new bridgetable();\n\t\t\t\tupdateresources[i].bridgeage = resources[i].bridgeage;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public T withStatement(Statement statement) {\n\t\tPropertyIdValue pid = statement.getMainSnak()\n\t\t\t\t.getPropertyId();\n\t\tArrayList<Statement> pidStatements = this.statements.get(pid);\n\t\tif (pidStatements == null) {\n\t\t\tpidStatements = new ArrayList<Statement>();\n\t\t\tthis.statements.put(pid, pidStatements);\n\t\t}\n\n\t\tpidStatements.add(statement);\n\t\treturn getThis();\n\t}", "private String toPath(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, \"\" + name.hashCode()) + size.getSuffix();\n }", "@SuppressWarnings(\"unchecked\")\n\tpublic Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException {\n\t\treturn decodeSignedRequest(signedRequest, Map.class);\n\t}", "public static boolean invertSPD(DMatrixRMaj mat, DMatrixRMaj result ) {\n if( mat.numRows != mat.numCols )\n throw new IllegalArgumentException(\"Must be a square matrix\");\n result.reshape(mat.numRows,mat.numRows);\n\n if( mat.numRows <= UnrolledCholesky_DDRM.MAX ) {\n // L*L' = A\n if( !UnrolledCholesky_DDRM.lower(mat,result) )\n return false;\n // L = inv(L)\n TriangularSolver_DDRM.invertLower(result.data,result.numCols);\n // inv(A) = inv(L')*inv(L)\n SpecializedOps_DDRM.multLowerTranA(result);\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.chol(mat.numCols);\n if( solver.modifiesA() )\n mat = mat.copy();\n\n if( !solver.setA(mat))\n return false;\n solver.invert(result);\n }\n\n return true;\n }", "private void appendJoin(StringBuffer where, StringBuffer buf, Join join)\r\n {\r\n buf.append(\",\");\r\n appendTableWithJoins(join.right, where, buf);\r\n if (where.length() > 0)\r\n {\r\n where.append(\" AND \");\r\n }\r\n join.appendJoinEqualities(where);\r\n }", "public Object getProperty(String property) {\n if(ExpandoMetaClass.isValidExpandoProperty(property)) {\n if(property.equals(ExpandoMetaClass.STATIC_QUALIFIER) ||\n property.equals(ExpandoMetaClass.CONSTRUCTOR) ||\n myMetaClass.hasProperty(this, property) == null) {\n return replaceDelegate().getProperty(property);\n }\n }\n return myMetaClass.getProperty(this, property);\n }", "@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }" ]
Swaps two specified partitions. Pair-wase partition swapping may be more prone to local minima than larger perturbations. Could consider "swapping" a list of <nodeId/partitionId>. This would allow a few nodes to be identified (random # btw 2-5?) and then "swapped" (shuffled? rotated?). @return modified cluster metadata.
[ "public static Cluster swapPartitions(final Cluster nextCandidateCluster,\n final int nodeIdA,\n final int partitionIdA,\n final int nodeIdB,\n final int partitionIdB) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n // Swap partitions between nodes!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdA,\n Lists.newArrayList(partitionIdB));\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdB,\n Lists.newArrayList(partitionIdA));\n\n return returnCluster;\n }" ]
[ "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n logger.info(\"Attempting to remove the following client: {}\", clientUUID);\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n clientService.remove(profileId, clientUUID);\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }", "public Where<T, ID> idEq(ID id) throws SQLException {\n\t\tif (idColumnName == null) {\n\t\t\tthrow new SQLException(\"Object has no id column specified\");\n\t\t}\n\t\taddClause(new SimpleComparison(idColumnName, idFieldType, id, SimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public <T extends Widget & Checkable> boolean addOnCheckChangedListener\n (OnCheckChangedListener listener) {\n final boolean added;\n synchronized (mListeners) {\n added = mListeners.add(listener);\n }\n if (added) {\n List<T> c = getCheckableChildren();\n for (int i = 0; i < c.size(); ++i) {\n listener.onCheckChanged(this, c.get(i), i);\n }\n }\n return added;\n }", "public static Method findGetter(final Object object, final String fieldName) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t}\n\t\t\n\t\tfinal Class<?> clazz = object.getClass();\n\t\t\n\t\t// find a standard getter\n\t\tfinal String standardGetterName = getMethodNameForField(GET_PREFIX, fieldName);\n\t\tMethod getter = findGetterWithCompatibleReturnType(standardGetterName, clazz, false);\n\t\t\n\t\t// if that fails, try for an isX() style boolean getter\n\t\tif( getter == null ) {\n\t\t\tfinal String booleanGetterName = getMethodNameForField(IS_PREFIX, fieldName);\n\t\t\tgetter = findGetterWithCompatibleReturnType(booleanGetterName, clazz, true);\n\t\t}\n\t\t\n\t\tif( getter == null ) {\n\t\t\tthrow new SuperCsvReflectionException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"unable to find getter for field %s in class %s - check that the corresponding nameMapping element matches the field name in the bean\",\n\t\t\t\t\t\tfieldName, clazz.getName()));\n\t\t}\n\t\t\n\t\treturn getter;\n\t}", "public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}", "public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }", "public static Integer parseInteger(String value) throws ParseException\n {\n Integer result = null;\n\n if (value.length() > 0 && value.indexOf(' ') == -1)\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n Number n = DatatypeConverter.parseDouble(value);\n result = Integer.valueOf(n.intValue());\n }\n }\n\n return result;\n }", "private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {\n this.stats.startTime = System.currentTimeMillis();\n try {\n // build and record parsed units\n reportProgress(Messages.compilation_beginningToCompile);\n\n if (this.options.complianceLevel >= ClassFileConstants.JDK9) {\n // in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:\n sortModuleDeclarationsFirst(sourceUnits);\n }\n if (this.annotationProcessorManager == null) {\n beginToCompile(sourceUnits);\n } else {\n ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs\n try {\n beginToCompile(sourceUnits);\n if (!lastRound) {\n processAnnotations();\n }\n if (!this.options.generateClassFiles) {\n // -proc:only was set on the command line\n return;\n }\n } catch (SourceTypeCollisionException e) {\n backupAptProblems();\n reset();\n // a generated type was referenced before it was created\n // the compiler either created a MissingType or found a BinaryType for it\n // so add the processor's generated files & start over,\n // but remember to only pass the generated files to the annotation processor\n int originalLength = originalUnits.length;\n int newProcessedLength = e.newAnnotationProcessorUnits.length;\n ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];\n System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);\n System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);\n this.annotationProcessorStartIndex = originalLength;\n compile(combinedUnits, e.isLastRound);\n return;\n }\n }\n // Restore the problems before the results are processed and cleaned up.\n restoreAptProblems();\n processCompiledUnits(0, lastRound);\n } catch (AbortCompilation e) {\n this.handleInternalException(e, null);\n }\n if (this.options.verbose) {\n if (this.totalUnits > 1) {\n this.out.println(\n Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));\n } else {\n this.out.println(\n Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));\n }\n }\n }", "@SuppressWarnings(\"unchecked\")\r\n public static <E> E[] filter(E[] elems, Filter<E> filter) {\r\n List<E> filtered = new ArrayList<E>();\r\n for (E elem: elems) {\r\n if (filter.accept(elem)) {\r\n filtered.add(elem);\r\n }\r\n }\r\n return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));\r\n }" ]
Append the WHERE part of the statement to the StringBuilder.
[ "protected boolean appendWhereStatement(StringBuilder sb, List<ArgumentHolder> argList, WhereOperation operation)\n\t\t\tthrows SQLException {\n\t\tif (where == null) {\n\t\t\treturn operation == WhereOperation.FIRST;\n\t\t}\n\t\toperation.appendBefore(sb);\n\t\twhere.appendSql((addTableName ? getTableName() : null), sb, argList);\n\t\toperation.appendAfter(sb);\n\t\treturn false;\n\t}" ]
[ "public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}", "private long getEndTime(ISuite suite, IInvokedMethod method)\n {\n // Find the latest end time for all tests in the suite.\n for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())\n {\n ITestContext testContext = entry.getValue().getTestContext();\n for (ITestNGMethod m : testContext.getAllTestMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n // If we can't find a matching test method it must be a configuration method.\n for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n }\n throw new IllegalStateException(\"Could not find matching end time.\");\n }", "public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }", "private void persistEnabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n if (disabledMarker.exists()) {\n if (!disabledMarker.delete()) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain enabled only until the next restart.\");\n }\n }\n }", "protected final Event processEvent() throws IOException {\n while (true) {\n String line;\n try {\n line = readLine();\n } catch (final EOFException ex) {\n if (doneOnce) {\n throw ex;\n }\n doneOnce = true;\n line = \"\";\n }\n\n // If the line is empty (a blank line), Dispatch the event, as defined below.\n if (line.isEmpty()) {\n // If the data buffer is an empty string, set the data buffer and the event name buffer to\n // the empty string and abort these steps.\n if (dataBuffer.length() == 0) {\n eventName = \"\";\n continue;\n }\n\n // If the event name buffer is not the empty string but is also not a valid NCName,\n // set the data buffer and the event name buffer to the empty string and abort these steps.\n // NOT IMPLEMENTED\n\n final Event.Builder eventBuilder = new Event.Builder();\n eventBuilder.withEventName(eventName.isEmpty() ? Event.MESSAGE_EVENT : eventName);\n eventBuilder.withData(dataBuffer.toString());\n\n // Set the data buffer and the event name buffer to the empty string.\n dataBuffer = new StringBuilder();\n eventName = \"\";\n\n return eventBuilder.build();\n // If the line starts with a U+003A COLON character (':')\n } else if (line.startsWith(\":\")) {\n // ignore the line\n // If the line contains a U+003A COLON character (':') character\n } else if (line.contains(\":\")) {\n // Collect the characters on the line before the first U+003A COLON character (':'),\n // and let field be that string.\n final int colonIdx = line.indexOf(\":\");\n final String field = line.substring(0, colonIdx);\n\n // Collect the characters on the line after the first U+003A COLON character (':'),\n // and let value be that string.\n // If value starts with a single U+0020 SPACE character, remove it from value.\n String value = line.substring(colonIdx + 1);\n value = value.startsWith(\" \") ? value.substring(1) : value;\n\n processField(field, value);\n // Otherwise, the string is not empty but does not contain a U+003A COLON character (':')\n // character\n } else {\n processField(line, \"\");\n }\n }\n }", "public static <T> NewManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new NewManagedBean<T>(attributes, clazz, new StringBeanIdentifier(BeanIdentifiers.forNewManagedBean(clazz)), beanManager);\n }", "public void setBackgroundColor(float r, float g, float b, float a) {\n setBackgroundColorR(r);\n setBackgroundColorG(g);\n setBackgroundColorB(b);\n setBackgroundColorA(a);\n }", "public void removeFilter(String filterName)\n {\n Filter filter = getFilterByName(filterName);\n if (filter != null)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.remove(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.remove(filter);\n }\n m_filtersByName.remove(filterName);\n m_filtersByID.remove(filter.getID());\n }\n }" ]
Two stage promotion, dry run and actual promotion to verify correctness. @param promotion @param client @param listener @param buildName @param buildNumber @throws IOException
[ "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 }" ]
[ "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 }", "public static boolean isFormatCorrect(String fileName, ReadOnlyStorageFormat format) {\n switch(format) {\n case READONLY_V0:\n case READONLY_V1:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n case READONLY_V2:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n default:\n throw new VoldemortException(\"Format type not supported\");\n }\n }", "private static boolean isDisabledHandler(final LogContext logContext, final String handlerName) {\n final Map<String, String> disableHandlers = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY);\n return disableHandlers != null && disableHandlers.containsKey(handlerName);\n }", "public Collection<Contact> getPublicList(String userId) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_LIST);\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\r\n Element contactsElement = response.getPayload();\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.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\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 appfwpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_stats response = (appfwpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}", "public static String createCustomExpressionInvocationText(CustomExpression customExpression, String customExpName, boolean usePreviousFieldValues) {\n String stringExpression;\n if (customExpression instanceof DJSimpleExpression) {\n DJSimpleExpression varexp = (DJSimpleExpression) customExpression;\n String symbol;\n switch (varexp.getType()) {\n case DJSimpleExpression.TYPE_FIELD:\n symbol = \"F\";\n break;\n case DJSimpleExpression.TYPE_VARIABLE:\n symbol = \"V\";\n break;\n case DJSimpleExpression.TYPE_PARAMATER:\n symbol = \"P\";\n break;\n default:\n throw new DJException(\"Invalid DJSimpleExpression, type must be FIELD, VARIABLE or PARAMETER\");\n }\n stringExpression = \"$\" + symbol + \"{\" + varexp.getVariableName() + \"}\";\n\n } else {\n String fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentFields()\";\n if (usePreviousFieldValues) {\n fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getPreviousFields()\";\n }\n\n String parametersMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentParams()\";\n String variablesMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentVariables()\";\n\n stringExpression = \"((\" + CustomExpression.class.getName() + \")$P{REPORT_PARAMETERS_MAP}.get(\\\"\" + customExpName + \"\\\")).\"\n + CustomExpression.EVAL_METHOD_NAME + \"( \" + fieldsMap + \", \" + variablesMap + \", \" + parametersMap + \" )\";\n }\n\n return stringExpression;\n }", "public static String keyVersionToString(ByteArray key,\n Map<Value, Set<ClusterNode>> versionMap,\n String storeName,\n Integer partitionId) {\n StringBuilder record = new StringBuilder();\n for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) {\n Value value = versionSet.getKey();\n Set<ClusterNode> nodeSet = versionSet.getValue();\n\n record.append(\"BAD_KEY,\");\n record.append(storeName + \",\");\n record.append(partitionId + \",\");\n record.append(ByteUtils.toHexString(key.get()) + \",\");\n record.append(nodeSet.toString().replace(\", \", \";\") + \",\");\n record.append(value.toString());\n }\n return record.toString();\n }", "public ResourceTransformerEntry resolveResourceTransformer(final PathAddress address, final PlaceholderResolver placeholderResolver) {\n return resolveResourceTransformer(address.iterator(), null, placeholderResolver);\n }" ]
Function to go through all the store definitions contained in the STORES directory and 1. Update metadata cache. 2. Update STORES_KEY by stitching together all these keys. 3. Update 'storeNames' list. This method is not thread safe. It is expected that the caller of this method will correctly handle concurrency issues. Currently this is not an issue since its invoked by init, put, add and delete store all of which use locks to deal with any concurrency related issues.
[ "private void initStoreDefinitions(Version storesXmlVersion) {\n if(this.storeDefinitionsStorageEngine == null) {\n throw new VoldemortException(\"The store definitions directory is empty\");\n }\n\n String allStoreDefinitions = \"<stores>\";\n Version finalStoresXmlVersion = null;\n if(storesXmlVersion != null) {\n finalStoresXmlVersion = storesXmlVersion;\n }\n this.storeNames.clear();\n\n ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();\n\n // Some test setups may result in duplicate entries for 'store' element.\n // Do the de-dup here\n Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();\n Version maxVersion = null;\n while(storesIterator.hasNext()) {\n Pair<String, Versioned<String>> storeDetail = storesIterator.next();\n String storeName = storeDetail.getFirst();\n Versioned<String> versionedStoreDef = storeDetail.getSecond();\n storeNameToDefMap.put(storeName, versionedStoreDef);\n Version curVersion = versionedStoreDef.getVersion();\n\n // Get the highest version from all the store entries\n if(maxVersion == null) {\n maxVersion = curVersion;\n } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {\n maxVersion = curVersion;\n }\n }\n\n // If the specified version is null, assign highest Version to\n // 'stores.xml' key\n if(finalStoresXmlVersion == null) {\n finalStoresXmlVersion = maxVersion;\n }\n\n // Go through all the individual stores and update metadata\n for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {\n String storeName = storeEntry.getKey();\n Versioned<String> versionedStoreDef = storeEntry.getValue();\n\n // Add all the store names to the list of storeNames\n this.storeNames.add(storeName);\n\n this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),\n versionedStoreDef.getVersion()));\n }\n\n Collections.sort(this.storeNames);\n for(String storeName: this.storeNames) {\n Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);\n // Stitch together to form the complete store definition list.\n allStoreDefinitions += versionedStoreDef.getValue();\n\n }\n\n allStoreDefinitions += \"</stores>\";\n\n // Update cache with the composite store definition list.\n metadataCache.put(STORES_KEY,\n convertStringToObject(STORES_KEY,\n new Versioned<String>(allStoreDefinitions,\n finalStoresXmlVersion)));\n }" ]
[ "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}", "@Override\n public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException {\n long deadline = unit.toMillis(timeout) + System.currentTimeMillis();\n lock.lock(); try {\n assert shutdown;\n while(activeCount != 0) {\n long remaining = deadline - System.currentTimeMillis();\n if (remaining <= 0) {\n break;\n }\n condition.await(remaining, TimeUnit.MILLISECONDS);\n }\n boolean allComplete = activeCount == 0;\n if (!allComplete) {\n ProtocolLogger.ROOT_LOGGER.debugf(\"ActiveOperation(s) %s have not completed within %d %s\", activeRequests.keySet(), timeout, unit);\n }\n return allComplete;\n } finally {\n lock.unlock();\n }\n }", "private void retrieveNextPage() {\n if (this.pageSize < Long.MAX_VALUE || this.itemLimit < Long.MAX_VALUE) {\n this.request.query(\"limit\", Math.min(this.pageSize, this.itemLimit - this.count));\n } else {\n this.request.query(\"limit\", null);\n }\n ResultBodyCollection<T> page = null;\n try {\n page = this.getNext();\n } catch (IOException exception) {\n // See comments in hasNext().\n this.ioException = exception;\n }\n if (page != null) {\n this.continuation = this.getContinuation(page);\n if (page.data != null && !page.data.isEmpty()) {\n this.count += page.data.size();\n this.nextData = page.data;\n } else {\n this.nextData = null;\n }\n } else {\n this.continuation = null;\n this.nextData = null;\n }\n }", "public int checkIn() {\n\n try {\n synchronized (STATIC_LOCK) {\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, false));\n CmsObject cms = getCmsObject();\n if (cms != null) {\n return checkInInternal();\n } else {\n m_logStream.println(\"No CmsObject given. Did you call init() first?\");\n return -1;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return -2;\n }\n }", "public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n children.add(parsedItemInfo);\n }\n }\n return children;\n }", "public AT_Row setPaddingRight(int paddingRight) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private boolean isOrdinal(int paramType) {\n\t\tswitch ( paramType ) {\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.NUMERIC:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\tcase Types.BIGINT:\n\t\t\tcase Types.DECIMAL: //for Oracle Driver\n\t\t\tcase Types.DOUBLE: //for Oracle Driver\n\t\t\tcase Types.FLOAT: //for Oracle Driver\n\t\t\t\treturn true;\n\t\t\tcase Types.CHAR:\n\t\t\tcase Types.LONGVARCHAR:\n\t\t\tcase Types.VARCHAR:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\tthrow new HibernateException( \"Unable to persist an Enum in a column of SQL Type: \" + paramType );\n\t\t}\n\t}", "static String createStatsType(Set<String> statsItems, String sortType,\n MtasFunctionParserFunction functionParser) {\n String statsType = STATS_BASIC;\n for (String statsItem : statsItems) {\n if (STATS_FULL_TYPES.contains(statsItem)) {\n statsType = STATS_FULL;\n break;\n } else if (STATS_ADVANCED_TYPES.contains(statsItem)) {\n statsType = STATS_ADVANCED;\n } else if (statsType != STATS_ADVANCED\n && STATS_BASIC_TYPES.contains(statsItem)) {\n statsType = STATS_BASIC;\n } else {\n Matcher m = fpStatsFunctionItems.matcher(statsItem.trim());\n if (m.find()) {\n if (STATS_FUNCTIONS.contains(m.group(2).trim())) {\n statsType = STATS_FULL;\n break;\n }\n }\n }\n }\n if (sortType != null && STATS_TYPES.contains(sortType)) {\n if (STATS_FULL_TYPES.contains(sortType)) {\n statsType = STATS_FULL;\n } else if (STATS_ADVANCED_TYPES.contains(sortType)) {\n statsType = (statsType == null || statsType != STATS_FULL)\n ? STATS_ADVANCED : statsType;\n }\n }\n return statsType;\n }", "public ResponseOnSingeRequest onComplete(Response response) {\n\n cancelCancellable();\n try {\n \n Map<String, List<String>> responseHeaders = null;\n if (responseHeaderMeta != null) {\n responseHeaders = new LinkedHashMap<String, List<String>>();\n if (responseHeaderMeta.isGetAll()) {\n for (Map.Entry<String, List<String>> header : response\n .getHeaders()) {\n responseHeaders.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue());\n }\n } else {\n for (String key : responseHeaderMeta.getKeys()) {\n if (response.getHeaders().containsKey(key)) {\n responseHeaders.put(key.toLowerCase(Locale.ROOT),\n response.getHeaders().get(key));\n }\n }\n }\n }\n\n int statusCodeInt = response.getStatusCode();\n String statusCode = statusCodeInt + \" \" + response.getStatusText();\n String charset = ParallecGlobalConfig.httpResponseBodyCharsetUsesResponseContentType &&\n response.getContentType()!=null ? \n AsyncHttpProviderUtils.parseCharset(response.getContentType())\n : ParallecGlobalConfig.httpResponseBodyDefaultCharset;\n if(charset == null){\n getLogger().error(\"charset is not provided from response content type. Use default\");\n charset = ParallecGlobalConfig.httpResponseBodyDefaultCharset; \n }\n reply(response.getResponseBody(charset), false, null, null, statusCode,\n statusCodeInt, responseHeaders);\n } catch (IOException e) {\n getLogger().error(\"fail response.getResponseBody \" + e);\n }\n\n return null;\n }" ]
Return all levels of moneyness for which data exists. Moneyness is returned as actual difference strike - par swap rate. @return The levels of moneyness as difference of strike to par swap rate.
[ "public double[] getMoneynessAsOffsets() {\r\n\t\tDoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.01;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn - x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\treturn moneyness.toArray();\r\n\t}" ]
[ "private boolean addonDependsOnReporting(Addon addon)\n {\n for (AddonDependency dep : addon.getDependencies())\n {\n if (dep.getDependency().equals(this.addon))\n {\n return true;\n }\n boolean subDep = addonDependsOnReporting(dep.getDependency());\n if (subDep)\n {\n return true;\n }\n }\n return false;\n }", "public static String getDateTimeStrConcise(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMddHHmmssSSSZ\");\n return sdf.format(d);\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 boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\ttry {\n\t\t\tClassLoader target = clazz.getClassLoader();\n\t\t\tif (target == null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tClassLoader cur = classLoader;\n\t\t\tif (cur == target) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\twhile (cur != null) {\n\t\t\t\tcur = cur.getParent();\n\t\t\t\tif (cur == target) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tcatch (SecurityException ex) {\n\t\t\t// Probably from the system ClassLoader - let's consider it safe.\n\t\t\treturn true;\n\t\t}\n\t}", "@SuppressWarnings(\"unchecked\")\n protected String addeDependency(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addDependency(dependency);\n }", "public List<ServerRedirect> tableServers(int clientId) {\n List<ServerRedirect> servers = new ArrayList<>();\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n servers = tableServers(client.getProfile().getId(), client.getActiveServerGroup());\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return servers;\n }", "public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }", "public BoxAPIResponse send(ProgressListener listener) {\n if (this.api == null) {\n this.backoffCounter.reset(BoxGlobalSettings.getMaxRequestAttempts());\n } else {\n this.backoffCounter.reset(this.api.getMaxRequestAttempts());\n }\n\n while (this.backoffCounter.getAttemptsRemaining() > 0) {\n try {\n return this.trySend(listener);\n } catch (BoxAPIException apiException) {\n if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {\n throw apiException;\n }\n\n try {\n this.resetBody();\n } catch (IOException ioException) {\n throw apiException;\n }\n\n try {\n this.backoffCounter.waitBackoff();\n } catch (InterruptedException interruptedException) {\n Thread.currentThread().interrupt();\n throw apiException;\n }\n }\n }\n\n throw new RuntimeException();\n }" ]
Commit all written data to the physical disk @throws IOException any io exception
[ "public void flush() throws IOException {\n checkMutable();\n long startTime = System.currentTimeMillis();\n channel.force(true);\n long elapsedTime = System.currentTimeMillis() - startTime;\n LogFlushStats.recordFlushRequest(elapsedTime);\n logger.debug(\"flush time \" + elapsedTime);\n setHighWaterMark.set(getSizeInBytes());\n logger.debug(\"flush high water mark:\" + highWaterMark());\n }" ]
[ "private static void writeUtf16Bom(OutputStream stream, boolean bigEndian) throws IOException {\n if (bigEndian) {\n stream.write(-2);\n stream.write(-1);\n } else {\n stream.write(-1);\n stream.write(-2);\n }\n }", "private DBHandling createDBHandling() throws BuildException\r\n {\r\n if ((_handling == null) || (_handling.length() == 0))\r\n {\r\n throw new BuildException(\"No handling specified\");\r\n }\r\n try\r\n {\r\n String className = \"org.apache.ojb.broker.platforms.\"+\r\n \t\t\t\t\t Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+\r\n \t\t\t\t\t \"DBHandling\";\r\n Class handlingClass = ClassHelper.getClass(className);\r\n\r\n return (DBHandling)handlingClass.newInstance();\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Invalid handling '\"+_handling+\"' specified\");\r\n }\r\n }", "private void addErrorCorrection(StringBuilder adjustedString, int codewordSize, int dataBlocks, int eccBlocks) {\r\n\r\n int x, poly, startWeight;\r\n\r\n /* Split into codewords and calculate Reed-Solomon error correction codes */\r\n switch (codewordSize) {\r\n case 6:\r\n x = 32;\r\n poly = 0x43;\r\n startWeight = 0x20;\r\n break;\r\n case 8:\r\n x = 128;\r\n poly = 0x12d;\r\n startWeight = 0x80;\r\n break;\r\n case 10:\r\n x = 512;\r\n poly = 0x409;\r\n startWeight = 0x200;\r\n break;\r\n case 12:\r\n x = 2048;\r\n poly = 0x1069;\r\n startWeight = 0x800;\r\n break;\r\n default:\r\n throw new OkapiException(\"Unrecognized codeword size: \" + codewordSize);\r\n }\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n int[] data = new int[dataBlocks + 3];\r\n int[] ecc = new int[eccBlocks + 3];\r\n\r\n for (int i = 0; i < dataBlocks; i++) {\r\n for (int weight = 0; weight < codewordSize; weight++) {\r\n if (adjustedString.charAt((i * codewordSize) + weight) == '1') {\r\n data[i] += (x >> weight);\r\n }\r\n }\r\n }\r\n\r\n rs.init_gf(poly);\r\n rs.init_code(eccBlocks, 1);\r\n rs.encode(dataBlocks, data);\r\n\r\n for (int i = 0; i < eccBlocks; i++) {\r\n ecc[i] = rs.getResult(i);\r\n }\r\n\r\n for (int i = (eccBlocks - 1); i >= 0; i--) {\r\n for (int weight = startWeight; weight > 0; weight = weight >> 1) {\r\n if ((ecc[i] & weight) != 0) {\r\n adjustedString.append('1');\r\n } else {\r\n adjustedString.append('0');\r\n }\r\n }\r\n }\r\n }", "public boolean isValid() {\n\t\tif(parsedHost != null) {\n\t\t\treturn true;\n\t\t}\n\t\tif(validationException != null) {\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tvalidate();\n\t\t\treturn true;\n\t\t} catch(HostNameException e) {\n\t\t\treturn false;\n\t\t}\n\t}", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "private static JSONObject parseStencil(String stencilId) throws JSONException {\n JSONObject stencilObject = new JSONObject();\n\n stencilObject.put(\"id\",\n stencilId.toString());\n\n return stencilObject;\n }", "private void normalizeSelectedCategories() {\r\n\r\n Collection<String> normalizedCategories = new ArrayList<String>(m_selectedCategories.size());\r\n for (CmsTreeItem item : m_categories.values()) {\r\n if (item.getCheckBox().isChecked()) {\r\n normalizedCategories.add(item.getId());\r\n }\r\n }\r\n m_selectedCategories = normalizedCategories;\r\n\r\n }", "public ProjectFile read() throws MPXJException\n {\n MPD9DatabaseReader reader = new MPD9DatabaseReader();\n reader.setProjectID(m_projectID);\n reader.setPreserveNoteFormatting(m_preserveNoteFormatting);\n reader.setDataSource(m_dataSource);\n reader.setConnection(m_connection);\n ProjectFile project = reader.read();\n return (project);\n }", "public static void append(File file, Writer writer, String charset) throws IOException {\n appendBuffered(file, writer, charset);\n }" ]
Record the details of the media being cached, to make it easier to recognize, now that we have access to that information. @param slot the slot from which a metadata cache is being created @param zos the stream to which the ZipFile is being written @param channel the low-level channel to which the cache is being written @throws IOException if there is a problem writing the media details entry
[ "private static void addCacheDetailsEntry(SlotReference slot, ZipOutputStream zos, WritableByteChannel channel) throws IOException {\n // Record the details of the media being cached, to make it easier to recognize now that we can.\n MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null) {\n zos.putNextEntry(new ZipEntry(CACHE_DETAILS_ENTRY));\n Util.writeFully(details.getRawBytes(), channel);\n }\n }" ]
[ "private Double zeroIsNull(Double value)\n {\n if (value != null && value.doubleValue() == 0)\n {\n value = null;\n }\n return value;\n }", "public void process(CustomFieldContainer indicators, ProjectProperties properties, Props props)\n {\n m_container = indicators;\n m_properties = properties;\n m_data = props.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n\n if (m_data != null)\n {\n int columnsCount = MPPUtility.getInt(m_data, 4);\n m_headerOffset = 8;\n for (int loop = 0; loop < columnsCount; loop++)\n {\n processColumns();\n }\n }\n }", "public static void createDirectory(Path dir, String dirDesc)\n {\n try\n {\n Files.createDirectories(dir);\n }\n catch (IOException ex)\n {\n throw new WindupException(\"Error creating \" + dirDesc + \" folder: \" + dir.toString() + \" due to: \" + ex.getMessage(), ex);\n }\n }", "public PreparedStatement getSelectByPKStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getSelectByPKStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }", "public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) {\n final PrintStream origSysOut = System.out;\n final PrintStream origSysErr = System.err;\n\n // Set warnings stream to System.err.\n warnings = System.err;\n AccessController.doPrivileged(new PrivilegedAction<Void>() {\n @SuppressForbidden(\"legitimate PrintStream with default charset.\")\n @Override\n public Void run() {\n System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysOut.write(b, off, len);\n }\n serializer.serialize(new AppendStdOutEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n\n System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() {\n @Override\n public void write(byte[] b, int off, int len) throws IOException {\n if (multiplexStdStreams) {\n origSysErr.write(b, off, len);\n }\n serializer.serialize(new AppendStdErrEvent(b, off, len));\n if (flushFrequently) serializer.flush();\n }\n })));\n return null;\n }\n });\n }", "private 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 }", "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 }" ]
Print a task UID. @param value task UID @return task UID string
[ "public static final String printTaskUID(Integer value)\n {\n ProjectFile file = PARENT_FILE.get();\n if (file != null)\n {\n file.getEventManager().fireTaskWrittenEvent(file.getTaskByUniqueID(value));\n }\n return (value.toString());\n }" ]
[ "public void updateExceptions(SortedSet<Date> exceptions) {\r\n\r\n SortedSet<Date> e = null == exceptions ? new TreeSet<Date>() : exceptions;\r\n if (!m_model.getExceptions().equals(e)) {\r\n m_model.setExceptions(e);\r\n m_view.updateExceptions();\r\n valueChanged();\r\n sizeChanged();\r\n }\r\n\r\n }", "private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }", "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 isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }", "@Override\n protected void checkType() {\n if (!isDependent() && getEnhancedAnnotated().isParameterizedType()) {\n throw BeanLogger.LOG.managedBeanWithParameterizedBeanClassMustBeDependent(type);\n }\n boolean passivating = beanManager.isPassivatingScope(getScope());\n if (passivating && !isPassivationCapableBean()) {\n if (!getEnhancedAnnotated().isSerializable()) {\n throw BeanLogger.LOG.passivatingBeanNeedsSerializableImpl(this);\n } else if (hasDecorators() && !allDecoratorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableDecorator(this, getFirstNonPassivationCapableDecorator());\n } else if (hasInterceptors() && !allInterceptorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableInterceptor(this, getFirstNonPassivationCapableInterceptor());\n }\n }\n }", "@Override\n public void onBindViewHolder(GalleryAdapter.ViewHolder holder, int position, List<Object> payloads) {\n if (payloads.isEmpty()) { // If doesn't have any payload then bind the fully item\n super.onBindViewHolder(holder, position, payloads);\n } else {\n for (Object payload : payloads) {\n boolean selected = isSelected(position);\n if (SELECTION_PAYLOAD.equals(payload)) {\n if (VIEW_TYPE_MEDIA == getItemViewType(position)) {\n MediaViewHolder viewHolder = (MediaViewHolder) holder;\n viewHolder.mCheckView.setChecked(selected);\n if (selected) {\n AnimationHelper.scaleView(holder.mImageView, SELECTED_SCALE);\n } else {\n AnimationHelper.scaleView(holder.mImageView, UNSELECTED_SCALE);\n }\n }\n }\n }\n }\n }", "public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) {\n\t\tDiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(\"referenceCurve\", new double[] {0.0, 1.0}, new double[] {1.0, 1.0});\n\t\treturn getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model);\n\t}", "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 B fields(List<F> fields) {\n if (instance.def.fields == null) {\n instance.def.fields = new ArrayList<F>(fields.size());\n }\n instance.def.fields.addAll(fields);\n return returnThis();\n }" ]
Utility function to set the current value in a ListBox. @return returns true if the option corresponding to the value was successfully selected in the ListBox
[ "public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }" ]
[ "public void detect(final String... packageNames) throws IOException {\n final String[] pkgNameFilter = new String[packageNames.length];\n for (int i = 0; i < pkgNameFilter.length; ++i) {\n pkgNameFilter[i] = packageNames[i].replace('.', '/');\n if (!pkgNameFilter[i].endsWith(\"/\")) {\n pkgNameFilter[i] = pkgNameFilter[i].concat(\"/\");\n }\n }\n final Set<File> files = new HashSet<>();\n final ClassLoader loader = Thread.currentThread().getContextClassLoader();\n for (final String packageName : pkgNameFilter) {\n final Enumeration<URL> resourceEnum = loader.getResources(packageName);\n while (resourceEnum.hasMoreElements()) {\n final URL url = resourceEnum.nextElement();\n if (\"file\".equals(url.getProtocol())) {\n final File dir = toFile(url);\n if (dir.isDirectory()) {\n files.add(dir);\n } else {\n throw new AssertionError(\"Not a recognized file URL: \" + url);\n }\n } else {\n final File jarFile = toFile(openJarURLConnection(url).getJarFileURL());\n if (jarFile.isFile()) {\n files.add(jarFile);\n } else {\n throw new AssertionError(\"Not a File: \" + jarFile);\n }\n }\n }\n }\n if (DEBUG) {\n print(\"Files to scan: %s\", files);\n }\n if (!files.isEmpty()) {\n // see http://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion\n detect(new ClassFileIterator(files.toArray(new File[0]), pkgNameFilter));\n }\n }", "public boolean contains(Vector3 p) {\n\t\tboolean ans = false;\n\t\tif(this.halfplane || p== null) return false;\n\n\t\tif (isCorner(p)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tPointLinePosition a12 = PointLineTest.pointLineTest(a,b,p);\n\t\tPointLinePosition a23 = PointLineTest.pointLineTest(b,c,p);\n\t\tPointLinePosition a31 = PointLineTest.pointLineTest(c,a,p);\n\n\t\tif ((a12 == PointLinePosition.LEFT && a23 == PointLinePosition.LEFT && a31 == PointLinePosition.LEFT ) ||\n\t\t\t\t(a12 == PointLinePosition.RIGHT && a23 == PointLinePosition.RIGHT && a31 == PointLinePosition.RIGHT ) ||\n\t\t\t\t(a12 == PointLinePosition.ON_SEGMENT ||a23 == PointLinePosition.ON_SEGMENT || a31 == PointLinePosition.ON_SEGMENT)) {\n\t\t\tans = true;\n\t\t}\n\n\t\treturn ans;\n\t}", "public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}", "private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) {\n\t\tif (logger.isTraceEnabled()) {\n\t\t\tlogger.trace(String.format(\"%s received %s\", ctx.channel(), frame.text()));\n\t\t}\n\n\t\taddTraceForFrame(frame, \"text\");\n\t\tctx.channel().write(new TextWebSocketFrame(\"Echo: \" + frame.text()));\n\t}", "public static String movePath( final String file,\n final String target ) {\n final String name = new File(file).getName();\n return target.endsWith(\"/\") ? target + name : target + '/' + name;\n }", "public static String getTextContent(Document document, boolean individualTokens) {\n String textContent = null;\n if (individualTokens) {\n List<String> tokens = getTextTokens(document);\n textContent = StringUtils.join(tokens, \",\");\n } else {\n textContent =\n document.getDocumentElement().getTextContent().trim().replaceAll(\"\\\\s+\", \",\");\n }\n return textContent;\n }", "public void prepareFilter( float transition ) {\n try {\n method.invoke( filter, new Object[] { new Float( transition ) } );\n }\n catch ( Exception e ) {\n throw new IllegalArgumentException(\"Error setting value for property: \"+property);\n }\n\t}", "private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }", "public void setPadding(float padding, Layout.Axis axis) {\n OrientedLayout layout = null;\n switch(axis) {\n case X:\n layout = mShiftLayout;\n break;\n case Y:\n layout = mShiftLayout;\n break;\n case Z:\n layout = mStackLayout;\n break;\n }\n if (layout != null) {\n if (!equal(layout.getDividerPadding(axis), padding)) {\n layout.setDividerPadding(padding, axis);\n\n if (layout.getOrientationAxis() == axis) {\n requestLayout();\n }\n }\n }\n\n }" ]
Permanently deletes a trashed file. @param fileID the ID of the trashed folder to permanently delete.
[ "public void deleteFile(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }" ]
[ "@Override\n public AuthInterface getAuthInterface() {\n if (authInterface == null) {\n authInterface = new AuthInterface(apiKey, sharedSecret, transport);\n }\n return authInterface;\n }", "private String toSQLPattern(String attribute) {\n String pattern = attribute.replace(\"*\", \"%\");\n if (!pattern.startsWith(\"%\")) {\n pattern = \"%\" + pattern;\n }\n if (!pattern.endsWith(\"%\")) {\n pattern = pattern.concat(\"%\");\n }\n return pattern;\n }", "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 void setPath(int pathId, String path) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_ACTUAL_PATH + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, path);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "protected List<String> parseWords(String line) {\n List<String> words = new ArrayList<String>();\n boolean insideWord = !isSpace(line.charAt(0));\n int last = 0;\n for( int i = 0; i < line.length(); i++) {\n char c = line.charAt(i);\n\n if( insideWord ) {\n // see if its at the end of a word\n if( isSpace(c)) {\n words.add( line.substring(last,i) );\n insideWord = false;\n }\n } else {\n if( !isSpace(c)) {\n last = i;\n insideWord = true;\n }\n }\n }\n\n // if the line ended add the final word\n if( insideWord ) {\n words.add( line.substring(last));\n }\n return words;\n }", "public boolean getOverAllocated()\n {\n Boolean overallocated = (Boolean) getCachedValue(ResourceField.OVERALLOCATED);\n if (overallocated == null)\n {\n Number peakUnits = getPeakUnits();\n Number maxUnits = getMaxUnits();\n overallocated = Boolean.valueOf(NumberHelper.getDouble(peakUnits) > NumberHelper.getDouble(maxUnits));\n set(ResourceField.OVERALLOCATED, overallocated);\n }\n return (overallocated.booleanValue());\n }", "public static void setTranslucentStatusFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);\n }\n }", "public ClientConfig setIdleConnectionTimeout(long idleConnectionTimeout, TimeUnit unit) {\n if (idleConnectionTimeout <= 0) {\n this.idleConnectionTimeoutMs = -1;\n } else {\n if(unit.toMinutes(idleConnectionTimeout) < 10) {\n throw new IllegalArgumentException(\"idleConnectionTimeout should be minimum of 10 minutes\");\n }\n this.idleConnectionTimeoutMs = unit.toMillis(idleConnectionTimeout);\n }\n return this;\n }", "public PayloadBuilder sound(final String sound) {\n if (sound != null) {\n aps.put(\"sound\", sound);\n } else {\n aps.remove(\"sound\");\n }\n return this;\n }" ]
Takes a String and converts it to a Date @param dateString the date @return Date denoted by dateString
[ "public Date toDate(String dateString) {\n Date date = null;\n DateFormat df = new SimpleDateFormat(\"yyyy-MM-dd\");\n try {\n date = df.parse(dateString);\n } catch (ParseException ex) {\n System.out.println(ex.fillInStackTrace());\n }\n return date;\n }" ]
[ "public static sslcipher_individualcipher_binding[] get(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static final Priority parsePriority(BigInteger priority)\n {\n return (priority == null ? null : Priority.getInstance(priority.intValue()));\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 }", "private static Class<?> getRawClass(Type type) {\n if (type instanceof Class) {\n return (Class<?>) type;\n }\n if (type instanceof ParameterizedType) {\n return getRawClass(((ParameterizedType) type).getRawType());\n }\n // For TypeVariable and WildcardType, returns the first upper bound.\n if (type instanceof TypeVariable) {\n return getRawClass(((TypeVariable) type).getBounds()[0]);\n }\n if (type instanceof WildcardType) {\n return getRawClass(((WildcardType) type).getUpperBounds()[0]);\n }\n if (type instanceof GenericArrayType) {\n Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());\n return Array.newInstance(componentClass, 0).getClass();\n }\n // This shouldn't happen as we captured all implementations of Type above (as or Java 8)\n throw new IllegalArgumentException(\"Unsupported type \" + type + \" of type class \" + type.getClass());\n }", "public static <T> OptionalValue<T> ofNullable(T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);\n }", "private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,\n\t\t\tQueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {\n\t\tJoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);\n\t\tif (localColumnName == null) {\n\t\t\tmatchJoinedFields(joinInfo, joinedQueryBuilder);\n\t\t} else {\n\t\t\tmatchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);\n\t\t}\n\t\tif (joinList == null) {\n\t\t\tjoinList = new ArrayList<JoinInfo>();\n\t\t}\n\t\tjoinList.add(joinInfo);\n\t}", "public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) {\n Preconditions.checkArgumentNotNull(target, \"target\");\n boolean modified = false;\n while (iterator.hasNext()) {\n modified |= target.add(iterator.next());\n }\n return modified;\n }", "@SuppressWarnings(\"unchecked\")\n\tpublic static Type getSuperclassTypeParameter(Class<?> subclass) {\n\t\tType superclass = subclass.getGenericSuperclass();\n\t\tif (superclass instanceof Class) {\n\t\t\tthrow new RuntimeException(\"Missing type parameter.\");\n\t\t}\n\t\treturn ((ParameterizedType) superclass).getActualTypeArguments()[0];\n\t}", "protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tboolean tryAgain = false;\r\n\t\tConnection result = null;\r\n\t\tConnection oldRawConnection = connectionHandle.getInternalConnection();\r\n\t\tString url = this.getConfig().getJdbcUrl();\r\n\t\t\r\n\t\tint acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts();\r\n\t\tlong acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs();\r\n\t\tAcquireFailConfig acquireConfig = new AcquireFailConfig();\r\n\t\tacquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));\r\n\t\tacquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs);\r\n\t\tacquireConfig.setLogMessage(\"Failed to acquire connection to \"+url);\r\n\t\tConnectionHook connectionHook = this.getConfig().getConnectionHook();\r\n\t\tdo{ \r\n\t\t\tresult = null;\r\n\t\t\ttry { \r\n\t\t\t\t// keep track of this hook.\r\n\t\t\t\tresult = this.obtainRawInternalConnection();\r\n\t\t\t\ttryAgain = false;\r\n\r\n\t\t\t\tif (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){\r\n\t\t\t\t\tlogger.info(\"Successfully re-established connection to \"+url);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tthis.getDbIsDown().set(false);\r\n\t\t\t\t\r\n\t\t\t\tconnectionHandle.setInternalConnection(result);\r\n\t\t\t\t\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\tconnectionHook.onAcquire(connectionHandle);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t\tConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL());\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\ttryAgain = connectionHook.onAcquireFail(e, acquireConfig);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlogger.error(String.format(\"Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d\", url, acquireRetryDelayInMs, acquireRetryAttempts), e);\r\n\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (acquireRetryAttempts > 0){\r\n\t\t\t\t\t\t\tThread.sleep(acquireRetryDelayInMs);\r\n\t \t\t\t\t\t}\r\n\t\t\t\t\t\ttryAgain = (acquireRetryAttempts--) > 0;\r\n\t\t\t\t\t} catch (InterruptedException e1) {\r\n\t\t\t\t\t\ttryAgain=false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (!tryAgain){\r\n\t\t\t\t\tif (oldRawConnection != null) {\r\n\t\t\t\t\t\toldRawConnection.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (result != null) {\r\n\t\t\t\t\t\tresult.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconnectionHandle.setInternalConnection(oldRawConnection);\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} while (tryAgain);\r\n\r\n\t\treturn result;\r\n\r\n\t}" ]
Create the Grid Point style.
[ "static Style get(final GridParam params) {\n final StyleBuilder builder = new StyleBuilder();\n\n final Symbolizer pointSymbolizer = crossSymbolizer(\"shape://plus\", builder, CROSS_SIZE,\n params.gridColor);\n final Style style = builder.createStyle(pointSymbolizer);\n final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();\n\n if (params.haloRadius > 0.0) {\n Symbolizer halo = crossSymbolizer(\"cross\", builder, CROSS_SIZE + params.haloRadius * 2.0,\n params.haloColor);\n symbolizers.add(0, halo);\n }\n\n return style;\n }" ]
[ "private static String getColumnTitle(final PropertyDescriptor _property) {\n final StringBuilder buffer = new StringBuilder();\n final String name = _property.getName();\n buffer.append(Character.toUpperCase(name.charAt(0)));\n for (int i = 1; i < name.length(); i++) {\n final char c = name.charAt(i);\n if (Character.isUpperCase(c)) {\n buffer.append(' ');\n }\n buffer.append(c);\n }\n return buffer.toString();\n }", "public static String getExtensionByMimeType(String type) {\n MimeTypes types = getDefaultMimeTypes();\n try {\n return types.forName(type).getExtension();\n } catch (Exception e) {\n LOGGER.warn(\"Can't detect extension for MIME-type \" + type, e);\n return \"\";\n }\n }", "private AffineTransform getAlignmentTransform() {\n final int offsetX;\n switch (this.settings.getParams().getAlign()) {\n case LEFT:\n offsetX = 0;\n break;\n case RIGHT:\n offsetX = this.settings.getMaxSize().width - this.settings.getSize().width;\n break;\n case CENTER:\n default:\n offsetX = (int) Math\n .floor(this.settings.getMaxSize().width / 2.0 - this.settings.getSize().width / 2.0);\n break;\n }\n\n final int offsetY;\n switch (this.settings.getParams().getVerticalAlign()) {\n case TOP:\n offsetY = 0;\n break;\n case BOTTOM:\n offsetY = this.settings.getMaxSize().height - this.settings.getSize().height;\n break;\n case MIDDLE:\n default:\n offsetY = (int) Math.floor(this.settings.getMaxSize().height / 2.0 -\n this.settings.getSize().height / 2.0);\n break;\n }\n\n return AffineTransform.getTranslateInstance(Math.round(offsetX), Math.round(offsetY));\n }", "@Override\n public Set<String> getProviderNames() {\n Set<String> result = new HashSet<>();\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n result.add(prov.getProviderName());\n } catch (Exception e) {\n Logger.getLogger(Monetary.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n return result;\n }", "@Override\r\n public String upload(byte[] data, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(data);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public Object getRealKey()\r\n {\r\n if(keyRealSubject != null)\r\n {\r\n return keyRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareKeyRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareKeyRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise key with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return keyRealSubject;\r\n }", "private Map<String, Class<? extends RulePhase>> loadPhases()\n {\n Map<String, Class<? extends RulePhase>> phases;\n phases = new HashMap<>();\n Furnace furnace = FurnaceHolder.getFurnace();\n for (RulePhase phase : furnace.getAddonRegistry().getServices(RulePhase.class))\n {\n @SuppressWarnings(\"unchecked\")\n Class<? extends RulePhase> unwrappedClass = (Class<? extends RulePhase>) Proxies.unwrap(phase).getClass();\n String simpleName = unwrappedClass.getSimpleName();\n phases.put(classNameToMapKey(simpleName), unwrappedClass);\n }\n return Collections.unmodifiableMap(phases);\n }", "public static void main(String[] args) {\r\n try {\r\n TreeFactory tf = new LabeledScoredTreeFactory();\r\n Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), \"UTF-8\"));\r\n TreeReader tr = new PennTreeReader(r, tf);\r\n Tree t = tr.readTree();\r\n while (t != null) {\r\n System.out.println(t);\r\n System.out.println();\r\n t = tr.readTree();\r\n }\r\n r.close();\r\n } catch (IOException ioe) {\r\n ioe.printStackTrace();\r\n }\r\n }", "public boolean hasDeploymentSubsystemModel(final String subsystemName) {\n final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);\n final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);\n return root.hasChild(subsystem);\n }" ]
Use this API to unset the properties of inatparam resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "public static base_response unset(nitro_service client, responderpolicy resource, String[] args) throws Exception{\n\t\tresponderpolicy unsetresource = new responderpolicy();\n\t\tunsetresource.name = resource.name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) {\n\t\tArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1);\n\t\tfactories.addAll(this.factories);\n\t\tfactories.add(0, factory);\n\t\treturn new ProductFactoryCascade<>(factories);\n\t}", "@IntRange(from = 0, to = OPAQUE)\n private static int resolveLineAlpha(\n @IntRange(from = 0, to = OPAQUE) final int sceneAlpha,\n final float maxDistance,\n final float distance) {\n final float alphaPercent = 1f - distance / maxDistance;\n final int alpha = (int) ((float) OPAQUE * alphaPercent);\n return alpha * sceneAlpha / OPAQUE;\n }", "private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }", "public BoxFileUploadSessionPartList listParts(int offset, int limit) {\n URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint();\n URLTemplate template = new URLTemplate(listPartsURL.toString());\n\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(OFFSET_QUERY_STRING, offset);\n String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString();\n\n //Template is initalized with the full URL. So empty string for the path.\n URL url = template.buildWithQuery(\"\", queryString);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n return new BoxFileUploadSessionPartList(jsonObject);\n }", "public void authenticate() {\n URL url;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String jwtAssertion = this.constructJWTAssertion();\n\n String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException ex) {\n // Use the Date advertised by the Box server as the current time to synchronize clocks\n List<String> responseDates = ex.getHeaders().get(\"Date\");\n NumericDate currentTime;\n if (responseDates != null) {\n String responseDate = responseDates.get(0);\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, d MMM yyyy HH:mm:ss zzz\");\n try {\n Date date = dateFormat.parse(responseDate);\n currentTime = NumericDate.fromMilliseconds(date.getTime());\n } catch (ParseException e) {\n currentTime = NumericDate.now();\n }\n } else {\n currentTime = NumericDate.now();\n }\n\n // Reconstruct the JWT assertion, which regenerates the jti claim, with the new \"current\" time\n jwtAssertion = this.constructJWTAssertion(currentTime);\n urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n // Re-send the updated request\n request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.setAccessToken(jsonObject.get(\"access_token\").asString());\n this.setLastRefresh(System.currentTimeMillis());\n this.setExpires(jsonObject.get(\"expires_in\").asLong() * 1000);\n\n //if token cache is specified, save to cache\n if (this.accessTokenCache != null) {\n String key = this.getAccessTokenCacheKey();\n JsonObject accessTokenCacheInfo = new JsonObject()\n .add(\"accessToken\", this.getAccessToken())\n .add(\"lastRefresh\", this.getLastRefresh())\n .add(\"expires\", this.getExpires());\n\n this.accessTokenCache.put(key, accessTokenCacheInfo.toString());\n }\n }", "public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }", "public static void block(DMatrix1Row A , DMatrix1Row A_tran ,\n final int blockLength )\n {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int blockHeight = Math.min( blockLength , A.numRows - i);\n\n int indexSrc = i*A.numCols;\n int indexDst = i;\n\n for( int j = 0; j < A.numCols; j += blockLength ) {\n int blockWidth = Math.min( blockLength , A.numCols - j);\n\n// int indexSrc = i*A.numCols + j;\n// int indexDst = j*A_tran.numCols + i;\n\n int indexSrcEnd = indexSrc + blockWidth;\n// for( int l = 0; l < blockWidth; l++ , indexSrc++ ) {\n for( ; indexSrc < indexSrcEnd; indexSrc++ ) {\n int rowSrc = indexSrc;\n int rowDst = indexDst;\n int end = rowDst + blockHeight;\n// for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) {\n for( ; rowDst < end; rowSrc += A.numCols ) {\n // faster to write in sequence than to read in sequence\n A_tran.data[ rowDst++ ] = A.data[ rowSrc ];\n }\n indexDst += A_tran.numCols;\n }\n }\n }\n }", "public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) {\n this.downloadRange(output, rangeStart, rangeEnd, null);\n }" ]
Extent aware Delete by Query @param query @param cld @throws PersistenceBrokerException
[ "private void deleteByQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n logger.debug(\"deleteByQuery \" + cld.getClassNameOfObject() + \", \" + query);\n }\n\n if (query instanceof QueryBySQL)\n {\n String sql = ((QueryBySQL) query).getSql();\n this.dbAccess.executeUpdateSQL(sql, cld);\n }\n else\n {\n // if query is Identity based transform it to a criteria based query first\n if (query instanceof QueryByIdentity)\n {\n QueryByIdentity qbi = (QueryByIdentity) query;\n Object oid = qbi.getExampleObject();\n // make sure it's an Identity\n if (!(oid instanceof Identity))\n {\n oid = serviceIdentity().buildIdentity(oid);\n }\n query = referencesBroker.getPKQuery((Identity) oid);\n }\n\n if (!cld.isInterface())\n {\n this.dbAccess.executeDelete(query, cld);\n }\n\n // if class is an extent, we have to delete all extent classes too\n String lastUsedTable = cld.getFullTableName();\n if (cld.isExtent())\n {\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (!extCld.getFullTableName().equals(lastUsedTable))\n {\n lastUsedTable = extCld.getFullTableName();\n this.dbAccess.executeDelete(query, extCld);\n }\n }\n }\n\n }\n }" ]
[ "public int[] getDefalutValuesArray() {\n int[] defaultValues = new int[5];\n\n defaultValues[0] = GLES20.GL_LINEAR_MIPMAP_NEAREST; // MIN FILTER\n defaultValues[1] = GLES20.GL_LINEAR; // MAG FILTER\n defaultValues[2] = 1; // ANISO FILTER\n defaultValues[3] = GLES20.GL_CLAMP_TO_EDGE; // WRAP S\n defaultValues[4] = GLES20.GL_CLAMP_TO_EDGE; // WRAP T\n\n return defaultValues;\n }", "@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }", "@Override\n\tpublic boolean addAll(Collection<? extends T> collection) {\n\t\tboolean changed = false;\n\t\tfor (T data : collection) {\n\t\t\ttry {\n\t\t\t\tif (addElement(data)) {\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not create data elements in dao\", e);\n\t\t\t}\n\t\t}\n\t\treturn changed;\n\t}", "public Duration getWork(Date startDate, Date endDate, TimeUnit format)\n {\n DateRange range = new DateRange(startDate, endDate);\n Long cachedResult = m_workingDateCache.get(range);\n long totalTime = 0;\n\n if (cachedResult == null)\n {\n //\n // We want the start date to be the earliest date, and the end date\n // to be the latest date. Set a flag here to indicate if we have swapped\n // the order of the supplied date.\n //\n boolean invert = false;\n if (startDate.getTime() > endDate.getTime())\n {\n invert = true;\n Date temp = startDate;\n startDate = endDate;\n endDate = temp;\n }\n\n Date canonicalStartDate = DateHelper.getDayStartDate(startDate);\n Date canonicalEndDate = DateHelper.getDayStartDate(endDate);\n\n if (canonicalStartDate.getTime() == canonicalEndDate.getTime())\n {\n ProjectCalendarDateRanges ranges = getRanges(startDate, null, null);\n if (ranges.getRangeCount() != 0)\n {\n totalTime = getTotalTime(ranges, startDate, endDate);\n }\n }\n else\n {\n //\n // Find the first working day in the range\n //\n Date currentDate = startDate;\n Calendar cal = Calendar.getInstance();\n cal.setTime(startDate);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n while (isWorkingDate(currentDate, day) == false && currentDate.getTime() < canonicalEndDate.getTime())\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n }\n\n if (currentDate.getTime() < canonicalEndDate.getTime())\n {\n //\n // Calculate the amount of working time for this day\n //\n totalTime += getTotalTime(getRanges(currentDate, null, day), currentDate, true);\n\n //\n // Process each working day until we reach the last day\n //\n while (true)\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n\n //\n // We have reached the last day\n //\n if (currentDate.getTime() >= canonicalEndDate.getTime())\n {\n break;\n }\n\n //\n // Skip this day if it has no working time\n //\n ProjectCalendarDateRanges ranges = getRanges(currentDate, null, day);\n if (ranges.getRangeCount() == 0)\n {\n continue;\n }\n\n //\n // Add the working time for the whole day\n //\n totalTime += getTotalTime(ranges);\n }\n }\n\n //\n // We are now at the last day\n //\n ProjectCalendarDateRanges ranges = getRanges(endDate, null, day);\n if (ranges.getRangeCount() != 0)\n {\n totalTime += getTotalTime(ranges, DateHelper.getDayStartDate(endDate), endDate);\n }\n }\n\n if (invert)\n {\n totalTime = -totalTime;\n }\n\n m_workingDateCache.put(range, Long.valueOf(totalTime));\n }\n else\n {\n totalTime = cachedResult.longValue();\n }\n\n return convertFormat(totalTime, format);\n }", "public ExtendedOutputStreamWriter append(double d) throws IOException {\n super.append(String.format(Locale.ROOT, doubleFormat, d));\n return this;\n }", "protected float getLayoutOffset() {\n //final int offsetSign = getOffsetSign();\n final float axisSize = getViewPortSize(getOrientationAxis());\n float layoutOffset = - axisSize / 2;\n Log.d(LAYOUT, TAG, \"getLayoutOffset(): dimension: %5.2f, layoutOffset: %5.2f\",\n axisSize, layoutOffset);\n\n return layoutOffset;\n }", "public AccrueType getAccrueType(int field)\n {\n AccrueType result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = AccrueTypeUtility.getInstance(m_fields[field], m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "protected long getRevisionIdFromResponse(JsonNode response) throws JsonMappingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"API response is null\");\n\t\t}\n\t\tJsonNode entity = null;\n\t\tif(response.has(\"entity\")) {\n\t\t\tentity = response.path(\"entity\");\n\t\t} else if(response.has(\"pageinfo\")) {\n\t\t\tentity = response.path(\"pageinfo\");\n\t\t} \n\t\tif(entity != null && entity.has(\"lastrevid\")) {\n\t\t\treturn entity.path(\"lastrevid\").asLong();\n\t\t}\n\t\tthrow new JsonMappingException(\"The last revision id could not be found in API response\");\n\t}", "public static long count(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}" ]
Convert to IPv6 EUI-64 section http://standards.ieee.org/develop/regauth/tut/eui64.pdf @param asMAC if true, this address is considered MAC and the EUI-64 is extended using ff-ff, otherwise this address is considered EUI-48 and extended using ff-fe Note that IPv6 treats MAC as EUI-48 and extends MAC to IPv6 addresses using ff-fe @return
[ "public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}" ]
[ "private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes,\tComponent component) {\n Long currentTimeOfComponent = 0L;\n String key = component.getComponentType();\n if (mapComponentTimes.containsKey(key)) {\n currentTimeOfComponent = mapComponentTimes.get(key);\n }\n //when transactions are run in parallel, we should log the longest transaction only to avoid that \n //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms \n Long maxTime = Math.max(component.getTime(), currentTimeOfComponent);\n mapComponentTimes.put(key, maxTime);\n }", "public static <X> ServiceTypeLoader<X> load(Class<X> serviceType) {\n return load(serviceType, Thread.currentThread().getContextClassLoader());\n }", "public static CustomInfo getOrCreateCustomInfo(Message message) {\n CustomInfo customInfo = message.get(CustomInfo.class);\n if (customInfo == null) {\n customInfo = new CustomInfo();\n message.put(CustomInfo.class, customInfo);\n }\n return customInfo;\n }", "protected final <T> StyleSupplier<T> createStyleSupplier(\n final Template template,\n final String styleRef) {\n return new StyleSupplier<T>() {\n @Override\n public Style load(\n final MfClientHttpRequestFactory requestFactory,\n final T featureSource) {\n final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser;\n return OptionalUtils.or(\n () -> template.getStyle(styleRef),\n () -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef))\n .orElse(template.getConfiguration().getDefaultStyle(NAME));\n }\n };\n }", "private void writeAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n Project.Assignments.Assignment.ExtendedAttribute attrib;\n List<Project.Assignments.Assignment.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (AssignmentField mpxFieldID : getAllAssignmentExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPAssignmentField.getID(mpxFieldID) | MPPAssignmentField.ASSIGNMENT_FIELD_BASE);\n\n attrib = m_factory.createProjectAssignmentsAssignmentExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }", "public static Organization createOrganization(final String name){\n final Organization organization = new Organization();\n organization.setName(name);\n\n return organization;\n\n }", "public void waitForAsyncFlush() {\n long numAdded = asyncBatchesAdded.get();\n\n synchronized (this) {\n while (numAdded > asyncBatchesProcessed) {\n try {\n wait();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\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 }", "public Archetype parse(String adl) {\n try {\n return parse(new StringReader(adl));\n } catch (IOException e) {\n // StringReader should never throw an IOException\n throw new AssertionError(e);\n }\n }" ]
This method is called when the locale of the parent file is updated. It resets the locale specific currency attributes to the default values for the new locale. @param properties project properties @param locale new locale
[ "public static void setLocale(ProjectProperties properties, Locale locale)\n {\n properties.setMpxDelimiter(LocaleData.getChar(locale, LocaleData.FILE_DELIMITER));\n properties.setMpxProgramName(LocaleData.getString(locale, LocaleData.PROGRAM_NAME));\n properties.setMpxCodePage((CodePage) LocaleData.getObject(locale, LocaleData.CODE_PAGE));\n\n properties.setCurrencySymbol(LocaleData.getString(locale, LocaleData.CURRENCY_SYMBOL));\n properties.setSymbolPosition((CurrencySymbolPosition) LocaleData.getObject(locale, LocaleData.CURRENCY_SYMBOL_POSITION));\n properties.setCurrencyDigits(LocaleData.getInteger(locale, LocaleData.CURRENCY_DIGITS));\n properties.setThousandsSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_THOUSANDS_SEPARATOR));\n properties.setDecimalSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_DECIMAL_SEPARATOR));\n\n properties.setDateOrder((DateOrder) LocaleData.getObject(locale, LocaleData.DATE_ORDER));\n properties.setTimeFormat((ProjectTimeFormat) LocaleData.getObject(locale, LocaleData.TIME_FORMAT));\n properties.setDefaultStartTime(DateHelper.getTimeFromMinutesPastMidnight(LocaleData.getInteger(locale, LocaleData.DEFAULT_START_TIME)));\n properties.setDateSeparator(LocaleData.getChar(locale, LocaleData.DATE_SEPARATOR));\n properties.setTimeSeparator(LocaleData.getChar(locale, LocaleData.TIME_SEPARATOR));\n properties.setAMText(LocaleData.getString(locale, LocaleData.AM_TEXT));\n properties.setPMText(LocaleData.getString(locale, LocaleData.PM_TEXT));\n properties.setDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n properties.setBarTextDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT));\n }" ]
[ "private String escapeQuotes(String value)\n {\n StringBuilder sb = new StringBuilder();\n int length = value.length();\n char c;\n\n sb.append('\"');\n for (int index = 0; index < length; index++)\n {\n c = value.charAt(index);\n sb.append(c);\n\n if (c == '\"')\n {\n sb.append('\"');\n }\n }\n sb.append('\"');\n\n return (sb.toString());\n }", "public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }", "private int[] readTypeAnnotations(final MethodVisitor mv,\n final Context context, int u, boolean visible) {\n char[] c = context.buffer;\n int[] offsets = new int[readUnsignedShort(u)];\n u += 2;\n for (int i = 0; i < offsets.length; ++i) {\n offsets[i] = u;\n int target = readInt(u);\n switch (target >>> 24) {\n case 0x00: // CLASS_TYPE_PARAMETER\n case 0x01: // METHOD_TYPE_PARAMETER\n case 0x16: // METHOD_FORMAL_PARAMETER\n u += 2;\n break;\n case 0x13: // FIELD\n case 0x14: // METHOD_RETURN\n case 0x15: // METHOD_RECEIVER\n u += 1;\n break;\n case 0x40: // LOCAL_VARIABLE\n case 0x41: // RESOURCE_VARIABLE\n for (int j = readUnsignedShort(u + 1); j > 0; --j) {\n int start = readUnsignedShort(u + 3);\n int length = readUnsignedShort(u + 5);\n createLabel(start, context.labels);\n createLabel(start + length, context.labels);\n u += 6;\n }\n u += 3;\n break;\n case 0x47: // CAST\n case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT\n case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT\n case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT\n case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT\n u += 4;\n break;\n // case 0x10: // CLASS_EXTENDS\n // case 0x11: // CLASS_TYPE_PARAMETER_BOUND\n // case 0x12: // METHOD_TYPE_PARAMETER_BOUND\n // case 0x17: // THROWS\n // case 0x42: // EXCEPTION_PARAMETER\n // case 0x43: // INSTANCEOF\n // case 0x44: // NEW\n // case 0x45: // CONSTRUCTOR_REFERENCE\n // case 0x46: // METHOD_REFERENCE\n default:\n u += 3;\n break;\n }\n int pathLength = readByte(u);\n if ((target >>> 24) == 0x42) {\n TypePath path = pathLength == 0 ? null : new TypePath(b, u);\n u += 1 + 2 * pathLength;\n u = readAnnotationValues(u + 2, c, true,\n mv.visitTryCatchAnnotation(target, path,\n readUTF8(u, c), visible));\n } else {\n u = readAnnotationValues(u + 3 + 2 * pathLength, c, true, null);\n }\n }\n return offsets;\n }", "public static String stringifyJavascriptObject(Object object) {\n StringBuilder bld = new StringBuilder();\n stringify(object, bld);\n return bld.toString();\n }", "public static void main(String[] args) {\n String modelFile = \"\";\n String outputFile = \"\";\n int numberOfRows = 0;\n try {\n modelFile = args[0];\n outputFile = args[1];\n numberOfRows = Integer.valueOf(args[2]);\n } catch (IndexOutOfBoundsException | NumberFormatException e) {\n System.out.println(\"ERROR! Invalid command line arguments, expecting: <scxml model file> \"\n + \"<desired csv output file> <desired number of output rows>\");\n return;\n }\n\n FileInputStream model = null;\n try {\n model = new FileInputStream(modelFile);\n } catch (FileNotFoundException e) {\n System.out.println(\"ERROR! Model file not found\");\n return;\n }\n\n SCXMLEngine engine = new SCXMLEngine();\n engine.setModelByInputFileStream(model);\n engine.setBootstrapMin(5);\n\n DataConsumer consumer = new DataConsumer();\n CSVFileWriter writer;\n try {\n writer = new CSVFileWriter(outputFile);\n } catch (IOException e) {\n System.out.println(\"ERROR! Can not write to output csv file\");\n return;\n }\n consumer.addDataWriter(writer);\n\n DefaultDistributor dist = new DefaultDistributor();\n dist.setThreadCount(5);\n dist.setMaxNumberOfLines(numberOfRows);\n dist.setDataConsumer(consumer);\n\n engine.process(dist);\n writer.closeCSVFile();\n\n System.out.println(\"COMPLETE!\");\n }", "public static final String printWorkGroup(WorkGroup value)\n {\n return (Integer.toString(value == null ? WorkGroup.DEFAULT.getValue() : value.getValue()));\n }", "public static final Date getFinishDate(byte[] data, int offset)\n {\n Date result;\n long days = getShort(data, offset);\n\n if (days == 0x8000)\n {\n result = null;\n }\n else\n {\n result = DateHelper.getDateFromLong(EPOCH + ((days - 1) * DateHelper.MS_PER_DAY));\n }\n\n return (result);\n }", "private static void addRedeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String deploymentName = deployment.getName();\n final Set<String> serverGroups = deployment.getServerGroups();\n if (serverGroups.isEmpty()) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(DEPLOYMENT, deploymentName)));\n } else {\n for (String serverGroup : serverGroups) {\n builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, deploymentName)));\n }\n }\n }", "private GraphicalIndicatorCriteria processCriteria(FieldType type)\n {\n GraphicalIndicatorCriteria criteria = new GraphicalIndicatorCriteria(m_properties);\n criteria.setLeftValue(type);\n\n int indicatorType = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setIndicator(indicatorType);\n\n if (m_dataOffset + 4 < m_data.length)\n {\n int operatorValue = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n TestOperator operator = (operatorValue == 0 ? TestOperator.IS_ANY_VALUE : TestOperator.getInstance(operatorValue - 0x3E7));\n criteria.setOperator(operator);\n\n if (operator != TestOperator.IS_ANY_VALUE)\n {\n processOperandValue(0, type, criteria);\n\n if (operator == TestOperator.IS_WITHIN || operator == TestOperator.IS_NOT_WITHIN)\n {\n processOperandValue(1, type, criteria);\n }\n }\n }\n\n return (criteria);\n }" ]
Performs a variety of tests to see if the provided matrix is a valid covariance matrix. @return 0 = is valid 1 = failed positive diagonal, 2 = failed on symmetry, 2 = failed on positive definite
[ "public static int isValid( DMatrixRMaj cov ) {\n if( !MatrixFeatures_DDRM.isDiagonalPositive(cov) )\n return 1;\n\n if( !MatrixFeatures_DDRM.isSymmetric(cov,TOL) )\n return 2;\n\n if( !MatrixFeatures_DDRM.isPositiveSemidefinite(cov) )\n return 3;\n\n return 0;\n }" ]
[ "public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\n }", "private String 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 dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }", "public static int[] toInt(double[] array) {\n int[] n = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (int) array[i];\n }\n return n;\n }", "public static double blackScholesOptionTheta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate theta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble theta = volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue + riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn theta;\n\t\t}\n\t}", "public Step createRootStep() {\n return new Step()\n .withName(\"Root step\")\n .withTitle(\"Allure step processing error: if you see this step something went wrong.\")\n .withStart(System.currentTimeMillis())\n .withStatus(Status.BROKEN);\n }", "private boolean moreDates(Calendar calendar, List<Date> dates)\n {\n boolean result;\n if (m_finishDate == null)\n {\n int occurrences = NumberHelper.getInt(m_occurrences);\n if (occurrences < 1)\n {\n occurrences = 1;\n }\n result = dates.size() < occurrences;\n }\n else\n {\n result = calendar.getTimeInMillis() <= m_finishDate.getTime();\n }\n return result;\n }", "@Override\n protected void checkType() {\n if (!isDependent() && getEnhancedAnnotated().isParameterizedType()) {\n throw BeanLogger.LOG.managedBeanWithParameterizedBeanClassMustBeDependent(type);\n }\n boolean passivating = beanManager.isPassivatingScope(getScope());\n if (passivating && !isPassivationCapableBean()) {\n if (!getEnhancedAnnotated().isSerializable()) {\n throw BeanLogger.LOG.passivatingBeanNeedsSerializableImpl(this);\n } else if (hasDecorators() && !allDecoratorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableDecorator(this, getFirstNonPassivationCapableDecorator());\n } else if (hasInterceptors() && !allInterceptorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableInterceptor(this, getFirstNonPassivationCapableInterceptor());\n }\n }\n }", "private String[] readXMLDeclaration(Reader r) throws KNXMLException\r\n\t{\r\n\t\tfinal StringBuffer buf = new StringBuffer(100);\r\n\t\ttry {\r\n\t\t\tfor (int c = 0; (c = r.read()) != -1 && c != '?';)\r\n\t\t\t\tbuf.append((char) c);\r\n\t\t}\r\n\t\tcatch (final IOException e) {\r\n\t\t\tthrow new KNXMLException(\"reading XML declaration, \" + e.getMessage(), buf\r\n\t\t\t\t.toString(), 0);\r\n\t\t}\r\n\t\tString s = buf.toString().trim();\r\n\r\n\t\tString version = null;\r\n\t\tString encoding = null;\r\n\t\tString standalone = null;\r\n\r\n\t\tfor (int state = 0; state < 3; ++state)\r\n\t\t\tif (state == 0 && s.startsWith(\"version\")) {\r\n\t\t\t\tversion = getAttValue(s = s.substring(7));\r\n\t\t\t\ts = s.substring(s.indexOf(version) + version.length() + 1).trim();\r\n\t\t\t}\r\n\t\t\telse if (state == 1 && s.startsWith(\"encoding\")) {\r\n\t\t\t\tencoding = getAttValue(s = s.substring(8));\r\n\t\t\t\ts = s.substring(s.indexOf(encoding) + encoding.length() + 1).trim();\r\n\t\t\t}\r\n\t\t\telse if (state == 1 || state == 2) {\r\n\t\t\t\tif (s.startsWith(\"standalone\")) {\r\n\t\t\t\t\tstandalone = getAttValue(s);\r\n\t\t\t\t\tif (!standalone.equals(\"yes\") && !standalone.equals(\"no\"))\r\n\t\t\t\t\t\tthrow new KNXMLException(\"invalid standalone pseudo-attribute\",\r\n\t\t\t\t\t\t\tstandalone, 0);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tthrow new KNXMLException(\"unknown XML declaration pseudo-attribute\", s, 0);\r\n\t\treturn new String[] { version, encoding, standalone };\r\n\t}" ]
Returns the organization of a given module @return Organization
[ "public Organization getModuleOrganization(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModuleOrganizationPath(moduleName, moduleVersion));\n final ClientResponse response = resource\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get module's organization\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(Organization.class);\n\n }" ]
[ "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public static appfwsignatures get(nitro_service service, String name) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tobj.set_name(name);\n\t\tappfwsignatures response = (appfwsignatures) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setDirectory(final String directory) {\n this.directory = new File(this.configuration.getDirectory(), directory);\n if (!this.directory.exists()) {\n throw new IllegalArgumentException(String.format(\n \"Directory does not exist: %s.\\n\" +\n \"Configuration contained value %s which is supposed to be relative to \" +\n \"configuration directory.\",\n this.directory, directory));\n }\n\n if (!this.directory.getAbsolutePath()\n .startsWith(this.configuration.getDirectory().getAbsolutePath())) {\n throw new IllegalArgumentException(String.format(\n \"All files and directories must be contained in the configuration directory the \" +\n \"directory provided in the configuration breaks that contract: %s in config \" +\n \"file resolved to %s.\",\n directory, this.directory));\n }\n }", "public void insert(Platform platform, Database model, int batchSize) throws SQLException\r\n {\r\n if (batchSize <= 1)\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n platform.insert(model, (DynaBean)it.next());\r\n }\r\n }\r\n else\r\n {\r\n for (int startIdx = 0; startIdx < _beans.size(); startIdx += batchSize)\r\n {\r\n platform.insert(model, _beans.subList(startIdx, startIdx + batchSize));\r\n }\r\n }\r\n }", "public static final String printPercent(Double value)\n {\n return value == null ? null : Double.toString(value.doubleValue() / 100.0);\n }", "public static Multimap<String, String> convertToMultiMap(final PObject objectParams) {\n Multimap<String, String> params = HashMultimap.create();\n if (objectParams != null) {\n Iterator<String> customParamsIter = objectParams.keys();\n while (customParamsIter.hasNext()) {\n String key = customParamsIter.next();\n if (objectParams.isArray(key)) {\n final PArray array = objectParams.optArray(key);\n for (int i = 0; i < array.size(); i++) {\n params.put(key, array.getString(i));\n }\n } else {\n params.put(key, objectParams.optString(key, \"\"));\n }\n }\n }\n\n return params;\n }", "public VerticalLayout getEmptyLayout() {\n\n m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey());\n setVisible(size() > 0);\n m_emptyLayout.setVisible(size() == 0);\n return m_emptyLayout;\n }", "private static void createDirectory(Path path) throws IOException {\n\t\ttry {\n\t\t\tFiles.createDirectory(path);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tif (!Files.isDirectory(path)) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}", "public SqlStatement getPreparedInsertStatement(ClassDescriptor cld)\r\n {\r\n SqlStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getInsertSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getInsertProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlInsertStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setInsertSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }" ]
We try to convert an Object to an Array and this is not easy in Java so we need a little bit of nasty magic. @param <T> Type of elements @param clazz Clazz of the Objct elements @param obj Object @return Array
[ "@SuppressWarnings({\"unchecked\", \"unused\"})\n public static <T> T[] object2Array(final Class<T> clazz, final Object obj) {\n return (T[]) obj;\n }" ]
[ "private Object readMetadataFromXML(InputSource source, Class target)\r\n throws MalformedURLException, ParserConfigurationException, SAXException, IOException\r\n {\r\n // TODO: make this configurable\r\n boolean validate = false;\r\n \r\n // get a xml reader instance:\r\n SAXParserFactory factory = SAXParserFactory.newInstance();\r\n log.info(\"RepositoryPersistor using SAXParserFactory : \" + factory.getClass().getName());\r\n if (validate)\r\n {\r\n factory.setValidating(true);\r\n }\r\n SAXParser p = factory.newSAXParser();\r\n XMLReader reader = p.getXMLReader();\r\n if (validate)\r\n {\r\n reader.setErrorHandler(new OJBErrorHandler());\r\n }\r\n\r\n Object result;\r\n if (DescriptorRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n DescriptorRepository repository = new DescriptorRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new RepositoryXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n result = repository;\r\n }\r\n else if (ConnectionRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n ConnectionRepository repository = new ConnectionRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n //LoggerFactory.getBootLogger().info(\"loading XML took \" + (stop - start) + \" msecs\");\r\n result = repository;\r\n }\r\n else\r\n throw new MetadataException(\"Could not build a repository instance for '\" + target +\r\n \"', using source \" + source);\r\n return result;\r\n }", "public static boolean checkVersionDirName(File versionDir) {\n return (versionDir.isDirectory() && versionDir.getName().contains(\"version-\") && !versionDir.getName()\n .endsWith(\".bak\"));\n }", "public X509Certificate getMappedCertificateForHostname(String hostname) throws CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException\n\t{\n\t\tString subject = getSubjectForHostname(hostname);\n\n\t\tString thumbprint = _subjectMap.get(subject);\n\n\t\tif(thumbprint == null) {\n\n\t\t\tKeyPair kp = getRSAKeyPair();\n\n\t\t\tX509Certificate newCert = CertificateCreator.generateStdSSLServerCertificate(kp.getPublic(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t getSigningCert(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t getSigningPrivateKey(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t subject);\n\n\t\t\taddCertAndPrivateKey(hostname, newCert, kp.getPrivate());\n\n\t\t\tthumbprint = ThumbprintUtil.getThumbprint(newCert);\n\n\t\t\t_subjectMap.put(subject, thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\n\t\t\treturn newCert;\n\n\t\t}\n return getCertificateByAlias(thumbprint);\n\n\n\t}", "public static boolean validate(final String ip) {\n Matcher matcher = pattern.matcher(ip);\n return matcher.matches();\n }", "private void setMasterTempo(double newTempo) {\n double oldTempo = Double.longBitsToDouble(masterTempo.getAndSet(Double.doubleToLongBits(newTempo)));\n if ((getTempoMaster() != null) && (Math.abs(newTempo - oldTempo) > getTempoEpsilon())) {\n // This is a change in tempo, so report it to any registered listeners, and update our metronome if we are synced.\n if (isSynced()) {\n metronome.setTempo(newTempo);\n notifyBeatSenderOfChange();\n }\n deliverTempoChangedAnnouncement(newTempo);\n }\n }", "@Override\r\n public V get(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V deltaResult = deltaMap.get(key);\r\n if (deltaResult == null) {\r\n return originalMap.get(key);\r\n }\r\n if (deltaResult == nullValue) {\r\n return null;\r\n }\r\n if (deltaResult == removedValue) {\r\n return null;\r\n }\r\n return deltaResult;\r\n }", "public WebSocketContext messageReceived(String receivedMessage) {\n this.stringMessage = S.string(receivedMessage).trim();\n isJson = stringMessage.startsWith(\"{\") || stringMessage.startsWith(\"]\");\n tryParseQueryParams();\n return this;\n }", "public static dnsglobal_binding get(nitro_service service) throws Exception{\n\t\tdnsglobal_binding obj = new dnsglobal_binding();\n\t\tdnsglobal_binding response = (dnsglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }" ]
ends the request and clears the cache. This can be called before the request is over, in which case the cache will be unavailable for the rest of the request.
[ "public static void endRequest() {\n final List<RequestScopedItem> result = CACHE.get();\n if (result != null) {\n CACHE.remove();\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }" ]
[ "static Style get(final GridParam params) {\n final StyleBuilder builder = new StyleBuilder();\n\n final Symbolizer pointSymbolizer = crossSymbolizer(\"shape://plus\", builder, CROSS_SIZE,\n params.gridColor);\n final Style style = builder.createStyle(pointSymbolizer);\n final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();\n\n if (params.haloRadius > 0.0) {\n Symbolizer halo = crossSymbolizer(\"cross\", builder, CROSS_SIZE + params.haloRadius * 2.0,\n params.haloColor);\n symbolizers.add(0, halo);\n }\n\n return style;\n }", "public static <ResultT> PollingState<ResultT> createFromPollingState(PollingState<?> other, ResultT result) {\n PollingState<ResultT> pollingState = new PollingState<>();\n pollingState.resource = result;\n pollingState.initialHttpMethod = other.initialHttpMethod();\n pollingState.status = other.status();\n pollingState.statusCode = other.statusCode();\n pollingState.azureAsyncOperationHeaderLink = other.azureAsyncOperationHeaderLink();\n pollingState.locationHeaderLink = other.locationHeaderLink();\n pollingState.putOrPatchResourceUri = other.putOrPatchResourceUri();\n pollingState.defaultRetryTimeout = other.defaultRetryTimeout;\n pollingState.retryTimeout = other.retryTimeout;\n pollingState.loggingContext = other.loggingContext;\n pollingState.finalStateVia = other.finalStateVia;\n return pollingState;\n }", "public List<BoxAPIResponse> execute(List<BoxAPIRequest> requests) {\n this.prepareRequest(requests);\n BoxJSONResponse batchResponse = (BoxJSONResponse) send();\n return this.parseResponse(batchResponse);\n }", "public static String common() {\n String common = SysProps.get(KEY_COMMON_CONF_TAG);\n if (S.blank(common)) {\n common = \"common\";\n }\n return common;\n }", "@Override\n public HandlerRegistration addChangeHandler(final ChangeHandler handler) {\n return getRangeInputElement().addDomHandler(handler, ChangeEvent.getType());\n }", "@Override\n\tpublic int compareTo(IPAddressString other) {\n\t\tif(this == other) {\n\t\t\treturn 0;\n\t\t}\n\t\tboolean isValid = isValid();\n\t\tboolean otherIsValid = other.isValid();\n\t\tif(!isValid && !otherIsValid) {\n\t\t\treturn toString().compareTo(other.toString());\n\t\t}\n\t\treturn addressProvider.providerCompare(other.addressProvider);\n\t}", "public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Iterables.contains(keys, input);\n\t\t\t}\n\t\t});\n\t}" ]
Stops all transitions.
[ "@Override\n public void stopTransition() {\n //call listeners so they can perform their actions first, like modifying this adapter's transitions\n for (int i = 0, size = mListenerList.size(); i < size; i++) {\n mListenerList.get(i).onTransitionEnd(this);\n }\n\n for (int i = 0, size = mTransitionList.size(); i < size; i++) {\n mTransitionList.get(i).stopTransition();\n }\n }" ]
[ "private void processChildTasks(Task parentTask) throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zparentactivity_=? and z_ent=? order by zorderinparentactivity\", parentTask.getUniqueID(), m_entityMap.get(\"Activity\"));\n for (Row row : rows)\n {\n Task task = parentTask.addTask();\n populateTask(row, task);\n processChildTasks(task);\n }\n }", "private void printStatistics(UsageStatistics usageStatistics,\n\t\t\tString entityLabel) {\n\t\tSystem.out.println(\"Processed \" + usageStatistics.count + \" \"\n\t\t\t\t+ entityLabel + \":\");\n\t\tSystem.out.println(\" * Labels: \" + usageStatistics.countLabels\n\t\t\t\t+ \", descriptions: \" + usageStatistics.countDescriptions\n\t\t\t\t+ \", aliases: \" + usageStatistics.countAliases);\n\t\tSystem.out.println(\" * Statements: \" + usageStatistics.countStatements\n\t\t\t\t+ \", with references: \"\n\t\t\t\t+ usageStatistics.countReferencedStatements);\n\t}", "private void updateToNextWorkStart(Calendar cal)\n {\n Date originalDate = cal.getTime();\n\n //\n // Find the date ranges for the current day\n //\n ProjectCalendarDateRanges ranges = getRanges(originalDate, cal, null);\n\n if (ranges != null)\n {\n //\n // Do we have a start time today?\n //\n Date calTime = DateHelper.getCanonicalTime(cal.getTime());\n Date startTime = null;\n for (DateRange range : ranges)\n {\n Date rangeStart = DateHelper.getCanonicalTime(range.getStart());\n Date rangeEnd = DateHelper.getCanonicalTime(range.getEnd());\n Date rangeStartDay = DateHelper.getDayStartDate(range.getStart());\n Date rangeEndDay = DateHelper.getDayStartDate(range.getEnd());\n\n if (rangeStartDay.getTime() != rangeEndDay.getTime())\n {\n rangeEnd = DateHelper.addDays(rangeEnd, 1);\n }\n\n if (calTime.getTime() < rangeEnd.getTime())\n {\n if (calTime.getTime() > rangeStart.getTime())\n {\n startTime = calTime;\n }\n else\n {\n startTime = rangeStart;\n }\n break;\n }\n }\n\n //\n // If we don't have a start time today - find the next working day\n // then retrieve the start time.\n //\n if (startTime == null)\n {\n Day day;\n int nonWorkingDayCount = 0;\n do\n {\n cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);\n day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n ++nonWorkingDayCount;\n if (nonWorkingDayCount > MAX_NONWORKING_DAYS)\n {\n cal.setTime(originalDate);\n break;\n }\n }\n while (!isWorkingDate(cal.getTime(), day));\n\n startTime = getStartTime(cal.getTime());\n }\n\n DateHelper.setTime(cal, startTime);\n }\n }", "private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException\n {\n net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();\n taskList.add(plannerTask);\n plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));\n plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));\n plannerTask.setName(getString(mpxjTask.getName()));\n plannerTask.setNote(mpxjTask.getNotes());\n plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));\n plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));\n plannerTask.setScheduling(getScheduling(mpxjTask.getType()));\n plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));\n if (mpxjTask.getMilestone())\n {\n plannerTask.setType(\"milestone\");\n }\n else\n {\n plannerTask.setType(\"normal\");\n }\n plannerTask.setWork(getDurationString(mpxjTask.getWork()));\n plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));\n\n ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();\n if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)\n {\n Constraint plannerConstraint = m_factory.createConstraint();\n plannerTask.setConstraint(plannerConstraint);\n if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)\n {\n plannerConstraint.setType(\"start-no-earlier-than\");\n }\n else\n {\n if (mpxjConstraintType == ConstraintType.MUST_START_ON)\n {\n plannerConstraint.setType(\"must-start-on\");\n }\n }\n\n plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));\n }\n\n //\n // Write predecessors\n //\n writePredecessors(mpxjTask, plannerTask);\n\n m_eventManager.fireTaskWrittenEvent(mpxjTask);\n\n //\n // Write child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();\n for (Task task : mpxjTask.getChildTasks())\n {\n writeTask(task, childTaskList);\n }\n }", "private ArrayTypeSignature getArrayTypeSignature(\r\n\t\t\tGenericArrayType genericArrayType) {\r\n\t\tFullTypeSignature componentTypeSignature = getFullTypeSignature(genericArrayType\r\n\t\t\t\t.getGenericComponentType());\r\n\t\tArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature(\r\n\t\t\t\tcomponentTypeSignature);\r\n\t\treturn arrayTypeSignature;\r\n\t}", "public OperationBuilder addInputStream(final InputStream in) {\n Assert.checkNotNullParam(\"in\", in);\n if (inputStreams == null) {\n inputStreams = new ArrayList<InputStream>();\n }\n inputStreams.add(in);\n return this;\n }", "public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}", "String checkVersion(String pluginName, String dependency, String requestedVersion, String availableVersion) {\n\t\tif (null == availableVersion) {\n\t\t\treturn \"Dependency \" + dependency + \" not found for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed.\\n\";\n\t\t}\n\t\tif (requestedVersion.startsWith(EXPR_START) || availableVersion.startsWith(EXPR_START)) {\n\t\t\treturn \"\";\n\t\t}\n\t\tVersion requested = new Version(requestedVersion);\n\t\tVersion available = new Version(availableVersion);\n\t\tif (requested.getMajor() != available.getMajor()) {\n\t\t\treturn \"Dependency \" + dependency + \" is provided in a incompatible API version for plug-in \" +\n\t\t\t\t\tpluginName + \", which requests version \" + requestedVersion +\n\t\t\t\t\t\", but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\tif (requested.after(available)) {\n\t\t\treturn \"Dependency \" + dependency + \" too old for \" + pluginName + \", version \" + requestedVersion +\n\t\t\t\t\t\" or higher needed, but version \" + availableVersion + \" supplied.\\n\";\n\t\t}\n\t\treturn \"\";\n\t}", "public void dumpKnownFieldMaps(Props props)\n {\n //for (int key=131092; key < 131098; key++)\n for (int key = 50331668; key < 50331674; key++)\n {\n byte[] fieldMapData = props.getByteArray(Integer.valueOf(key));\n if (fieldMapData != null)\n {\n System.out.println(\"KEY: \" + key);\n createFieldMap(fieldMapData);\n System.out.println(toString());\n clear();\n }\n }\n }" ]
Format the message using the pattern and the arguments. @param pattern the pattern in the format of "{1} this is a {2}" @param arguments the arguments. @return the formatted result.
[ "public static String format(String pattern, Object... arguments) {\n String msg = pattern;\n if (arguments != null) {\n for (int index = 0; index < arguments.length; index++) {\n msg = msg.replaceAll(\"\\\\{\" + (index + 1) + \"\\\\}\", String.valueOf(arguments[index]));\n }\n }\n return msg;\n }" ]
[ "public final void reset()\n {\n for (int i = 0; i < permutationIndices.length; i++)\n {\n permutationIndices[i] = i;\n }\n remainingPermutations = totalPermutations;\n }", "public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }", "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 }", "@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 }", "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\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 List<I_CmsFacetQueryItem> parseFacetQueryItems(JSONObject queryFacetObject) throws JSONException {\n\n JSONArray items = queryFacetObject.getJSONArray(JSON_KEY_QUERY_FACET_QUERY);\n List<I_CmsFacetQueryItem> result = new ArrayList<I_CmsFacetQueryItem>(items.length());\n for (int i = 0; i < items.length(); i++) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(items.getJSONObject(i));\n if (item != null) {\n result.add(item);\n }\n }\n return result;\n }", "public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){\n\t\tHazardCurve survivalProbabilities = new HazardCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tsurvivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn survivalProbabilities;\n\t}", "public static base_response update(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile updateresource = new dbdbprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.interpretquery = resource.interpretquery;\n\t\tupdateresource.stickiness = resource.stickiness;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.conmultiplex = resource.conmultiplex;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Returns the default safety level preference for the user. @see com.flickr4java.flickr.Flickr#SAFETYLEVEL_MODERATE @see com.flickr4java.flickr.Flickr#SAFETYLEVEL_RESTRICTED @see com.flickr4java.flickr.Flickr#SAFETYLEVEL_SAFE @return The current users safety-level @throws FlickrException
[ "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 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 }", "private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\n }", "private Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"ID\");\n String shifts = row.getString(\"SHIFTS\");\n map.put(workPatternID, createTimeEntryRowList(shifts));\n }\n return map;\n }", "public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }", "public void setResourceCalendar(ProjectCalendar calendar)\n {\n set(ResourceField.CALENDAR, calendar);\n if (calendar == null)\n {\n setResourceCalendarUniqueID(null);\n }\n else\n {\n calendar.setResource(this);\n setResourceCalendarUniqueID(calendar.getUniqueID());\n }\n }", "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static double checkDouble(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInDoubleRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), DOUBLE_MIN, DOUBLE_MAX);\n\t\t}\n\n\t\treturn number.doubleValue();\n\t}", "@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\n }" ]
Get prototype name. @return prototype name
[ "public String getPrototypeName() {\n\t\tString name = getClass().getName();\n\t\tif (name.startsWith(ORG_GEOMAJAS)) {\n\t\t\tname = name.substring(ORG_GEOMAJAS.length());\n\t\t}\n\t\tname = name.replace(\".dto.\", \".impl.\");\n\t\treturn name.substring(0, name.length() - 4) + \"Impl\";\n\t}" ]
[ "public static void resetNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).reset();\n\t}", "private Map<String, String> getLocaleProperties() {\n\n if (m_localeProperties == null) {\n m_localeProperties = CmsCollectionsGenericWrapper.createLazyMap(\n new CmsProperty.CmsPropertyLocaleTransformer(m_properties, m_locale));\n }\n return m_localeProperties;\n }", "public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }", "public String addPostRunDependent(FunctionalTaskItem dependentTaskItem) {\n IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem);\n this.addPostRunDependent(taskItem);\n return taskItem.key();\n }", "protected Patch createProcessedPatch(final Patch original) {\n\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n\n // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications\n return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);\n }", "public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }", "public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage,\n List<Versioned<V>> multiPutValues) {\n List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<V> value: multiPutValues) {\n Iterator<Versioned<V>> iter = valuesInStorage.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<V> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(obsolete) {\n // add to return value if obsolete\n obsoleteVals.add(value);\n } else {\n // else update the set of accepted versions\n valuesInStorage.add(value);\n }\n }\n\n return obsoleteVals;\n }", "public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Emits a sentence fragment combining all the merge actions.
[ "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 }" ]
[ "@Override\n\tprotected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\t// nothing to do\n\t}", "public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}", "private void stopAllServersAndRemoveCamelContext(CamelContext camelContext) {\n log.debug(\"Stopping all servers associated with {}\", camelContext);\n List<SingleBusLocatorRegistrar> registrars = locatorRegistrar.getAllRegistars(camelContext);\n registrars.forEach(registrar -> registrar.stopAllServersAndRemoveCamelContext());\n }", "public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\n }", "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 }", "protected void setBeanDeploymentArchivesAccessibility() {\n for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) {\n Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>();\n for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) {\n if (candidate.equals(beanDeploymentArchive)) {\n continue;\n }\n accessibleArchives.add(candidate);\n }\n beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives);\n }\n }", "public static TestCaseStartedEvent withExecutorInfo(TestCaseStartedEvent event) {\n event.getLabels().add(createHostLabel(getHostname()));\n event.getLabels().add(createThreadLabel(format(\"%s.%s(%s)\",\n ManagementFactory.getRuntimeMXBean().getName(),\n Thread.currentThread().getName(),\n Thread.currentThread().getId())\n ));\n return event;\n }", "public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }", "protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) {\n Session sess = this.getSession();\n if (sess != null) {\n String json;\n try {\n json = this.mapper.writeValueAsString(objectToSend);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Failed to serialize object\", e);\n }\n sess.getRemote().sendString(json, cb);\n }\n }" ]
Generic method used to create a field map from a block of data. @param data field map data
[ "private void createFieldMap(byte[] data)\n {\n int index = 0;\n int lastDataBlockOffset = 0;\n int dataBlockIndex = 0;\n\n while (index < data.length)\n {\n long mask = MPPUtility.getInt(data, index + 0);\n //mask = mask << 4;\n\n int dataBlockOffset = MPPUtility.getShort(data, index + 4);\n //int metaFlags = MPPUtility.getByte(data, index + 8);\n FieldType type = getFieldType(MPPUtility.getInt(data, index + 12));\n int category = MPPUtility.getShort(data, index + 20);\n //int sizeInBytes = MPPUtility.getShort(data, index + 22);\n //int metaIndex = MPPUtility.getInt(data, index + 24);\n\n //\n // Categories\n //\n // 02 - Short values [RATE_UNITS, WORKGROUP, ACCRUE, TIME_UNITS, PRIORITY, TASK_TYPE, CONSTRAINT, ACCRUE, PERCENTAGE, SHORT, WORK_UNITS] - BOOKING_TYPE, EARNED_VALUE_METHOD, DELIVERABLE_TYPE, RESOURCE_REQUEST_TYPE - we have as string in MPXJ????\n // 03 - Int values [DURATION, INTEGER] - Recalc outline codes as Boolean?\n // 05 - Rate, Number [RATE, NUMERIC]\n // 08 - String (and some durations!!!) [STRING, DURATION]\n // 0B - Boolean (meta block 0?) - [BOOLEAN]\n // 13 - Date - [DATE]\n // 48 - GUID - [GUID]\n // 64 - Boolean (meta block 1?)- [BOOLEAN]\n // 65 - Work, Currency [WORK, CURRENCY]\n // 66 - Units [UNITS]\n // 1D - Raw bytes [BINARY, ASCII_STRING] - Exception: outline code indexes, they are integers, but stored as part of a binary block\n\n int varDataKey;\n if (useTypeAsVarDataKey())\n {\n Integer substitute = substituteVarDataKey(type);\n if (substitute == null)\n {\n varDataKey = (MPPUtility.getInt(data, index + 12) & 0x0000FFFF);\n }\n else\n {\n varDataKey = substitute.intValue();\n }\n }\n else\n {\n varDataKey = MPPUtility.getByte(data, index + 6);\n }\n\n FieldLocation location;\n int metaBlock;\n\n switch (category)\n {\n case 0x0B:\n {\n location = FieldLocation.META_DATA;\n metaBlock = 0;\n break;\n }\n\n case 0x64:\n {\n location = FieldLocation.META_DATA;\n metaBlock = 1;\n break;\n }\n\n default:\n {\n metaBlock = 0;\n if (dataBlockOffset != 65535)\n {\n location = FieldLocation.FIXED_DATA;\n if (dataBlockOffset < lastDataBlockOffset)\n {\n ++dataBlockIndex;\n }\n lastDataBlockOffset = dataBlockOffset;\n int typeSize = getFixedDataFieldSize(type);\n\n if (dataBlockOffset + typeSize > m_maxFixedDataSize[dataBlockIndex])\n {\n m_maxFixedDataSize[dataBlockIndex] = dataBlockOffset + typeSize;\n }\n }\n else\n {\n if (varDataKey != 0)\n {\n location = FieldLocation.VAR_DATA;\n }\n else\n {\n location = FieldLocation.UNKNOWN;\n }\n }\n break;\n }\n }\n\n FieldItem item = new FieldItem(type, location, dataBlockIndex, dataBlockOffset, varDataKey, mask, metaBlock);\n if (m_debug)\n {\n System.out.println(ByteArrayHelper.hexdump(data, index, 28, false) + \" \" + item + \" mpxjDataType=\" + item.getType().getDataType() + \" index=\" + index);\n }\n m_map.put(type, item);\n\n index += 28;\n }\n }" ]
[ "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getPluginInformation() {\n return pluginInformation();\n }", "public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public String convertToPrefixLength() throws AddressStringException {\n\t\tIPAddress address = toAddress();\n\t\tInteger prefix;\n\t\tif(address == null) {\n\t\t\tif(isPrefixOnly()) {\n\t\t\t\tprefix = getNetworkPrefixLength();\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = address.getBlockMaskPrefixLength(true);\n\t\t\tif(prefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn IPAddressSegment.toUnsignedString(prefix, 10, \n\t\t\t\tnew StringBuilder(IPAddressSegment.toUnsignedStringLength(prefix, 10) + 1).append(IPAddress.PREFIX_LEN_SEPARATOR)).toString();\n\t}", "@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}", "@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 Set<String> rangeByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (lexRange.hasLimit()) {\n return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to(), lexRange.offset(), lexRange.count());\n } else {\n return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to());\n }\n }\n });\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear()\n && d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }", "private Set<Annotation> getFieldAnnotations(final Class<?> clazz)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn new LinkedHashSet<Annotation>(asList(clazz.getDeclaredField(propertyName).getAnnotations()));\n\t\t}\n\t\tcatch (final NoSuchFieldException e)\n\t\t{\n\t\t\tif (clazz.getSuperclass() != null)\n\t\t\t{\n\t\t\t\treturn getFieldAnnotations(clazz.getSuperclass());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogger.debug(\"Cannot find propertyName: {}, declaring class: {}\", propertyName, clazz);\n\t\t\t\treturn new LinkedHashSet<Annotation>(0);\n\t\t\t}\n\t\t}\n\t}", "public Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\n }" ]
Retrieve an instance of the TaskField class based on the data read from an MPX file. @param value value from an MS Project file @return TaskField instance
[ "public static TaskField getMpxjField(int value)\n {\n TaskField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }" ]
[ "public LayerType toDto(Class<? extends com.vividsolutions.jts.geom.Geometry> geometryClass) {\n\t\tif (geometryClass == LineString.class) {\n\t\t\treturn LayerType.LINESTRING;\n\t\t} else if (geometryClass == MultiLineString.class) {\n\t\t\treturn LayerType.MULTILINESTRING;\n\t\t} else if (geometryClass == Point.class) {\n\t\t\treturn LayerType.POINT;\n\t\t} else if (geometryClass == MultiPoint.class) {\n\t\t\treturn LayerType.MULTIPOINT;\n\t\t} else if (geometryClass == Polygon.class) {\n\t\t\treturn LayerType.POLYGON;\n\t\t} else if (geometryClass == MultiPolygon.class) {\n\t\t\treturn LayerType.MULTIPOLYGON;\n\t\t} else {\n\t\t\treturn LayerType.GEOMETRY;\n\t\t}\n\t}", "public static String encode(String value) throws UnsupportedEncodingException {\n if (isNullOrEmpty(value)) return value;\n return URLEncoder.encode(value, URL_ENCODING);\n }", "public List<String> deviceTypes() {\n Integer count = json().size(DEVICE_FAMILIES);\n List<String> deviceTypes = new ArrayList<String>(count);\n for(int i = 0 ; i < count ; i++) {\n String familyNumber = json().stringValue(DEVICE_FAMILIES, i);\n if(familyNumber.equals(\"1\")) deviceTypes.add(\"iPhone\");\n if(familyNumber.equals(\"2\")) deviceTypes.add(\"iPad\");\n }\n return deviceTypes;\n }", "public void updateLinks(ServiceReference<S> serviceReference) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);\n boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);\n if (isAlreadyLinked && !canBeLinked) {\n linkerManagement.unlink(declaration, serviceReference);\n } else if (!isAlreadyLinked && canBeLinked) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }", "public static String replaceErrorMsg(String origMsg) {\n\n String replaceMsg = origMsg;\n for (ERROR_TYPE errorType : ERROR_TYPE.values()) {\n\n if (origMsg == null) {\n replaceMsg = PcConstants.NA;\n return replaceMsg;\n }\n\n if (origMsg.contains(errorMapOrig.get(errorType))) {\n replaceMsg = errorMapReplace.get(errorType);\n break;\n }\n\n }\n\n return replaceMsg;\n\n }", "public void addFilter(Filter filter)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.add(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.add(filter);\n }\n\n m_filtersByName.put(filter.getName(), filter);\n m_filtersByID.put(filter.getID(), filter);\n }", "public static sslfipskey get(nitro_service service, String fipskeyname) throws Exception{\n\t\tsslfipskey obj = new sslfipskey();\n\t\tobj.set_fipskeyname(fipskeyname);\n\t\tsslfipskey response = (sslfipskey) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setType(CheckBoxType type) {\n this.type = type;\n switch (type) {\n case FILLED:\n Element input = DOM.getChild(getElement(), 0);\n input.setAttribute(\"class\", CssName.FILLED_IN);\n break;\n case INTERMEDIATE:\n addStyleName(type.getCssName() + \"-checkbox\");\n break;\n default:\n addStyleName(type.getCssName());\n break;\n }\n }", "public static void append(File file, Object text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file, true);\n if (!file.exists()) {\n writeUTF16BomIfRequired(charset, out);\n }\n writer = new OutputStreamWriter(out, charset);\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }" ]
Handles Multi Instance Encapsulation message. Decapsulates an Application Command message and handles it using the right instance. @param serialMessage the serial message to process. @param offset the offset at which to start procesing.
[ "private void handleMultiInstanceEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Encapsulation\");\r\n\t\tint instance = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);\r\n\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Instance = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), instance));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);\r\n\t}" ]
[ "public static final BigDecimal printRate(Rate rate)\n {\n BigDecimal result = null;\n if (rate != null && rate.getAmount() != 0)\n {\n result = new BigDecimal(rate.getAmount());\n }\n return result;\n }", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }", "public void setColorRange(int firstIndex, int lastIndex, int color1, int color2) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(lastIndex-firstIndex), color1, color2);\n\t}", "public final List<Throwable> validate() {\n List<Throwable> validationErrors = new ArrayList<>();\n this.accessAssertion.validate(validationErrors, this);\n\n for (String jdbcDriver: this.jdbcDrivers) {\n try {\n Class.forName(jdbcDriver);\n } catch (ClassNotFoundException e) {\n try {\n Configuration.class.getClassLoader().loadClass(jdbcDriver);\n } catch (ClassNotFoundException e1) {\n validationErrors.add(new ConfigurationException(String.format(\n \"Unable to load JDBC driver: %s ensure that the web application has the jar \" +\n \"on its classpath\", jdbcDriver)));\n }\n }\n }\n\n if (this.configurationFile == null) {\n validationErrors.add(new ConfigurationException(\"Configuration file is field on configuration \" +\n \"object is null\"));\n }\n if (this.templates.isEmpty()) {\n validationErrors.add(new ConfigurationException(\"There are not templates defined.\"));\n }\n for (Template template: this.templates.values()) {\n template.validate(validationErrors, this);\n }\n\n for (HttpProxy proxy: this.proxies) {\n proxy.validate(validationErrors, this);\n }\n\n try {\n ColorParser.toColor(this.opaqueTileErrorColor);\n } catch (RuntimeException ex) {\n validationErrors.add(new ConfigurationException(\"Cannot parse opaqueTileErrorColor\", ex));\n }\n\n try {\n ColorParser.toColor(this.transparentTileErrorColor);\n } catch (RuntimeException ex) {\n validationErrors.add(new ConfigurationException(\"Cannot parse transparentTileErrorColor\", ex));\n }\n\n if (smtp != null) {\n smtp.validate(validationErrors, this);\n }\n\n return validationErrors;\n }", "public Where<T, ID> eq(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }", "public int createLogs(String topic, final int partitions, final boolean forceEnlarge) {\n TopicNameValidator.validate(topic);\n synchronized (logCreationLock) {\n final int configPartitions = getPartition(topic);\n if (configPartitions >= partitions || !forceEnlarge) {\n return configPartitions;\n }\n topicPartitionsMap.put(topic, partitions);\n if (config.getEnableZookeeper()) {\n if (getLogPool(topic, 0) != null) {//created already\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.ENLARGE, topic));\n } else {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n }\n return partitions;\n }\n }", "public String computeTrackSignature(final String title, final SearchableItem artist, final int duration,\n final WaveformDetail waveformDetail, final BeatGrid beatGrid) {\n final String safeTitle = (title == null)? \"\" : title;\n final String artistName = (artist == null)? \"[no artist]\" : artist.label;\n try {\n // Compute the SHA-1 hash of our fields\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(safeTitle.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digest.update(artistName.getBytes(\"UTF-8\"));\n digest.update((byte) 0);\n digestInteger(digest, duration);\n digest.update(waveformDetail.getData());\n for (int i = 1; i <= beatGrid.beatCount; i++) {\n digestInteger(digest, beatGrid.getBeatWithinBar(i));\n digestInteger(digest, (int)beatGrid.getTimeWithinTrack(i));\n }\n byte[] result = digest.digest();\n\n // Create a hex string representation of the hash\n StringBuilder hex = new StringBuilder(result.length * 2);\n for (byte aResult : result) {\n hex.append(Integer.toString((aResult & 0xff) + 0x100, 16).substring(1));\n }\n\n return hex.toString();\n\n } catch (NullPointerException e) {\n logger.info(\"Returning null track signature because an input element was null.\", e);\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"Unable to obtain SHA-1 MessageDigest instance for computing track signatures.\", e);\n } catch (UnsupportedEncodingException e) {\n logger.error(\"Unable to work with UTF-8 string encoding for computing track signatures.\", e);\n }\n return null; // We were unable to compute a signature\n }", "private PersistenceBroker obtainBroker()\r\n {\r\n PersistenceBroker _broker;\r\n try\r\n {\r\n if (pbKey == null)\r\n {\r\n //throw new OJBRuntimeException(\"Not possible to do action, cause no tx runnning and no PBKey is set\");\r\n log.warn(\"No tx runnning and PBKey is null, try to use the default PB\");\r\n _broker = PersistenceBrokerFactory.defaultPersistenceBroker();\r\n }\r\n else\r\n {\r\n _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);\r\n }\r\n }\r\n catch (PBFactoryException e)\r\n {\r\n log.error(\"Could not obtain PB for PBKey \" + pbKey, e);\r\n throw new OJBRuntimeException(\"Unexpected micro-kernel exception\", e);\r\n }\r\n return _broker;\r\n }" ]
Retrieves the value component of a criteria expression. @param field field type @param block block data @return field value
[ "private Object getValue(FieldType field, byte[] block)\n {\n Object result = null;\n\n switch (block[0])\n {\n case 0x07: // Field\n {\n result = getFieldType(block);\n break;\n }\n\n case 0x01: // Constant value\n {\n result = getConstantValue(field, block);\n break;\n }\n\n case 0x00: // Prompt\n {\n result = getPromptValue(field, block);\n break;\n }\n }\n\n return result;\n }" ]
[ "public float getBoundsHeight(){\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.y - v.minCorner.y;\n }\n return 0f;\n }", "private void writeTermStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\n\t\t// Make sure all keys are present in label count map:\n\t\tfor (String key : usageStatistics.aliasCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\t\tfor (String key : usageStatistics.descriptionCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Language,Labels,Descriptions,Aliases\");\n\t\t\tfor (Entry<String, Integer> entry : usageStatistics.labelCounts\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tcountKey(usageStatistics.aliasCounts, entry.getKey(), 0);\n\t\t\t\tint aCount = usageStatistics.aliasCounts.get(entry.getKey());\n\t\t\t\tcountKey(usageStatistics.descriptionCounts, entry.getKey(), 0);\n\t\t\t\tint dCount = usageStatistics.descriptionCounts.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue() + \",\"\n\t\t\t\t\t\t+ dCount + \",\" + aCount);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }", "public static URL findConfigResource(String resourceName) {\n if (Strings.isNullOrEmpty(resourceName)) {\n return null;\n }\n\n final URL url = resourceName.startsWith(ROOT) ? DefaultConfiguration.class.getResource(resourceName)\n : DefaultConfiguration.class.getResource(ROOT + resourceName);\n\n if (url != null) {\n return url;\n }\n\n // This is useful to get resource under META-INF directory\n String[] resourceNamePrefix = new String[] {\"META-INF/fabric8/\", \"META-INF/fabric8/\"};\n\n for (String resource : resourceNamePrefix) {\n String fullResourceName = resource + resourceName;\n\n URL candidate = KubernetesResourceLocator.class.getResource(fullResourceName.startsWith(ROOT) ? fullResourceName : ROOT + fullResourceName);\n if (candidate != null) {\n return candidate;\n }\n }\n\n return null;\n }", "private String getSite(CmsObject cms, CmsFavoriteEntry entry) {\n\n CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(entry.getSiteRoot());\n Item item = m_sitesContainer.getItem(entry.getSiteRoot());\n if (item != null) {\n return (String)(item.getItemProperty(\"caption\").getValue());\n }\n String result = entry.getSiteRoot();\n if (site != null) {\n if (!CmsStringUtil.isEmpty(site.getTitle())) {\n result = site.getTitle();\n }\n }\n return result;\n }", "public void addAll(OptionsContainerBuilder container) {\n\t\tfor ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {\n\t\t\taddAll( entry.getKey(), entry.getValue().build() );\n\t\t}\n\t}", "public void deployApplication(String applicationName, String... classpathLocations) throws IOException {\n\n final List<URL> classpathElements = Arrays.stream(classpathLocations)\n .map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath))\n .collect(Collectors.toList());\n\n deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()]));\n }", "public WebSocketContext reTag(String label) {\n WebSocketConnectionRegistry registry = manager.tagRegistry();\n registry.signOff(connection);\n registry.signIn(label, connection);\n return this;\n }", "private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }" ]
Base64 encodes a byte array. @param bytes Bytes to encode. @return Encoded string. @throws IllegalArgumentException if {@code bytes} is null or exceeds 3/4ths of {@code Integer.MAX_VALUE}.
[ "public static String base64Encode(byte[] bytes) {\n if (bytes == null) {\n throw new IllegalArgumentException(\"Input bytes must not be null.\");\n }\n if (bytes.length >= BASE64_UPPER_BOUND) {\n throw new IllegalArgumentException(\n \"Input bytes length must not exceed \" + BASE64_UPPER_BOUND);\n }\n\n // Every three bytes is encoded into four characters.\n //\n // Example:\n // input |0 1 0 1 0 0 1 0|0 1 1 0 1 1 1 1|0 1 1 0 0 0 1 0|\n // encode grouping |0 1 0 1 0 0|1 0 0 1 1 0|1 1 1 1 0 1|1 0 0 0 1 0|\n // encoded ascii | U | m | 9 | i |\n\n int triples = bytes.length / 3;\n\n // If the number of input bytes is not a multiple of three, padding characters will be added.\n if (bytes.length % 3 != 0) {\n triples += 1;\n }\n\n // The encoded string will have four characters for every three bytes.\n char[] encoding = new char[triples << 2];\n\n for (int in = 0, out = 0; in < bytes.length; in += 3, out += 4) {\n int triple = (bytes[in] & 0xff) << 16;\n if (in + 1 < bytes.length) {\n triple |= ((bytes[in + 1] & 0xff) << 8);\n }\n if (in + 2 < bytes.length) {\n triple |= (bytes[in + 2] & 0xff);\n }\n encoding[out] = BASE64_CHARS.charAt((triple >> 18) & 0x3f);\n encoding[out + 1] = BASE64_CHARS.charAt((triple >> 12) & 0x3f);\n encoding[out + 2] = BASE64_CHARS.charAt((triple >> 6) & 0x3f);\n encoding[out + 3] = BASE64_CHARS.charAt(triple & 0x3f);\n }\n\n // Add padding characters if needed.\n for (int i = encoding.length - (triples * 3 - bytes.length); i < encoding.length; i++) {\n encoding[i] = '=';\n }\n\n return String.valueOf(encoding);\n }" ]
[ "public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(String enterpriseId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(enterpriseId,\n DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }", "private int calcItemWidth(RecyclerView rvCategories) {\n if (itemWidth == null || itemWidth == 0) {\n for (int i = 0; i < rvCategories.getChildCount(); i++) {\n itemWidth = rvCategories.getChildAt(i).getWidth();\n if (itemWidth != 0) {\n break;\n }\n }\n }\n // in case of call before view was created\n if (itemWidth == null) {\n itemWidth = 0;\n }\n return itemWidth;\n }", "public MaterializeBuilder withActivity(Activity activity) {\n this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);\n this.mActivity = activity;\n return this;\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 synchronized void register(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factory != null ) {\n if ( factories == null ) {\n factories = new HashMap<String, List<Callable<Class< ? >>>>();\n }\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l == null ) {\n l = new ArrayList<Callable<Class< ? >>>();\n factories.put( serviceName,\n l );\n }\n l.add( factory );\n }\n }", "public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }", "private void writeTasks() throws IOException\n {\n writeAttributeTypes(\"task_types\", TaskField.values());\n\n m_writer.writeStartList(\"tasks\");\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task);\n }\n m_writer.writeEndList();\n }", "@Deprecated\n @SuppressWarnings(\"deprecation\")\n public void push(String eventName, HashMap<String, Object> chargeDetails,\n ArrayList<HashMap<String, Object>> items)\n throws InvalidEventNameException {\n // This method is for only charged events\n if (!eventName.equals(Constants.CHARGED_EVENT)) {\n throw new InvalidEventNameException(\"Not a charged event\");\n }\n CleverTapAPI cleverTapAPI = weakReference.get();\n if(cleverTapAPI == null){\n Logger.d(\"CleverTap Instance is null.\");\n } else {\n cleverTapAPI.pushChargedEvent(chargeDetails, items);\n }\n }", "public static 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 }" ]
Load a list of entities using the information in the context @param session The session @param lockOptions The locking details @param ogmContext The context with the information to load the entities @return the list of entities corresponding to the given context
[ "@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}" ]
[ "public static final Date parseDate(String value)\n {\n Date result = null;\n\n try\n {\n if (value != null && !value.isEmpty())\n {\n result = DATE_FORMAT.get().parse(value);\n }\n }\n catch (ParseException ex)\n {\n // Ignore\n }\n\n return result;\n }", "@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }", "public static int[] toInt(double[] array) {\n int[] n = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n n[i] = (int) array[i];\n }\n return n;\n }", "private int getPositiveInteger(String number) {\n try {\n return Math.max(0, Integer.parseInt(number));\n } catch (NumberFormatException e) {\n return 0;\n }\n }", "@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }", "public static String nameFromOffset(long offset) {\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMinimumIntegerDigits(20);\n nf.setMaximumFractionDigits(0);\n nf.setGroupingUsed(false);\n return nf.format(offset) + Log.FileSuffix;\n }", "public static void main(final String[] args) {\n if (System.getProperty(\"db.name\") == null) {\n System.out.println(\"Not running in multi-instance mode: no DB to connect to\");\n System.exit(1);\n }\n while (true) {\n try {\n Class.forName(\"org.postgresql.Driver\");\n DriverManager.getConnection(\"jdbc:postgresql://\" + System.getProperty(\"db.host\") + \":5432/\" +\n System.getProperty(\"db.name\"),\n System.getProperty(\"db.username\"),\n System.getProperty(\"db.password\"));\n System.out.println(\"Opened database successfully. Running in multi-instance mode\");\n System.exit(0);\n return;\n } catch (Exception e) {\n System.out.println(\"Failed to connect to the DB: \" + e.toString());\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e1) {\n //ignored\n }\n }\n }\n }", "public static void addService(final ServiceTarget serviceTarget, final Bootstrap.Configuration configuration,\n final ControlledProcessState processState, final BootstrapListener bootstrapListener,\n final RunningModeControl runningModeControl, final AbstractVaultReader vaultReader, final ManagedAuditLogger auditLogger,\n final DelegatingConfigurableAuthorizer authorizer, final ManagementSecurityIdentitySupplier securityIdentitySupplier,\n final SuspendController suspendController) {\n\n // Install Executor services\n final ThreadGroup threadGroup = new ThreadGroup(\"ServerService ThreadGroup\");\n final String namePattern = \"ServerService Thread Pool -- %t\";\n final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<ThreadFactory>() {\n public ThreadFactory run() {\n return new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null);\n }\n });\n\n // TODO determine why QueuelessThreadPoolService makes boot take > 35 secs\n// final QueuelessThreadPoolService serverExecutorService = new QueuelessThreadPoolService(Integer.MAX_VALUE, false, new TimeSpec(TimeUnit.SECONDS, 5));\n// serverExecutorService.getThreadFactoryInjector().inject(threadFactory);\n final boolean forDomain = ProcessType.DOMAIN_SERVER == getProcessType(configuration.getServerEnvironment());\n final ServerExecutorService serverExecutorService = new ServerExecutorService(threadFactory, forDomain);\n serviceTarget.addService(MANAGEMENT_EXECUTOR, serverExecutorService)\n .addAliases(Services.JBOSS_SERVER_EXECUTOR, ManagementRemotingServices.SHUTDOWN_EXECUTOR_NAME) // Use this executor for mgmt shutdown for now\n .install();\n final ServerScheduledExecutorService serverScheduledExecutorService = new ServerScheduledExecutorService(threadFactory);\n serviceTarget.addService(JBOSS_SERVER_SCHEDULED_EXECUTOR, serverScheduledExecutorService)\n .addAliases(JBOSS_SERVER_SCHEDULED_EXECUTOR)\n .addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, serverScheduledExecutorService.executorInjector)\n .install();\n\n final CapabilityRegistry capabilityRegistry = configuration.getCapabilityRegistry();\n ServerService service = new ServerService(configuration, processState, null, bootstrapListener, new ServerDelegatingResourceDefinition(),\n runningModeControl, vaultReader, auditLogger, authorizer, securityIdentitySupplier, capabilityRegistry, suspendController);\n\n ExternalManagementRequestExecutor.install(serviceTarget, threadGroup, EXECUTOR_CAPABILITY.getCapabilityServiceName(), service.getStabilityMonitor());\n\n ServiceBuilder<?> serviceBuilder = serviceTarget.addService(Services.JBOSS_SERVER_CONTROLLER, service);\n serviceBuilder.addDependency(DeploymentMountProvider.SERVICE_NAME,DeploymentMountProvider.class, service.injectedDeploymentRepository);\n serviceBuilder.addDependency(ContentRepository.SERVICE_NAME, ContentRepository.class, service.injectedContentRepository);\n serviceBuilder.addDependency(Services.JBOSS_SERVICE_MODULE_LOADER, ServiceModuleLoader.class, service.injectedModuleLoader);\n serviceBuilder.addDependency(Services.JBOSS_EXTERNAL_MODULE_SERVICE, ExternalModuleService.class,\n service.injectedExternalModuleService);\n serviceBuilder.addDependency(PATH_MANAGER_CAPABILITY.getCapabilityServiceName(), PathManager.class, service.injectedPathManagerService);\n if (configuration.getServerEnvironment().isAllowModelControllerExecutor()) {\n serviceBuilder.addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, service.getExecutorServiceInjector());\n }\n if (configuration.getServerEnvironment().getLaunchType() == ServerEnvironment.LaunchType.DOMAIN) {\n serviceBuilder.addDependency(HostControllerConnectionService.SERVICE_NAME, ControllerInstabilityListener.class,\n service.getContainerInstabilityInjector());\n }\n\n serviceBuilder.install();\n }", "private void getYearlyDates(Calendar calendar, List<Date> dates)\n {\n if (m_relative)\n {\n getYearlyRelativeDates(calendar, dates);\n }\n else\n {\n getYearlyAbsoluteDates(calendar, dates);\n }\n }" ]
helper method to set the TranslucentStatusFlag @param on
[ "public static void setTranslucentStatusFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);\n }\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 setGamma(float rGamma, float gGamma, float bGamma) {\n\t\tthis.rGamma = rGamma;\n\t\tthis.gGamma = gGamma;\n\t\tthis.bGamma = bGamma;\n\t\tinitialized = false;\n\t}", "public void setEmptyDefault(String iso) {\n if (iso == null || iso.isEmpty()) {\n iso = DEFAULT_COUNTRY;\n }\n int defaultIdx = mCountries.indexOfIso(iso);\n mSelectedCountry = mCountries.get(defaultIdx);\n mCountrySpinner.setSelection(defaultIdx);\n }", "protected void appendSQLClause(SelectionCriteria c, StringBuffer buf)\r\n {\r\n // BRJ : handle SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n buf.append(c.getAttribute());\r\n return;\r\n }\r\n \r\n // BRJ : criteria attribute is a query\r\n if (c.getAttribute() instanceof Query)\r\n {\r\n Query q = (Query) c.getAttribute();\r\n buf.append(\"(\");\r\n buf.append(getSubQuerySQL(q));\r\n buf.append(\")\");\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n return;\r\n }\r\n\r\n\t\tAttributeInfo attrInfo = getAttributeInfo((String) c.getAttribute(), false, c.getUserAlias(), c.getPathClasses());\r\n TableAlias alias = attrInfo.tableAlias;\r\n\r\n if (alias != null)\r\n {\r\n boolean hasExtents = alias.hasExtents();\r\n\r\n if (hasExtents)\r\n {\r\n // BRJ : surround with braces if alias has extents\r\n buf.append(\"(\");\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n\r\n c.setNumberOfExtentsToBind(alias.extents.size());\r\n Iterator iter = alias.iterateExtents();\r\n while (iter.hasNext())\r\n {\r\n TableAlias tableAlias = (TableAlias) iter.next();\r\n buf.append(\" OR \");\r\n appendCriteria(tableAlias, attrInfo.pathInfo, c, buf);\r\n }\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n // no extents\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n }\r\n }\r\n else\r\n {\r\n // alias null\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n }\r\n\r\n }", "public Path getReportDirectory()\n {\n WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());\n Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);\n createDirectoryIfNeeded(path);\n return path.toAbsolutePath();\n }", "public String login(Authentication authentication) {\n\t\tString token = getToken();\n\t\treturn login(token, authentication);\n\t}", "private static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) {\n // since indy does not give us the runtime types\n // we produce first a dummy call site, which then changes the target to one,\n // that does the method selection including the the direct call to the \n // real method.\n MutableCallSite mc = new MutableCallSite(type);\n MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall);\n mc.setTarget(mh);\n return mc;\n }", "public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\n\t}", "public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }" ]
Validates the binding types
[ "private void checkBindings(EnhancedAnnotation<T> annotatedAnnotation) {\n Set<Annotation> bindings = annotatedAnnotation.getMetaAnnotations(Qualifier.class);\n if (bindings.size() > 0) {\n for (Annotation annotation : bindings) {\n if (!annotation.annotationType().equals(Named.class)) {\n throw MetadataLogger.LOG.qualifierOnStereotype(annotatedAnnotation);\n }\n }\n }\n }" ]
[ "public ILog getLog(String topic, int partition) {\n TopicNameValidator.validate(topic);\n Pool<Integer, Log> p = getLogPool(topic, partition);\n return p == null ? null : p.get(partition);\n }", "private static int getColumnWidth(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n if (Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) {\n return 70;\n } else if (type == Boolean.class) {\n return 10;\n } else if (Number.class.isAssignableFrom(type)) {\n return 60;\n } else if (type == String.class) {\n return 100;\n } else if (Date.class.isAssignableFrom(type)) {\n return 50;\n } else {\n return 50;\n }\n }", "boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireNanos(permit, unit.toNanos(timeout));\n }", "private void removeGroupIdFromTablePaths(int groupIdToRemove) {\n PreparedStatement queryStatement = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PATH);\n results = queryStatement.executeQuery();\n // this is a hashamp from a pathId to the string of groups\n HashMap<Integer, String> idToGroups = new HashMap<Integer, String>();\n while (results.next()) {\n int pathId = results.getInt(Constants.GENERIC_ID);\n String stringGroupIds = results.getString(Constants.PATH_PROFILE_GROUP_IDS);\n int[] groupIds = Utils.arrayFromStringOfIntegers(stringGroupIds);\n String newGroupIds = \"\";\n for (int i = 0; i < groupIds.length; i++) {\n if (groupIds[i] != groupIdToRemove) {\n newGroupIds += (groupIds[i] + \",\");\n }\n }\n idToGroups.put(pathId, newGroupIds);\n }\n\n // now i want to go though the hashmap and for each pathId, add\n // update the newGroupIds\n for (Map.Entry<Integer, String> entry : idToGroups.entrySet()) {\n Integer pathId = entry.getKey();\n String newGroupIds = entry.getValue();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH\n + \" SET \" + Constants.PATH_PROFILE_GROUP_IDS + \" = ? \"\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newGroupIds);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private boolean isSplit(ProjectCalendar calendar, List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n if (calendar != null && assignment.getTotalAmount().getDuration() == 0)\n {\n Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);\n if (calendarWork.getDuration() != 0)\n {\n result = true;\n break;\n }\n }\n }\n return result;\n }", "private static final double printDurationFractionsOfMinutes(Duration duration, int factor)\n {\n double result = 0;\n\n if (duration != null)\n {\n result = duration.getDuration();\n\n switch (duration.getUnits())\n {\n case HOURS:\n case ELAPSED_HOURS:\n {\n result *= 60;\n break;\n }\n\n case DAYS:\n {\n result *= (60 * 8);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n result *= (60 * 24);\n break;\n }\n\n case WEEKS:\n {\n result *= (60 * 8 * 5);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n result *= (60 * 24 * 7);\n break;\n }\n\n case MONTHS:\n {\n result *= (60 * 8 * 5 * 4);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n result *= (60 * 24 * 30);\n break;\n }\n\n case YEARS:\n {\n result *= (60 * 8 * 5 * 52);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n result *= (60 * 24 * 365);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n result *= factor;\n\n return (result);\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean confirm = false;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Remove metadata related to rebalancing\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n if(allNodes) {\n System.out.println(\" node = all nodes\");\n } else {\n System.out.println(\" node = \" + Joiner.on(\", \").join(nodeIds));\n }\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm, \"remove metadata related to rebalancing\")) {\n return;\n }\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds);\n\n doMetaClearRebalance(adminClient, nodeIds);\n }", "public int compare(Vector3 o1, Vector3 o2) {\n\t\tint ans = 0;\n\n\t\tif (o1 != null && o2 != null) {\n\t\t\tVector3 d1 = o1;\n\t\t\tVector3 d2 = o2;\n\n\t\t\tif (d1.x > d2.x)\n\t\t\t\treturn 1;\n\t\t\tif (d1.x < d2.x)\n\t\t\t\treturn -1;\n\t\t\t// x1 == x2\n\t\t\tif (d1.y > d2.y)\n\t\t\t\treturn 1;\n\t\t\tif (d1.y < d2.y)\n\t\t\t\treturn -1;\n\t\t} else {\n\t\t\tif (o1 == null && o2 == null)\n\t\t\t\treturn 0;\n\t\t\tif (o1 == null && o2 != null)\n\t\t\t\treturn 1;\n\t\t\tif (o1 != null && o2 == null)\n\t\t\t\treturn -1;\n\t\t}\n\t\t\n\t\treturn ans;\n\t}", "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}" ]
This returns all profiles associated with a server name @param serverName server Name @return profile UUID @throws Exception exception
[ "public Profile[] getProfilesForServerName(String serverName) throws Exception {\n int profileId = -1;\n ArrayList<Profile> returnProfiles = new ArrayList<Profile>();\n\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_PROFILE_ID + \" FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ? GROUP BY \" +\n Constants.GENERIC_PROFILE_ID\n );\n queryStatement.setString(1, serverName);\n results = queryStatement.executeQuery();\n\n while (results.next()) {\n profileId = results.getInt(Constants.GENERIC_PROFILE_ID);\n\n Profile profile = ProfileService.getInstance().findProfile(profileId);\n\n returnProfiles.add(profile);\n }\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\n if (returnProfiles.size() == 0) {\n return null;\n }\n return returnProfiles.toArray(new Profile[0]);\n }" ]
[ "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // check constraints now after all classes have been processed\r\n for (Iterator it = getClasses(); it.hasNext();)\r\n {\r\n ((ClassDescriptorDef)it.next()).checkConstraints(checkLevel);\r\n }\r\n // additional model constraints that either deal with bigger parts of the model or\r\n // can only be checked after the individual classes have been checked (e.g. specific\r\n // attributes have been ensured)\r\n new ModelConstraints().check(this, checkLevel);\r\n }", "public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}", "public boolean isDuplicateName(String name) {\n if (name == null || name.trim().isEmpty()) {\n return false;\n }\n List<AssignmentRow> as = view.getAssignmentRows();\n if (as != null && !as.isEmpty()) {\n int nameCount = 0;\n for (AssignmentRow row : as) {\n if (name.trim().compareTo(row.getName()) == 0) {\n nameCount++;\n if (nameCount > 1) {\n return true;\n }\n }\n }\n }\n return false;\n }", "private String toLengthText(long bytes) {\n if (bytes < 1024) {\n return bytes + \" B\";\n } else if (bytes < 1024 * 1024) {\n return (bytes / 1024) + \" KB\";\n } else if (bytes < 1024 * 1024 * 1024) {\n return String.format(\"%.2f MB\", bytes / (1024.0 * 1024.0));\n } else {\n return String.format(\"%.2f GB\", bytes / (1024.0 * 1024.0 * 1024.0));\n }\n }", "protected ObjectPool setupPool(JdbcConnectionDescriptor jcd)\r\n {\r\n log.info(\"Create new ObjectPool for DBCP connections:\" + jcd);\r\n\r\n try\r\n {\r\n ClassHelper.newInstance(jcd.getDriver());\r\n }\r\n catch (InstantiationException e)\r\n {\r\n log.fatal(\"Unable to instantiate the driver class: \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n catch (IllegalAccessException e)\r\n {\r\n log.fatal(\"IllegalAccessException while instantiating the driver class: \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n log.fatal(\"Could not find the driver class : \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n\r\n // Get the configuration for the connection pool\r\n GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();\r\n\r\n // Get the additional abandoned configuration\r\n AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();\r\n\r\n // Create the ObjectPool that serves as the actual pool of connections.\r\n final ObjectPool connectionPool = createConnectionPool(conf, ac);\r\n\r\n // Create a DriverManager-based ConnectionFactory that\r\n // the connectionPool will use to create Connection instances\r\n final org.apache.commons.dbcp.ConnectionFactory connectionFactory;\r\n connectionFactory = createConnectionFactory(jcd);\r\n\r\n // Create PreparedStatement object pool (if any)\r\n KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd);\r\n\r\n // Set validation query and auto-commit mode\r\n final String validationQuery;\r\n final boolean defaultAutoCommit;\r\n final boolean defaultReadOnly = false;\r\n validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery();\r\n defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE);\r\n\r\n //\r\n // Now we'll create the PoolableConnectionFactory, which wraps\r\n // the \"real\" Connections created by the ConnectionFactory with\r\n // the classes that implement the pooling functionality.\r\n //\r\n final PoolableConnectionFactory poolableConnectionFactory;\r\n poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,\r\n connectionPool,\r\n statementPoolFactory,\r\n validationQuery,\r\n defaultReadOnly,\r\n defaultAutoCommit,\r\n ac);\r\n return poolableConnectionFactory.getPool();\r\n }", "public void beforeClose(PBStateEvent event)\r\n {\r\n /*\r\n arminw:\r\n this is a workaround for use in managed environments. When a PB instance is used\r\n within a container a PB.close call is done when leave the container method. This close\r\n the PB handle (but the real instance is still in use) and the PB listener are notified.\r\n But the JTA tx was not committed at\r\n this point in time and the session cache should not be cleared, because the updated/new\r\n objects will be pushed to the real cache on commit call (if we clear, nothing to push).\r\n So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle\r\n is closed), if true we don't reset the session cache.\r\n */\r\n if(!broker.isInTransaction())\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clearing the session cache\");\r\n resetSessionCache();\r\n }\r\n }", "public void processCalendar(Row calendarRow, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> workPatternAssignmentMap, Map<Integer, List<Row>> exceptionAssignmentMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n //\n // Create the calendar and add the default working hours\n //\n ProjectCalendar calendar = m_project.addCalendar();\n Integer dominantWorkPatternID = calendarRow.getInteger(\"DOMINANT_WORK_PATTERN\");\n calendar.setUniqueID(calendarRow.getInteger(\"CALENDARID\"));\n processWorkPattern(calendar, dominantWorkPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n calendar.setName(calendarRow.getString(\"NAMK\"));\n\n //\n // Add any additional working weeks\n //\n List<Row> rows = workPatternAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"WORK_PATTERN\");\n if (!workPatternID.equals(dominantWorkPatternID))\n {\n ProjectCalendarWeek week = calendar.addWorkWeek();\n week.setDateRange(new DateRange(row.getDate(\"START_DATE\"), row.getDate(\"END_DATE\")));\n processWorkPattern(week, workPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n }\n }\n }\n\n //\n // Add exceptions - not sure how exceptions which turn non-working days into working days are handled by Asta - if at all?\n //\n rows = exceptionAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Date startDate = row.getDate(\"STARU_DATE\");\n Date endDate = row.getDate(\"ENE_DATE\");\n calendar.addCalendarException(startDate, endDate);\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }", "@RequestMapping(value = \"api/edit/server\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getjqRedirects(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(ServerRedirectService.getInstance().tableServers(clientId), \"servers\");\n returnJson.put(\"hostEditor\", Client.isAvailable());\n return returnJson;\n }" ]
Creates a Bytes object by copying the value of the given String
[ "public static final Bytes of(String s) {\n Objects.requireNonNull(s);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(StandardCharsets.UTF_8);\n return new Bytes(data, s);\n }" ]
[ "private void enableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(true);\n }\n }", "private void deliverFaderStartCommand(Set<Integer> playersToStart, Set<Integer> playersToStop) {\n for (final FaderStartListener listener : getFaderStartListeners()) {\n try {\n listener.fadersChanged(playersToStart, playersToStop);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering fader start command to listener\", t);\n }\n }\n }", "public Map<DeckReference, AlbumArt> getLoadedArt() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, AlbumArt>(hotCache));\n }", "protected boolean isSameSnakSet(Iterator<Snak> snaks1, Iterator<Snak> snaks2) {\n\t\tArrayList<Snak> snakList1 = new ArrayList<>(5);\n\t\twhile (snaks1.hasNext()) {\n\t\t\tsnakList1.add(snaks1.next());\n\t\t}\n\n\t\tint snakCount2 = 0;\n\t\twhile (snaks2.hasNext()) {\n\t\t\tsnakCount2++;\n\t\t\tSnak snak2 = snaks2.next();\n\t\t\tboolean found = false;\n\t\t\tfor (int i = 0; i < snakList1.size(); i++) {\n\t\t\t\tif (snak2.equals(snakList1.get(i))) {\n\t\t\t\t\tsnakList1.set(i, null);\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn snakCount2 == snakList1.size();\n\t}", "private static JSONObject parseBounds(Bounds bounds) throws JSONException {\n if (bounds != null) {\n JSONObject boundsObject = new JSONObject();\n JSONObject lowerRight = new JSONObject();\n JSONObject upperLeft = new JSONObject();\n\n lowerRight.put(\"x\",\n bounds.getLowerRight().getX().doubleValue());\n lowerRight.put(\"y\",\n bounds.getLowerRight().getY().doubleValue());\n\n upperLeft.put(\"x\",\n bounds.getUpperLeft().getX().doubleValue());\n upperLeft.put(\"y\",\n bounds.getUpperLeft().getY().doubleValue());\n\n boundsObject.put(\"lowerRight\",\n lowerRight);\n boundsObject.put(\"upperLeft\",\n upperLeft);\n\n return boundsObject;\n }\n\n return new JSONObject();\n }", "public void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n }", "public static cmppolicylabel[] get(nitro_service service) throws Exception{\n\t\tcmppolicylabel obj = new cmppolicylabel();\n\t\tcmppolicylabel[] response = (cmppolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Date min(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) < 0) ? d1 : d2;\n }\n return result;\n }", "private void processDependencies()\n {\n Set<Task> tasksWithBars = new HashSet<Task>();\n FastTrackTable table = m_data.getTable(FastTrackTableType.ACTBARS);\n for (MapRow row : table)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(ActBarField._ACTIVITY));\n if (task == null || tasksWithBars.contains(task))\n {\n continue;\n }\n tasksWithBars.add(task);\n\n String predecessors = row.getString(ActBarField.PREDECESSORS);\n if (predecessors == null || predecessors.isEmpty())\n {\n continue;\n }\n\n for (String predecessor : predecessors.split(\", \"))\n {\n Matcher matcher = RELATION_REGEX.matcher(predecessor);\n matcher.matches();\n\n Integer id = Integer.valueOf(matcher.group(1));\n RelationType type = RELATION_TYPE_MAP.get(matcher.group(3));\n if (type == null)\n {\n type = RelationType.FINISH_START;\n }\n\n String sign = matcher.group(4);\n double lag = NumberHelper.getDouble(matcher.group(5));\n if (\"-\".equals(sign))\n {\n lag = -lag;\n }\n\n Task targetTask = m_project.getTaskByID(id);\n if (targetTask != null)\n {\n Duration lagDuration = Duration.getInstance(lag, m_data.getDurationTimeUnit());\n Relation relation = task.addPredecessor(targetTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }" ]
Returns the name of the directory where the dumpfile of the given type and date should be stored. @param dumpContentType the type of the dump @param dateStamp the date of the dump in format YYYYMMDD @return the local directory name for the dumpfile
[ "public static String getDumpFileDirectoryName(\n\t\t\tDumpContentType dumpContentType, String dateStamp) {\n\t\treturn dumpContentType.toString().toLowerCase() + \"-\" + dateStamp;\n\t}" ]
[ "public Date[] getDates()\n {\n int frequency = NumberHelper.getInt(m_frequency);\n if (frequency < 1)\n {\n frequency = 1;\n }\n\n Calendar calendar = DateHelper.popCalendar(m_startDate);\n List<Date> dates = new ArrayList<Date>();\n\n switch (m_recurrenceType)\n {\n case DAILY:\n {\n getDailyDates(calendar, frequency, dates);\n break;\n }\n\n case WEEKLY:\n {\n getWeeklyDates(calendar, frequency, dates);\n break;\n }\n\n case MONTHLY:\n {\n getMonthlyDates(calendar, frequency, dates);\n break;\n }\n\n case YEARLY:\n {\n getYearlyDates(calendar, dates);\n break;\n }\n }\n\n DateHelper.pushCalendar(calendar);\n \n return dates.toArray(new Date[dates.size()]);\n }", "private static double arcAngle(Point center, Point a, Point b, Rect area, int radius) {\n double angle = threePointsAngle(center, a, b);\n Point innerPoint = findMidnormalPoint(center, a, b, area, radius);\n Point midInsectPoint = new Point((a.x + b.x) / 2, (a.y + b.y) / 2);\n double distance = pointsDistance(midInsectPoint, innerPoint);\n if (distance > radius) {\n return 360 - angle;\n }\n return angle;\n }", "private String generatedBuilderSimpleName(TypeElement type) {\n String packageName = elements.getPackageOf(type).getQualifiedName().toString();\n String originalName = type.getQualifiedName().toString();\n checkState(originalName.startsWith(packageName + \".\"));\n String nameWithoutPackage = originalName.substring(packageName.length() + 1);\n return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll(\"\\\\.\", \"_\"));\n }", "public void flipBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n data[word] ^= (1 << offset);\n }", "public static Map<String, String> parseProperties(String s) {\n\t\tMap<String, String> properties = new HashMap<String, String>();\n\t\tif (!StringUtils.isEmpty(s)) {\n\t\t\tMatcher matcher = PROPERTIES_PATTERN.matcher(s);\n\t\t\tint start = 0;\n\t\t\twhile (matcher.find()) {\n\t\t\t\taddKeyValuePairAsProperty(s.substring(start, matcher.start()), properties);\n\t\t\t\tstart = matcher.start() + 1;\n\t\t\t}\n\t\t\taddKeyValuePairAsProperty(s.substring(start), properties);\n\t\t}\n\t\treturn properties;\n\t}", "int cancel(int downloadId) {\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tfor (DownloadRequest request : mCurrentRequests) {\n\t\t\t\tif (request.getDownloadId() == downloadId) {\n\t\t\t\t\trequest.cancel();\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}", "@NonNull\n @Override\n public Loader<SortedList<FtpFile>> getLoader() {\n return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {\n @Override\n public SortedList<FtpFile> loadInBackground() {\n SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {\n @Override\n public int compare(FtpFile lhs, FtpFile rhs) {\n if (lhs.isDirectory() && !rhs.isDirectory()) {\n return -1;\n } else if (rhs.isDirectory() && !lhs.isDirectory()) {\n return 1;\n } else {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n }\n\n @Override\n public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {\n return oldItem.getName().equals(newItem.getName());\n }\n\n @Override\n public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {\n return item1.getName().equals(item2.getName());\n }\n });\n\n\n if (!ftp.isConnected()) {\n // Connect\n try {\n ftp.connect(server, port);\n\n ftp.setFileType(FTP.ASCII_FILE_TYPE);\n ftp.enterLocalPassiveMode();\n ftp.setUseEPSVwithIPv4(false);\n\n if (!(loggedIn = ftp.login(username, password))) {\n ftp.logout();\n Log.e(TAG, \"Login failed\");\n }\n } catch (IOException e) {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException ignored) {\n }\n }\n Log.e(TAG, \"Could not connect to server.\");\n }\n }\n\n if (loggedIn) {\n try {\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n sortedList.beginBatchedUpdates();\n for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {\n FtpFile file;\n if (f.isDirectory()) {\n file = new FtpDir(mCurrentPath, f.getName());\n } else {\n file = new FtpFile(mCurrentPath, f.getName());\n }\n if (isItemVisible(file)) {\n sortedList.add(file);\n }\n }\n sortedList.endBatchedUpdates();\n } catch (IOException e) {\n Log.e(TAG, \"IOException: \" + e.getMessage());\n }\n }\n\n return sortedList;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n forceLoad();\n }\n };\n }", "public RangeInfo subListBorders(int size) {\n if (inclusive == null) throw new IllegalStateException(\"Should not call subListBorders on a non-inclusive aware IntRange\");\n int tempFrom = from;\n if (tempFrom < 0) {\n tempFrom += size;\n }\n int tempTo = to;\n if (tempTo < 0) {\n tempTo += size;\n }\n if (tempFrom > tempTo) {\n return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true);\n }\n return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false);\n }", "public void increasePriority(int overrideId, int ordinal, int pathId, String clientUUID) {\n logger.info(\"Increase priority\");\n\n int origPriority = -1;\n int newPriority = -1;\n int origId = 0;\n int newId = 0;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n results = null;\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n statement.setInt(1, pathId);\n statement.setString(2, clientUUID);\n results = statement.executeQuery();\n\n int ordinalCount = 0;\n while (results.next()) {\n if (results.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID) == overrideId) {\n ordinalCount++;\n if (ordinalCount == ordinal) {\n origPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n origId = results.getInt(Constants.GENERIC_ID);\n break;\n }\n }\n newPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n newId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // update priorities\n if (origPriority != -1 && newPriority != -1) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, origPriority);\n statement.setInt(2, newId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, newPriority);\n statement.setInt(2, origId);\n statement.executeUpdate();\n }\n } catch (Exception e) {\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
Gets the current version of the database schema. This version is taken from the migration table and represent the latest successful entry. @return the current schema version
[ "public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }" ]
[ "private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }", "private <A extends Annotation> AnnotationConverter<A> getConverter(Annotation annotation) {\n\t\tMappingOption mappingOption = annotation.annotationType().getAnnotation( MappingOption.class );\n\t\tif ( mappingOption == null ) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// wrong type would be a programming error of the annotation developer\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tClass<? extends AnnotationConverter<A>> converterClass = (Class<? extends AnnotationConverter<A>>) mappingOption.value();\n\n\t\ttry {\n\t\t\treturn converterClass.newInstance();\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow log.cannotConvertAnnotation( converterClass, e );\n\t\t}\n\t}", "private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }", "public static void checkArrayLength(String parameterName, int actualLength,\n int expectedLength) {\n if (actualLength != expectedLength) {\n throw Exceptions.IllegalArgument(\n \"Array %s should have %d elements, not %d\", parameterName,\n expectedLength, actualLength);\n }\n }", "private void writeCompressedText(File file, byte[] compressedContent) throws IOException\r\n {\r\n ByteArrayInputStream bais = new ByteArrayInputStream(compressedContent);\r\n GZIPInputStream gis = new GZIPInputStream(bais);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(gis));\r\n BufferedWriter output = new BufferedWriter(new FileWriter(file));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n gis.close();\r\n bais.close();\r\n output.close();\r\n }", "private void getMultipleValues(Method method, Object object, Map<String, String> map)\n {\n try\n {\n int index = 1;\n while (true)\n {\n Object value = filterValue(method.invoke(object, Integer.valueOf(index)));\n if (value != null)\n {\n map.put(getPropertyName(method, index), String.valueOf(value));\n }\n ++index;\n }\n }\n catch (Exception ex)\n {\n // Reached the end of the valid indexes\n }\n }", "private boolean computeEigenValues() {\n // make a copy of the internal tridiagonal matrix data for later use\n diagSaved = helper.copyDiag(diagSaved);\n offSaved = helper.copyOff(offSaved);\n\n vector.setQ(null);\n vector.setFastEigenvalues(true);\n\n // extract the eigenvalues\n if( !vector.process(-1,null,null) )\n return false;\n\n // save a copy of them since this data structure will be recycled next\n values = helper.copyEigenvalues(values);\n return true;\n }", "public static byte[] getBytes(String string, String encoding) {\n try {\n return string.getBytes(encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }", "public void signOff(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key);\n if (null == connections) {\n return;\n }\n connections.remove(connection);\n }" ]
Remember execution time for all executed suites.
[ "@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n long millis = e.getExecutionTime();\n String suiteName = e.getDescription().getDisplayName();\n \n List<Long> values = hints.get(suiteName);\n if (values == null) {\n hints.put(suiteName, values = new ArrayList<>());\n }\n values.add(millis);\n while (values.size() > historyLength)\n values.remove(0);\n }" ]
[ "public static base_responses update(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite updateresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbsite();\n\t\t\t\tupdateresources[i].sitename = resources[i].sitename;\n\t\t\t\tupdateresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\tupdateresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\tupdateresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\tupdateresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException {\n build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(),\n getSvnAuthenticationProvider(build), buildListener));\n }", "public void addNotification(@Observes final DesignerNotificationEvent event) {\n if (user.getIdentifier().equals(event.getUserId())) {\n\n if (event.getNotification() != null && !event.getNotification().equals(\"openinxmleditor\")) {\n final NotificationPopupView view = new NotificationPopupView();\n activeNotifications.add(view);\n view.setPopupPosition(getMargin(),\n activeNotifications.size() * SPACING);\n\n view.setNotification(event.getNotification());\n view.setType(event.getType());\n view.setNotificationWidth(getWidth() + \"px\");\n view.show(new Command() {\n\n @Override\n public void execute() {\n //The notification has been shown and can now be removed\n deactiveNotifications.add(view);\n remove();\n }\n });\n }\n }\n }", "@Override\n\tpublic synchronized boolean fireEventAndWait(Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, NoSuchElementException, InterruptedException {\n\t\ttry {\n\n\t\t\tboolean handleChanged = false;\n\t\t\tboolean result = false;\n\n\t\t\tif (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals(\"\")) {\n\t\t\t\tLOGGER.debug(\"switching to frame: \" + eventable.getRelatedFrame());\n\t\t\t\ttry {\n\n\t\t\t\t\tswitchToFrame(eventable.getRelatedFrame());\n\t\t\t\t} catch (NoSuchFrameException e) {\n\t\t\t\t\tLOGGER.debug(\"Frame not found, possibly while back-tracking..\", e);\n\t\t\t\t\t// TODO Stefan, This exception is caught to prevent stopping\n\t\t\t\t\t// from working\n\t\t\t\t\t// This was the case on the Gmail case; find out if not switching\n\t\t\t\t\t// (catching)\n\t\t\t\t\t// Results in good performance...\n\t\t\t\t}\n\t\t\t\thandleChanged = true;\n\t\t\t}\n\n\t\t\tWebElement webElement =\n\t\t\t\t\tbrowser.findElement(eventable.getIdentification().getWebDriverBy());\n\n\t\t\tif (webElement != null) {\n\t\t\t\tresult = fireEventWait(webElement, eventable);\n\t\t\t}\n\n\t\t\tif (handleChanged) {\n\t\t\t\tbrowser.switchTo().defaultContent();\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tthrow e;\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\treturn false;\n\t\t}\n\t}", "public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }", "public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}", "public Collection<Locale> getCountries() {\n Collection<Locale> result = get(KEY_QUERY_COUNTRIES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "private boolean costRateTableWriteRequired(CostRateTableEntry entry, Date from)\n {\n boolean fromDate = (DateHelper.compare(from, DateHelper.FIRST_DATE) > 0);\n boolean toDate = (DateHelper.compare(entry.getEndDate(), DateHelper.LAST_DATE) > 0);\n boolean costPerUse = (NumberHelper.getDouble(entry.getCostPerUse()) != 0);\n boolean overtimeRate = (entry.getOvertimeRate() != null && entry.getOvertimeRate().getAmount() != 0);\n boolean standardRate = (entry.getStandardRate() != null && entry.getStandardRate().getAmount() != 0);\n return (fromDate || toDate || costPerUse || overtimeRate || standardRate);\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 }" ]
Get global hotkey provider for current platform @param useSwingEventQueue whether the provider should be using Swing Event queue or a regular thread @return new instance of Provider, or null if platform is not supported @see X11Provider @see WindowsProvider @see CarbonProvider
[ "public static Provider getCurrentProvider(boolean useSwingEventQueue) {\n Provider provider;\n if (Platform.isX11()) {\n provider = new X11Provider();\n } else if (Platform.isWindows()) {\n provider = new WindowsProvider();\n } else if (Platform.isMac()) {\n provider = new CarbonProvider();\n } else {\n LOGGER.warn(\"No suitable provider for \" + System.getProperty(\"os.name\"));\n return null;\n }\n provider.setUseSwingEventQueue(useSwingEventQueue);\n provider.init();\n return provider;\n\n }" ]
[ "private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)\n {\n AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);\n if (ruleProvider == null)\n return;\n\n if (!timeTakenByProvider.containsKey(ruleProvider))\n {\n RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)\n .create();\n model.setRuleIndex(ruleIndex);\n model.setRuleProviderID(ruleProvider.getMetadata().getID());\n model.setTimeTaken(timeTaken);\n\n timeTakenByProvider.put(ruleProvider, model.getElement().id());\n }\n else\n {\n RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);\n RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);\n }", "public Collection<User> getFavorites(String photoId, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n\r\n parameters.put(\"method\", METHOD_GET_FAVORITES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n List<User> users = new ArrayList<User>();\r\n\r\n Element userRoot = response.getPayload();\r\n NodeList userNodes = userRoot.getElementsByTagName(\"person\");\r\n for (int i = 0; i < userNodes.getLength(); i++) {\r\n Element userElement = (Element) userNodes.item(i);\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n user.setUsername(userElement.getAttribute(\"username\"));\r\n user.setFaveDate(userElement.getAttribute(\"favedate\"));\r\n users.add(user);\r\n }\r\n return users;\r\n }", "private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }", "public static base_response update(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder updateresource = new sslocspresponder();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.cache = resource.cache;\n\t\tupdateresource.cachetimeout = resource.cachetimeout;\n\t\tupdateresource.batchingdepth = resource.batchingdepth;\n\t\tupdateresource.batchingdelay = resource.batchingdelay;\n\t\tupdateresource.resptimeout = resource.resptimeout;\n\t\tupdateresource.respondercert = resource.respondercert;\n\t\tupdateresource.trustresponder = resource.trustresponder;\n\t\tupdateresource.producedattimeskew = resource.producedattimeskew;\n\t\tupdateresource.signingcert = resource.signingcert;\n\t\tupdateresource.usenonce = resource.usenonce;\n\t\tupdateresource.insertclientcert = resource.insertclientcert;\n\t\treturn updateresource.update_resource(client);\n\t}", "public final PJsonArray getJSONArray(final String key) {\n final JSONArray val = this.obj.optJSONArray(key);\n if (val == null) {\n throw new ObjectMissingException(this, key);\n }\n return new PJsonArray(this, val, key);\n }", "public static int[] insertArray(int[] original, int index, int[] inserted) {\n int[] modified = new int[original.length + inserted.length];\n System.arraycopy(original, 0, modified, 0, index);\n System.arraycopy(inserted, 0, modified, index, inserted.length);\n System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);\n return modified;\n }", "public static appfwprofile_denyurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_denyurl_binding obj = new appfwprofile_denyurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_denyurl_binding response[] = (appfwprofile_denyurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void endRequest() {\n final List<RequestScopedItem> result = CACHE.get();\n if (result != null) {\n CACHE.remove();\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }", "public String tag(ImapRequestLineReader request) throws ProtocolException {\n CharacterValidator validator = new TagCharValidator();\n return consumeWord(request, validator);\n }" ]
Use this API to fetch appfwjsoncontenttype resources of given names .
[ "public static appfwjsoncontenttype[] get(nitro_service service, String jsoncontenttypevalue[]) throws Exception{\n\t\tif (jsoncontenttypevalue !=null && jsoncontenttypevalue.length>0) {\n\t\t\tappfwjsoncontenttype response[] = new appfwjsoncontenttype[jsoncontenttypevalue.length];\n\t\t\tappfwjsoncontenttype obj[] = new appfwjsoncontenttype[jsoncontenttypevalue.length];\n\t\t\tfor (int i=0;i<jsoncontenttypevalue.length;i++) {\n\t\t\t\tobj[i] = new appfwjsoncontenttype();\n\t\t\t\tobj[i].set_jsoncontenttypevalue(jsoncontenttypevalue[i]);\n\t\t\t\tresponse[i] = (appfwjsoncontenttype) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public void setAttribute(final String name, final Attribute attribute) {\n if (name.equals(MAP_KEY)) {\n this.mapAttribute = (MapAttribute) attribute;\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 ServerGroup addServerGroup(String groupName) {\n ServerGroup group = new ServerGroup();\n\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", groupName),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP, params));\n group = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return group;\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 }", "private Pair<Double, String>\n summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\n\" + title + \"\\n\");\n\n Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>();\n for(Integer zoneId: cluster.getZoneIds()) {\n zoneToBalanceStats.put(zoneId, new ZoneBalanceStats());\n }\n\n for(Node node: cluster.getNodes()) {\n int curCount = nodeIdToPartitionCount.get(node.getId());\n builder.append(\"\\tNode ID: \" + node.getId() + \" : \" + curCount + \" (\" + node.getHost()\n + \")\\n\");\n zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount);\n }\n\n // double utilityToBeMinimized = Double.MIN_VALUE;\n double utilityToBeMinimized = 0;\n for(Integer zoneId: cluster.getZoneIds()) {\n builder.append(\"Zone \" + zoneId + \"\\n\");\n builder.append(zoneToBalanceStats.get(zoneId).dumpStats());\n utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility();\n /*- \n * Another utility function to consider \n if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) {\n utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility();\n }\n */\n }\n\n return Pair.create(utilityToBeMinimized, builder.toString());\n }", "@Override\n protected void denyImportDeclaration(ImportDeclaration importDeclaration) {\n LOG.debug(\"CXFImporter destroy a proxy for \" + importDeclaration);\n ServiceRegistration serviceRegistration = map.get(importDeclaration);\n serviceRegistration.unregister();\n\n // set the importDeclaration has unhandled\n super.unhandleImportDeclaration(importDeclaration);\n\n map.remove(importDeclaration);\n }", "private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {\n\t\tif ( configurationResourceUrl != null ) {\n\t\t\ttry ( InputStream openStream = configurationResourceUrl.openStream() ) {\n\t\t\t\thotRodConfiguration.load( openStream );\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow log.failedLoadingHotRodConfigurationProperties( e );\n\t\t\t}\n\t\t}\n\t}", "public void setShadow(float radius, float dx, float dy, int color) {\n\t\tshadowRadius = radius;\n\t\tshadowDx = dx;\n\t\tshadowDy = dy;\n\t\tshadowColor = color;\n\t\tupdateShadow();\n\t}", "public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}" ]
Turns a series of strings into their corresponding license entities by using regular expressions @param licStrings The list of license strings @return A set of license entities
[ "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 static CharSequence getAt(CharSequence text, IntRange range) {\n return getAt(text, (Range) range);\n }", "private void computeUnnamedParams() {\n unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList()));\n }", "public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}", "public static double TopsoeDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double den = p[i] + q[i];\n r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);\n }\n }\n return r;\n }", "void writeBestRankTriples() {\n\t\tfor (Resource resource : this.rankBuffer.getBestRankedStatements()) {\n\t\t\ttry {\n\t\t\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\t\t\tRdfWriter.RDF_TYPE, RdfWriter.WB_BEST_RANK.toString());\n\t\t\t} catch (RDFHandlerException e) {\n\t\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tthis.rankBuffer.clear();\n\t}", "public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken, Integer paginationPageSize) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>)readerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class,\n OauthToken.class, RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, paginationPageSize, false);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }", "public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }", "public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}", "public static authenticationradiuspolicy_vpnvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnvserver_binding obj = new authenticationradiuspolicy_vpnvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnvserver_binding response[] = (authenticationradiuspolicy_vpnvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Seeks to the given holiday within the given year @param holidayString @param yearString
[ "public void seekToHolidayYear(String holidayString, String yearString) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary());\n }" ]
[ "public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);\r\n }", "public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {\n int points = DEFAULT_ARC_POINTS;\n\n MVCArray res = new MVCArray();\n\n if (startBearing > endBearing) {\n endBearing += 360.0;\n }\n double deltaBearing = endBearing - startBearing;\n deltaBearing = deltaBearing / points;\n for (int i = 0; (i < points + 1); i++) {\n res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));\n }\n\n return res;\n\n }", "public BoxFile.Info getFileInfo(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }", "public static Info inviteUserToEnterprise(BoxAPIConnection api, String userLogin, String enterpriseID) {\n\n URL url = INVITE_CREATION_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n JsonObject body = new JsonObject();\n\n JsonObject enterprise = new JsonObject();\n enterprise.add(\"id\", enterpriseID);\n body.add(\"enterprise\", enterprise);\n\n JsonObject actionableBy = new JsonObject();\n actionableBy.add(\"login\", userLogin);\n body.add(\"actionable_by\", actionableBy);\n\n request.setBody(body);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxInvite invite = new BoxInvite(api, responseJSON.get(\"id\").asString());\n return invite.new Info(responseJSON);\n }", "private String parameter(Options opt, Parameter p[]) {\n\tStringBuilder par = new StringBuilder(1000);\n\tfor (int i = 0; i < p.length; i++) {\n\t par.append(p[i].name() + typeAnnotation(opt, p[i].type()));\n\t if (i + 1 < p.length)\n\t\tpar.append(\", \");\n\t}\n\treturn par.toString();\n }", "@SuppressWarnings(\"rawtypes\")\n private static <T> Constructor<T> findConstructor(final Class<T> clazz, final Object... args)\n throws NoSuchConstructorException, AmbiguousConstructorException {\n final Object[] cArgs = (args == null) ? new Object[0] : args;\n Constructor<T> constructorToUse = null;\n final Constructor<?>[] candidates = clazz.getConstructors();\n Arrays.sort(candidates, ConstructorComparator.INSTANCE);\n int minTypeDiffWeight = Integer.MAX_VALUE;\n Set<Constructor<?>> ambiguousConstructors = null;\n for (final Constructor candidate : candidates) {\n final Class[] paramTypes = candidate.getParameterTypes();\n if (constructorToUse != null && cArgs.length > paramTypes.length) {\n // Already found greedy constructor that can be satisfied.\n // Do not look any further, there are only less greedy\n // constructors left.\n break;\n }\n if (paramTypes.length != cArgs.length) {\n continue;\n }\n final int typeDiffWeight = getTypeDifferenceWeight(paramTypes, cArgs);\n if (typeDiffWeight < minTypeDiffWeight) { \n // Choose this constructor if it represents the closest match.\n constructorToUse = candidate;\n minTypeDiffWeight = typeDiffWeight;\n ambiguousConstructors = null;\n } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {\n if (ambiguousConstructors == null) {\n ambiguousConstructors = new LinkedHashSet<Constructor<?>>();\n ambiguousConstructors.add(constructorToUse);\n }\n ambiguousConstructors.add(candidate);\n }\n }\n if (ambiguousConstructors != null && !ambiguousConstructors.isEmpty()) {\n throw new AmbiguousConstructorException(clazz, cArgs, ambiguousConstructors);\n }\n if (constructorToUse == null) {\n throw new NoSuchConstructorException(clazz, cArgs);\n }\n return constructorToUse;\n }", "public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n // 1. handle the special cases first.\r\n if (row == 0)\r\n {\r\n return true;\r\n }\r\n\r\n if (row == 1)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n m_activeIterator.absolute(1);\r\n return true;\r\n }\r\n if (row == -1)\r\n {\r\n m_activeIteratorIndex = m_rsIterators.size();\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n m_activeIterator.absolute(-1);\r\n return true;\r\n }\r\n\r\n // now do the real work.\r\n boolean movedToAbsolute = false;\r\n boolean retval = false;\r\n setNextIterator();\r\n\r\n // row is positive, so index from beginning.\r\n if (row > 0)\r\n {\r\n int sizeCount = 0;\r\n Iterator it = m_rsIterators.iterator();\r\n OJBIterator temp = null;\r\n while (it.hasNext() && !movedToAbsolute)\r\n {\r\n temp = (OJBIterator) it.next();\r\n if (temp.size() < row)\r\n {\r\n sizeCount += temp.size();\r\n }\r\n else\r\n {\r\n // move to the offset - sizecount\r\n m_currentCursorPosition = row - sizeCount;\r\n retval = temp.absolute(m_currentCursorPosition);\r\n movedToAbsolute = true;\r\n }\r\n }\r\n\r\n }\r\n\r\n // row is negative, so index from end\r\n else if (row < 0)\r\n {\r\n int sizeCount = 0;\r\n OJBIterator temp = null;\r\n for (int i = m_rsIterators.size(); ((i >= 0) && !movedToAbsolute); i--)\r\n {\r\n temp = (OJBIterator) m_rsIterators.get(i);\r\n if (temp.size() < row)\r\n {\r\n sizeCount += temp.size();\r\n }\r\n else\r\n {\r\n // move to the offset - sizecount\r\n m_currentCursorPosition = row + sizeCount;\r\n retval = temp.absolute(m_currentCursorPosition);\r\n movedToAbsolute = true;\r\n }\r\n }\r\n }\r\n\r\n return retval;\r\n }", "private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {\n if (!getWaveformListeners().isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);\n for (final WaveformListener listener : getWaveformListeners()) {\n try {\n listener.detailChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform detail update to listener\", t);\n }\n }\n }\n });\n }\n }", "public void check(ReferenceDescriptorDef refDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureClassRef(refDef, checkLevel);\r\n checkProxyPrefetchingLimit(refDef, checkLevel);\r\n }" ]
Creates the tables according to the schema files. @throws PlatformException If some error occurred
[ "public void initDB() throws PlatformException\r\n {\r\n if (_initScripts.isEmpty())\r\n {\r\n createInitScripts();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueSQLTask sqlTask = new TorqueSQLTask(); \r\n File outputDir = null;\r\n \r\n try\r\n {\r\n outputDir = new File(getWorkDir(), \"sql\");\r\n\r\n outputDir.mkdir();\r\n writeCompressedTexts(outputDir, _initScripts);\r\n\r\n project.setBasedir(outputDir.getAbsolutePath());\r\n\r\n // executing the generated sql, but this time with a torque task \r\n TorqueSQLExec sqlExec = new TorqueSQLExec();\r\n TorqueSQLExec.OnError onError = new TorqueSQLExec.OnError();\r\n\r\n sqlExec.setProject(project);\r\n onError.setValue(\"continue\");\r\n sqlExec.setAutocommit(true);\r\n sqlExec.setDriver(_jcd.getDriver());\r\n sqlExec.setOnerror(onError);\r\n sqlExec.setUserid(_jcd.getUserName());\r\n sqlExec.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n sqlExec.setUrl(getDBManipulationUrl());\r\n sqlExec.setSrcDir(outputDir.getAbsolutePath());\r\n sqlExec.setSqlDbMap(SQL_DB_MAP_NAME);\r\n sqlExec.execute();\r\n \r\n deleteDir(outputDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if (outputDir != null)\r\n {\r\n deleteDir(outputDir);\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }" ]
[ "synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }", "private static String getBindingId(Server server) {\n Endpoint ep = server.getEndpoint();\n BindingInfo bi = ep.getBinding().getBindingInfo();\n return bi.getBindingId();\n }", "public static int cudnnCTCLoss(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the\n mini batch size, A is the alphabet size) */\n Pointer probs, /** probabilities after softmax, in GPU memory */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n Pointer costs, /** the returned costs of CTC, in GPU memory */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the dimensions are T,N,A */\n Pointer gradients, /** the returned CTC gradients, in GPU memory, to compute costs only, set it to NULL */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n Pointer workspace, /** pointer to the workspace, in GPU memory */\n long workSpaceSizeInBytes)/** the workspace size needed */\n {\n return checkResult(cudnnCTCLossNative(handle, probsDesc, probs, labels, labelLengths, inputLengths, costs, gradientsDesc, gradients, algo, ctcLossDesc, workspace, workSpaceSizeInBytes));\n }", "private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n }", "static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }", "public 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}", "@Override\n public void detachScriptFile(IScriptable target) {\n IScriptFile scriptFile = mScriptMap.remove(target);\n if (scriptFile != null) {\n scriptFile.invokeFunction(\"onDetach\", new Object[] { target });\n }\n }", "public Date getTime(String fieldName) {\n\t\ttry {\n\t\t\tif (hasValue(fieldName)) {\n\t\t\t\treturn new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000);\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a time.\", e);\n\t\t}\n\t}", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
Lookup a native pointer to a collider and return its Java object. @param nativePointer native pointer to C++ Collider @return Java GVRCollider object
[ "static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }" ]
[ "public static BoxLegalHoldPolicy.Info createOngoing(BoxAPIConnection api, String name, String description) {\n URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_name\", name)\n .add(\"is_ongoing\", true);\n if (description != null) {\n requestJSON.add(\"description\", description);\n }\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldPolicy createdPolicy = new BoxLegalHoldPolicy(api, responseJSON.get(\"id\").asString());\n return createdPolicy.new Info(responseJSON);\n }", "public static String ellipsize(String text, int maxLength, String end) {\n if (text != null && text.length() > maxLength) {\n return text.substring(0, maxLength - end.length()) + end;\n }\n return text;\n }", "public AT_Row setPaddingRight(int paddingRight) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static <E extends Style.HasCssName, F extends Enum<? extends Style.HasCssName>> void addUniqueEnumStyleName(final UIObject uiObject,\n final Class<F> enumClass,\n final E style) {\n removeEnumStyleNames(uiObject, enumClass);\n addEnumStyleName(uiObject, style);\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 }", "private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\n }", "@Override\n public void close(SocketDestination destination) {\n factory.setLastClosedTimestamp(destination);\n queuedPool.reset(destination);\n }", "@JmxOperation(description = \"Forcefully invoke the log cleaning\")\n public void cleanLogs() {\n synchronized(lock) {\n try {\n for(Environment environment: environments.values()) {\n environment.cleanLog();\n }\n } catch(DatabaseException e) {\n throw new VoldemortException(e);\n }\n }\n }", "public MediaType removeQualityValue() {\n\t\tif (!this.parameters.containsKey(PARAM_QUALITY_FACTOR)) {\n\t\t\treturn this;\n\t\t}\n\t\tMap<String, String> params = new LinkedHashMap<String, String>(this.parameters);\n\t\tparams.remove(PARAM_QUALITY_FACTOR);\n\t\treturn new MediaType(this, params);\n\t}" ]
Create a new builder for multiple unpaginated requests on the view. @param keyType {@link com.cloudant.client.api.views.Key.Type} of the key emitted by the view @param valueType class of the type of value emitted by the view @param <K> type of key emitted by the view @param <V> type of value emitted by the view @return a new {@link MultipleRequestBuilder} for the database view specified by this ViewRequestBuilder
[ "public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType,\n Class<V> valueType) {\n return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(),\n valueType));\n }" ]
[ "public Object getBeliefValue(String agent_name, final String belief_name,\n Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n belief_value = bia.getBeliefbase()\n .getBelief(belief_name).getFact();\n return null;\n }\n }).get(new ThreadSuspendable());\n return belief_value;\n }", "public static double blackModelDgitialCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;\n\t}", "private void writeToDelegate(byte[] data) {\n\n if (m_delegateStream != null) {\n try {\n m_delegateStream.write(data);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }", "public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }", "private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }", "private void writeProjectProperties(ProjectProperties record) throws IOException\n {\n // the ProjectProperties class from MPXJ has the details of how many days per week etc....\n // so I've assigned these variables in here, but actually use them in other methods\n // see the write task method, that's where they're used, but that method only has a Task object\n m_minutesPerDay = record.getMinutesPerDay().doubleValue();\n m_minutesPerWeek = record.getMinutesPerWeek().doubleValue();\n m_daysPerMonth = record.getDaysPerMonth().doubleValue();\n\n // reset buffer to be empty, then concatenate data as required by USACE\n m_buffer.setLength(0);\n m_buffer.append(\"PROJ \");\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // DataDate\n m_buffer.append(SDEFmethods.lset(record.getManager(), 4) + \" \"); // ProjIdent\n m_buffer.append(SDEFmethods.lset(record.getProjectTitle(), 48) + \" \"); // ProjName\n m_buffer.append(SDEFmethods.lset(record.getSubject(), 36) + \" \"); // ContrName\n m_buffer.append(\"P \"); // ArrowP\n m_buffer.append(SDEFmethods.lset(record.getKeywords(), 7)); // ContractNum\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // ProjStart\n m_buffer.append(m_formatter.format(record.getFinishDate()).toUpperCase()); // ProjEnd\n m_writer.println(m_buffer);\n }", "public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);\r\n }", "public static protocolhttpband[] get(nitro_service service, protocolhttpband_args args) throws Exception{\n\t\tprotocolhttpband obj = new protocolhttpband();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tprotocolhttpband[] response = (protocolhttpband[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "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 }" ]
<<<<<< measureUntilFull helper methods
[ "@Override\n protected boolean changeDirection(int currentIndex, int centerIndex, boolean inBounds) {\n boolean changed = false;\n if (getGravityInternal() == Gravity.CENTER &&\n currentIndex <= centerIndex &&\n currentIndex == 0 || !inBounds) {\n\n changed = true;\n }\n return changed;\n }" ]
[ "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 deleteArtifact(final String gavc, 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.getArtifactPath(gavc));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to DELETE artifact \" + gavc;\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 }", "@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }", "public void setIndirectionHandlerClass(Class indirectionHandlerClass)\r\n {\r\n if(indirectionHandlerClass == null)\r\n {\r\n //throw new MetadataException(\"No IndirectionHandlerClass specified.\");\r\n /**\r\n * andrew.clute\r\n * Allow the default IndirectionHandler for the given ProxyFactory implementation\r\n * when the parameter is not given\r\n */\r\n indirectionHandlerClass = getDefaultIndirectionHandlerClass();\r\n }\r\n if(indirectionHandlerClass.isInterface()\r\n || Modifier.isAbstract(indirectionHandlerClass.getModifiers())\r\n || !getIndirectionHandlerBaseClass().isAssignableFrom(indirectionHandlerClass))\r\n {\r\n throw new MetadataException(\"Illegal class \"\r\n + indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass. Must be a concrete subclass of \"\r\n + getIndirectionHandlerBaseClass().getName());\r\n }\r\n _indirectionHandlerClass = indirectionHandlerClass;\r\n }", "private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }", "public final void setFindDetails(boolean findDetails) {\n this.findDetails.set(findDetails);\n if (findDetails) {\n primeCache(); // Get details for any tracks that were already loaded on players.\n } else {\n // Inform our listeners, on the proper thread, that the detailed waveforms are no longer available\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(detailHotCache.keySet());\n detailHotCache.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n deliverWaveformDetailUpdate(deck.player, null);\n }\n }\n });\n }\n }", "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 }", "public static Chart getTrajectoryChart(String title, Trajectory t){\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[t.size()];\n\t\t double[] yData = new double[t.size()];\n\t\t for(int i = 0; i < t.size(); i++){\n\t\t \txData[i] = t.get(i).x;\n\t\t \tyData[i] = t.get(i).y;\n\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(title, \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\n\t\t return chart;\n\t\t //Show it\n\t\t // SwingWrapper swr = new SwingWrapper(chart);\n\t\t // swr.displayChart();\n\t\t} \n\t\treturn null;\n\t}", "public static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }" ]
Sets the ProjectCalendar instance from which this calendar is derived. @param calendar base calendar instance
[ "public void setParent(ProjectCalendar calendar)\n {\n // I've seen a malformed MSPDI file which sets the parent calendar to itself.\n // Silently ignore this here.\n if (calendar != this)\n {\n if (getParent() != null)\n {\n getParent().removeDerivedCalendar(this);\n }\n\n super.setParent(calendar);\n\n if (calendar != null)\n {\n calendar.addDerivedCalendar(this);\n }\n clearWorkingDateCache();\n }\n }" ]
[ "public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static String simpleTypeName(Object obj) {\n if (obj == null) {\n return \"null\";\n }\n\n return simpleTypeName(obj.getClass(), false);\n }", "@Override\n public EthiopicDate date(int prolepticYear, int month, int dayOfMonth) {\n return EthiopicDate.of(prolepticYear, month, dayOfMonth);\n }", "public static void writeShort(byte[] bytes, short value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 8));\n bytes[offset + 1] = (byte) (0xFF & value);\n }", "public void execute()\n {\n Runnable task = new Runnable()\n {\n public void run()\n {\n final V result = performTask();\n SwingUtilities.invokeLater(new Runnable()\n {\n public void run()\n {\n postProcessing(result);\n latch.countDown();\n }\n });\n }\n };\n new Thread(task, \"SwingBackgroundTask-\" + id).start();\n }", "@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 static rnatip_stats get(nitro_service service, String Rnatip) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\tobj.set_Rnatip(Rnatip);\n\t\trnatip_stats response = (rnatip_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static aaapreauthenticationpolicy_aaaglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_aaaglobal_binding obj = new aaapreauthenticationpolicy_aaaglobal_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_aaaglobal_binding response[] = (aaapreauthenticationpolicy_aaaglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String getSimpleClassName(String className) {\n\t\t// get the last part of the class name\n\t\tString[] parts = className.split(\"\\\\.\");\n\t\tif (parts.length <= 1) {\n\t\t\treturn className;\n\t\t} else {\n\t\t\treturn parts[parts.length - 1];\n\t\t}\n\t}" ]
Populate the authenticated user profiles in the Shiro subject. @param profiles the linked hashmap of profiles
[ "public static void populateSubject(final LinkedHashMap<String, CommonProfile> profiles) {\n if (profiles != null && profiles.size() > 0) {\n final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);\n try {\n if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, false));\n } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, true));\n }\n } catch (final HttpAction e) {\n throw new TechnicalException(e);\n }\n }\n }" ]
[ "protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) {\n \tMap<String, TermImpl> updatedValues = new HashMap<>();\n \tfor(NameWithUpdate update : updates.values()) {\n if (!update.write) {\n continue;\n }\n updatedValues.put(update.value.getLanguageCode(), monolingualToJackson(update.value));\n \t}\n \treturn updatedValues;\n }", "public static base_responses delete(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static base_responses update(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface updateresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new Interface();\n\t\t\t\tupdateresources[i].id = resources[i].id;\n\t\t\t\tupdateresources[i].speed = resources[i].speed;\n\t\t\t\tupdateresources[i].duplex = resources[i].duplex;\n\t\t\t\tupdateresources[i].flowctl = resources[i].flowctl;\n\t\t\t\tupdateresources[i].autoneg = resources[i].autoneg;\n\t\t\t\tupdateresources[i].hamonitor = resources[i].hamonitor;\n\t\t\t\tupdateresources[i].tagall = resources[i].tagall;\n\t\t\t\tupdateresources[i].trunk = resources[i].trunk;\n\t\t\t\tupdateresources[i].lacpmode = resources[i].lacpmode;\n\t\t\t\tupdateresources[i].lacpkey = resources[i].lacpkey;\n\t\t\t\tupdateresources[i].lagtype = resources[i].lagtype;\n\t\t\t\tupdateresources[i].lacppriority = resources[i].lacppriority;\n\t\t\t\tupdateresources[i].lacptimeout = resources[i].lacptimeout;\n\t\t\t\tupdateresources[i].ifalias = resources[i].ifalias;\n\t\t\t\tupdateresources[i].throughput = resources[i].throughput;\n\t\t\t\tupdateresources[i].bandwidthhigh = resources[i].bandwidthhigh;\n\t\t\t\tupdateresources[i].bandwidthnormal = resources[i].bandwidthnormal;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void linkOneToOne(Object obj, ClassDescriptor cld, ObjectReferenceDescriptor rds, boolean insert)\n {\n storeAndLinkOneToOne(true, obj, cld, rds, true);\n }", "public Dataset<String, String> getDataset(Dataset<String, String> oldData, Index<String> goodFeatures) {\r\n //public Dataset getDataset(List data, Collection goodFeatures) {\r\n //makeAnswerArraysAndTagIndex(data);\r\n\r\n int[][] oldDataArray = oldData.getDataArray();\r\n int[] oldLabelArray = oldData.getLabelsArray();\r\n Index<String> oldFeatureIndex = oldData.featureIndex;\r\n\r\n int[] oldToNewFeatureMap = new int[oldFeatureIndex.size()];\r\n\r\n int[][] newDataArray = new int[oldDataArray.length][];\r\n\r\n System.err.print(\"Building reduced dataset...\");\r\n\r\n int size = oldFeatureIndex.size();\r\n int max = 0;\r\n for (int i = 0; i < size; i++) {\r\n oldToNewFeatureMap[i] = goodFeatures.indexOf(oldFeatureIndex.get(i));\r\n if (oldToNewFeatureMap[i] > max) {\r\n max = oldToNewFeatureMap[i];\r\n }\r\n }\r\n\r\n for (int i = 0; i < oldDataArray.length; i++) {\r\n int[] data = oldDataArray[i];\r\n size = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n if (oldToNewFeatureMap[data[j]] > 0) {\r\n size++;\r\n }\r\n }\r\n int[] newData = new int[size];\r\n int index = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n int f = oldToNewFeatureMap[data[j]];\r\n if (f > 0) {\r\n newData[index++] = f;\r\n }\r\n }\r\n newDataArray[i] = newData;\r\n }\r\n\r\n Dataset<String, String> train = new Dataset<String, String>(oldData.labelIndex, oldLabelArray, goodFeatures, newDataArray, newDataArray.length);\r\n\r\n System.err.println(\"done.\");\r\n if (flags.featThreshFile != null) {\r\n System.err.println(\"applying thresholds...\");\r\n List<Pair<Pattern,Integer>> thresh = getThresholds(flags.featThreshFile);\r\n train.applyFeatureCountThreshold(thresh);\r\n } else if (flags.featureThreshold > 1) {\r\n System.err.println(\"Removing Features with counts < \" + flags.featureThreshold);\r\n train.applyFeatureCountThreshold(flags.featureThreshold);\r\n }\r\n train.summaryStatistics();\r\n return train;\r\n }", "private PlayState3 findPlayState3() {\n PlayState3 result = PLAY_STATE_3_MAP.get(packetBytes[157]);\n if (result == null) {\n return PlayState3.UNKNOWN;\n }\n return result;\n }", "public static final Boolean parseBoolean(String value)\n {\n return (value == null || value.charAt(0) != '1' ? Boolean.FALSE : Boolean.TRUE);\n }", "public static final PatchOperationTarget createStandalone(final ModelControllerClient controllerClient) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(CORE_SERVICES);\n return new RemotePatchOperationTarget(address, controllerClient);\n }", "public double[] getZeroRates(double[] maturities)\n\t{\n\t\tdouble[] values = new double[maturities.length];\n\n\t\tfor(int i=0; i<maturities.length; i++) {\n\t\t\tvalues[i] = getZeroRate(maturities[i]);\n\t\t}\n\n\t\treturn values;\n\t}" ]
Init the headers of the table regarding the filters @return String[]
[ "private String[] getHeaders() {\n final List<String> headers = new ArrayList<>();\n\n if(decorator.getShowSources()){\n headers.add(SOURCE_FIELD);\n }\n\n if(decorator.getShowSourcesVersion()){\n headers.add(SOURCE_VERSION_FIELD);\n }\n\n if(decorator.getShowTargets()){\n headers.add(TARGET_FIELD);\n }\n\n if(decorator.getShowTargetsDownloadUrl()){\n headers.add(DOWNLOAD_URL_FIELD);\n }\n\n if(decorator.getShowTargetsSize()){\n headers.add(SIZE_FIELD);\n }\n\n if(decorator.getShowScopes()){\n headers.add(SCOPE_FIELD);\n }\n\n if(decorator.getShowLicenses()){\n headers.add(LICENSE_FIELD);\n }\n\n if(decorator.getShowLicensesLongName()){\n headers.add(LICENSE_LONG_NAME_FIELD);\n }\n\n if(decorator.getShowLicensesUrl()){\n headers.add(LICENSE_URL_FIELD);\n }\n\n if(decorator.getShowLicensesComment()){\n headers.add(LICENSE_COMMENT_FIELD);\n }\n\n return headers.toArray(new String[headers.size()]);\n }" ]
[ "public void setWholeDay(Boolean isWholeDay) {\r\n\r\n if (m_model.isWholeDay() ^ ((null != isWholeDay) && isWholeDay.booleanValue())) {\r\n m_model.setWholeDay(isWholeDay);\r\n valueChanged();\r\n }\r\n }", "public VerticalLayout getEmptyLayout() {\n\n m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey());\n setVisible(size() > 0);\n m_emptyLayout.setVisible(size() == 0);\n return m_emptyLayout;\n }", "private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }", "private void tagvalue(Options opt, Doc c) {\n\tTag tags[] = c.tags(\"tagvalue\");\n\tif (tags.length == 0)\n\t return;\n\t\n\tfor (Tag tag : tags) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 2) {\n\t\tSystem.err.println(\"@tagvalue expects two fields: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(Align.RIGHT, Font.TAG.wrap(opt, \"{\" + t[0] + \" = \" + t[1] + \"}\"));\n\t}\n }", "public ParallelTaskBuilder setSshPrivKeyRelativePath(\n String privKeyRelativePath) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\n }", "public List<Ticket> checkTickets(Set<String> tickets) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CHECK_TICKETS);\r\n\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = tickets.iterator();\r\n while (it.hasNext()) {\r\n if (sb.length() > 0) {\r\n sb.append(\",\");\r\n }\r\n Object obj = it.next();\r\n if (obj instanceof Ticket) {\r\n sb.append(((Ticket) obj).getTicketId());\r\n } else {\r\n sb.append(obj);\r\n }\r\n }\r\n parameters.put(\"tickets\", sb.toString());\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n // <uploader>\r\n // <ticket id=\"128\" complete=\"1\" photoid=\"2995\" />\r\n // <ticket id=\"129\" complete=\"0\" />\r\n // <ticket id=\"130\" complete=\"2\" />\r\n // <ticket id=\"131\" invalid=\"1\" />\r\n // </uploader>\r\n\r\n List<Ticket> list = new ArrayList<Ticket>();\r\n Element uploaderElement = response.getPayload();\r\n NodeList ticketNodes = uploaderElement.getElementsByTagName(\"ticket\");\r\n int n = ticketNodes.getLength();\r\n for (int i = 0; i < n; i++) {\r\n Element ticketElement = (Element) ticketNodes.item(i);\r\n String id = ticketElement.getAttribute(\"id\");\r\n String complete = ticketElement.getAttribute(\"complete\");\r\n boolean invalid = \"1\".equals(ticketElement.getAttribute(\"invalid\"));\r\n String photoId = ticketElement.getAttribute(\"photoid\");\r\n Ticket info = new Ticket();\r\n info.setTicketId(id);\r\n info.setInvalid(invalid);\r\n info.setStatus(Integer.parseInt(complete));\r\n info.setPhotoId(photoId);\r\n list.add(info);\r\n }\r\n return list;\r\n }", "protected Query buildMtoNImplementorQuery(Collection ids)\r\n {\r\n String[] indFkCols = getFksToThisClass();\r\n String[] indItemFkCols = getFksToItemClass();\r\n FieldDescriptor[] pkFields = getOwnerClassDescriptor().getPkFields();\r\n FieldDescriptor[] itemPkFields = getItemClassDescriptor().getPkFields();\r\n String[] cols = new String[indFkCols.length + indItemFkCols.length];\r\n int[] jdbcTypes = new int[indFkCols.length + indItemFkCols.length];\r\n\r\n // concatenate the columns[]\r\n System.arraycopy(indFkCols, 0, cols, 0, indFkCols.length);\r\n System.arraycopy(indItemFkCols, 0, cols, indFkCols.length, indItemFkCols.length);\r\n\r\n Criteria crit = buildPrefetchCriteria(ids, indFkCols, indItemFkCols, itemPkFields);\r\n\r\n // determine the jdbcTypes of the pks\r\n for (int i = 0; i < pkFields.length; i++)\r\n {\r\n jdbcTypes[i] = pkFields[i].getJdbcType().getType();\r\n }\r\n for (int i = 0; i < itemPkFields.length; i++)\r\n {\r\n jdbcTypes[pkFields.length + i] = itemPkFields[i].getJdbcType().getType();\r\n }\r\n\r\n ReportQueryByMtoNCriteria q = new ReportQueryByMtoNCriteria(getItemClassDescriptor().getClassOfObject(), cols,\r\n crit, false);\r\n q.setIndirectionTable(getCollectionDescriptor().getIndirectionTable());\r\n q.setJdbcTypes(jdbcTypes);\r\n\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n //check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n q.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n \r\n return q;\r\n }", "public void forceApply(String conflictResolution) {\n\n URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"conflict_resolution\", conflictResolution);\n request.setBody(requestJSON.toString());\n request.send();\n }", "static String toFormattedString(final String iban) {\n final StringBuilder ibanBuffer = new StringBuilder(iban);\n final int length = ibanBuffer.length();\n\n for (int i = 0; i < length / 4; i++) {\n ibanBuffer.insert((i + 1) * 4 + i, ' ');\n }\n\n return ibanBuffer.toString().trim();\n }" ]
Restores a saved connection state into this BoxAPIConnection. @see #save @param state the saved state that was created with {@link #save}.
[ "public void restore(String state) {\n JsonObject json = JsonObject.readFrom(state);\n String accessToken = json.get(\"accessToken\").asString();\n String refreshToken = json.get(\"refreshToken\").asString();\n long lastRefresh = json.get(\"lastRefresh\").asLong();\n long expires = json.get(\"expires\").asLong();\n String userAgent = json.get(\"userAgent\").asString();\n String tokenURL = json.get(\"tokenURL\").asString();\n String baseURL = json.get(\"baseURL\").asString();\n String baseUploadURL = json.get(\"baseUploadURL\").asString();\n boolean autoRefresh = json.get(\"autoRefresh\").asBoolean();\n int maxRequestAttempts = json.get(\"maxRequestAttempts\").asInt();\n\n this.accessToken = accessToken;\n this.refreshToken = refreshToken;\n this.lastRefresh = lastRefresh;\n this.expires = expires;\n this.userAgent = userAgent;\n this.tokenURL = tokenURL;\n this.baseURL = baseURL;\n this.baseUploadURL = baseUploadURL;\n this.autoRefresh = autoRefresh;\n this.maxRequestAttempts = maxRequestAttempts;\n }" ]
[ "public String asString() throws IOException {\n long len = getContentLength();\n ByteArrayOutputStream buf;\n if (0 < len) {\n buf = new ByteArrayOutputStream((int) len);\n } else {\n buf = new ByteArrayOutputStream();\n }\n writeTo(buf);\n return decode(buf.toByteArray(), getCharacterEncoding());\n }", "public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }", "public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void stop() {\n instanceLock.writeLock().lock();\n try {\n for (final NamespaceChangeStreamListener streamer : nsStreamers.values()) {\n streamer.stop();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "@Override\n public Map<String, String> values() {\n Map<String, String> values = new LinkedHashMap<>();\n for (Row each : delegates) {\n for (Entry<String, String> entry : each.values().entrySet()) {\n String name = entry.getKey();\n if (!values.containsKey(name)) {\n values.put(name, entry.getValue());\n }\n }\n }\n return values;\n }", "static ItemIdValueImpl fromIri(String iri) {\n\t\tint separator = iri.lastIndexOf('/') + 1;\n\t\ttry {\n\t\t\treturn new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator));\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid Wikibase entity IRI: \" + iri, e);\n\t\t}\n\t}", "public static String determineFieldName(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);\n\t}", "public static String getModuleName(final String moduleId) {\n final int splitter = moduleId.indexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(0, splitter);\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 }" ]
Delivers the correct JSON Object for the dockers @param dockers @throws org.json.JSONException
[ "private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }" ]
[ "public static base_response delete(nitro_service client, String ipv6prefix) throws Exception {\n\t\tonlinkipv6prefix deleteresource = new onlinkipv6prefix();\n\t\tdeleteresource.ipv6prefix = ipv6prefix;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }", "public Client setFriendlyName(int profileId, String clientUUID, String friendlyName) throws Exception {\n // first see if this friendlyName is already in use\n Client client = this.findClientFromFriendlyName(profileId, friendlyName);\n if (client != null && !client.getUUID().equals(clientUUID)) {\n throw new Exception(\"Friendly name already in use\");\n }\n\n PreparedStatement statement = null;\n int rowsAffected = 0;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_FRIENDLY_NAME + \" = ?\" +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = ?\" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\"\n );\n statement.setString(1, friendlyName);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n\n rowsAffected = statement.executeUpdate();\n } catch (Exception e) {\n\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (rowsAffected == 0) {\n return null;\n }\n return this.findClient(clientUUID, profileId);\n }", "protected void reportProgress(String taskDecription) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.setTaskName(taskDecription);\n }\n }", "private void processResources() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zresource where zproject=? order by zorderinproject\", m_projectID);\n for (Row row : rows)\n {\n Resource resource = m_project.addResource();\n resource.setUniqueID(row.getInteger(\"Z_PK\"));\n resource.setEmailAddress(row.getString(\"ZEMAIL\"));\n resource.setInitials(row.getString(\"ZINITIALS\"));\n resource.setName(row.getString(\"ZTITLE_\"));\n resource.setGUID(row.getUUID(\"ZUNIQUEID\"));\n resource.setType(row.getResourceType(\"ZTYPE\"));\n resource.setMaterialLabel(row.getString(\"ZMATERIALUNIT\"));\n\n if (resource.getType() == ResourceType.WORK)\n {\n resource.setMaxUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZAVAILABLEUNITS_\")) * 100.0));\n }\n\n Integer calendarID = row.getInteger(\"ZRESOURCECALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n calendar.setName(resource.getName());\n resource.setResourceCalendar(calendar);\n }\n }\n\n m_eventManager.fireResourceReadEvent(resource);\n }\n }", "private static Parameter buildParameter(final Map<String, GenericsType> genericFromReceiver, final Map<String, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) {\n if (genericFromReceiver.isEmpty() && (placeholdersFromContext==null||placeholdersFromContext.isEmpty())) {\n return methodParameter;\n }\n if (paramType.isArray()) {\n ClassNode componentType = paramType.getComponentType();\n Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName());\n Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType);\n return new Parameter(component.getType().makeArray(), component.getName());\n }\n ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType);\n\n return new Parameter(resolved, methodParameter.getName());\n }", "public void setPatternScheme(final boolean isWeekDayBased) {\n\n if (isWeekDayBased ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isWeekDayBased) {\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n } else {\n m_model.setWeekDay(null);\n m_model.setWeekOfMonth(null);\n }\n m_model.setMonth(getPatternDefaultValues().getMonth());\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }", "public static java.sql.Date newDate() {\n return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS);\n }", "public Set<BsonValue> getPausedDocumentIds(final MongoNamespace namespace) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final Set<BsonValue> pausedDocumentIds = new HashSet<>();\n\n for (final CoreDocumentSynchronizationConfig config :\n this.syncConfig.getSynchronizedDocuments(namespace)) {\n if (config.isPaused()) {\n pausedDocumentIds.add(config.getDocumentId());\n }\n }\n\n return pausedDocumentIds;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }" ]
Returns the foreignkey to the specified table. @param name The name of the foreignkey @param tableName The name of the referenced table @return The foreignkey def or <code>null</code> if it does not exist
[ "public ForeignkeyDef getForeignkey(String name, String tableName)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()) &&\r\n def.getTableName().equals(tableName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }" ]
[ "public void checkAllRequirementsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (Field field: this.dependantsInJson) {\n final Collection<String> requirements = this.dependantToRequirementsMap.get(field);\n if (!requirements.isEmpty()) {\n errors.append(\"\\n\");\n String type = field.getType().getName();\n if (field.getType().isArray()) {\n type = field.getType().getComponentType().getName() + \"[]\";\n }\n errors.append(\"\\t* \").append(type).append(' ').append(field.getName()).append(\" depends on \")\n .append(requirements);\n }\n }\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @Requires dependencies of '\" +\n currentPath + \"': \" + errors);\n }", "@SuppressFBWarnings(value = \"DMI_COLLECTION_OF_URLS\", justification = \"Only local URLs involved\")\n private Map<ConfigurationKey, Object> readFileProperties(Set<URL> files) {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n for (URL file : files) {\n ConfigurationLogger.LOG.readingPropertiesFile(file);\n Properties fileProperties = loadProperties(file);\n for (String name : fileProperties.stringPropertyNames()) {\n processKeyValue(found, name, fileProperties.getProperty(name));\n }\n }\n return found;\n }", "@Override\n public ImageSource apply(ImageSource input) {\n final int[][] pixelMatrix = new int[3][3];\n\n int w = input.getWidth();\n int h = input.getHeight();\n\n int[][] output = new int[h][w];\n\n for (int j = 1; j < h - 1; j++) {\n for (int i = 1; i < w - 1; i++) {\n pixelMatrix[0][0] = input.getR(i - 1, j - 1);\n pixelMatrix[0][1] = input.getRGB(i - 1, j);\n pixelMatrix[0][2] = input.getRGB(i - 1, j + 1);\n pixelMatrix[1][0] = input.getRGB(i, j - 1);\n pixelMatrix[1][2] = input.getRGB(i, j + 1);\n pixelMatrix[2][0] = input.getRGB(i + 1, j - 1);\n pixelMatrix[2][1] = input.getRGB(i + 1, j);\n pixelMatrix[2][2] = input.getRGB(i + 1, j + 1);\n\n int edge = (int) convolution(pixelMatrix);\n int rgb = (edge << 16 | edge << 8 | edge);\n output[j][i] = rgb;\n }\n }\n\n MatrixSource source = new MatrixSource(output);\n return source;\n }", "public void setIntVec(int[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update short indices with int array\");\n }\n if (!NativeIndexBuffer.setIntArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }", "public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\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 void refreshBitmapShader()\n\t{\n\t\tshader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\t}", "public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public int consume(Map<String, String> initialVars) {\r\n int result = 0;\n\r\n for (int i = 0; i < repeatNumber; i++) {\r\n result += super.consume(initialVars);\r\n }\n\r\n return result;\r\n }" ]
compares two AST nodes
[ "public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}" ]
[ "private LocatorSelectionStrategy getLocatorSelectionStrategy(String locatorSelectionStrategy) {\n if (null == locatorSelectionStrategy) {\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Strategy \" + locatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n\n if (locatorSelectionStrategyMap.containsKey(locatorSelectionStrategy)) {\n return locatorSelectionStrategyMap.get(locatorSelectionStrategy).getInstance();\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"LocatorSelectionStrategy \" + locatorSelectionStrategy\n + \" not registered at LocatorClientEnabler.\");\n }\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n }", "public void setAngularUpperLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularUpperLimits(getNative(), limitX, limitY, limitZ);\n }", "public static Attachment writeAttachmentWithErrorMessage(Throwable throwable, String title) {\n String message = throwable.getMessage();\n try {\n return writeAttachment(message.getBytes(CONFIG.getAttachmentsEncoding()), title);\n } catch (Exception e) {\n e.addSuppressed(throwable);\n LOGGER.error(String.format(\"Can't write attachment \\\"%s\\\"\", title), e);\n }\n return new Attachment();\n }", "private void verifyClusterStoreDefinition() {\n if(SystemStoreConstants.isSystemStore(storeDefinition.getName())) {\n // TODO: Once \"todo\" in StorageService.initSystemStores is complete,\n // this early return can be removed and verification can be enabled\n // for system stores.\n return;\n }\n\n Set<Integer> clusterZoneIds = cluster.getZoneIds();\n\n if(clusterZoneIds.size() > 1) { // Zoned\n Map<Integer, Integer> zoneRepFactor = storeDefinition.getZoneReplicationFactor();\n Set<Integer> storeDefZoneIds = zoneRepFactor.keySet();\n\n if(!clusterZoneIds.equals(storeDefZoneIds)) {\n throw new VoldemortException(\"Zone IDs in cluster (\" + clusterZoneIds\n + \") are incongruent with zone IDs in store defs (\"\n + storeDefZoneIds + \")\");\n }\n\n for(int zoneId: clusterZoneIds) {\n if(zoneRepFactor.get(zoneId) > cluster.getNumberOfNodesInZone(zoneId)) {\n throw new VoldemortException(\"Not enough nodes (\"\n + cluster.getNumberOfNodesInZone(zoneId)\n + \") in zone with id \" + zoneId\n + \" for replication factor of \"\n + zoneRepFactor.get(zoneId) + \".\");\n }\n }\n } else { // Non-zoned\n\n if(storeDefinition.getReplicationFactor() > cluster.getNumberOfNodes()) {\n System.err.println(storeDefinition);\n System.err.println(cluster);\n throw new VoldemortException(\"Not enough nodes (\" + cluster.getNumberOfNodes()\n + \") for replication factor of \"\n + storeDefinition.getReplicationFactor() + \".\");\n }\n }\n }", "public void process(InputStream is) throws Exception\n {\n readHeader(is);\n readVersion(is);\n readTableData(readTableHeaders(is), is);\n }", "public static List<ObjectModelResolver> getResolvers() {\n if (resolvers == null) {\n synchronized (serviceLoader) {\n if (resolvers == null) {\n List<ObjectModelResolver> foundResolvers = new ArrayList<ObjectModelResolver>();\n for (ObjectModelResolver resolver : serviceLoader) {\n foundResolvers.add(resolver);\n }\n resolvers = foundResolvers;\n }\n }\n }\n\n return resolvers;\n }", "public String interpolate( String input, RecursionInterceptor recursionInterceptor )\n\t throws InterpolationException\n\t {\n\t try\n\t {\n\t return interpolate( input, recursionInterceptor, new HashSet<String>() );\n\t }\n\t finally\n\t {\n\t if ( !cacheAnswers )\n\t {\n\t existingAnswers.clear();\n\t }\n\t }\n\t }", "protected void captureCenterEye(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshotCenterCallback == null) {\n return;\n }\n\n // TODO: when we will use multithreading, create new camera using centercamera as we are adding posteffects into it\n final GVRCamera centerCamera = mMainScene.getMainCameraRig().getCenterCamera();\n final GVRMaterial postEffect = new GVRMaterial(this, GVRMaterial.GVRShaderType.VerticalFlip.ID);\n\n centerCamera.addPostEffect(postEffect);\n\n GVRRenderTexture posteffectRenderTextureB = null;\n GVRRenderTexture posteffectRenderTextureA = null;\n\n if(isMultiview) {\n posteffectRenderTextureA = mRenderBundle.getEyeCapturePostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getEyeCapturePostEffectRenderTextureB();\n renderTarget = mRenderBundle.getEyeCaptureRenderTarget();\n renderTarget.cullFromCamera(mMainScene, centerCamera ,mRenderBundle.getShaderManager());\n renderTarget.beginRendering(centerCamera);\n }\n else {\n posteffectRenderTextureA = mRenderBundle.getPostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getPostEffectRenderTextureB();\n }\n\n renderTarget.render(mMainScene,centerCamera, mRenderBundle.getShaderManager(), posteffectRenderTextureA, posteffectRenderTextureB);\n centerCamera.removePostEffect(postEffect);\n readRenderResult(renderTarget, EYE.MULTIVIEW, false);\n\n if(isMultiview)\n renderTarget.endRendering();\n\n final Bitmap bitmap = Bitmap.createBitmap(mReadbackBufferWidth, mReadbackBufferHeight, Bitmap.Config.ARGB_8888);\n mReadbackBuffer.rewind();\n bitmap.copyPixelsFromBuffer(mReadbackBuffer);\n final GVRScreenshotCallback callback = mScreenshotCenterCallback;\n Threads.spawn(new Runnable() {\n public void run() {\n callback.onScreenCaptured(bitmap);\n }\n });\n\n mScreenshotCenterCallback = null;\n }", "public static DMatrixRMaj diagonal(int numRows , int numCols , double min , double max , Random rand ) {\n if( max < min )\n throw new IllegalArgumentException(\"The max must be >= the min\");\n\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int N = Math.min(numRows,numCols);\n\n double r = max-min;\n\n for( int i = 0; i < N; i++ ) {\n ret.set(i,i, rand.nextDouble()*r+min);\n }\n\n return ret;\n }" ]
Pauses a given deployment @param deployment The deployment to pause @param listener The listener that will be notified when the pause is complete
[ "public synchronized void pauseDeployment(final String deployment, ServerActivityCallback listener) {\n final List<ControlPoint> eps = new ArrayList<ControlPoint>();\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n if(!ep.isPaused()) {\n eps.add(ep);\n }\n }\n }\n CountingRequestCountCallback realListener = new CountingRequestCountCallback(eps.size(), listener);\n for (ControlPoint ep : eps) {\n ep.pause(realListener);\n }\n }" ]
[ "public static <E> Set<E> intersection(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n s.addAll(s1);\r\n s.retainAll(s2);\r\n return s;\r\n }", "private List<String> getMavenModules(MavenModuleSetBuild mavenBuild) throws IOException, InterruptedException {\n FilePath pathToModuleRoot = mavenBuild.getModuleRoot();\n FilePath pathToPom = new FilePath(pathToModuleRoot, mavenBuild.getProject().getRootPOM(null));\n return pathToPom.act(new MavenModulesExtractor());\n }", "public void addBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final boolean statementBatchingSupported = m_batchStatementsInProgress.containsKey(stmt);\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n stmt.executeUpdate();\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.addBatch(stmt);\r\n }\r\n }", "@Override\r\n public V remove(Object key) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.remove(key);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.remove(key));\r\n }\r\n }\r\n }", "public void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }", "public static String blur(int radius, int sigma) {\n if (radius < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radius > 150) {\n throw new IllegalArgumentException(\"Radius must be lower or equal than 150.\");\n }\n if (sigma < 0) {\n throw new IllegalArgumentException(\"Sigma must be greater than zero.\");\n }\n return FILTER_BLUR + \"(\" + radius + \",\" + sigma + \")\";\n }", "@Override\n\tpublic void handlePopups() {\n\t\t/*\n\t\t * try { executeJavaScript(\"window.alert = function(msg){return true;};\" +\n\t\t * \"window.confirm = function(msg){return true;};\" +\n\t\t * \"window.prompt = function(msg){return true;};\"); } catch (CrawljaxException e) {\n\t\t * LOGGER.error(\"Handling of PopUp windows failed\", e); }\n\t\t */\n\n\t\t/* Workaround: Popups handling currently not supported in PhantomJS. */\n\t\tif (browser instanceof PhantomJSDriver) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (ExpectedConditions.alertIsPresent().apply(browser) != null) {\n\t\t\ttry {\n\t\t\t\tbrowser.switchTo().alert().accept();\n\t\t\t\tLOGGER.info(\"Alert accepted\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"Handling of PopUp windows failed\");\n\t\t\t}\n\t\t}\n\t}", "public void randomize() {\n\t\tnumKnots = 4 + (int)(6*Math.random());\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tfor (int i = 0; i < numKnots; i++) {\n\t\t\txKnots[i] = (int)(255 * Math.random());\n\t\t\tyKnots[i] = 0xff000000 | ((int)(255 * Math.random()) << 16) | ((int)(255 * Math.random()) << 8) | (int)(255 * Math.random());\n\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\t}\n\t\txKnots[0] = -1;\n\t\txKnots[1] = 0;\n\t\txKnots[numKnots-2] = 255;\n\t\txKnots[numKnots-1] = 256;\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}", "public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {\n if (searchView != null) {\n searchView.setOnCloseListener(new SearchView.OnCloseListener() {\n @Override public boolean onClose() {\n return listener.onClose();\n }\n });\n } else if (supportView != null) {\n supportView.setOnCloseListener(listener);\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }" ]
This method changes the value of an agent's belief through its external access @param agent_name The name of the agent to change a belief @param belief_name The name of the belief to change @param new_value The new value of the belief to be changed @param connector The connector to get the external access
[ "public void setBeliefValue(String agent_name, final String belief_name,\n final Object new_value, Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n bia.getBeliefbase().getBelief(belief_name)\n .setFact(new_value);\n return null;\n }\n }).get(new ThreadSuspendable());\n }" ]
[ "public Future<PutObjectResult> putAsync(String key, String value) {\n return Future.of(() -> put(key, value), this.uploadService)\n .flatMap(t->t.fold(p->Future.ofResult(p),e->Future.ofError(e)));\n }", "public static long getMaxIdForClass(\r\n PersistenceBroker brokerForClass, ClassDescriptor cldForOriginalOrExtent, FieldDescriptor original)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor field = null;\r\n if (!original.getClassDescriptor().equals(cldForOriginalOrExtent))\r\n {\r\n // check if extent match not the same table\r\n if (!original.getClassDescriptor().getFullTableName().equals(\r\n cldForOriginalOrExtent.getFullTableName()))\r\n {\r\n // we have to look for id's in extent class table\r\n field = cldForOriginalOrExtent.getFieldDescriptorByName(original.getAttributeName());\r\n }\r\n }\r\n else\r\n {\r\n field = original;\r\n }\r\n if (field == null)\r\n {\r\n // if null skip this call\r\n return 0;\r\n }\r\n\r\n String column = field.getColumnName();\r\n long result = 0;\r\n ResultSet rs = null;\r\n Statement stmt = null;\r\n StatementManagerIF sm = brokerForClass.serviceStatementManager();\r\n String table = cldForOriginalOrExtent.getFullTableName();\r\n // String column = cld.getFieldDescriptorByName(fieldName).getColumnName();\r\n String sql = SM_SELECT_MAX + column + SM_FROM + table;\r\n try\r\n {\r\n //lookup max id for the current class\r\n stmt = sm.getGenericStatement(cldForOriginalOrExtent, Query.NOT_SCROLLABLE);\r\n rs = stmt.executeQuery(sql);\r\n rs.next();\r\n result = rs.getLong(1);\r\n }\r\n catch (Exception e)\r\n {\r\n log.warn(\"Cannot lookup max value from table \" + table + \" for column \" + column +\r\n \", PB was \" + brokerForClass + \", using jdbc-descriptor \" +\r\n brokerForClass.serviceConnectionManager().getConnectionDescriptor(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n sm.closeResources(stmt, rs);\r\n }\r\n catch (Exception ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n return result;\r\n }", "public static int Maximum(ImageSource fastBitmap, int startX, int startY, int width, int height) {\r\n int max = 0;\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getRGB(j, i);\r\n if (gray > max) {\r\n max = gray;\r\n }\r\n }\r\n }\r\n } else {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getG(j, i);\r\n if (gray > max) {\r\n max = gray;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return max;\r\n }", "public boolean removeHandlerFactory(ManagementRequestHandlerFactory instance) {\n for(;;) {\n final ManagementRequestHandlerFactory[] snapshot = updater.get(this);\n final int length = snapshot.length;\n int index = -1;\n for(int i = 0; i < length; i++) {\n if(snapshot[i] == instance) {\n index = i;\n break;\n }\n }\n if(index == -1) {\n return false;\n }\n final ManagementRequestHandlerFactory[] newVal = new ManagementRequestHandlerFactory[length - 1];\n System.arraycopy(snapshot, 0, newVal, 0, index);\n System.arraycopy(snapshot, index + 1, newVal, index, length - index - 1);\n if (updater.compareAndSet(this, snapshot, newVal)) {\n return true;\n }\n }\n }", "public static MediaType text( String subType, Charset charset ) {\n return nonBinary( TEXT, subType, charset );\n }", "public com.squareup.okhttp.Call postUiAutopilotWaypointCall(Boolean addToBeginning, Boolean clearOtherWaypoints,\n Long destinationId, String datasource, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v2/ui/autopilot/waypoint/\";\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (addToBeginning != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"add_to_beginning\", addToBeginning));\n }\n\n if (clearOtherWaypoints != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"clear_other_waypoints\", clearOtherWaypoints));\n }\n\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (destinationId != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"destination_id\", destinationId));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = {\n\n };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"POST\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }", "public static void setEntity(HttpConnection connnection, String body, String contentType) {\n connnection.requestProperties.put(\"Content-type\", contentType);\n connnection.setRequestBody(body);\n }", "public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\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 }" ]
Parses the query facet configurations. @param rangeFacetObject The JSON sub-node with the query facet configurations. @return The query facet configurations.
[ "protected I_CmsSearchConfigurationFacetRange parseRangeFacet(JSONObject rangeFacetObject) {\n\n try {\n String range = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_RANGE);\n String name = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(rangeFacetObject, JSON_KEY_FACET_MINCOUNT);\n String start = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_START);\n String end = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_END);\n String gap = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_GAP);\n List<String> sother = parseOptionalStringValues(rangeFacetObject, JSON_KEY_RANGE_FACET_OTHER);\n Boolean hardEnd = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_RANGE_FACET_HARDEND);\n List<I_CmsSearchConfigurationFacetRange.Other> other = null;\n if (sother != null) {\n other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sother.size());\n for (String so : sother) {\n try {\n I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf(\n so);\n other.add(o);\n } catch (Exception e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e);\n }\n }\n }\n Boolean isAndFacet = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(rangeFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n rangeFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetRange(\n range,\n start,\n end,\n gap,\n other,\n hardEnd,\n name,\n minCount,\n label,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1,\n JSON_KEY_RANGE_FACET_RANGE\n + \", \"\n + JSON_KEY_RANGE_FACET_START\n + \", \"\n + JSON_KEY_RANGE_FACET_END\n + \", \"\n + JSON_KEY_RANGE_FACET_GAP),\n e);\n return null;\n }\n\n }" ]
[ "public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }", "private void readResourceAssignment(Allocation gpAllocation)\n {\n Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1);\n Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1);\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n if (task != null && resource != null)\n {\n ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource);\n mpxjAssignment.setUnits(gpAllocation.getLoad());\n m_eventManager.fireAssignmentReadEvent(mpxjAssignment);\n }\n }", "protected List<CmsUUID> undelete() throws CmsException {\n\n List<CmsUUID> modifiedResources = new ArrayList<CmsUUID>();\n CmsObject cms = m_context.getCms();\n for (CmsResource resource : m_context.getResources()) {\n CmsLockActionRecord actionRecord = null;\n try {\n actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource);\n cms.undeleteResource(cms.getSitePath(resource), true);\n modifiedResources.add(resource.getStructureId());\n } finally {\n if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) {\n\n try {\n cms.unlockResource(resource);\n } catch (CmsLockException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }\n }\n }\n return modifiedResources;\n }", "public TokenList extractSubList( Token begin , Token end ) {\n if( begin == end ) {\n remove(begin);\n return new TokenList(begin,begin);\n } else {\n if( first == begin ) {\n first = end.next;\n }\n if( last == end ) {\n last = begin.previous;\n }\n if( begin.previous != null ) {\n begin.previous.next = end.next;\n }\n if( end.next != null ) {\n end.next.previous = begin.previous;\n }\n begin.previous = null;\n end.next = null;\n\n TokenList ret = new TokenList(begin,end);\n size -= ret.size();\n return ret;\n }\n }", "private long getTime(Date start, Date end, long target, boolean after)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n int diff = DateHelper.compare(startTime, endTime, target);\n if (diff == 0)\n {\n if (after == true)\n {\n total = (endTime.getTime() - target);\n }\n else\n {\n total = (target - startTime.getTime());\n }\n }\n else\n {\n if ((after == true && diff < 0) || (after == false && diff > 0))\n {\n total = (endTime.getTime() - startTime.getTime());\n }\n }\n }\n return (total);\n }", "private void readCollectionElement(\n\t\tfinal Object optionalOwner,\n\t\tfinal Serializable optionalKey,\n\t\tfinal CollectionPersister persister,\n\t\tfinal CollectionAliases descriptor,\n\t\tfinal ResultSet rs,\n\t\tfinal SharedSessionContractImplementor session)\n\t\t\t\tthrows HibernateException, SQLException {\n\n\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t//implement persister.readKey using the grid type (later)\n\t\tfinal Serializable collectionRowKey = (Serializable) persister.readKey(\n\t\t\t\trs,\n\t\t\t\tdescriptor.getSuffixedKeyAliases(),\n\t\t\t\tsession\n\t\t);\n\n\t\tif ( collectionRowKey != null ) {\n\t\t\t// we found a collection element in the result set\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"found row of collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, collectionRowKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tObject owner = optionalOwner;\n\t\t\tif ( owner == null ) {\n\t\t\t\towner = persistenceContext.getCollectionOwner( collectionRowKey, persister );\n\t\t\t\tif ( owner == null ) {\n\t\t\t\t\t//TODO: This is assertion is disabled because there is a bug that means the\n\t\t\t\t\t//\t original owner of a transient, uninitialized collection is not known\n\t\t\t\t\t//\t if the collection is re-referenced by a different object associated\n\t\t\t\t\t//\t with the current Session\n\t\t\t\t\t//throw new AssertionFailure(\"bug loading unowned collection\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPersistentCollection rowCollection = persistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, collectionRowKey );\n\n\t\t\tif ( rowCollection != null ) {\n\t\t\t\thydrateRowCollection( persister, descriptor, rs, owner, rowCollection );\n\t\t\t}\n\n\t\t}\n\t\telse if ( optionalKey != null ) {\n\t\t\t// we did not find a collection element in the result set, so we\n\t\t\t// ensure that a collection is created with the owner's identifier,\n\t\t\t// since what we have is an empty collection\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"result set contains (possibly empty) collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, optionalKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tpersistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, optionalKey ); // handle empty collection\n\n\t\t}\n\n\t\t// else no collection element, but also no owner\n\n\t}", "public String getResourcePath()\n {\n switch (resourceType)\n {\n case ANDROID_ASSETS: return assetPath;\n\n case ANDROID_RESOURCE: return resourceFilePath;\n\n case LINUX_FILESYSTEM: return filePath;\n\n case NETWORK: return url.getPath();\n\n case INPUT_STREAM: return inputStreamName;\n\n default: return null;\n }\n }", "public static String determineMutatorName(@Nonnull final String fieldName) {\n\t\tCheck.notEmpty(fieldName, \"fieldName\");\n\t\tfinal Matcher m = PATTERN.matcher(fieldName);\n\t\tCheck.stateIsTrue(m.find(), \"passed field name '%s' is not applicable\", fieldName);\n\t\tfinal String name = m.group();\n\t\treturn METHOD_SET_PREFIX + name.substring(0, 1).toUpperCase() + name.substring(1);\n\t}", "public void execute()\n {\n Runnable task = new Runnable()\n {\n public void run()\n {\n final V result = performTask();\n SwingUtilities.invokeLater(new Runnable()\n {\n public void run()\n {\n postProcessing(result);\n latch.countDown();\n }\n });\n }\n };\n new Thread(task, \"SwingBackgroundTask-\" + id).start();\n }" ]
Method which performs strength checks on password. It returns outcome which can be used by CLI. @param isAdminitrative - administrative checks are less restrictive. This means that weak password or one which violates restrictions is not indicated as failure. Administrative checks are usually performed by admin changing/setting default password for user. @param userName - the name of user for which password is set. @param password - password. @return
[ "public PasswordCheckResult check(boolean isAdminitrative, String userName, String password) {\n // TODO: allow custom restrictions?\n List<PasswordRestriction> passwordValuesRestrictions = getPasswordRestrictions();\n final PasswordStrengthCheckResult strengthResult = this.passwordStrengthChecker.check(userName, password, passwordValuesRestrictions);\n\n final int failedRestrictions = strengthResult.getRestrictionFailures().size();\n final PasswordStrength strength = strengthResult.getStrength();\n final boolean strongEnough = assertStrength(strength);\n\n PasswordCheckResult.Result resultAction;\n String resultMessage = null;\n if (isAdminitrative) {\n if (strongEnough) {\n if (failedRestrictions > 0) {\n resultAction = Result.WARN;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.ACCEPT;\n }\n } else {\n resultAction = Result.WARN;\n resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());\n }\n } else {\n if (strongEnough) {\n if (failedRestrictions > 0) {\n resultAction = Result.REJECT;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.ACCEPT;\n }\n } else {\n if (failedRestrictions > 0) {\n resultAction = Result.REJECT;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.REJECT;\n resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());\n }\n }\n }\n\n return new PasswordCheckResult(resultAction, resultMessage);\n\n }" ]
[ "public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }", "public List<ModelNode> getAllowedValues() {\n if (allowedValues == null) {\n return Collections.emptyList();\n }\n return Arrays.asList(this.allowedValues);\n }", "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 HostName toHostName() {\n\t\tHostName host = fromHost;\n\t\tif(host == null) {\n\t\t\tfromHost = host = toCanonicalHostName();\n\t\t}\n\t\treturn host;\n\t}", "public static int longestCommonContiguousSubstring(String s, String t) {\r\n if (s.length() == 0 || t.length() == 0) {\r\n return 0;\r\n }\r\n int M = s.length();\r\n int N = t.length();\r\n int[][] d = new int[M + 1][N + 1];\r\n for (int j = 0; j <= N; j++) {\r\n d[0][j] = 0;\r\n }\r\n for (int i = 0; i <= M; i++) {\r\n d[i][0] = 0;\r\n }\r\n\r\n int max = 0;\r\n for (int i = 1; i <= M; i++) {\r\n for (int j = 1; j <= N; j++) {\r\n if (s.charAt(i - 1) == t.charAt(j - 1)) {\r\n d[i][j] = d[i - 1][j - 1] + 1;\r\n } else {\r\n d[i][j] = 0;\r\n }\r\n\r\n if (d[i][j] > max) {\r\n max = d[i][j];\r\n }\r\n }\r\n }\r\n // System.err.println(\"LCCS(\" + s + \",\" + t + \") = \" + max);\r\n return max;\r\n }", "@SuppressWarnings(\"WeakerAccess\")\n protected void clearRmiTargetsMap(ClassLoaderLeakPreventor preventor, Map<?, ?> rmiTargetsMap) {\n try {\n final Field cclField = preventor.findFieldOfClass(\"sun.rmi.transport.Target\", \"ccl\");\n preventor.debug(\"Looping \" + rmiTargetsMap.size() + \" RMI Targets to find leaks\");\n for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {\n Object target = iter.next(); // sun.rmi.transport.Target\n ClassLoader ccl = (ClassLoader) cclField.get(target);\n if(preventor.isClassLoaderOrChild(ccl)) {\n preventor.warn(\"Removing RMI Target: \" + target);\n iter.remove();\n }\n }\n }\n catch (Exception ex) {\n preventor.error(ex);\n }\n }", "public <T extends Widget & Checkable> boolean uncheck(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, false);\n }", "private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }", "private CmsVfsEntryBean buildVfsEntryBeanForQuickSearch(\n CmsResource resource,\n Multimap<CmsResource, CmsResource> childMap,\n Set<CmsResource> filterMatches,\n Set<String> parentPaths,\n boolean isRoot)\n throws CmsException {\n\n CmsObject cms = getCmsObject();\n String title = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();\n boolean isMatch = filterMatches.contains(resource);\n List<CmsVfsEntryBean> childBeans = Lists.newArrayList();\n\n Collection<CmsResource> children = childMap.get(resource);\n if (!children.isEmpty()) {\n for (CmsResource child : children) {\n CmsVfsEntryBean childBean = buildVfsEntryBeanForQuickSearch(\n child,\n childMap,\n filterMatches,\n parentPaths,\n false);\n childBeans.add(childBean);\n }\n } else if (filterMatches.contains(resource)) {\n if (parentPaths.contains(resource.getRootPath())) {\n childBeans = null;\n }\n // otherwise childBeans remains an empty list\n }\n\n String rootPath = resource.getRootPath();\n CmsVfsEntryBean result = new CmsVfsEntryBean(\n rootPath,\n resource.getStructureId(),\n title,\n CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), true),\n isRoot,\n isEditable(cms, resource),\n childBeans,\n isMatch);\n String siteRoot = null;\n if (OpenCms.getSiteManager().startsWithShared(rootPath)) {\n siteRoot = OpenCms.getSiteManager().getSharedFolder();\n } else {\n String tempSiteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);\n if (tempSiteRoot != null) {\n siteRoot = tempSiteRoot;\n } else {\n siteRoot = \"\";\n }\n }\n result.setSiteRoot(siteRoot);\n return result;\n }" ]
Add views to the tree. @param parentNode parent tree node @param file views container
[ "private void addViews(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (View view : file.getViews())\n {\n final View v = view;\n MpxjTreeNode childNode = new MpxjTreeNode(view)\n {\n @Override public String toString()\n {\n return v.getName();\n }\n };\n parentNode.add(childNode);\n }\n }" ]
[ "public Jar setJarPrefix(String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (value != null && jarPrefixFile != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixFile + \")\");\n this.jarPrefixStr = value;\n return this;\n }", "private PlayState1 findPlayState1() {\n PlayState1 result = PLAY_STATE_1_MAP.get(packetBytes[123]);\n if (result == null) {\n return PlayState1.UNKNOWN;\n }\n return result;\n }", "public PathAddress append(List<PathElement> additionalElements) {\n final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size());\n newList.addAll(pathAddressList);\n newList.addAll(additionalElements);\n return pathAddress(newList);\n }", "public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }", "void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }", "public static ActorSystem createAndGetActorSystem() {\n if (actorSystem == null || actorSystem.isTerminated()) {\n actorSystem = ActorSystem.create(PcConstants.ACTOR_SYSTEM, conf);\n }\n return actorSystem;\n }", "public ManageableCollection createCollectionProxy(PBKey brokerKey, Query query, Class collectionClass)\r\n {\r\n Object args[] = {brokerKey, collectionClass, query};\r\n\r\n try\r\n {\r\n return (ManageableCollection) getCollectionProxyConstructor(collectionClass).newInstance(args);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void setOffline(boolean value){\n offline = value;\n if (offline) {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to offline, won't send events queue\");\n } else {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to online, sending events queue\");\n flush();\n }\n }", "public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }" ]
Create a field map for enterprise custom fields. @param props props data @param c target class
[ "public void createEnterpriseCustomFieldMap(Props props, Class<?> c)\n {\n byte[] fieldMapData = null;\n for (Integer key : ENTERPRISE_CUSTOM_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData != null)\n {\n int index = 4;\n while (index < fieldMapData.length)\n {\n //Looks like the custom fields have varying types, it may be that the last byte of the four represents the type?\n //System.out.println(ByteArrayHelper.hexdump(fieldMapData, index, 4, false));\n int typeValue = MPPUtility.getInt(fieldMapData, index);\n FieldType type = getFieldType(typeValue);\n if (type != null && type.getClass() == c && type.toString().startsWith(\"Enterprise Custom Field\"))\n {\n int varDataKey = (typeValue & 0xFFFF);\n FieldItem item = new FieldItem(type, FieldLocation.VAR_DATA, 0, 0, varDataKey, 0, 0);\n m_map.put(type, item);\n //System.out.println(item);\n }\n //System.out.println((type == null ? \"?\" : type.getClass().getSimpleName() + \".\" + type) + \" \" + Integer.toHexString(typeValue));\n\n index += 4;\n }\n }\n }" ]
[ "public static boolean isSpreadSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSpreadSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSpreadSafe();\r\n }\r\n return false;\r\n }", "public static auditnslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_systemglobal_binding obj = new auditnslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_systemglobal_binding response[] = (auditnslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }", "public static rewritepolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\trewritepolicy_csvserver_binding obj = new rewritepolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\trewritepolicy_csvserver_binding response[] = (rewritepolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }", "public static void setIndex(Matcher matcher, int idx) {\n int count = getCount(matcher);\n if (idx < -count || idx >= count) {\n throw new IndexOutOfBoundsException(\"index is out of range \" + (-count) + \"..\" + (count - 1) + \" (index = \" + idx + \")\");\n }\n if (idx == 0) {\n matcher.reset();\n } else if (idx > 0) {\n matcher.reset();\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n } else if (idx < 0) {\n matcher.reset();\n idx += getCount(matcher);\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n }\n }", "public static java.sql.Time newTime() {\n return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);\n }", "public Archetype parse(String adl) {\n try {\n return parse(new StringReader(adl));\n } catch (IOException e) {\n // StringReader should never throw an IOException\n throw new AssertionError(e);\n }\n }", "private void setCrosstabOptions() {\n\t\tif (djcross.isUseFullWidth()){\n\t\t\tjrcross.setWidth(layoutManager.getReport().getOptions().getPrintableWidth());\n\t\t} else {\n\t\t\tjrcross.setWidth(djcross.getWidth());\n\t\t}\n\t\tjrcross.setHeight(djcross.getHeight());\n\n\t\tjrcross.setColumnBreakOffset(djcross.getColumnBreakOffset());\n\n jrcross.setIgnoreWidth(djcross.isIgnoreWidth());\n\t}" ]
Answer the orderBy of all Criteria and Sub Criteria the elements are of class Criteria.FieldHelper @return List
[ "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }" ]
[ "protected RdfSerializer createRdfSerializer() throws IOException {\n\n\t\tString outputDestinationFinal;\n\t\tif (this.outputDestination != null) {\n\t\t\toutputDestinationFinal = this.outputDestination;\n\t\t} else {\n\t\t\toutputDestinationFinal = \"{PROJECT}\" + this.taskName + \"{DATE}\"\n\t\t\t\t\t+ \".nt\";\n\t\t}\n\n\t\tOutputStream exportOutputStream = getOutputStream(this.useStdOut,\n\t\t\t\tinsertDumpInformation(outputDestinationFinal),\n\t\t\t\tthis.compressionType);\n\n\t\tRdfSerializer serializer = new RdfSerializer(RDFFormat.NTRIPLES,\n\t\t\t\texportOutputStream, this.sites,\n\t\t\t\tPropertyRegister.getWikidataPropertyRegister());\n\t\tserializer.setTasks(this.tasks);\n\n\t\treturn serializer;\n\t}", "@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}", "private void logOriginalResponseHistory(\n PluginResponse httpServletResponse, History history) throws URIException {\n RequestInformation requestInfo = requestInformation.get();\n if (requestInfo.handle && requestInfo.client.getIsActive()) {\n logger.info(\"Storing original response history\");\n history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setOriginalResponseContentType(httpServletResponse.getContentType());\n history.setOriginalResponseData(httpServletResponse.getContentString());\n logger.info(\"Done storing\");\n }\n }", "private void printStatistics(UsageStatistics usageStatistics,\n\t\t\tString entityLabel) {\n\t\tSystem.out.println(\"Processed \" + usageStatistics.count + \" \"\n\t\t\t\t+ entityLabel + \":\");\n\t\tSystem.out.println(\" * Labels: \" + usageStatistics.countLabels\n\t\t\t\t+ \", descriptions: \" + usageStatistics.countDescriptions\n\t\t\t\t+ \", aliases: \" + usageStatistics.countAliases);\n\t\tSystem.out.println(\" * Statements: \" + usageStatistics.countStatements\n\t\t\t\t+ \", with references: \"\n\t\t\t\t+ usageStatistics.countReferencedStatements);\n\t}", "public UriComponentsBuilder queryParams(MultiValueMap<String, String> params) {\n\t\tAssert.notNull(params, \"'params' must not be null\");\n\t\tthis.queryParams.putAll(params);\n\t\treturn this;\n\t}", "public void setColorInterpolated(int index, int firstIndex, int lastIndex, int color) {\n\t\tint firstColor = map[firstIndex];\n\t\tint lastColor = map[lastIndex];\n\t\tfor (int i = firstIndex; i <= index; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(index-firstIndex), firstColor, color);\n\t\tfor (int i = index; i < lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-index)/(lastIndex-index), color, lastColor);\n\t}", "public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }", "public static Class<?> loadClass(String classname, DataFormat<?> dataFormat) {\n\n // first try context classoader\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n if(cl != null) {\n LOG.tryLoadingClass(classname, cl);\n try {\n return cl.loadClass(classname);\n }\n catch(Exception e) {\n // ignore\n }\n }\n\n // else try the classloader which loaded the dataformat\n cl = dataFormat.getClass().getClassLoader();\n try {\n LOG.tryLoadingClass(classname, cl);\n return cl.loadClass(classname);\n }\n catch (ClassNotFoundException e) {\n throw LOG.classNotFound(classname, e);\n }\n\n }", "@Nullable\n\tpublic Import find(@Nonnull final String typeName) {\n\t\tCheck.notEmpty(typeName, \"typeName\");\n\t\tImport ret = null;\n\t\tfinal Type type = new Type(typeName);\n\t\tfor (final Import imp : imports) {\n\t\t\tif (imp.getType().getName().equals(type.getName())) {\n\t\t\t\tret = imp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ret == null) {\n\t\t\tfinal Type javaLangType = Type.evaluateJavaLangType(typeName);\n\t\t\tif (javaLangType != null) {\n\t\t\t\tret = Import.of(javaLangType);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}" ]
Configs created by this ConfigBuilder will have the given Redis hostname. @param host the Redis hostname @return this ConfigBuilder
[ "public ConfigBuilder withHost(final String host) {\n if (host == null || \"\".equals(host)) {\n throw new IllegalArgumentException(\"host must not be null or empty: \" + host);\n }\n this.host = host;\n return this;\n }" ]
[ "public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "protected void addEnumList(String key, List<? extends Enum> list) {\n optionsMap.put(key, list.stream().map(i -> i.toString()).collect(Collectors.toList()));\n }", "public synchronized void pauseDeployment(final String deployment, ServerActivityCallback listener) {\n final List<ControlPoint> eps = new ArrayList<ControlPoint>();\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n if(!ep.isPaused()) {\n eps.add(ep);\n }\n }\n }\n CountingRequestCountCallback realListener = new CountingRequestCountCallback(eps.size(), listener);\n for (ControlPoint ep : eps) {\n ep.pause(realListener);\n }\n }", "public static final String printWorkGroup(WorkGroup value)\n {\n return (Integer.toString(value == null ? WorkGroup.DEFAULT.getValue() : value.getValue()));\n }", "public void prepareServer() {\n try {\n server = new Server(0);\n jettyHandler = new AbstractHandler() {\n public void handle(String target, Request req, HttpServletRequest request,\n HttpServletResponse response) throws IOException, ServletException {\n response.setContentType(\"text/plain\");\n\n String[] operands = request.getRequestURI().split(\"/\");\n\n String name = \"\";\n String command = \"\";\n String value = \"\";\n\n //operands[0] = \"\", request starts with a \"/\"\n\n if (operands.length >= 2) {\n name = operands[1];\n }\n\n if (operands.length >= 3) {\n command = operands[2];\n }\n\n if (operands.length >= 4) {\n value = operands[3];\n }\n\n if (command.equals(\"report\")) { //report a number of lines written\n response.getWriter().write(makeReport(name, value));\n } else if (command.equals(\"request\") && value.equals(\"block\")) { //request a new block of work\n response.getWriter().write(requestBlock(name));\n } else if (command.equals(\"request\") && value.equals(\"name\")) { //request a new name to report with\n response.getWriter().write(requestName());\n } else { //non recognized response\n response.getWriter().write(\"exit\");\n }\n\n ((Request) request).setHandled(true);\n }\n };\n\n server.setHandler(jettyHandler);\n\n // Select any available port\n server.start();\n Connector[] connectors = server.getConnectors();\n NetworkConnector nc = (NetworkConnector) connectors[0];\n listeningPort = nc.getLocalPort();\n hostName = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "public static base_response add(nitro_service client, vpath resource) throws Exception {\n\t\tvpath addresource = new vpath();\n\t\taddresource.name = resource.name;\n\t\taddresource.destip = resource.destip;\n\t\taddresource.encapmode = resource.encapmode;\n\t\treturn addresource.add_resource(client);\n\t}", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }", "String getFacetParamKey(String facet) {\n\n I_CmsSearchControllerFacetField fieldFacet = m_result.getController().getFieldFacets().getFieldFacetController().get(\n facet);\n if (fieldFacet != null) {\n return fieldFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetRange rangeFacet = m_result.getController().getRangeFacets().getRangeFacetController().get(\n facet);\n if (rangeFacet != null) {\n return rangeFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetQuery queryFacet = m_result.getController().getQueryFacet();\n if ((queryFacet != null) && queryFacet.getConfig().getName().equals(facet)) {\n return queryFacet.getConfig().getParamKey();\n }\n\n // Facet did not exist\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_FACET_NOT_CONFIGURED_1, facet), new Throwable());\n\n return null;\n }" ]
Returns true if the default profile for the specified uuid is active @return true if active, otherwise false
[ "public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }" ]
[ "public static base_responses add(nitro_service client, cacheselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheselector addresources[] = new cacheselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cacheselector();\n\t\t\t\taddresources[i].selectorname = resources[i].selectorname;\n\t\t\t\taddresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "protected T checkReturnValue(T instance) {\n if (instance == null && !isDependent()) {\n throw BeanLogger.LOG.nullNotAllowedFromProducer(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()));\n }\n if (instance == null) {\n InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek();\n if (injectionPoint != null) {\n Class<?> injectionPointRawType = Reflections.getRawType(injectionPoint.getType());\n if (injectionPointRawType.isPrimitive()) {\n return cast(Defaults.getJlsDefaultValue(injectionPointRawType));\n }\n }\n }\n if (instance != null && !(instance instanceof Serializable)) {\n if (beanManager.isPassivatingScope(getScope())) {\n throw BeanLogger.LOG.nonSerializableProductError(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()));\n }\n InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek();\n if (injectionPoint != null && injectionPoint.getBean() != null && Beans.isPassivatingScope(injectionPoint.getBean(), beanManager)) {\n // Transient field is passivation capable injection point\n if (!(injectionPoint.getMember() instanceof Field) || !injectionPoint.isTransient()) {\n throw BeanLogger.LOG.unserializableProductInjectionError(this, Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()),\n injectionPoint, Formats.formatAsStackTraceElement(injectionPoint.getMember()));\n }\n }\n }\n return instance;\n }", "public static boolean reconnect(final Jedis jedis, final int reconAttempts, final long reconnectSleepTime) {\n int i = 1;\n do {\n try {\n jedis.disconnect();\n try {\n Thread.sleep(reconnectSleepTime);\n } catch (Exception e2) {\n }\n jedis.connect();\n } catch (JedisConnectionException jce) {\n } // Ignore bad connection attempts\n catch (Exception e3) {\n LOG.error(\"Unknown Exception while trying to reconnect to Redis\", e3);\n }\n } while (++i <= reconAttempts && !testJedisConnection(jedis));\n return testJedisConnection(jedis);\n }", "public static String encodeUserInfo(String userInfo, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(userInfo, encoding, HierarchicalUriComponents.Type.USER_INFO);\n\t}", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static int checkInteger(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInIntegerRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), INTEGER_MIN, INTEGER_MAX);\n\t\t}\n\n\t\treturn number.intValue();\n\t}", "public static base_response delete(nitro_service client, application resource) throws Exception {\n\t\tapplication deleteresource = new application();\n\t\tdeleteresource.appname = resource.appname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public T transitFloat(int propertyId, float... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofFloat(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofFloat(property, vals));\n return self();\n }", "public static lbmonitor_binding get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonitor_binding obj = new lbmonitor_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonitor_binding response = (lbmonitor_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "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 }" ]
Notifies that multiple footer items are inserted. @param positionStart the position. @param itemCount the item count.
[ "public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (newFooterItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);\n }" ]
[ "@NotNull\n private String getFQName(@NotNull final String localName, Object... params) {\n final StringBuilder builder = new StringBuilder();\n builder.append(storeName);\n builder.append('.');\n builder.append(localName);\n for (final Object param : params) {\n builder.append('#');\n builder.append(param);\n }\n //noinspection ConstantConditions\n return StringInterner.intern(builder.toString());\n }", "public void bindScriptBundleToScene(GVRScriptBundle scriptBundle, GVRScene scene) throws IOException, GVRScriptException {\n for (GVRSceneObject sceneObject : scene.getSceneObjects()) {\n bindBundleToSceneObject(scriptBundle, sceneObject);\n }\n }", "@SuppressWarnings(\"checkstyle:illegalcatch\")\n private boolean sendMessage(final byte[] messageToSend) {\n try {\n connectionPool.execute(new PooledObjectConsumer<TcpConnection>() {\n @Override\n public void accept(final TcpConnection tcpConnection) throws IOException {\n tcpConnection.write(messageToSend);\n }\n });\n } catch (final Exception e) {\n addError(String.format(\"Error sending message via tcp://%s:%s\",\n getGraylogHost(), getGraylogPort()), e);\n\n return false;\n }\n\n return true;\n }", "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}", "private void readResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n for (Project.Resources.Resource.Baseline baseline : xmlResource.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjResource.setBaselineCost(cost);\n mpxjResource.setBaselineWork(work);\n }\n else\n {\n mpxjResource.setBaselineCost(number, cost);\n mpxjResource.setBaselineWork(number, work);\n }\n }\n }", "protected void addAllowedValuesToDescription(ModelNode result, ParameterValidator validator) {\n if (allowedValues != null) {\n for (ModelNode allowedValue : allowedValues) {\n result.get(ModelDescriptionConstants.ALLOWED).add(allowedValue);\n }\n } else if (validator instanceof AllowedValuesValidator) {\n AllowedValuesValidator avv = (AllowedValuesValidator) validator;\n List<ModelNode> allowed = avv.getAllowedValues();\n if (allowed != null) {\n for (ModelNode ok : allowed) {\n result.get(ModelDescriptionConstants.ALLOWED).add(ok);\n }\n }\n }\n }", "private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }", "protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {\n StringBuilder baseURL = new StringBuilder();\n if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {\n baseURL.append(httpServletRequest.getContextPath());\n }\n if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {\n baseURL.append(httpServletRequest.getServletPath());\n }\n return baseURL;\n }", "@Override\n public boolean supportsNativeRotation() {\n return this.params.useNativeAngle &&\n (this.params.serverType == WmsLayerParam.ServerType.MAPSERVER ||\n this.params.serverType == WmsLayerParam.ServerType.GEOSERVER);\n }" ]
Attempt to shutdown the server. As much shutdown as possible will be completed, even if intermediate errors are encountered. @throws VoldemortException
[ "@Override\n protected void stopInner() throws VoldemortException {\n List<VoldemortException> exceptions = new ArrayList<VoldemortException>();\n\n logger.info(\"Stopping services:\" + getIdentityNode().getId());\n /* Stop in reverse order */\n exceptions.addAll(stopOnlineServices());\n for(VoldemortService service: Utils.reversed(basicServices)) {\n try {\n service.stop();\n } catch(VoldemortException e) {\n exceptions.add(e);\n logger.error(e);\n }\n }\n logger.info(\"All services stopped for Node:\" + getIdentityNode().getId());\n\n if(exceptions.size() > 0)\n throw exceptions.get(0);\n // release lock of jvm heap\n JNAUtils.tryMunlockall();\n }" ]
[ "public static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }", "public int getBoneIndex(GVRSceneObject bone)\n {\n for (int i = 0; i < getNumBones(); ++i)\n if (mBones[i] == bone)\n return i;\n return -1;\n }", "public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) {\n URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get(\"id\").asString());\n BoxCollaboration.Info info = collaboration.new Info(entryObject);\n collaborations.add(info);\n }\n\n return collaborations;\n }", "public void enableCustomResponse(String custom, int path_id, String client_uuid) throws Exception {\n\n updateRequestResponseTables(\"custom_response\", custom, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }", "public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }", "void gc() {\n if (stopped) {\n return;\n }\n long expirationTime = System.currentTimeMillis() - timeout;\n for (Iterator<Map.Entry<InputStreamKey, TimedStreamEntry>> iter = streamMap.entrySet().iterator(); iter.hasNext();) {\n if (stopped) {\n return;\n }\n Map.Entry<InputStreamKey, TimedStreamEntry> entry = iter.next();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n if (timedStreamEntry.timestamp.get() <= expirationTime) {\n iter.remove();\n InputStreamKey key = entry.getKey();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }\n }", "public static boolean isEasterSunday(LocalDate date) {\n\t\tint y = date.getYear();\n\t\tint a = y % 19;\n\t\tint b = y / 100;\n\t\tint c = y % 100;\n\t\tint d = b / 4;\n\t\tint e = b % 4;\n\t\tint f = (b + 8) / 25;\n\t\tint g = (b - f + 1) / 3;\n\t\tint h = (19 * a + b - d - g + 15) % 30;\n\t\tint i = c / 4;\n\t\tint k = c % 4;\n\t\tint l = (32 + 2 * e + 2 * i - h - k) % 7;\n\t\tint m = (a + 11 * h + 22 * l) / 451;\n\t\tint easterSundayMonth\t= (h + l - 7 * m + 114) / 31;\n\t\tint easterSundayDay\t\t= ((h + l - 7 * m + 114) % 31) + 1;\n\n\t\tint month = date.getMonthValue();\n\t\tint day = date.getDayOfMonth();\n\n\t\treturn (easterSundayMonth == month) && (easterSundayDay == day);\n\t}", "private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }", "public static final String printWorkContour(WorkContour value)\n {\n return (Integer.toString(value == null ? WorkContour.FLAT.getValue() : value.getValue()));\n }" ]
Updates the value in HashMap and writeBack as Atomic step
[ "@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\n }" ]
[ "public void initialize() {\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessagePriority.High));\n\t}", "public void implicitDoubleStep( int x1 , int x2 ) {\n if( printHumps )\n System.out.println(\"Performing implicit double step\");\n\n // compute the wilkinson shift\n double z11 = A.get(x2 - 1, x2 - 1);\n double z12 = A.get(x2 - 1, x2);\n double z21 = A.get(x2, x2 - 1);\n double z22 = A.get(x2, x2);\n\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n if( normalize ) {\n temp[0] = a11;temp[1] = a21;temp[2] = a12;temp[3] = a22;temp[4] = a32;\n temp[5] = z11;temp[6] = z22;temp[7] = z12;temp[8] = z21;\n\n double max = Math.abs(temp[0]);\n for( int j = 1; j < temp.length; j++ ) {\n if( Math.abs(temp[j]) > max )\n max = Math.abs(temp[j]);\n }\n a11 /= max;a21 /= max;a12 /= max;a22 /= max;a32 /= max;\n z11 /= max;z22 /= max;z12 /= max;z21 /= max;\n }\n\n // these equations are derived when the eigenvalues are extracted from the lower right\n // 2 by 2 matrix. See page 388 of Fundamentals of Matrix Computations 2nd ed for details.\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = ((a11- z11)*(a11- z22)- z21 * z12)/a21 + a12;\n b21 = a11 + a22 - z11 - z22;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = ((a11- z11)*(a11- z22)- z21 * z12) + a12*a21;\n b21 = (a11 + a22 - z11 - z22)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11 , b21 , b31 );\n }", "private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }", "String generateSynopsis() {\n synopsisOptions = buildSynopsisOptions(opts, arg, domain);\n StringBuilder synopsisBuilder = new StringBuilder();\n if (parentName != null) {\n synopsisBuilder.append(parentName).append(\" \");\n }\n synopsisBuilder.append(commandName);\n if (isOperation && !opts.isEmpty()) {\n synopsisBuilder.append(\"(\");\n } else {\n synopsisBuilder.append(\" \");\n }\n boolean hasOptions = arg != null || !opts.isEmpty();\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" [\");\n }\n if (hasActions) {\n synopsisBuilder.append(\" <action>\");\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ] || [\");\n }\n SynopsisOption opt;\n while ((opt = retrieveNextOption(synopsisOptions, false)) != null) {\n String content = addSynopsisOption(opt);\n if (content != null) {\n synopsisBuilder.append(content.trim());\n if (isOperation) {\n if (!synopsisOptions.isEmpty()) {\n synopsisBuilder.append(\",\");\n } else {\n synopsisBuilder.append(\")\");\n }\n }\n synopsisBuilder.append(\" \");\n }\n }\n if (hasActions && hasOptions) {\n synopsisBuilder.append(\" ]\");\n }\n return synopsisBuilder.toString();\n }", "public Weld addBeanDefiningAnnotations(Class<? extends Annotation>... annotations) {\n for (Class<? extends Annotation> annotation : annotations) {\n this.extendedBeanDefiningAnnotations.add(annotation);\n }\n return this;\n }", "public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\n\t\tint timeIndex\t= model.getTimeIndex(startTime);\n\t\t// Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves\n\t\tArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>();\n\t\tint firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime);\n\t\tdouble firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex);\n\t\tif(firstLiborTime>startTime) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime));\n\t\t}\n\t\t// Vector of times for the forward curve\n\t\tdouble[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)];\n\t\ttimes[0]=0;\n\t\tint indexOffset = firstLiborTime==startTime ? 0 : 1;\n\t\tfor(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(timeIndex,i));\n\t\t\ttimes[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime;\n\t\t}\n\n\t\tRandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]);\n\t\treturn ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex));\n\n\t}", "public static int getMemberDimension() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getDimension();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getDimension();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getDimension();\r\n }\r\n }\r\n return 0;\r\n }", "private void printImage(PrintStream out, ItemDocument itemDocument) {\n\t\tString imageFile = null;\n\n\t\tif (itemDocument != null) {\n\t\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t\tboolean isImage = \"P18\".equals(sg.getProperty().getId());\n\t\t\t\tif (!isImage) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Statement s : sg) {\n\t\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\t\tValue value = s.getMainSnak().getValue();\n\t\t\t\t\t\tif (value instanceof StringValue) {\n\t\t\t\t\t\t\timageFile = ((StringValue) value).getString();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (imageFile != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (imageFile == null) {\n\t\t\tout.print(\",\\\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\\\"\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tString imageFileEncoded;\n\t\t\t\timageFileEncoded = URLEncoder.encode(\n\t\t\t\t\t\timageFile.replace(\" \", \"_\"), \"utf-8\");\n\t\t\t\t// Keep special title symbols unescaped:\n\t\t\t\timageFileEncoded = imageFileEncoded.replace(\"%3A\", \":\")\n\t\t\t\t\t\t.replace(\"%2F\", \"/\");\n\t\t\t\tout.print(\",\"\n\t\t\t\t\t\t+ csvStringEscape(\"http://commons.wikimedia.org/w/thumb.php?f=\"\n\t\t\t\t\t\t\t\t+ imageFileEncoded) + \"&w=50\");\n\t\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Your JRE does not support UTF-8 encoding. Srsly?!\", e);\n\t\t\t}\n\t\t}\n\t}", "private void initializeVideoInfo() {\n VIDEO_INFO.put(\"The Big Bang Theory\", \"http://thetvdb.com/banners/_cache/posters/80379-9.jpg\");\n VIDEO_INFO.put(\"Breaking Bad\", \"http://thetvdb.com/banners/_cache/posters/81189-22.jpg\");\n VIDEO_INFO.put(\"Arrow\", \"http://thetvdb.com/banners/_cache/posters/257655-15.jpg\");\n VIDEO_INFO.put(\"Game of Thrones\", \"http://thetvdb.com/banners/_cache/posters/121361-26.jpg\");\n VIDEO_INFO.put(\"Lost\", \"http://thetvdb.com/banners/_cache/posters/73739-2.jpg\");\n VIDEO_INFO.put(\"How I met your mother\",\n \"http://thetvdb.com/banners/_cache/posters/75760-29.jpg\");\n VIDEO_INFO.put(\"Dexter\", \"http://thetvdb.com/banners/_cache/posters/79349-24.jpg\");\n VIDEO_INFO.put(\"Sleepy Hollow\", \"http://thetvdb.com/banners/_cache/posters/269578-5.jpg\");\n VIDEO_INFO.put(\"The Vampire Diaries\", \"http://thetvdb.com/banners/_cache/posters/95491-27.jpg\");\n VIDEO_INFO.put(\"Friends\", \"http://thetvdb.com/banners/_cache/posters/79168-4.jpg\");\n VIDEO_INFO.put(\"New Girl\", \"http://thetvdb.com/banners/_cache/posters/248682-9.jpg\");\n VIDEO_INFO.put(\"The Mentalist\", \"http://thetvdb.com/banners/_cache/posters/82459-1.jpg\");\n VIDEO_INFO.put(\"Sons of Anarchy\", \"http://thetvdb.com/banners/_cache/posters/82696-1.jpg\");\n }" ]
Convert this lattice to store data in the given convention. Conversion involving receiver premium assumes zero wide collar. @param targetConvention The convention to store the data in. @param displacement The displacement to use, if applicable. @param model The model for context. @return The converted lattice.
[ "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}" ]
[ "@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }", "public Duration getWork(FastTrackField type)\n {\n Double value = (Double) getObject(type);\n return value == null ? null : Duration.getInstance(value.doubleValue(), m_table.getWorkTimeUnit());\n }", "public List<String> getServiceImplementations(String serviceTypeName) {\n final List<String> strings = services.get(serviceTypeName);\n return strings == null ? Collections.<String>emptyList() : Collections.unmodifiableList(strings);\n }", "protected void updateStep(int stepNo) {\n\n if ((0 <= stepNo) && (stepNo < m_steps.size())) {\n Class<? extends A_CmsSetupStep> cls = m_steps.get(stepNo);\n A_CmsSetupStep step;\n try {\n step = cls.getConstructor(I_SetupUiContext.class).newInstance(this);\n showStep(step);\n m_stepNo = stepNo; // Only update step number if no exceptions\n } catch (Exception e) {\n CmsSetupErrorDialog.showErrorDialog(e);\n }\n\n }\n }", "private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }", "public static base_responses reset(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface resetresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new Interface();\n\t\t\t\tresetresources[i].id = resources[i].id;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}", "@SuppressWarnings(\"deprecation\")\n protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) {\n final AbstractOperationContext delegateContext = getDelegateContext(operationId);\n CurrentOperationIdHolder.setCurrentOperationID(operationId);\n try {\n return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext);\n } finally {\n CurrentOperationIdHolder.setCurrentOperationID(null);\n }\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 }", "@Override\n\tpublic T next() {\n\t\tSQLException sqlException = null;\n\t\ttry {\n\t\t\tT result = nextThrow();\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\tsqlException = e;\n\t\t}\n\t\t// we have to throw if there is no next or on a SQLException\n\t\tlast = null;\n\t\tcloseQuietly();\n\t\tthrow new IllegalStateException(\"Could not get next result for \" + dataClass, sqlException);\n\t}" ]
Set the row, column, and value @return this
[ "public FluoKeyValueGenerator set(RowColumnValue rcv) {\n setRow(rcv.getRow());\n setColumn(rcv.getColumn());\n setValue(rcv.getValue());\n return this;\n }" ]
[ "public void begin(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n data = new TimingData(key);\n executionInfo.put(key, data);\n }\n data.begin();\n }", "public void fireEvent(Type eventType, Object event, Annotation... qualifiers) {\n final EventMetadata metadata = new EventMetadataImpl(eventType, null, qualifiers);\n notifier.fireEvent(eventType, event, metadata, qualifiers);\n }", "public LayerType toDto(Class<? extends com.vividsolutions.jts.geom.Geometry> geometryClass) {\n\t\tif (geometryClass == LineString.class) {\n\t\t\treturn LayerType.LINESTRING;\n\t\t} else if (geometryClass == MultiLineString.class) {\n\t\t\treturn LayerType.MULTILINESTRING;\n\t\t} else if (geometryClass == Point.class) {\n\t\t\treturn LayerType.POINT;\n\t\t} else if (geometryClass == MultiPoint.class) {\n\t\t\treturn LayerType.MULTIPOINT;\n\t\t} else if (geometryClass == Polygon.class) {\n\t\t\treturn LayerType.POLYGON;\n\t\t} else if (geometryClass == MultiPolygon.class) {\n\t\t\treturn LayerType.MULTIPOLYGON;\n\t\t} else {\n\t\t\treturn LayerType.GEOMETRY;\n\t\t}\n\t}", "private static void defineField(Map<String, FieldType> container, String name, FieldType type, String alias)\n {\n container.put(name, type);\n if (alias != null)\n {\n ALIASES.put(type, alias);\n }\n }", "public static nssimpleacl[] get(nitro_service service, String aclname[]) throws Exception{\n\t\tif (aclname !=null && aclname.length>0) {\n\t\t\tnssimpleacl response[] = new nssimpleacl[aclname.length];\n\t\t\tnssimpleacl obj[] = new nssimpleacl[aclname.length];\n\t\t\tfor (int i=0;i<aclname.length;i++) {\n\t\t\t\tobj[i] = new nssimpleacl();\n\t\t\t\tobj[i].set_aclname(aclname[i]);\n\t\t\t\tresponse[i] = (nssimpleacl) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private JSONValue toJsonStringList(Collection<? extends Object> list) {\n\n if (null != list) {\n JSONArray array = new JSONArray();\n for (Object o : list) {\n array.set(array.size(), new JSONString(o.toString()));\n }\n return array;\n } else {\n return null;\n }\n }", "private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateImagePath = DockerUtils.getImagePath(imageTag);\n String manifestPath;\n\n // Try to get manifest, assuming reverse proxy\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Try to get manifest, assuming proxy-less\n candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf(\"/\") + 1);\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Couldn't find correct manifest\n listener.getLogger().println(\"Could not find corresponding manifest.json file in Artifactory.\");\n return false;\n }", "private String getPropertyLabel(PropertyIdValue propertyIdValue) {\n\t\tPropertyRecord propertyRecord = this.propertyRecords\n\t\t\t\t.get(propertyIdValue);\n\t\tif (propertyRecord == null || propertyRecord.propertyDocument == null) {\n\t\t\treturn propertyIdValue.getId();\n\t\t} else {\n\t\t\treturn getLabel(propertyIdValue, propertyRecord.propertyDocument);\n\t\t}\n\t}", "public static 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}" ]
Gets the Kullback Leibler divergence. @param p P vector. @param q Q vector. @return The Kullback Leibler divergence between u and v.
[ "public static double KullbackLeiblerDivergence(double[] p, double[] q) {\n boolean intersection = false;\n double k = 0;\n\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n intersection = true;\n k += p[i] * Math.log(p[i] / q[i]);\n }\n }\n\n if (intersection)\n return k;\n else\n return Double.POSITIVE_INFINITY;\n }" ]
[ "private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }", "private static int skipEndOfLine(String text, int offset)\n {\n char c;\n boolean finished = false;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case ' ': // found that OBJDATA could be followed by a space the EOL\n case '\\r':\n case '\\n':\n {\n ++offset;\n break;\n }\n\n case '}':\n {\n offset = -1;\n finished = true;\n break;\n }\n\n default:\n {\n finished = true;\n break;\n }\n }\n }\n\n return (offset);\n }", "public Stats getPhotosetStats(String photosetId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSET_STATS, \"photoset_id\", photosetId, date);\n }", "public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "protected void captureCenterEye(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshotCenterCallback == null) {\n return;\n }\n\n // TODO: when we will use multithreading, create new camera using centercamera as we are adding posteffects into it\n final GVRCamera centerCamera = mMainScene.getMainCameraRig().getCenterCamera();\n final GVRMaterial postEffect = new GVRMaterial(this, GVRMaterial.GVRShaderType.VerticalFlip.ID);\n\n centerCamera.addPostEffect(postEffect);\n\n GVRRenderTexture posteffectRenderTextureB = null;\n GVRRenderTexture posteffectRenderTextureA = null;\n\n if(isMultiview) {\n posteffectRenderTextureA = mRenderBundle.getEyeCapturePostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getEyeCapturePostEffectRenderTextureB();\n renderTarget = mRenderBundle.getEyeCaptureRenderTarget();\n renderTarget.cullFromCamera(mMainScene, centerCamera ,mRenderBundle.getShaderManager());\n renderTarget.beginRendering(centerCamera);\n }\n else {\n posteffectRenderTextureA = mRenderBundle.getPostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getPostEffectRenderTextureB();\n }\n\n renderTarget.render(mMainScene,centerCamera, mRenderBundle.getShaderManager(), posteffectRenderTextureA, posteffectRenderTextureB);\n centerCamera.removePostEffect(postEffect);\n readRenderResult(renderTarget, EYE.MULTIVIEW, false);\n\n if(isMultiview)\n renderTarget.endRendering();\n\n final Bitmap bitmap = Bitmap.createBitmap(mReadbackBufferWidth, mReadbackBufferHeight, Bitmap.Config.ARGB_8888);\n mReadbackBuffer.rewind();\n bitmap.copyPixelsFromBuffer(mReadbackBuffer);\n final GVRScreenshotCallback callback = mScreenshotCenterCallback;\n Threads.spawn(new Runnable() {\n public void run() {\n callback.onScreenCaptured(bitmap);\n }\n });\n\n mScreenshotCenterCallback = null;\n }", "private <T> CoreRemoteMongoCollection<T> getRemoteCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass\n ) {\n return remoteClient\n .getDatabase(namespace.getDatabaseName())\n .getCollection(namespace.getCollectionName(), resultClass);\n }", "protected void printFeatures(IN wi, Collection<String> features) {\r\n if (flags.printFeatures == null || writtenNum > flags.printFeaturesUpto) {\r\n return;\r\n }\r\n try {\r\n if (cliqueWriter == null) {\r\n cliqueWriter = new PrintWriter(new FileOutputStream(\"feats\" + flags.printFeatures + \".txt\"), true);\r\n writtenNum = 0;\r\n }\r\n } catch (Exception ioe) {\r\n throw new RuntimeException(ioe);\r\n }\r\n if (writtenNum >= flags.printFeaturesUpto) {\r\n return;\r\n }\r\n if (wi instanceof CoreLabel) {\r\n cliqueWriter.print(wi.get(TextAnnotation.class) + ' ' + wi.get(PartOfSpeechAnnotation.class) + ' '\r\n + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\\t');\r\n } else {\r\n cliqueWriter.print(wi.get(CoreAnnotations.TextAnnotation.class)\r\n + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\\t');\r\n }\r\n boolean first = true;\r\n for (Object feat : features) {\r\n if (first) {\r\n first = false;\r\n } else {\r\n cliqueWriter.print(\" \");\r\n }\r\n cliqueWriter.print(feat);\r\n }\r\n cliqueWriter.println();\r\n writtenNum++;\r\n }", "private boolean isTileVisible(final ReferencedEnvelope tileBounds) {\n if (FloatingPointUtil.equals(this.transformer.getRotation(), 0.0)) {\n return true;\n }\n\n final GeometryFactory gfac = new GeometryFactory();\n final Optional<Geometry> rotatedMapBounds = getRotatedMapBounds(gfac);\n\n if (rotatedMapBounds.isPresent()) {\n return rotatedMapBounds.get().intersects(gfac.toGeometry(tileBounds));\n } else {\n // in case of an error, we simply load the tile\n return true;\n }\n }", "protected MetaMatcher createMetaMatcher(String filterAsString, Map<String, MetaMatcher> metaMatchers) {\n \tfor ( String key : metaMatchers.keySet() ){\n \t\tif ( filterAsString.startsWith(key)){\n \t\t\treturn metaMatchers.get(key);\n \t\t}\n \t}\n if (filterAsString.startsWith(GROOVY)) {\n return new GroovyMetaMatcher();\n }\n return new DefaultMetaMatcher();\n }" ]
Use this API to fetch all the nsrollbackcmd resources that are configured on netscaler.
[ "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}" ]
[ "public static void closeMASCaseManager(File caseManager) {\n\n FileWriter caseManagerWriter;\n try {\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\"}\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger\n .getLogger(\"CreateMASCaseManager.closeMASCaseManager\");\n logger.info(\"ERROR: There is a mistake closing caseManager file.\\n\");\n }\n\n }", "public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n return getModuleDependencies(module, filters, 1, new ArrayList<String>());\n }", "public static base_response add(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey addresource = new sslcertkey();\n\t\taddresource.certkey = resource.certkey;\n\t\taddresource.cert = resource.cert;\n\t\taddresource.key = resource.key;\n\t\taddresource.password = resource.password;\n\t\taddresource.fipskey = resource.fipskey;\n\t\taddresource.inform = resource.inform;\n\t\taddresource.passplain = resource.passplain;\n\t\taddresource.expirymonitor = resource.expirymonitor;\n\t\taddresource.notificationperiod = resource.notificationperiod;\n\t\taddresource.bundle = resource.bundle;\n\t\treturn addresource.add_resource(client);\n\t}", "public boolean equivalent(Element otherElement, boolean logging) {\n\t\tif (eventable.getElement().equals(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalAttributes(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element attributes equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (eventable.getElement().equalId(otherElement)) {\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element ID equal\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!eventable.getElement().getText().equals(\"\")\n\t\t\t\t&& eventable.getElement().equalText(otherElement)) {\n\n\t\t\tif (logging) {\n\t\t\t\tLOGGER.info(\"Element text equal\");\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "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 URI setPath(final URI initialUri, final String path) {\n String finalPath = path;\n if (!finalPath.startsWith(\"/\")) {\n finalPath = '/' + path;\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,\n initialUri.getQuery(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n finalPath, initialUri.getQuery(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public void finishFlow(final String code, final String state) throws ApiException {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (codeVerifier == null)\n throw new IllegalArgumentException(\"code_verifier is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(\"grant_type=\");\n builder.append(encode(\"authorization_code\"));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&code=\");\n builder.append(encode(code));\n builder.append(\"&code_verifier=\");\n builder.append(encode(codeVerifier));\n update(account, builder.toString());\n }", "private final void handleHttpWorkerResponse(\n ResponseOnSingeRequest respOnSingleReq) throws Exception {\n // Successful response from GenericAsyncHttpWorker\n\n // Jeff 20310411: use generic response\n\n String responseContent = respOnSingleReq.getResponseBody();\n response.setResponseContent(respOnSingleReq.getResponseBody());\n\n /**\n * Poller logic if pollable: check if need to poll/ or already complete\n * 1. init poller data and HttpPollerProcessor 2. check if task\n * complete, if not, send the request again.\n */\n if (request.isPollable()) {\n boolean scheduleNextPoll = false;\n boolean errorFindingUuid = false;\n\n // set JobId of the poller\n if (!pollerData.isUuidHasBeenSet()) {\n String jobId = httpPollerProcessor\n .getUuidFromResponse(respOnSingleReq);\n\n if (jobId.equalsIgnoreCase(PcConstants.NA)) {\n errorFindingUuid = true;\n pollingErrorCount++;\n logger.error(\"!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. \"\n\n + \"DEBUG: REGEX_JOBID: \"\n + httpPollerProcessor.getJobIdRegex()\n\n + \"RESPONSE: \"\n + respOnSingleReq.getResponseBody()\n + \" polling Error count\"\n + pollingErrorCount\n + \" at \" + PcDateUtils.getNowDateTimeStrStandard());\n // fail fast\n pollerData.setError(true);\n pollerData.setComplete(true);\n\n } else {\n pollerData.setJobIdAndMarkHasBeenSet(jobId);\n // if myResponse has other errors, mark poll data as error.\n pollerData.setError(httpPollerProcessor\n .ifThereIsErrorInResponse(respOnSingleReq));\n }\n\n }\n if (!pollerData.isError()) {\n\n pollerData\n .setComplete(httpPollerProcessor\n .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));\n pollerData.setCurrentProgress(httpPollerProcessor\n .getProgressFromResponse(respOnSingleReq));\n }\n\n // poll again only if not complete AND no error; 2015: change to\n // over limit\n scheduleNextPoll = !pollerData.isComplete()\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError());\n\n // Schedule next poll and return. (not to answer back to manager yet\n // )\n if (scheduleNextPoll\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError())) {\n\n pollMessageCancellable = getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(httpPollerProcessor\n .getPollIntervalMillis(),\n TimeUnit.MILLISECONDS), getSelf(),\n OperationWorkerMsgType.POLL_PROGRESS,\n getContext().system().dispatcher(), getSelf());\n\n logger.info(\"\\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND\"\n + String.format(\"PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent,\n PcDateUtils.getNowDateTimeStrStandard()));\n\n String responseContentNew = errorFindingUuid ? responseContent\n + \"_PollingErrorCount:\" + pollingErrorCount\n : responseContent;\n logger.info(responseContentNew);\n // log\n pollerData.getPollingHistoryMap().put(\n \"RECV_\" + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\"PROGRESS:%.3f, BODY:%s\",\n pollerData.getCurrentProgress(),\n responseContent));\n return;\n } else {\n pollerData\n .getPollingHistoryMap()\n .put(\"RECV_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\n \"POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent));\n }\n\n }// end if (request.isPollable())\n\n reply(respOnSingleReq.isFailObtainResponse(),\n respOnSingleReq.getErrorMessage(),\n respOnSingleReq.getStackTrace(),\n respOnSingleReq.getStatusCode(),\n respOnSingleReq.getStatusCodeInt(),\n respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());\n\n }", "public BoxFile.Info restoreFile(String fileID) {\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }" ]
Sets the top padding for all cells in the table. @param paddingTop new padding, ignored if smaller than 0 @return this to allow chaining
[ "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 <FT, FID> FT createForeignShell(ConnectionSource connectionSource, Object val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tFT foreignObject = castDao.createObjectInstance();\n\t\tforeignIdField.assignField(connectionSource, foreignObject, val, false, objectCache);\n\t\treturn foreignObject;\n\t}", "public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }", "@RequestMapping(value = \"group\", method = RequestMethod.GET)\n public String newGroupGet(Model model) {\n model.addAttribute(\"groups\",\n pathOverrideService.findAllGroups());\n return \"groups\";\n }", "boolean awaitState(final InternalState expected) {\n synchronized (this) {\n final InternalState initialRequired = this.requiredState;\n for(;;) {\n final InternalState required = this.requiredState;\n // Stop in case the server failed to reach the state\n if(required == InternalState.FAILED) {\n return false;\n // Stop in case the required state changed\n } else if (initialRequired != required) {\n return false;\n }\n final InternalState current = this.internalState;\n if(expected == current) {\n return true;\n }\n try {\n wait();\n } catch(InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n }\n }", "@Override\n public void process(TestCaseResult context) {\n context.getParameters().add(new Parameter()\n .withName(getName())\n .withValue(getValue())\n .withKind(ParameterKind.valueOf(getKind()))\n );\n }", "public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n System.arraycopy(data, offset, buffer, bufferOffset, size);\n }", "public BUILDER setAttributeGroup(String attributeGroup) {\n assert attributeGroup == null || attributeGroup.length() > 0;\n //noinspection deprecation\n this.attributeGroup = attributeGroup;\n return (BUILDER) this;\n }", "private ClassTypeSignature getClassTypeSignature(\r\n\t\t\tParameterizedType parameterizedType) {\r\n\t\tClass<?> rawType = (Class<?>) parameterizedType.getRawType();\r\n\t\tType[] typeArguments = parameterizedType.getActualTypeArguments();\r\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length];\r\n\t\tfor (int i = 0; i < typeArguments.length; i++) {\r\n\t\t\ttypeArgSignatures[i] = getTypeArgSignature(typeArguments[i]);\r\n\t\t}\r\n\r\n\t\tString binaryName = rawType.isMemberClass() ? rawType.getSimpleName()\r\n\t\t\t\t: rawType.getName();\r\n\t\tClassTypeSignature ownerTypeSignature = parameterizedType\r\n\t\t\t\t.getOwnerType() == null ? null\r\n\t\t\t\t: (ClassTypeSignature) getFullTypeSignature(parameterizedType\r\n\t\t\t\t\t\t.getOwnerType());\r\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\r\n\t\t\t\tbinaryName, typeArgSignatures, ownerTypeSignature);\r\n\t\treturn classTypeSignature;\r\n\t}", "public boolean isDeleted(Identity id)\r\n {\r\n ObjectEnvelope envelope = buffer.getByIdentity(id);\r\n\r\n return (envelope != null && envelope.needsDelete());\r\n }" ]
Start the drag operation of a scene object with a rigid body. @param sceneObject Scene object with a rigid body attached to it. @param hitX rel position in x-axis. @param hitY rel position in y-axis. @param hitZ rel position in z-axis. @return true if success, otherwise returns false.
[ "public boolean startDrag(final GVRSceneObject sceneObject,\n final float hitX, final float hitY, final float hitZ) {\n final GVRRigidBody dragMe = (GVRRigidBody)sceneObject.getComponent(GVRRigidBody.getComponentType());\n if (dragMe == null || dragMe.getSimulationType() != GVRRigidBody.DYNAMIC || !contains(dragMe))\n return false;\n\n GVRTransform t = sceneObject.getTransform();\n\n final Vector3f relPos = new Vector3f(hitX, hitY, hitZ);\n relPos.mul(t.getScaleX(), t.getScaleY(), t.getScaleZ());\n relPos.rotate(new Quaternionf(t.getRotationX(), t.getRotationY(), t.getRotationZ(), t.getRotationW()));\n\n final GVRSceneObject pivotObject = mPhysicsDragger.startDrag(sceneObject,\n relPos.x, relPos.y, relPos.z);\n if (pivotObject == null)\n return false;\n\n mPhysicsContext.runOnPhysicsThread(new Runnable() {\n @Override\n public void run() {\n mRigidBodyDragMe = dragMe;\n NativePhysics3DWorld.startDrag(getNative(), pivotObject.getNative(), dragMe.getNative(),\n hitX, hitY, hitZ);\n }\n });\n\n return true;\n }" ]
[ "public static int findFirstNonAnnotationLine(ASTNode node, SourceCode sourceCode) {\r\n if (node instanceof AnnotatedNode && !((AnnotatedNode) node).getAnnotations().isEmpty()) {\r\n\r\n // HACK: Groovy line numbers are broken when annotations have a parameter :(\r\n // so we must look at the lineNumber, not the lastLineNumber\r\n AnnotationNode lastAnnotation = null;\r\n for (AnnotationNode annotation : ((AnnotatedNode) node).getAnnotations()) {\r\n if (lastAnnotation == null) lastAnnotation = annotation;\r\n else if (lastAnnotation.getLineNumber() < annotation.getLineNumber()) lastAnnotation = annotation;\r\n }\r\n\r\n String rawLine = getRawLine(sourceCode, lastAnnotation.getLastLineNumber()-1);\r\n\r\n if(rawLine == null) {\r\n return node.getLineNumber();\r\n }\r\n\r\n // is the annotation the last thing on the line?\r\n if (rawLine.length() > lastAnnotation.getLastColumnNumber()) {\r\n // no it is not\r\n return lastAnnotation.getLastLineNumber();\r\n }\r\n // yes it is the last thing, return the next thing\r\n return lastAnnotation.getLastLineNumber() + 1;\r\n }\r\n return node.getLineNumber();\r\n }", "public static appqoepolicy[] get(nitro_service service) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tappqoepolicy[] response = (appqoepolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void registerCollectionSizeGauge(\n\t\t\tCollectionSizeGauge collectionSizeGauge) {\n\t\tString name = createMetricName(LocalTaskExecutorService.class,\n\t\t\t\t\"queue-size\");\n\t\tmetrics.register(name, collectionSizeGauge);\n\t}", "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 static sslfipskey get(nitro_service service, String fipskeyname) throws Exception{\n\t\tsslfipskey obj = new sslfipskey();\n\t\tobj.set_fipskeyname(fipskeyname);\n\t\tsslfipskey response = (sslfipskey) obj.get_resource(service);\n\t\treturn response;\n\t}", "public String createSessionForResource(String configPath, String fileName) throws CmsUgcException {\n\n CmsUgcSession formSession = CmsUgcSessionFactory.getInstance().createSessionForFile(\n getCmsObject(),\n getRequest(),\n configPath,\n fileName);\n return \"\" + formSession.getId();\n }", "public static AdminClient getAdminClient(String url) {\n ClientConfig config = new ClientConfig().setBootstrapUrls(url)\n .setConnectionTimeout(5, TimeUnit.SECONDS);\n\n AdminClientConfig adminConfig = new AdminClientConfig().setAdminSocketTimeoutSec(5);\n return new AdminClient(adminConfig, config);\n }", "protected String getJavaExecutablePath() {\n String executableName = isWindows() ? \"bin/java.exe\" : \"bin/java\";\n return PROPERTIES.getJavaHome().resolve(executableName).toAbsolutePath().toString();\n }", "public Configuration[] getConfigurations(String name) {\n ArrayList<Configuration> valuesList = new ArrayList<Configuration>();\n\n logger.info(\"Getting data for {}\", name);\n\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION;\n if (name != null) {\n queryString += \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n if (name != null) {\n statement.setString(1, name);\n }\n\n results = statement.executeQuery();\n while (results.next()) {\n Configuration config = new Configuration();\n config.setValue(results.getString(Constants.DB_TABLE_CONFIGURATION_VALUE));\n config.setKey(results.getString(Constants.DB_TABLE_CONFIGURATION_NAME));\n config.setId(results.getInt(Constants.GENERIC_ID));\n logger.info(\"the configValue is = {}\", config.getValue());\n valuesList.add(config);\n }\n } catch (SQLException sqe) {\n logger.info(\"Exception in sql\");\n sqe.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (valuesList.size() == 0) {\n return null;\n }\n\n return valuesList.toArray(new Configuration[0]);\n }" ]
Sets the global. Does not add the global to the ExecutionResults. @param identifier The identifier of the global @param object The instance to be set as the global. @return
[ "public static Command newSetGlobal(String identifier,\n Object object) {\n return getCommandFactoryProvider().newSetGlobal( identifier,\n object );\n }" ]
[ "void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }", "private void wrongUsage() {\n\n String usage = \"Usage: java -cp $PATH_TO_OPENCMS_JAR org.opencms.rmi.CmsRemoteShellClient\\n\"\n + \" -script=[path to script] (optional) \\n\"\n + \" -registryPort=[port of RMI registry] (optional, default is \"\n + CmsRemoteShellConstants.DEFAULT_PORT\n + \")\\n\"\n + \" -additional=[additional commands class name] (optional)\";\n System.out.println(usage);\n System.exit(1);\n }", "public void sendJsonToTagged(Object data, String label) {\n sendToTagged(JSON.toJSONString(data), label);\n }", "public List<Formation> listFormation(String appName) {\n return connection.execute(new FormationList(appName), apiKey);\n }", "public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}", "private JSONArray getApplicablePathNames (String requestUrl, Integer requestType) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n List<EndpointOverride> applicablePaths;\n JSONArray pathNames = new JSONArray();\n // Get all paths that match the request\n applicablePaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, requestInfo.client,\n requestInfo.profile,\n requestUrl + \"?\" + requestInfo.originalRequestInfo.getQueryString(),\n requestType, true);\n // Extract just the path name from each path\n for (EndpointOverride path : applicablePaths) {\n JSONObject pathName = new JSONObject();\n pathName.put(\"name\", path.getPathName());\n pathNames.put(pathName);\n }\n\n return pathNames;\n }", "public MessageSet read(long readOffset, long size) throws IOException {\n return new FileMessageSet(channel, this.offset + readOffset, //\n Math.min(this.offset + readOffset + size, highWaterMark()), false, new AtomicBoolean(false));\n }", "@SuppressWarnings(\"deprecation\")\n private void cancelRequestAndWorkerOnHost(List<String> targetHosts) {\n\n List<String> validTargetHosts = new ArrayList<String>(workers.keySet());\n validTargetHosts.retainAll(targetHosts);\n logger.info(\"targetHosts for cancel: Total: {}\"\n + \" Valid in current manager with worker threads: {}\",\n targetHosts.size(), validTargetHosts.size());\n\n for (String targetHost : validTargetHosts) {\n\n ActorRef worker = workers.get(targetHost);\n\n if (worker != null && !worker.isTerminated()) {\n worker.tell(OperationWorkerMsgType.CANCEL, getSelf());\n logger.info(\"Submitted CANCEL request on Host {}\", targetHost);\n } else {\n logger.info(\n \"Did NOT Submitted \"\n + \"CANCEL request on Host {} as worker on this host is null or already killed\",\n targetHost);\n }\n\n }\n\n }", "public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }" ]
Compute singular values and U and V at the same time
[ "private boolean computeUWV() {\n bidiag.getDiagonal(diag,off);\n qralg.setMatrix(numRowsT,numColsT,diag,off);\n\n// long pointA = System.currentTimeMillis();\n // compute U and V matrices\n if( computeU )\n Ut = bidiag.getU(Ut,true,compact);\n if( computeV )\n Vt = bidiag.getV(Vt,true,compact);\n\n qralg.setFastValues(false);\n if( computeU )\n qralg.setUt(Ut);\n else\n qralg.setUt(null);\n if( computeV )\n qralg.setVt(Vt);\n else\n qralg.setVt(null);\n\n// long pointB = System.currentTimeMillis();\n\n boolean ret = !qralg.process();\n\n// long pointC = System.currentTimeMillis();\n// System.out.println(\" compute UV \"+(pointB-pointA)+\" QR = \"+(pointC-pointB));\n\n return ret;\n }" ]
[ "public int readFrom(byte[] src, int srcOffset, long destOffset, int length) {\n int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length));\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src, srcOffset, readLen);\n return readLen;\n }", "public Duration getStartSlack()\n {\n Duration startSlack = (Duration) getCachedValue(TaskField.START_SLACK);\n if (startSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n startSlack = DateHelper.getVariance(this, getEarlyStart(), getLateStart(), duration.getUnits());\n set(TaskField.START_SLACK, startSlack);\n }\n }\n return (startSlack);\n }", "public static Iterable<BoxFileVersionRetention.Info> getRetentions(\n final BoxAPIConnection api, QueryFilter filter, String ... fields) {\n filter.addFields(fields);\n return new BoxResourceIterable<BoxFileVersionRetention.Info>(api,\n ALL_RETENTIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), filter.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected BoxFileVersionRetention.Info factory(JsonObject jsonObject) {\n BoxFileVersionRetention retention = new BoxFileVersionRetention(api, jsonObject.get(\"id\").asString());\n return retention.new Info(jsonObject);\n }\n };\n }", "private String[] getFksToThisClass()\r\n {\r\n String indTable = getCollectionDescriptor().getIndirectionTable();\r\n String[] fks = getCollectionDescriptor().getFksToThisClass();\r\n String[] result = new String[fks.length];\r\n\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = indTable + \".\" + fks[i];\r\n }\r\n\r\n return result;\r\n }", "public void checkSpecialization() {\n if (isSpecializing()) {\n boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);\n String previousSpecializedBeanName = null;\n for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {\n String name = specializedBean.getName();\n if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {\n // there may be multiple beans specialized by this bean - make sure they all share the same name\n throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);\n }\n previousSpecializedBeanName = name;\n if (isNameDefined && name != null) {\n throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());\n }\n\n // When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are\n // added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among\n // these types are NOT types of the specializing bean (that's the way java works)\n boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>\n && specializedBean.getBeanClass().getTypeParameters().length > 0\n && !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));\n for (Type specializedType : specializedBean.getTypes()) {\n if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n boolean contains = getTypes().contains(specializedType);\n if (!contains) {\n for (Type specializingType : getTypes()) {\n // In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be\n // equal in the java sense. Therefore we have to use our own equality util.\n if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {\n contains = true;\n break;\n }\n }\n }\n if (!contains) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n }\n }\n }\n }", "public static dos_stats get(nitro_service service, options option) throws Exception{\n\t\tdos_stats obj = new dos_stats();\n\t\tdos_stats[] response = (dos_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}", "public void setBodyFilter(int pathId, String bodyFilter) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_BODY_FILTER + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, bodyFilter);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}", "public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable unsetresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new bridgetable();\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}" ]
Return given duration in a human-friendly format. For example, "4 minutes" or "1 second". Returns only largest meaningful unit of time, from seconds up to hours. The longest duration it supports is hours. This method assumes that there are 60 minutes in an hour, 60 seconds in a minute and 1000 milliseconds in a second. All currently supplied chronologies use this definition.
[ "public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) {\n Resources res = context.getResources();\n Duration duration = readableDuration.toDuration();\n\n final int hours = (int) duration.getStandardHours();\n if (hours != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours);\n }\n\n final int minutes = (int) duration.getStandardMinutes();\n if (minutes != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes);\n }\n\n final int seconds = (int) duration.getStandardSeconds();\n return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds);\n }" ]
[ "public static void symmLowerToFull( DMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new MatrixDimensionException(\"Must be a square matrix\");\n\n final int cols = A.numCols;\n\n for (int row = 0; row < A.numRows; row++) {\n for (int col = row+1; col < cols; col++) {\n A.data[row*cols+col] = A.data[col*cols+row];\n }\n }\n }", "public static final double getDouble(String value)\n {\n return (value == null || value.length() == 0 ? 0 : Double.parseDouble(value));\n }", "public static base_response add(nitro_service client, dnspolicylabel resource) throws Exception {\n\t\tdnspolicylabel addresource = new dnspolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.transform = resource.transform;\n\t\treturn addresource.add_resource(client);\n\t}", "private void populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\n }\n }", "public static <T> List<T> copyOf(Collection<T> source) {\n Preconditions.checkNotNull(source);\n if (source instanceof ImmutableList<?>) {\n return (ImmutableList<T>) source;\n }\n if (source.isEmpty()) {\n return Collections.emptyList();\n }\n return ofInternal(source.toArray());\n }", "public FieldType getFieldTypeFromVarDataKey(Integer key)\n {\n FieldType result = null;\n for (Entry<FieldType, FieldMap.FieldItem> entry : m_map.entrySet())\n {\n if (entry.getValue().getFieldLocation() == FieldLocation.VAR_DATA && entry.getValue().getVarDataKey().equals(key))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\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 }", "private CollectionDescriptorDef cloneCollection(CollectionDescriptorDef collDef, String prefix)\r\n {\r\n CollectionDescriptorDef copyCollDef = new CollectionDescriptorDef(collDef, prefix);\r\n\r\n copyCollDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyCollDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyCollDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyCollDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included collection \"+\r\n copyCollDef.getName()+\" from class \"+collDef.getOwner().getName()); \r\n }\r\n copyCollDef.applyModifications(mod);\r\n }\r\n return copyCollDef;\r\n }", "public void addLicense(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n // Try to find an existing license that match the new one\n final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);\n final DbLicense license = licenseHandler.resolve(licenseId);\n\n // If there is no existing license that match this one let's use the provided value but\n // only if the artifact has no license yet. Otherwise it could mean that users has already\n // identify the license manually.\n if(license == null){\n if(dbArtifact.getLicenses().isEmpty()){\n LOG.warn(\"Add reference to a non existing license called \" + licenseId + \" in artifact \" + dbArtifact.getGavc());\n repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);\n }\n }\n // Add only if the license is not already referenced\n else if(!dbArtifact.getLicenses().contains(license.getName())){\n repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());\n }\n }" ]
Get the correct google api key. Tries to read a workplace key first. @param cms CmsObject @param sitePath site path @return key value @throws CmsException exception
[ "private String getApiKey(CmsObject cms, String sitePath) throws CmsException {\n\n String res = cms.readPropertyObject(\n sitePath,\n CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,\n true).getValue();\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {\n res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();\n }\n return res;\n\n }" ]
[ "public void setMatrix(int[] matrix) {\n\t\tthis.matrix = matrix;\n\t\tsum = 0;\n\t\tfor (int i = 0; i < matrix.length; i++)\n\t\t\tsum += matrix[i];\n\t}", "protected VelocityContext createContext()\n {\n VelocityContext context = new VelocityContext();\n context.put(META_KEY, META);\n context.put(UTILS_KEY, UTILS);\n context.put(MESSAGES_KEY, MESSAGES);\n return context;\n }", "static JobContext copy() {\n JobContext current = current_.get();\n //JobContext ctxt = new JobContext(keepParent ? current : null);\n JobContext ctxt = new JobContext(null);\n if (null != current) {\n ctxt.bag_.putAll(current.bag_);\n }\n return ctxt;\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 }", "private boolean hasToBuilderMethod(\n DeclaredType builder,\n boolean isExtensible,\n Iterable<ExecutableElement> methods) {\n for (ExecutableElement method : methods) {\n if (isToBuilderMethod(builder, method)) {\n if (!isExtensible) {\n messager.printMessage(ERROR,\n \"No accessible no-args Builder constructor available to implement toBuilder\",\n method);\n }\n return true;\n }\n }\n return false;\n }", "public com.squareup.okhttp.Call getCharactersCharacterIdShipCall(Integer characterId, String datasource,\n String ifNoneMatch, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v1/characters/{character_id}/ship/\".replaceAll(\"\\\\{\" + \"character_id\" + \"\\\\}\",\n apiClient.escapeString(characterId.toString()));\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n if (ifNoneMatch != null) {\n localVarHeaderParams.put(\"If-None-Match\", apiClient.parameterToString(ifNoneMatch));\n }\n\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = { \"application/json\" };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"GET\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }", "public void setContentType(int pathId, String contentType) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_CONTENT_TYPE + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, contentType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }", "public ConfigBuilder withHost(final String host) {\n if (host == null || \"\".equals(host)) {\n throw new IllegalArgumentException(\"host must not be null or empty: \" + host);\n }\n this.host = host;\n return this;\n }" ]
Adds the complex number with a scalar value. @param z1 Complex Number. @param scalar Scalar value. @return Returns new ComplexNumber instance containing the add of specified complex number with scalar value.
[ "public static ComplexNumber Add(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real + scalar, z1.imaginary);\r\n }" ]
[ "public static <T_Result, T_Source> List<T_Result> map(Collection<T_Source> source,\n Mapper<T_Result, T_Source> mapper) {\n List<T_Result> result = new LinkedList<T_Result>();\n for (T_Source element : source) {\n result.add(mapper.map(element));\n }\n return result;\n }", "public void remove(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\tconvertedObjects.remove(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}", "public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }", "private void checkUndefinedNotification(Notification notification) {\n String type = notification.getType();\n PathAddress source = notification.getSource();\n Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);\n if (!descriptions.keySet().contains(type)) {\n missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));\n }\n }", "private void populateContainer(FieldType field, List<Pair<String, String>> items)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n for (Pair<String, String> pair : items)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setValue(pair.getFirst());\n item.setDescription(pair.getSecond());\n table.add(item);\n }\n }", "public FluoKeyValueGenerator set(RowColumnValue rcv) {\n setRow(rcv.getRow());\n setColumn(rcv.getColumn());\n setValue(rcv.getValue());\n return this;\n }", "public static String make512Safe(StringBuffer input, String newline) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString content = input.toString();\n\t\tString rest = content;\n\t\twhile (!rest.isEmpty()) {\n\t\t\tif (rest.contains(\"\\n\")) {\n\t\t\t\tString line = rest.substring(0, rest.indexOf(\"\\n\"));\n\t\t\t\trest = rest.substring(rest.indexOf(\"\\n\") + 1);\n\t\t\t\tif (line.length() > 1 && line.charAt(line.length() - 1) == '\\r')\n\t\t\t\t\tline = line.substring(0, line.length() - 1);\n\t\t\t\tappend512Safe(line, result, newline);\n\t\t\t} else {\n\t\t\t\tappend512Safe(rest, result, newline);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result.toString();\n\t}", "public Snackbar actionLabel(CharSequence actionButtonLabel) {\n mActionLabel = actionButtonLabel;\n if (snackbarAction != null) {\n snackbarAction.setText(mActionLabel);\n }\n return this;\n }", "public void setWeekDay(String weekDayStr) {\n\n final WeekDay weekDay = WeekDay.valueOf(weekDayStr);\n if ((m_model.getWeekDay() != null) || !m_model.getWeekDay().equals(weekDay)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(weekDay);\n onValueChange();\n }\n });\n\n }\n\n }" ]
Allocates a new next buffer and pending fetch.
[ "private void requestBlock() {\n next = ByteBuffer.allocate(blockSizeBytes);\n long requestTimeout = retryParams.getRequestTimeoutMillisForCurrentAttempt();\n pendingFetch = raw.readObjectAsync(next, filename, fetchPosition, requestTimeout);\n }" ]
[ "public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}", "@Nullable\n public ResultT first() {\n final CoreRemoteMongoCursor<ResultT> cursor = iterator();\n if (!cursor.hasNext()) {\n return null;\n }\n return cursor.next();\n }", "public static base_response add(nitro_service client, nslimitselector resource) throws Exception {\n\t\tnslimitselector addresource = new nslimitselector();\n\t\taddresource.selectorname = resource.selectorname;\n\t\taddresource.rule = resource.rule;\n\t\treturn addresource.add_resource(client);\n\t}", "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 }", "public static boolean reconnect(final Jedis jedis, final int reconAttempts, final long reconnectSleepTime) {\n int i = 1;\n do {\n try {\n jedis.disconnect();\n try {\n Thread.sleep(reconnectSleepTime);\n } catch (Exception e2) {\n }\n jedis.connect();\n } catch (JedisConnectionException jce) {\n } // Ignore bad connection attempts\n catch (Exception e3) {\n LOG.error(\"Unknown Exception while trying to reconnect to Redis\", e3);\n }\n } while (++i <= reconAttempts && !testJedisConnection(jedis));\n return testJedisConnection(jedis);\n }", "public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }", "private void onRead0() {\n assert inWire.startUse();\n\n ensureCapacity();\n\n try {\n\n while (!inWire.bytes().isEmpty()) {\n\n try (DocumentContext dc = inWire.readingDocument()) {\n if (!dc.isPresent())\n return;\n\n try {\n if (YamlLogging.showServerReads())\n logYaml(dc);\n onRead(dc, outWire);\n onWrite(outWire);\n } catch (Exception e) {\n Jvm.warn().on(getClass(), \"inWire=\" + inWire.getClass() + \",yaml=\" + Wires.fromSizePrefixedBlobs(dc), e);\n }\n }\n }\n\n } finally {\n assert inWire.endUse();\n }\n }", "@Override\n protected void stopInner() throws VoldemortException {\n List<VoldemortException> exceptions = new ArrayList<VoldemortException>();\n\n logger.info(\"Stopping services:\" + getIdentityNode().getId());\n /* Stop in reverse order */\n exceptions.addAll(stopOnlineServices());\n for(VoldemortService service: Utils.reversed(basicServices)) {\n try {\n service.stop();\n } catch(VoldemortException e) {\n exceptions.add(e);\n logger.error(e);\n }\n }\n logger.info(\"All services stopped for Node:\" + getIdentityNode().getId());\n\n if(exceptions.size() > 0)\n throw exceptions.get(0);\n // release lock of jvm heap\n JNAUtils.tryMunlockall();\n }", "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 }" ]
Checks a returned Javascript value where we expect a boolean but could get null. @param val The value from Javascript to be checked. @param def The default return value, which can be null. @return The actual value, or if null, returns false.
[ "protected Boolean checkBoolean(Object val, Boolean def) {\n return (val == null) ? def : (Boolean) val;\n }" ]
[ "public static void removeZeros( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) {\n ImplCommonOps_DSCC.removeZeros(input,output,tol);\n }", "private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }", "public static RebalanceTaskInfo decodeRebalanceTaskInfoMap(VAdminProto.RebalanceTaskInfoMap rebalanceTaskInfoMap) {\n RebalanceTaskInfo rebalanceTaskInfo = new RebalanceTaskInfo(\n rebalanceTaskInfoMap.getStealerId(),\n rebalanceTaskInfoMap.getDonorId(),\n decodeStoreToPartitionIds(rebalanceTaskInfoMap.getPerStorePartitionIdsList()),\n new ClusterMapper().readCluster(new StringReader(rebalanceTaskInfoMap.getInitialCluster())));\n return rebalanceTaskInfo;\n }", "private double convertToConvention(double value, DataKey key, QuotingConvention toConvention, double toDisplacement,\r\n\t\t\tQuotingConvention fromConvention, double fromDisplacement, AnalyticModel model) {\r\n\r\n\t\tif(toConvention == fromConvention) {\r\n\t\t\tif(toConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\t\treturn value;\r\n\t\t\t} else {\r\n\t\t\t\tif(toDisplacement == fromDisplacement) {\r\n\t\t\t\t\treturn value;\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model),\r\n\t\t\t\t\t\t\tkey, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tSchedule floatSchedule\t= floatMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor);\r\n\t\tSchedule fixSchedule\t= fixMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor);\r\n\r\n\t\tdouble forward = Swap.getForwardSwapRate(fixSchedule, floatSchedule, model.getForwardCurve(forwardCurveName), model);\r\n\t\tdouble optionMaturity = floatSchedule.getFixing(0);\r\n\t\tdouble offset = key.moneyness /10000.0;\r\n\t\tdouble optionStrike = forward + (quotingConvention == QuotingConvention.RECEIVERPRICE ? -offset : offset);\r\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(fixSchedule.getFixing(0), fixSchedule, model.getDiscountCurve(discountCurveName), model);\r\n\r\n\t\tif(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL)) {\r\n\t\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forward + fromDisplacement, value, optionMaturity, optionStrike + fromDisplacement, payoffUnit);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL)) {\r\n\t\t\treturn AnalyticFormulas.bachelierOptionValue(forward, value, optionMaturity, optionStrike, payoffUnit);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.RECEIVERPRICE)) {\r\n\t\t\treturn value + (forward - optionStrike) * payoffUnit;\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {\r\n\t\t\treturn AnalyticFormulas.blackScholesOptionImpliedVolatility(forward + toDisplacement, optionMaturity, optionStrike + toDisplacement, payoffUnit, value);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {\r\n\t\t\treturn AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, value);\r\n\t\t}\r\n\t\telse if(toConvention.equals(QuotingConvention.RECEIVERPRICE) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {\r\n\t\t\treturn value - (forward - optionStrike) * payoffUnit;\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model),\r\n\t\t\t\t\tkey, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model);\r\n\t\t}\r\n\t}", "private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }", "public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }", "public void copyTo(int start, int end, byte[] dest, int destPos) {\n // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object\n arraycopy(start, dest, destPos, end - start);\n }", "public void remove(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n m_container.removeComponent(row);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }", "public void inverse(GVRPose src)\n {\n if (getSkeleton() != src.getSkeleton())\n throw new IllegalArgumentException(\"GVRPose.copy: input pose is incompatible with this pose\");\n src.sync();\n int numbones = getNumBones();\n Bone srcBone = src.mBones[0];\n Bone dstBone = mBones[0];\n\n mNeedSync = true;\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n srcBone.LocalMatrix.set(dstBone.WorldMatrix);\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(0), dstBone.toString());\n\n }\n for (int i = 1; i < numbones; ++i)\n {\n srcBone = src.mBones[i];\n dstBone = mBones[i];\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n dstBone.Changed = WORLD_ROT | WORLD_POS;\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(i), dstBone.toString());\n }\n }\n sync();\n }" ]
Get the GroupDiscussInterface. @return The GroupDiscussInterface
[ "@Override\n public GroupDiscussInterface getDiscussionInterface() {\n if (discussionInterface == null) {\n discussionInterface = new GroupDiscussInterface(apiKey, sharedSecret, transport);\n }\n return discussionInterface;\n }" ]
[ "@Override\n public CopticDate date(int prolepticYear, int month, int dayOfMonth) {\n return CopticDate.of(prolepticYear, month, dayOfMonth);\n }", "public String readSnippet(String name) {\n\n String path = CmsStringUtil.joinPaths(\n m_context.getSetupBean().getWebAppRfsPath(),\n CmsSetupBean.FOLDER_SETUP,\n \"html\",\n name);\n try (InputStream stream = new FileInputStream(path)) {\n byte[] data = CmsFileUtil.readFully(stream, false);\n String result = new String(data, \"UTF-8\");\n return result;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n List<String> storeNames = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET_RO);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(KEY_MAX_VERSION);\n metaKeys.add(KEY_CURRENT_VERSION);\n metaKeys.add(KEY_STORAGE_FORMAT);\n }\n\n doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);\n }", "private static void processTaskFilter(ProjectFile project, Filter filter)\n {\n for (Task task : project.getTasks())\n {\n if (filter.evaluate(task, null))\n {\n System.out.println(task.getID() + \",\" + task.getUniqueID() + \",\" + task.getName());\n }\n }\n }", "public long removeRangeByScore(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByScore(getKey(), scoreRange.from(), scoreRange.to());\n }\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}", "private int countHours(Integer hours)\n {\n int value = hours.intValue();\n int hoursPerDay = 0;\n int hour = 0;\n while (value > 0)\n {\n // Move forward until we find a working hour\n while (hour < 24)\n {\n if ((value & 0x1) != 0)\n {\n ++hoursPerDay;\n }\n value = value >> 1;\n ++hour;\n }\n }\n return hoursPerDay;\n }", "public static void checkMinimumArrayLength(String parameterName,\n int actualLength, int minimumLength) {\n if (actualLength < minimumLength) {\n throw Exceptions\n .IllegalArgument(\n \"Array %s should have at least %d elements, but it only has %d\",\n parameterName, minimumLength, actualLength);\n }\n }", "List<W3CEndpointReference> lookupEndpoints(QName serviceName,\n MatcherDataType matcherData) throws ServiceLocatorFault,\n InterruptedExceptionFault {\n SLPropertiesMatcher matcher = createMatcher(matcherData);\n List<String> names = null;\n List<W3CEndpointReference> result = new ArrayList<W3CEndpointReference>();\n String adress;\n try {\n initLocator();\n if (matcher == null) {\n names = locatorClient.lookup(serviceName);\n } else {\n names = locatorClient.lookup(serviceName, matcher);\n }\n } catch (ServiceLocatorException e) {\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(serviceName.toString()\n + \"throws ServiceLocatorFault\");\n throw new ServiceLocatorFault(e.getMessage(), serviceFaultDetail);\n } catch (InterruptedException e) {\n InterruptionFaultDetail interruptionFaultDetail = new InterruptionFaultDetail();\n interruptionFaultDetail.setInterruptionDetail(serviceName\n .toString() + \"throws InterruptionFault\");\n throw new InterruptedExceptionFault(e.getMessage(),\n interruptionFaultDetail);\n }\n if (names != null && !names.isEmpty()) {\n for (int i = 0; i < names.size(); i++) {\n adress = names.get(i);\n result.add(buildEndpoint(serviceName, adress));\n }\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"lookup Endpoints for \" + serviceName\n + \" failed, service is not known.\");\n }\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(\"lookup Endpoint for \"\n + serviceName + \" failed, service is not known.\");\n throw new ServiceLocatorFault(\"Can not find Endpoint\",\n serviceFaultDetail);\n }\n return result;\n }" ]
Performs a put operation with the specified composite request object @param requestWrapper A composite request object containing the key and value @return Version of the value for the successful put
[ "public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n List<Versioned<V>> versionedValues;\n long startTime = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"PUT requested for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + startTime\n + \" . Nested GET and PUT VERSION requests to follow ---\");\n }\n\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent put might be faster such that all the\n // steps might finish within the allotted time\n requestWrapper.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(requestWrapper);\n Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues);\n\n long endTime = System.currentTimeMillis();\n if(versioned == null)\n versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock());\n else\n versioned.setObject(requestWrapper.getRawValue());\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime);\n if(timeLeft <= 0) {\n throw new StoreTimeoutException(\"PUT request timed out\");\n }\n CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(),\n versioned,\n timeLeft);\n putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs());\n Version result = putVersionedWithCustomTimeout(putVersionedRequestObject);\n long endTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT response received for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + endTimeInMs);\n }\n return result;\n }" ]
[ "public static String[] removeDuplicateStrings(String[] array) {\n if (isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n Collections.addAll(set, array);\n return toStringArray(set);\n }", "private boolean initCheckTypeModifiers() {\n\n Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()));\n if (classInfoclass != null) {\n try {\n Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, \"setFlags\", short.class));\n return setFlags != null;\n } catch (Exception exceptionIgnored) {\n BootstrapLogger.LOG.usingOldJandexVersion();\n return false;\n }\n } else {\n return true;\n }\n }", "protected synchronized PersistenceBroker getBroker() throws PBFactoryException\r\n {\r\n /*\r\n mkalen:\r\n NB! The loadProfileIfNeeded must be called _before_ acquiring a broker below,\r\n since some methods in PersistenceBrokerImpl will keep a local reference to\r\n the descriptor repository that was active during broker construction/refresh\r\n (not checking the repository beeing used on method invocation).\r\n\r\n PersistenceBrokerImpl#getClassDescriptor(Class clazz) is such a method,\r\n that will throw ClassNotPersistenceCapableException on the following scenario:\r\n\r\n (All happens in one thread only):\r\n t0: activate per-thread metadata changes\r\n t1: load, register and activate profile A\r\n t2: load object O1 witch collection proxy C to objects {O2} (C stores profile key K(A))\r\n t3: close broker from t2\r\n t4: load, register and activate profile B\r\n t5: reference O1.getO2Collection, causing C loadData() to be invoked\r\n t6: C calls getBroker\r\n broker B is created and descriptorRepository is set to descriptors from profile B\r\n t7: C calls loadProfileIfNeeded, re-activating profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback (via QueryReferenceBroker) to getClassDescriptor\r\n the local descriptorRepository from t6 is used!\r\n => We will now try to query for {O2} with profile B\r\n (even though we re-activated profile A in t7)\r\n => ClassNotPersistenceCapableException\r\n\r\n Keeping loadProfileIfNeeded() at the start of this method changes everything from t6:\r\n t6: C calls loadProfileIfNeeded, re-activating profile A\r\n t7: C calls getBroker,\r\n broker B is created and descriptorRepository is set to descriptors from profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback to getClassDescriptor,\r\n the local descriptorRepository from t6 is used\r\n => We query for {O2} with profile A\r\n => All good :-)\r\n */\r\n if (_perThreadDescriptorsEnabled)\r\n {\r\n loadProfileIfNeeded();\r\n }\r\n\r\n PersistenceBroker broker;\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found or was closed, create a intern new one\r\n if (broker == null || broker.isClosed())\r\n {\r\n broker = PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n // signal that we use a new internal obtained PB instance to read the\r\n // data and that this instance have to be closed after use\r\n _needsClose = true;\r\n }\r\n return broker;\r\n }", "private static void bodyWithBuilder(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename,\n Predicate<PropertyCodeGenerator> isOptional) {\n Variable result = new Variable(\"result\");\n\n code.add(\" %1$s %2$s = new %1$s(\\\"%3$s{\", StringBuilder.class, result, typename);\n boolean midStringLiteral = true;\n boolean midAppends = true;\n boolean prependCommas = false;\n\n PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values()\n .stream()\n .filter(isOptional)\n .reduce((first, second) -> second)\n .get();\n\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n if (isOptional.test(generator)) {\n if (midStringLiteral) {\n code.add(\"\\\")\");\n }\n if (midAppends) {\n code.add(\";%n \");\n }\n code.add(\"if (\");\n if (generator.initialState() == Initially.OPTIONAL) {\n generator.addToStringCondition(code);\n } else {\n code.add(\"!%s.contains(%s.%s)\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n }\n code.add(\") {%n %s.append(\\\"\", result);\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), property.getField());\n if (!prependCommas) {\n code.add(\".append(\\\", \\\")\");\n }\n code.add(\";%n }%n \");\n if (generator.equals(lastOptionalGenerator)) {\n code.add(\"return %s.append(\\\"\", result);\n midStringLiteral = true;\n midAppends = true;\n } else {\n midStringLiteral = false;\n midAppends = false;\n }\n } else {\n if (!midAppends) {\n code.add(\"%s\", result);\n }\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), (Excerpt) generator::addToStringValue);\n midStringLiteral = false;\n midAppends = true;\n prependCommas = true;\n }\n }\n\n checkState(prependCommas, \"Unexpected state at end of toString method\");\n checkState(midAppends, \"Unexpected state at end of toString method\");\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n code.add(\"}\\\").toString();%n\", result);\n }", "@Deprecated\r\n public Category browse(String catId) throws FlickrException {\r\n List<Subcategory> subcategories = new ArrayList<Subcategory>();\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_BROWSE);\r\n\r\n if (catId != null) {\r\n parameters.put(\"cat_id\", catId);\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 categoryElement = response.getPayload();\r\n\r\n Category category = new Category();\r\n category.setName(categoryElement.getAttribute(\"name\"));\r\n category.setPath(categoryElement.getAttribute(\"path\"));\r\n category.setPathIds(categoryElement.getAttribute(\"pathids\"));\r\n\r\n NodeList subcatNodes = categoryElement.getElementsByTagName(\"subcat\");\r\n for (int i = 0; i < subcatNodes.getLength(); i++) {\r\n Element node = (Element) subcatNodes.item(i);\r\n Subcategory subcategory = new Subcategory();\r\n subcategory.setId(Integer.parseInt(node.getAttribute(\"id\")));\r\n subcategory.setName(node.getAttribute(\"name\"));\r\n subcategory.setCount(Integer.parseInt(node.getAttribute(\"count\")));\r\n\r\n subcategories.add(subcategory);\r\n }\r\n\r\n NodeList groupNodes = categoryElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element node = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(node.getAttribute(\"nsid\"));\r\n group.setName(node.getAttribute(\"name\"));\r\n group.setMembers(node.getAttribute(\"members\"));\r\n\r\n groups.add(group);\r\n }\r\n\r\n category.setGroups(groups);\r\n category.setSubcategories(subcategories);\r\n\r\n return category;\r\n }", "public static ResourceField getMpxjField(int value)\n {\n ResourceField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }", "public void setAngularUpperLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularUpperLimits(getNative(), limitX, limitY, limitZ);\n }", "private float[] generateParticleVelocities()\n {\n float [] particleVelocities = new float[mEmitRate * 3];\n Vector3f temp = new Vector3f(0,0,0);\n for ( int i = 0; i < mEmitRate * 3 ; i +=3 )\n {\n temp.x = mParticlePositions[i];\n temp.y = mParticlePositions[i+1];\n temp.z = mParticlePositions[i+2];\n\n\n float velx = mRandom.nextFloat() * (maxVelocity.x- minVelocity.x)\n + minVelocity.x;\n\n float vely = mRandom.nextFloat() * (maxVelocity.y - minVelocity.y)\n + minVelocity.y;\n float velz = mRandom.nextFloat() * (maxVelocity.z - minVelocity.z)\n + minVelocity.z;\n\n temp = temp.normalize();\n temp.mul(velx, vely, velz, temp);\n\n particleVelocities[i] = temp.x;\n particleVelocities[i+1] = temp.y;\n particleVelocities[i+2] = temp.z;\n }\n\n return particleVelocities;\n\n }", "public void setOffset(float offset, final Axis axis) {\n if (!equal(mOffset.get(axis), offset)) {\n mOffset.set(offset, axis);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }" ]
Increase the priority of an overrideId @param overrideId ID of override @param pathId ID of path containing override @param clientUUID UUID of client
[ "public void increasePriority(int overrideId, int ordinal, int pathId, String clientUUID) {\n logger.info(\"Increase priority\");\n\n int origPriority = -1;\n int newPriority = -1;\n int origId = 0;\n int newId = 0;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n results = null;\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n statement.setInt(1, pathId);\n statement.setString(2, clientUUID);\n results = statement.executeQuery();\n\n int ordinalCount = 0;\n while (results.next()) {\n if (results.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID) == overrideId) {\n ordinalCount++;\n if (ordinalCount == ordinal) {\n origPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n origId = results.getInt(Constants.GENERIC_ID);\n break;\n }\n }\n newPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n newId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // update priorities\n if (origPriority != -1 && newPriority != -1) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, origPriority);\n statement.setInt(2, newId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, newPriority);\n statement.setInt(2, origId);\n statement.executeUpdate();\n }\n } catch (Exception e) {\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
[ "public static long crc32(byte[] bytes, int offset, int size) {\n CRC32 crc = new CRC32();\n crc.update(bytes, offset, size);\n return crc.getValue();\n }", "public void clearResponseSettings(int pathId, String clientUUID) throws Exception {\n logger.info(\"clearing response settings\");\n this.setResponseEnabled(pathId, false, clientUUID);\n OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_RESPONSE);\n EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_RESPONSE, pathId, clientUUID);\n }", "public ItemRequest<Project> findById(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"GET\");\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void enableDeviceNetworkInfoReporting(boolean value){\n enableNetworkInfoReporting = value;\n StorageHelper.putBoolean(context,storageKeyWithSuffix(Constants.NETWORK_INFO),enableNetworkInfoReporting);\n getConfigLogger().verbose(getAccountId(), \"Device Network Information reporting set to \" + enableNetworkInfoReporting);\n }", "public void schedule(BackoffTask task, long initialDelay, long fixedDelay) {\n \tsynchronized (queue) {\n\t \tstart();\n\t queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay));\n \t}\n }", "public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tList<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );\n\t\tfor ( String name : pathWithoutAlias ) {\n\t\t\tsubPath.add( name );\n\t\t\tif ( isAssociation( targetTypeName, subPath ) ) {\n\t\t\t\treturn subPath;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\n }", "public static Set<Annotation> filterInterceptorBindings(BeanManagerImpl beanManager, Collection<Annotation> annotations) {\n Set<Annotation> interceptorBindings = new InterceptorBindingSet(beanManager);\n for (Annotation annotation : annotations) {\n if (beanManager.isInterceptorBinding(annotation.annotationType())) {\n interceptorBindings.add(annotation);\n }\n }\n return interceptorBindings;\n }", "public static double Y0(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n\r\n double ans1 = -2957821389.0 + y * (7062834065.0 + y * (-512359803.6\r\n + y * (10879881.29 + y * (-86327.92757 + y * 228.4622733))));\r\n double ans2 = 40076544269.0 + y * (745249964.8 + y * (7189466.438\r\n + y * (47447.26470 + y * (226.1030244 + y * 1.0))));\r\n\r\n return (ans1 / ans2) + 0.636619772 * J0(x) * Math.log(x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 0.785398164;\r\n\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n + y * (-0.934945152e-7))));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\n }" ]
Return a new client that may be cached or not. Given properties are always use when not cached, and only used at creation time for cached clients. @param name if null, default client. Otherwise, helpful to retrieve cached clients later. @param p a set of properties. Implementation specific. Unknown properties are silently ignored. @param cached if false, the client will not be cached and subsequent calls with the same name will return different objects.
[ "public static JqmClient getClient(String name, Properties p, boolean cached)\n {\n Properties p2 = null;\n if (binder == null)\n {\n bind();\n }\n if (p == null)\n {\n p2 = props;\n }\n else\n {\n p2 = new Properties(props);\n p2.putAll(p);\n }\n return binder.getClientFactory().getClient(name, p2, cached);\n }" ]
[ "public static snmpuser get(nitro_service service, String name) throws Exception{\n\t\tsnmpuser obj = new snmpuser();\n\t\tobj.set_name(name);\n\t\tsnmpuser response = (snmpuser) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static vpnvserver_appcontroller_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_appcontroller_binding obj = new vpnvserver_appcontroller_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_appcontroller_binding response[] = (vpnvserver_appcontroller_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private String getSymbolName(char c)\n {\n String result = null;\n\n switch (c)\n {\n case ',':\n {\n result = \"Comma\";\n break;\n }\n\n case '.':\n {\n result = \"Period\";\n break;\n }\n }\n\n return result;\n }", "public static aaagroup_authorizationpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_authorizationpolicy_binding response[] = (aaagroup_authorizationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void addCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(!dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().add(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.addModulesOrganization(corporateGroupId, dbOrganization);\n }", "public static String stripHtml(String html) {\n\n if (html == null) {\n return null;\n }\n Element el = DOM.createDiv();\n el.setInnerHTML(html);\n return el.getInnerText();\n }", "public static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }", "public String getSQL92LikePattern() throws IllegalArgumentException {\n\t\tif (escape.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> escape char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardSingle.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardSingle char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardMulti.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardMulti char should be of length exactly 1\");\n\t\t}\n\t\treturn LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),\n\t\t\t\tisMatchingCase(), pattern);\n\t}", "public void addControllerType(GVRControllerType controllerType)\n {\n if (cursorControllerTypes == null)\n {\n cursorControllerTypes = new ArrayList<GVRControllerType>();\n }\n else if (cursorControllerTypes.contains(controllerType))\n {\n return;\n }\n cursorControllerTypes.add(controllerType);\n }" ]
Count the statements and property uses of an item or property document. @param usageStatistics statistics object to store counters in @param statementDocument document to count the statements of
[ "protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
[ "public static synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}", "private int bestSurroundingSet(int index, int length, int... valid) {\r\n int option1 = set[index - 1];\r\n if (index + 1 < length) {\r\n // we have two options to check\r\n int option2 = set[index + 1];\r\n if (contains(valid, option1) && contains(valid, option2)) {\r\n return Math.min(option1, option2);\r\n } else if (contains(valid, option1)) {\r\n return option1;\r\n } else if (contains(valid, option2)) {\r\n return option2;\r\n } else {\r\n return valid[0];\r\n }\r\n } else {\r\n // we only have one option to check\r\n if (contains(valid, option1)) {\r\n return option1;\r\n } else {\r\n return valid[0];\r\n }\r\n }\r\n }", "public final URI render(\n final MapfishMapContext mapContext,\n final ScalebarAttributeValues scalebarParams,\n final File tempFolder,\n final Template template)\n throws IOException, ParserConfigurationException {\n final double dpi = mapContext.getDPI();\n\n // get the map bounds\n final Rectangle paintArea = new Rectangle(mapContext.getMapSize());\n MapBounds bounds = mapContext.getBounds();\n\n final DistanceUnit mapUnit = getUnit(bounds);\n final Scale scale = bounds.getScale(paintArea, PDF_DPI);\n final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,\n bounds.getProjection(), dpi, bounds.getCenter());\n\n DistanceUnit scaleUnit = scalebarParams.getUnit();\n if (scaleUnit == null) {\n scaleUnit = mapUnit;\n }\n\n // adjust scalebar width and height to the DPI value\n final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?\n scalebarParams.getSize().width : scalebarParams.getSize().height;\n\n final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)\n * scaleDenominator / scalebarParams.intervals;\n final double niceIntervalLengthInWorldUnits =\n getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);\n\n final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();\n settings.setParams(scalebarParams);\n settings.setMaxSize(scalebarParams.getSize());\n settings.setPadding(getPadding(settings));\n\n // start the rendering\n File path = null;\n if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {\n // render scalebar as SVG\n final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());\n\n try {\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".svg\", tempFolder);\n CreateMapProcessor.saveSvgFile(graphics2D, path);\n } finally {\n graphics2D.dispose();\n }\n } else {\n // render scalebar as raster graphic\n double dpiRatio = mapContext.getDPI() / PDF_DPI;\n final BufferedImage bufferedImage = new BufferedImage(\n (int) Math.round(scalebarParams.getSize().width * dpiRatio),\n (int) Math.round(scalebarParams.getSize().height * dpiRatio),\n TYPE_4BYTE_ABGR);\n final Graphics2D graphics2D = bufferedImage.createGraphics();\n\n try {\n AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());\n graphics2D.scale(dpiRatio, dpiRatio);\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n graphics2D.setTransform(saveAF);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".png\", tempFolder);\n ImageUtils.writeImage(bufferedImage, \"png\", path);\n } finally {\n graphics2D.dispose();\n }\n }\n\n return path.toURI();\n }", "public String addressPath() {\n if (isLeaf) {\n ManagementModelNode parent = (ManagementModelNode)getParent();\n return parent.addressPath();\n }\n\n StringBuilder builder = new StringBuilder();\n for (Object pathElement : getUserObjectPath()) {\n UserObject userObj = (UserObject)pathElement;\n if (userObj.isRoot()) { // don't want to escape root\n builder.append(userObj.getName());\n continue;\n }\n\n builder.append(userObj.getName());\n builder.append(\"=\");\n builder.append(userObj.getEscapedValue());\n builder.append(\"/\");\n }\n\n return builder.toString();\n }", "public static base_response delete(nitro_service client, application resource) throws Exception {\n\t\tapplication deleteresource = new application();\n\t\tdeleteresource.appname = resource.appname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public String getHostName() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostName();\n }\n return ((InetAddress)addr).getHostName();\n }", "public static byte numberOfBytesRequired(long number) {\n if(number < 0)\n number = -number;\n for(byte i = 1; i <= SIZE_OF_LONG; i++)\n if(number < (1L << (8 * i)))\n return i;\n throw new IllegalStateException(\"Should never happen.\");\n }", "public void set(final Argument argument) {\n if (argument != null) {\n map.put(argument.getKey(), Collections.singleton(argument));\n }\n }", "@Override\n public void map(GenericData.Record record,\n AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,\n Reporter reporter) throws IOException {\n\n byte[] keyBytes = null;\n byte[] valBytes = null;\n Object keyRecord = null;\n Object valRecord = null;\n try {\n keyRecord = record.get(keyField);\n valRecord = record.get(valField);\n keyBytes = keySerializer.toBytes(keyRecord);\n valBytes = valueSerializer.toBytes(valRecord);\n\n this.collectorWrapper.setCollector(collector);\n this.mapper.map(keyBytes, valBytes, this.collectorWrapper);\n\n recordCounter++;\n } catch (OutOfMemoryError oom) {\n logger.error(oomErrorMessage(reporter));\n if (keyBytes == null) {\n logger.error(\"keyRecord caused OOM!\");\n } else {\n logger.error(\"keyRecord: \" + keyRecord);\n logger.error(\"valRecord: \" + (valBytes == null ? \"caused OOM\" : valRecord));\n }\n throw new VoldemortException(oomErrorMessage(reporter), oom);\n }\n }" ]
Set the background color of the progress spinner disc. @param colorRes Resource id of the color.
[ "public void setProgressBackgroundColor(int colorRes) {\n mCircleView.setBackgroundColor(colorRes);\n mProgress.setBackgroundColor(getResources().getColor(colorRes));\n }" ]
[ "public void start() {\n instanceLock.writeLock().lock();\n try {\n for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry :\n nsStreamers.entrySet()) {\n streamerEntry.getValue().start();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "public List<String> scan() {\n try {\n JarFile jar = new JarFile(jarURL.getFile());\n try {\n List<String> result = new ArrayList<>();\n Enumeration<JarEntry> en = jar.entries();\n while (en.hasMoreElements()) {\n JarEntry entry = en.nextElement();\n String path = entry.getName();\n boolean match = includes.size() == 0;\n if (!match) {\n for (String pattern : includes) {\n if ( patternMatches(pattern, path)) {\n match = true;\n break;\n }\n }\n }\n if (match) {\n for (String pattern : excludes) {\n if ( patternMatches(pattern, path)) {\n match = false;\n break;\n }\n }\n }\n if (match) {\n result.add(path);\n }\n }\n return result;\n } finally {\n jar.close();\n }\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }", "public void setSpeed(float newValue) {\n if (newValue < 0) newValue = 0;\n this.pitch.setValue( newValue );\n this.speed.setValue( newValue );\n }", "public static Statement open(String jndiPath) {\n try {\n Context ctx = new InitialContext();\n DataSource ds = (DataSource) ctx.lookup(jndiPath);\n Connection conn = ds.getConnection();\n return conn.createStatement();\n } catch (NamingException e) {\n throw new DukeException(\"No database configuration found via JNDI at \" +\n jndiPath, e);\n } catch (SQLException e) {\n throw new DukeException(\"Error connecting to database via \" +\n jndiPath, e);\n }\n }", "public final void notifyContentItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (newContentItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount, itemCount);\n }", "public static dnspolicy_dnspolicylabel_binding[] get(nitro_service service, String name) throws Exception{\n\t\tdnspolicy_dnspolicylabel_binding obj = new dnspolicy_dnspolicylabel_binding();\n\t\tobj.set_name(name);\n\t\tdnspolicy_dnspolicylabel_binding response[] = (dnspolicy_dnspolicylabel_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected StrongCounter getCounterOrCreateIt(String counterName, int initialValue) {\n\t\tCounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager );\n\t\tif ( !counterManager.isDefined( counterName ) ) {\n\t\t\tLOG.tracef( \"Counter %s is not defined, creating it\", counterName );\n\n\t\t\t// global configuration is mandatory in order to define\n\t\t\t// a new clustered counter with persistent storage\n\t\t\tvalidateGlobalConfiguration();\n\n\t\t\tcounterManager.defineCounter( counterName,\n\t\t\t\tCounterConfiguration.builder(\n\t\t\t\t\tCounterType.UNBOUNDED_STRONG )\n\t\t\t\t\t\t.initialValue( initialValue )\n\t\t\t\t\t\t.storage( Storage.PERSISTENT )\n\t\t\t\t\t\t.build() );\n\t\t}\n\n\t\tStrongCounter strongCounter = counterManager.getStrongCounter( counterName );\n\t\treturn strongCounter;\n\t}", "public void setOfflineState(boolean setToOffline) {\n // acquire write lock\n writeLock.lock();\n try {\n String currentState = ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(),\n \"UTF-8\");\n if(setToOffline) {\n // from NORMAL_SERVER to OFFLINE_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.OFFLINE_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, false);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, false);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, false);\n initCache(READONLY_FETCH_ENABLED_KEY);\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n logger.warn(\"Already in OFFLINE_SERVER state.\");\n return;\n } else {\n logger.error(\"Cannot enter OFFLINE_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter OFFLINE_SERVER state from \"\n + currentState);\n }\n } else {\n // from OFFLINE_SERVER to NORMAL_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n logger.warn(\"Already in NORMAL_SERVER state.\");\n return;\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY);\n init();\n initNodeId(getNodeIdNoLock());\n } else {\n logger.error(\"Cannot enter NORMAL_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter NORMAL_SERVER state from \"\n + currentState);\n }\n }\n } finally {\n writeLock.unlock();\n }\n }", "protected void destroyConnection(ConnectionHandle conn) {\r\n\t\tpostDestroyConnection(conn);\r\n\t\tconn.setInReplayMode(true); // we're dead, stop attempting to replay anything\r\n\t\ttry {\r\n\t\t\t\tconn.internalClose();\r\n\t\t} catch (SQLException e) {\r\n\t\t\tlogger.error(\"Error in attempting to close connection\", e);\r\n\t\t}\r\n\t}" ]
Returns the URL of a classpath resource. @param resourceName The name of the resource. @return The URL.
[ "public static URL findConfigResource(String resourceName) {\n if (Strings.isNullOrEmpty(resourceName)) {\n return null;\n }\n\n final URL url = resourceName.startsWith(ROOT) ? DefaultConfiguration.class.getResource(resourceName)\n : DefaultConfiguration.class.getResource(ROOT + resourceName);\n\n if (url != null) {\n return url;\n }\n\n // This is useful to get resource under META-INF directory\n String[] resourceNamePrefix = new String[] {\"META-INF/fabric8/\", \"META-INF/fabric8/\"};\n\n for (String resource : resourceNamePrefix) {\n String fullResourceName = resource + resourceName;\n\n URL candidate = KubernetesResourceLocator.class.getResource(fullResourceName.startsWith(ROOT) ? fullResourceName : ROOT + fullResourceName);\n if (candidate != null) {\n return candidate;\n }\n }\n\n return null;\n }" ]
[ "public static <T> IteratorFromReaderFactory<T> getFactory(String delim, Function<String,T> op) {\r\n return new DelimitRegExIteratorFactory<T>(delim, op);\r\n }", "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }", "public boolean equalId(Element otherElement) {\r\n\t\tif (getElementId() == null || otherElement.getElementId() == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn getElementId().equalsIgnoreCase(otherElement.getElementId());\r\n\t}", "public static auditmessages[] get(nitro_service service) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public void invert(DMatrixRBlock A_inv) {\n int M = Math.min(QR.numRows,QR.numCols);\n if( A_inv.numRows != M || A_inv.numCols != M )\n throw new IllegalArgumentException(\"A_inv must be square an have dimension \"+M);\n\n\n // Solve for A^-1\n // Q*R*A^-1 = I\n\n // Apply householder reflectors to the identity matrix\n // y = Q^T*I = Q^T\n MatrixOps_DDRB.setIdentity(A_inv);\n decomposer.applyQTran(A_inv);\n\n // Solve using upper triangular R matrix\n // R*A^-1 = y\n // A^-1 = R^-1*y\n TriangularSolver_DDRB.solve(QR.blockLength,true,\n new DSubmatrixD1(QR,0,M,0,M),new DSubmatrixD1(A_inv),false);\n }", "public ParallelTaskBuilder setReplaceVarMapToSingleTarget(\n List<StrStrMap> replacementVarMapList, String uniformTargetHost) {\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skil setting.\");\n return this;\n }\n this.replacementVarMapNodeSpecific.clear();\n this.targetHosts.clear();\n int i = 0;\n for (StrStrMap ssm : replacementVarMapList) {\n if (ssm == null)\n continue;\n String hostName = PcConstants.API_PREFIX + i;\n ssm.addPair(PcConstants.UNIFORM_TARGET_HOST_VAR, uniformTargetHost);\n replacementVarMapNodeSpecific.put(hostName, ssm);\n targetHosts.add(hostName);\n ++i;\n }\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\n \"Set requestReplacementType as {} for single target. Will disable the set target hosts.\"\n + \"Also Simulated \"\n + \"Now Already set targetHost list with size {}. \\nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.\",\n requestReplacementType.toString(), targetHosts.size());\n\n return this;\n }", "public BoxFileUploadSessionPartList listParts(int offset, int limit) {\n URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint();\n URLTemplate template = new URLTemplate(listPartsURL.toString());\n\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(OFFSET_QUERY_STRING, offset);\n String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString();\n\n //Template is initalized with the full URL. So empty string for the path.\n URL url = template.buildWithQuery(\"\", queryString);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n return new BoxFileUploadSessionPartList(jsonObject);\n }", "public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }", "public static base_response unset(nitro_service client, nsconfig resource, String[] args) throws Exception{\n\t\tnsconfig unsetresource = new nsconfig();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Calculates the beginLine of a violation report. @param pmdViolation The violation for which the beginLine should be calculated. @return The beginLine is assumed to be the line with the smallest number. However, if the smallest number is out-of-range (non-positive), it takes the other number.
[ "private static int calculateBeginLine(RuleViolation pmdViolation) {\n int minLine = Math.min(pmdViolation.getBeginLine(), pmdViolation.getEndLine());\n return minLine > 0 ? minLine : calculateEndLine(pmdViolation);\n }" ]
[ "public BufferedImage getBufferedImage(int width, int height) {\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, width, height, null);\n g2d.dispose();\n return (buf);\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 }", "@SuppressWarnings({\"deprecation\", \"WeakerAccess\"})\n protected void removeShutdownHook(ClassLoaderLeakPreventor preventor, Thread shutdownHook) {\n final String displayString = \"'\" + shutdownHook + \"' of type \" + shutdownHook.getClass().getName();\n preventor.error(\"Removing shutdown hook: \" + displayString);\n Runtime.getRuntime().removeShutdownHook(shutdownHook);\n\n if(executeShutdownHooks) { // Shutdown hooks should be executed\n \n preventor.info(\"Executing shutdown hook now: \" + displayString);\n // Make sure it's from protected ClassLoader\n shutdownHook.start(); // Run cleanup immediately\n \n if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish\n try {\n shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run\n }\n catch (InterruptedException e) {\n // Do nothing\n }\n if(shutdownHook.isAlive()) {\n preventor.warn(shutdownHook + \"still running after \" + shutdownHookWaitMs + \" ms - Stopping!\");\n shutdownHook.stop();\n }\n }\n }\n }", "protected final boolean isPatternValid() {\n\n switch (getPatternType()) {\n case DAILY:\n return isEveryWorkingDay() || isIntervalValid();\n case WEEKLY:\n return isIntervalValid() && isWeekDaySet();\n case MONTHLY:\n return isIntervalValid() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case YEARLY:\n return isMonthSet() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case INDIVIDUAL:\n case NONE:\n return true;\n default:\n return false;\n }\n }", "protected String getDBManipulationUrl()\r\n {\r\n JdbcConnectionDescriptor jcd = getConnection();\r\n\r\n return jcd.getProtocol()+\":\"+jcd.getSubProtocol()+\":\"+jcd.getDbAlias();\r\n }", "public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public UpdateBuilder<T, ID> updateColumnValue(String columnName, Object value) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetValue(columnName, fieldType, value));\n\t\treturn this;\n\t}", "public static String readTag(Reader r) throws IOException {\r\n if ( ! r.ready()) {\r\n return null;\r\n }\r\n StringBuilder b = new StringBuilder(\"<\");\r\n int c = r.read();\r\n while (c >= 0) {\r\n b.append((char) c);\r\n if (c == '>') {\r\n break;\r\n }\r\n c = r.read();\r\n }\r\n if (b.length() == 1) {\r\n return null;\r\n }\r\n return b.toString();\r\n }", "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }" ]
Clears out the statement handles. @param internalClose if true, close the inner statement handle too.
[ "protected void clearStatementCaches(boolean internalClose) {\r\n\r\n\t\tif (this.statementCachingEnabled){ // safety\r\n\r\n\t\t\tif (internalClose){\r\n\t\t\t\tthis.callableStatementCache.clear();\r\n\t\t\t\tthis.preparedStatementCache.clear();\r\n\t\t\t} else {\r\n\t\t\t\tif (this.pool.closeConnectionWatch){ // debugging enabled?\r\n\t\t\t\t\tthis.callableStatementCache.checkForProperClosure();\r\n\t\t\t\t\tthis.preparedStatementCache.checkForProperClosure();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
[ "public ParallelTaskBuilder prepareTcp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.TCP);\n cb.getTcpMeta().setCommand(command);\n return cb;\n }", "public static final void setPosition(UIObject o, Rect pos) {\n Style style = o.getElement().getStyle();\n style.setPropertyPx(\"left\", pos.x);\n style.setPropertyPx(\"top\", pos.y);\n }", "public static <T> NewManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new NewManagedBean<T>(attributes, clazz, new StringBeanIdentifier(BeanIdentifiers.forNewManagedBean(clazz)), beanManager);\n }", "public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }", "private void injectAdditionalStyles() {\n\n try {\n Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();\n for (String stylesheet : stylesheets) {\n A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }", "public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }", "public synchronized void stop() {\n if (isRunning()) {\n socket.get().close();\n socket.set(null);\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "public static Integer getDurationUnits(RecurringTask recurrence)\n {\n Duration duration = recurrence.getDuration();\n Integer result = null;\n\n if (duration != null)\n {\n result = UNITS_MAP.get(duration.getUnits());\n }\n\n return (result);\n }", "public static base_responses add(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile addresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].apikey = resources[i].apikey;\n\t\t\t\taddresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
if you don't have an argument, choose the value that is going to be inserted into the map instead @param commandLineOption specification of the command line options @param value the value that is going to be inserted into the map instead of the argument
[ "public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }" ]
[ "private void readProjectExtendedAttributes(Project project)\n {\n Project.ExtendedAttributes attributes = project.getExtendedAttributes();\n if (attributes != null)\n {\n for (Project.ExtendedAttributes.ExtendedAttribute ea : attributes.getExtendedAttribute())\n {\n readFieldAlias(ea);\n }\n }\n }", "public static int getXPathLocation(String dom, String xpath) {\n\t\tString dom_lower = dom.toLowerCase();\n\t\tString xpath_lower = xpath.toLowerCase();\n\t\tString[] elements = xpath_lower.split(\"/\");\n\t\tint pos = 0;\n\t\tint temp;\n\t\tint number;\n\t\tfor (String element : elements) {\n\t\t\tif (!element.isEmpty() && !element.startsWith(\"@\") && !element.contains(\"()\")) {\n\t\t\t\tif (element.contains(\"[\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnumber =\n\t\t\t\t\t\t\t\tInteger.parseInt(element.substring(element.indexOf(\"[\") + 1,\n\t\t\t\t\t\t\t\t\t\telement.indexOf(\"]\")));\n\t\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnumber = 1;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < number; i++) {\n\t\t\t\t\t// find new open element\n\t\t\t\t\ttemp = dom_lower.indexOf(\"<\" + stripEndSquareBrackets(element), pos);\n\n\t\t\t\t\tif (temp > -1) {\n\t\t\t\t\t\tpos = temp + 1;\n\n\t\t\t\t\t\t// if depth>1 then goto end of current element\n\t\t\t\t\t\tif (number > 1 && i < number - 1) {\n\t\t\t\t\t\t\tpos =\n\t\t\t\t\t\t\t\t\tgetCloseElementLocation(dom_lower, pos,\n\t\t\t\t\t\t\t\t\t\t\tstripEndSquareBrackets(element));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pos - 1;\n\t}", "public DocumentReaderAndWriter<IN> makeReaderAndWriter() {\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>)\r\n Class.forName(flags.readerAndWriter).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.readerAndWriter: '%s'\", flags.readerAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }", "public 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 static String format(String format) {\n\n if (format == null) {\n format = DEFAULT_FORMAT;\n } else {\n if (format.contains(\"M\")) {\n format = format.replace(\"M\", \"m\");\n }\n\n if (format.contains(\"Y\")) {\n format = format.replace(\"Y\", \"y\");\n }\n\n if (format.contains(\"D\")) {\n format = format.replace(\"D\", \"d\");\n }\n }\n return format;\n }", "public static base_response clear(nitro_service client, Interface resource) throws Exception {\n\t\tInterface clearresource = new Interface();\n\t\tclearresource.id = resource.id;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "private I_CmsSearchIndex getIndex() {\n\n I_CmsSearchIndex index = null;\n // get the configured index or the selected index\n if (isInitialCall()) {\n // the search form is in the initial state\n // get the configured index\n index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName());\n } else {\n // the search form is not in the inital state, the submit button was used already or the\n // search index was changed already\n // get the selected index in the search dialog\n index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter(\"indexName.0\"));\n }\n return index;\n }", "private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }", "public void 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 }" ]
Allows the closure to be called for NullObject @param closure the closure to call on the object @return result of calling the closure
[ "public <T> T with( Closure<T> closure ) {\n return DefaultGroovyMethods.with( null, closure ) ;\n }" ]
[ "public static authenticationvserver_binding get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_binding obj = new authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_binding response = (authenticationvserver_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setHighlightStrength(float _highlightStrength) {\n mHighlightStrength = _highlightStrength;\n for (PieModel model : mPieData) {\n highlightSlice(model);\n }\n invalidateGlobal();\n }", "void setLanguage(final Locale locale) {\n\n if (!m_languageSelect.getValue().equals(locale)) {\n m_languageSelect.setValue(locale);\n }\n }", "public int[] getDefalutValuesArray() {\n int[] defaultValues = new int[5];\n\n defaultValues[0] = GLES20.GL_LINEAR_MIPMAP_NEAREST; // MIN FILTER\n defaultValues[1] = GLES20.GL_LINEAR; // MAG FILTER\n defaultValues[2] = 1; // ANISO FILTER\n defaultValues[3] = GLES20.GL_CLAMP_TO_EDGE; // WRAP S\n defaultValues[4] = GLES20.GL_CLAMP_TO_EDGE; // WRAP T\n\n return defaultValues;\n }", "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "public void startScenario( Class<?> testClass, Method method, List<NamedArgument> arguments ) {\n listener.scenarioStarted( testClass, method, arguments );\n\n if( method.isAnnotationPresent( Pending.class ) ) {\n Pending annotation = method.getAnnotation( Pending.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n } else if( method.isAnnotationPresent( NotImplementedYet.class ) ) {\n NotImplementedYet annotation = method.getAnnotation( NotImplementedYet.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n }\n\n }", "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 boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }", "@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }" ]
Calculates the next snapshot version based on the current release version @param fromVersion The version to bump to next development version @return The next calculated development (snapshot) version
[ "protected String calculateNextVersion(String fromVersion) {\n // first turn it to release version\n fromVersion = calculateReleaseVersion(fromVersion);\n String nextVersion;\n int lastDotIndex = fromVersion.lastIndexOf('.');\n try {\n if (lastDotIndex != -1) {\n // probably a major minor version e.g., 2.1.1\n String minorVersionToken = fromVersion.substring(lastDotIndex + 1);\n String nextMinorVersion;\n int lastDashIndex = minorVersionToken.lastIndexOf('-');\n if (lastDashIndex != -1) {\n // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5)\n String buildNumber = minorVersionToken.substring(lastDashIndex + 1);\n int nextBuildNumber = Integer.parseInt(buildNumber) + 1;\n nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber;\n } else {\n nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + \"\";\n }\n nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion;\n } else {\n // maybe it's just a major version; try to parse as an int\n int nextMajorVersion = Integer.parseInt(fromVersion) + 1;\n nextVersion = nextMajorVersion + \"\";\n }\n } catch (NumberFormatException e) {\n return fromVersion;\n }\n return nextVersion + \"-SNAPSHOT\";\n }" ]
[ "public void addSource(GVRAudioSource audioSource)\n {\n synchronized (mAudioSources)\n {\n if (!mAudioSources.contains(audioSource))\n {\n audioSource.setListener(this);\n mAudioSources.add(audioSource);\n }\n }\n }", "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}", "private int getIndicatorStartPos() {\n switch (getPosition()) {\n case TOP:\n return mIndicatorClipRect.left;\n case RIGHT:\n return mIndicatorClipRect.top;\n case BOTTOM:\n return mIndicatorClipRect.left;\n default:\n return mIndicatorClipRect.top;\n }\n }", "public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }", "protected void populateTasksByStealer(List<StealerBasedRebalanceTask> sbTaskList) {\n // Setup mapping of stealers to work for this run.\n for(StealerBasedRebalanceTask task: sbTaskList) {\n if(task.getStealInfos().size() != 1) {\n throw new VoldemortException(\"StealerBasedRebalanceTasks should have a list of RebalancePartitionsInfo of length 1.\");\n }\n\n RebalanceTaskInfo stealInfo = task.getStealInfos().get(0);\n int stealerId = stealInfo.getStealerId();\n if(!this.tasksByStealer.containsKey(stealerId)) {\n this.tasksByStealer.put(stealerId, new ArrayList<StealerBasedRebalanceTask>());\n }\n this.tasksByStealer.get(stealerId).add(task);\n }\n\n if(tasksByStealer.isEmpty()) {\n return;\n }\n // Shuffle order of each stealer's work list. This randomization\n // helps to get rid of any \"patterns\" in how rebalancing tasks were\n // added to the task list passed in.\n for(List<StealerBasedRebalanceTask> taskList: tasksByStealer.values()) {\n Collections.shuffle(taskList);\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 }", "private void setTableAliasForClassDescriptor(ClassDescriptor aCld, TableAlias anAlias)\r\n {\r\n if (m_cldToAlias.get(aCld) == null)\r\n {\r\n m_cldToAlias.put(aCld, anAlias);\r\n } \r\n }", "public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,\n IllegalAccessException, IllegalArgumentException, InvocationTargetException,\n NoSuchMethodException, SecurityException {\n URLClassLoader sysloader = (URLClassLoader) loader;\n Class<?> sysclass = URLClassLoader.class;\n\n Method method =\n sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});\n method.setAccessible(true);\n method.invoke(sysloader, new Object[] {url});\n\n }", "synchronized void openConnection(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception {\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n channelHandler.executeRequest(new ServerRegisterRequest(), null, callback);\n // HC is the same version, so it will support sending the subject\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IDENTITY, Boolean.TRUE);\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IN_VM, Boolean.TRUE);\n channelHandler.addHandlerFactory(new TransactionalProtocolOperationHandler(controller, channelHandler, responseAttachmentSupport));\n ok = true;\n } finally {\n if(!ok) {\n connection.close();\n }\n }\n }" ]
Checks whether a property can be added to a Properties. @param typeManager @param properties the properties object @param typeId the type id @param filter the property filter @param id the property id @return true if the property should be added
[ "public static boolean checkAddProperty(\r\n CmsCmisTypeManager typeManager,\r\n Properties properties,\r\n String typeId,\r\n Set<String> filter,\r\n String id) {\r\n\r\n if ((properties == null) || (properties.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Properties must not be null!\");\r\n }\r\n\r\n if (id == null) {\r\n throw new IllegalArgumentException(\"Id must not be null!\");\r\n }\r\n\r\n TypeDefinition type = typeManager.getType(typeId);\r\n if (type == null) {\r\n throw new IllegalArgumentException(\"Unknown type: \" + typeId);\r\n }\r\n if (!type.getPropertyDefinitions().containsKey(id)) {\r\n throw new IllegalArgumentException(\"Unknown property: \" + id);\r\n }\r\n\r\n String queryName = type.getPropertyDefinitions().get(id).getQueryName();\r\n\r\n if ((queryName != null) && (filter != null)) {\r\n if (!filter.contains(queryName)) {\r\n return false;\r\n } else {\r\n filter.remove(queryName);\r\n }\r\n }\r\n\r\n return true;\r\n }" ]
[ "public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }", "@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\n }\n }", "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 }", "private Integer getIntegerPropertyOverrideValue(String name, String key) {\n if (properties != null) {\n String propertyName = getPropertyName(name, key);\n\n String propertyOverrideValue = properties.getProperty(propertyName);\n\n if (propertyOverrideValue != null) {\n try {\n return Integer.parseInt(propertyOverrideValue);\n }\n catch (NumberFormatException e) {\n logger.error(\"Could not parse property override key={}, value={}\",\n key, propertyOverrideValue);\n }\n }\n }\n return null;\n }", "public static void isManagementResourceRemoveable(OperationContext context, PathAddress otherManagementEndpoint) throws OperationFailedException {\n ModelNode remotingConnector;\n try {\n remotingConnector = context.readResourceFromRoot(\n PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, \"jmx\"), PathElement.pathElement(\"remoting-connector\", \"jmx\")), false).getModel();\n } catch (Resource.NoSuchResourceException ex) {\n return;\n }\n if (!remotingConnector.hasDefined(USE_MGMT_ENDPOINT) ||\n (remotingConnector.hasDefined(USE_MGMT_ENDPOINT) && context.resolveExpressions(remotingConnector.get(USE_MGMT_ENDPOINT)).asBoolean(true))) {\n try {\n context.readResourceFromRoot(otherManagementEndpoint, false);\n } catch (NoSuchElementException ex) {\n throw RemotingLogger.ROOT_LOGGER.couldNotRemoveResource(context.getCurrentAddress());\n }\n }\n }", "synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }", "public static long wrapped(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n double valA;\n int indexCbase= 0;\n int endOfKLoop = b.numRows*b.numCols;\n\n for( int i = 0; i < a.numRows; i++ ) {\n int indexA = i*a.numCols;\n\n // need to assign dataC to a value initially\n int indexB = 0;\n int indexC = indexCbase;\n int end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) {\n c.set( indexC++ , valA*b.get(indexB++));\n }\n\n // now add to it\n while( indexB != endOfKLoop ) { // k loop\n indexC = indexCbase;\n end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) { // j loop\n c.plus( indexC++ , valA*b.get(indexB++));\n }\n }\n indexCbase += c.numCols;\n }\n\n return System.currentTimeMillis() - timeBefore;\n }", "public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }", "public void notifyHeaderItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \" + toPosition + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition, toPosition);\n }" ]