query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Sets the current reference definition derived from the current member, and optionally some attributes. @param template The template @param attributes The attributes of the tag @exception XDocletException If an error occurs @doc.tag type="block" @doc.param name="attributes" optional="true" description="Attributes of the reference as name-value pairs 'name=value', separated by commas" @doc.param name="auto-delete" optional="true" description="Whether to automatically delete the referenced object on object deletion" @doc.param name="auto-retrieve" optional="true" description="Whether to automatically retrieve the referenced object" @doc.param name="auto-update" optional="true" description="Whether to automatically update the referenced object" @doc.param name="class-ref" optional="true" description="The fully qualified name of the class owning the referenced field" @doc.param name="database-foreignkey" optional="true" description="Whether a database foreignkey shall be created" values="true,false" @doc.param name="documentation" optional="true" description="Documentation on the reference" @doc.param name="foreignkey" optional="true" description="The fields in the current type used for implementing the reference" @doc.param name="otm-dependent" optional="true" description="Whether the reference is dependent on otm" @doc.param name="proxy" optional="true" description="Whether to use a proxy for the reference" @doc.param name="proxy-prefetching-limit" optional="true" description="Specifies the amount of objects to prefetch" @doc.param name="refresh" optional="true" description="Whether to automatically refresh the reference" @doc.param name="remote-foreignkey" optional="true" description="The fields in the referenced type corresponding to the local fields (is only used for the table definition)"
[ "public void processReference(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n ReferenceDescriptorDef refDef = _curClassDef.getReference(name);\r\n String attrName;\r\n\r\n if (refDef == null)\r\n {\r\n refDef = new ReferenceDescriptorDef(name);\r\n _curClassDef.addReference(refDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processReference\", \" Processing reference \"+refDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n refDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n // storing default info for later use\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_A_REFERENCE,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n refDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE, type.getQualifiedName());\r\n\r\n // searching for default type\r\n String typeName = searchForPersistentSubType(type);\r\n\r\n if (typeName != null)\r\n {\r\n refDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CLASS_REF, typeName);\r\n }\r\n\r\n _curReferenceDef = refDef;\r\n generate(template);\r\n _curReferenceDef = null;\r\n }" ]
[ "public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }", "public PagedList<V> convert(final PagedList<U> uList) {\n if (uList == null || uList.isEmpty()) {\n return new PagedList<V>() {\n @Override\n public Page<V> nextPage(String s) throws RestException, IOException {\n return null;\n }\n };\n }\n Page<U> uPage = uList.currentPage();\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return new PagedList<V>(vPage) {\n @Override\n public Page<V> nextPage(String nextPageLink) throws RestException, IOException {\n Page<U> uPage = uList.nextPage(nextPageLink);\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return vPage;\n }\n };\n }", "public static String writeSingleClientConfigAvro(Properties props) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstProp = true;\n for(String key: props.stringPropertyNames()) {\n if(firstProp) {\n firstProp = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n avroConfig = avroConfig + \"\\t\\t\\\"\" + key + \"\\\": \\\"\" + props.getProperty(key) + \"\\\"\";\n }\n if(avroConfig.isEmpty()) {\n return \"{}\";\n } else {\n return \"{\\n\" + avroConfig + \"\\n\\t}\";\n }\n }", "public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }", "public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}", "public ReportWriter getReportWriter(final JasperPrint _jasperPrint, final String _format, final Map<JRExporterParameter,Object> _parameters) {\n final JRExporter exporter = FormatInfoRegistry.getInstance().getExporter(_format);\n exporter.setParameters(_parameters);\n\n if (_jasperPrint.getPages().size() > PAGES_THRESHHOLD) {\n return new FileReportWriter(_jasperPrint, exporter);\n } else {\n return new MemoryReportWriter(_jasperPrint, exporter);\n }\n }", "public Long getOldestTaskCreatedTime(){\n\t Timer.Context ctx = getOldestTaskTimeTimer.time();\n\t try {\n \t long oldest = Long.MAX_VALUE;\n \t \n \t /*\n \t * I am asking this question first, because if I ask it after I could\n \t * miss the oldest time if the oldest is polled and worked on\n \t */\n \t Long oldestQueueTime = this.taskQueue.getOldestQueueTime();\n \t if(oldestQueueTime != null)\n \t oldest = oldestQueueTime;\n \t \n \t //there is a tiny race condition here... but we just want to make our best attempt\n \t long inProgressOldestTime = tasksInProgressTracker.getOldestTime();\n \t \n \t if(inProgressOldestTime < oldest)\n \t oldest = inProgressOldestTime;\n \t \n \t return oldest;\n\t } finally {\n\t ctx.stop();\n\t }\n\t}", "public static Event map(EventType eventType) {\n Event event = new Event();\n event.setEventType(mapEventTypeEnum(eventType.getEventType()));\n Date date = (eventType.getTimestamp() == null)\n ? new Date() : eventType.getTimestamp().toGregorianCalendar().getTime();\n event.setTimestamp(date);\n event.setOriginator(mapOriginatorType(eventType.getOriginator()));\n MessageInfo messageInfo = mapMessageInfo(eventType.getMessageInfo());\n event.setMessageInfo(messageInfo);\n String content = mapContent(eventType.getContent());\n event.setContent(content);\n event.getCustomInfo().clear();\n event.getCustomInfo().putAll(mapCustomInfo(eventType.getCustomInfo()));\n return event;\n }", "public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }" ]
Use this API to add dbdbprofile.
[ "public static base_response add(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile addresource = new dbdbprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.interpretquery = resource.interpretquery;\n\t\taddresource.stickiness = resource.stickiness;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.conmultiplex = resource.conmultiplex;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public void saveAsPropertyBundle() throws UnsupportedEncodingException, CmsException, IOException {\n\n switch (m_bundleType) {\n case XML:\n saveLocalization();\n loadAllRemainingLocalizations();\n createPropertyVfsBundleFiles();\n saveToPropertyVfsBundle();\n m_bundleType = BundleType.PROPERTY;\n removeXmlBundleFile();\n\n break;\n default:\n throw new IllegalArgumentException(\n \"The method should only be called when editing an XMLResourceBundle.\");\n }\n\n }", "private Date getTime(String value) throws MPXJException\n {\n try\n {\n Number hours = m_twoDigitFormat.parse(value.substring(0, 2));\n Number minutes = m_twoDigitFormat.parse(value.substring(2, 4));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n Date result = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n return result;\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse time \" + value, ex);\n }\n }", "public static sslparameter get(nitro_service service) throws Exception{\n\t\tsslparameter obj = new sslparameter();\n\t\tsslparameter[] response = (sslparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }", "public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}", "protected void writeEntries(final StorageAwareResource resource, final ZipOutputStream zipOut) throws IOException {\n final BufferedOutputStream bufferedOutput = new BufferedOutputStream(zipOut);\n ZipEntry _zipEntry = new ZipEntry(\"emf-contents\");\n zipOut.putNextEntry(_zipEntry);\n try {\n this.writeContents(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n ZipEntry _zipEntry_1 = new ZipEntry(\"resource-description\");\n zipOut.putNextEntry(_zipEntry_1);\n try {\n this.writeResourceDescription(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n if (this.storeNodeModel) {\n ZipEntry _zipEntry_2 = new ZipEntry(\"node-model\");\n zipOut.putNextEntry(_zipEntry_2);\n try {\n this.writeNodeModel(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n }\n }", "public static final Bytes of(String s, Charset c) {\n Objects.requireNonNull(s);\n Objects.requireNonNull(c);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(c);\n return new Bytes(data);\n }", "public static authenticationvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_auditnslogpolicy_binding obj = new authenticationvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_auditnslogpolicy_binding response[] = (authenticationvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}" ]
Test the list of TimephasedWork instances to see if any of them have been modified. @param list list of TimephasedWork instances @return boolean flag
[ "public boolean getWorkModified(List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n result = assignment.getModified();\n if (result)\n {\n break;\n }\n }\n return result;\n }" ]
[ "private List<TimephasedWork> splitWork(CostRateTable table, ProjectCalendar calendar, TimephasedWork work, int rateIndex)\n {\n List<TimephasedWork> result = new LinkedList<TimephasedWork>();\n work.setTotalAmount(Duration.getInstance(0, work.getAmountPerDay().getUnits()));\n\n while (true)\n {\n CostRateTableEntry rate = table.get(rateIndex);\n Date splitDate = rate.getEndDate();\n if (splitDate.getTime() >= work.getFinish().getTime())\n {\n result.add(work);\n break;\n }\n\n Date currentPeriodEnd = calendar.getPreviousWorkFinish(splitDate);\n\n TimephasedWork currentPeriod = new TimephasedWork(work);\n currentPeriod.setFinish(currentPeriodEnd);\n result.add(currentPeriod);\n\n Date nextPeriodStart = calendar.getNextWorkStart(splitDate);\n work.setStart(nextPeriodStart);\n\n ++rateIndex;\n }\n\n return result;\n }", "private static QName getServiceName(Server server) {\n QName serviceName;\n String bindingId = getBindingId(server);\n EndpointInfo eInfo = server.getEndpoint().getEndpointInfo();\n \n if (JAXRS_BINDING_ID.equals(bindingId)) {\n serviceName = eInfo.getName();\n } else {\n ServiceInfo serviceInfo = eInfo.getService();\n serviceName = serviceInfo.getName();\n }\n return serviceName;\n }", "public GVRComponent detachComponent(long type) {\n NativeSceneObject.detachComponent(getNative(), type);\n synchronized (mComponents) {\n GVRComponent component = mComponents.remove(type);\n if (component != null) {\n component.setOwnerObject(null);\n }\n return component;\n }\n }", "public String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "public static callhome get(nitro_service service) throws Exception{\n\t\tcallhome obj = new callhome();\n\t\tcallhome[] response = (callhome[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "@Override\n\tpublic Integer getPrefixLengthForSingleBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tInteger divPrefix = div.getPrefixLengthForSingleBlock();\n\t\t\tif(divPrefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\ttotalPrefix += divPrefix;\n\t\t\tif(divPrefix < div.getBitCount()) {\n\t\t\t\t//remaining segments must be full range or we return null\n\t\t\t\tfor(i++; i < count; i++) {\n\t\t\t\t\tAddressDivisionBase laterDiv = getDivision(i);\n\t\t\t\t\tif(!laterDiv.isFullRange()) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cacheBits(totalPrefix);\n\t}", "public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }", "private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {\n\t\tFilter filter = null;\n\t\tif (null != layerFilter) {\n\t\t\tfilter = filterService.parseFilter(layerFilter);\n\t\t}\n\t\tif (null != featureIds) {\n\t\t\tFilter fidFilter = filterService.createFidFilter(featureIds);\n\t\t\tif (null == filter) {\n\t\t\t\tfilter = fidFilter;\n\t\t\t} else {\n\t\t\t\tfilter = filterService.createAndFilter(filter, fidFilter);\n\t\t\t}\n\t\t}\n\t\treturn filter;\n\t}", "@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }" ]
Update the anchor based on arcore best knowledge of the world @param scale
[ "protected void update(float scale) {\n // Updates only when the plane is in the scene\n GVRSceneObject owner = getOwnerObject();\n\n if ((owner != null) && isEnabled() && owner.isEnabled())\n {\n convertFromARtoVRSpace(scale);\n }\n }" ]
[ "@Override\n public void invert( ZMatrixRMaj inv ) {\n if( inv.numRows != n || inv.numCols != n ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n if( inv.data == t ) {\n throw new IllegalArgumentException(\"Passing in the same matrix that was decomposed.\");\n }\n\n if(decomposer.isLower()) {\n setToInverseL(inv.data);\n } else {\n throw new RuntimeException(\"Implement\");\n }\n }", "public static CmsJspResourceWrapper convertResource(CmsObject cms, Object input) throws CmsException {\n\n CmsJspResourceWrapper result;\n if (input instanceof CmsResource) {\n result = CmsJspResourceWrapper.wrap(cms, (CmsResource)input);\n } else {\n result = CmsJspResourceWrapper.wrap(cms, convertRawResource(cms, input));\n }\n return result;\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 }", "public static long raiseToPower(int value, int power)\n {\n if (power < 0)\n {\n throw new IllegalArgumentException(\"This method does not support negative powers.\");\n }\n long result = 1;\n for (int i = 0; i < power; i++)\n {\n result *= value;\n }\n return result;\n }", "public String getHealthMemory() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Logging JVM Stats\\n\");\n MonitorProvider mp = MonitorProvider.getInstance();\n PerformUsage perf = mp.getJVMMemoryUsage();\n sb.append(perf.toString());\n\n if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {\n sb.append(\"========= WARNING: MEM USAGE > \" + THRESHOLD_PERCENT\n + \"!!\");\n sb.append(\" !! Live Threads List=============\\n\");\n sb.append(mp.getThreadUsage().toString());\n sb.append(\"========================================\\n\");\n sb.append(\"========================JVM Thread Dump====================\\n\");\n ThreadInfo[] threadDump = mp.getThreadDump();\n for (ThreadInfo threadInfo : threadDump) {\n sb.append(threadInfo.toString() + \"\\n\");\n }\n sb.append(\"===========================================================\\n\");\n }\n sb.append(\"Logged JVM Stats\\n\");\n\n return sb.toString();\n }", "public static nsconfig get(nitro_service service) throws Exception{\n\t\tnsconfig obj = new nsconfig();\n\t\tnsconfig[] response = (nsconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }", "public String get() {\n\t\tsynchronized (LOCK) {\n\t\t\tif (!initialised) {\n\t\t\t\t// generate the random number\n\t\t\t\tRandom rnd = new Random();\t// @todo need a different seed, this is now time based and I\n\t\t\t\t// would prefer something different, like an object address\n\t\t\t\t// get the random number, instead of getting an integer and converting that to base64 later,\n\t\t\t\t// we get a string and narrow that down to base64, use the top 6 bits of the characters\n\t\t\t\t// as they are more random than the bottom ones...\n\t\t\t\trnd.nextBytes(value);\t\t// get some random characters\n\t\t\t\tvalue[3] = BASE64[((value[3] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[4] = BASE64[((value[4] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[5] = BASE64[((value[5] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[6] = BASE64[((value[6] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[7] = BASE64[((value[7] >> 2) & BITS_6)]; // NOSONAR\n\n\t\t\t\t// complete the time part in the HIGH value of the token\n\t\t\t\t// this also sets the initial low value\n\t\t\t\tcompleteToken(rnd);\n\n\t\t\t\tinitialised = true;\n\t\t\t}\n\n\t\t\t// fill in LOW value in id\n\t\t\tint l = low;\n\t\t\tvalue[0] = BASE64[(l & BITS_6)];\n\t\t\tl >>= SHIFT_6;\n\t\t\tvalue[1] = BASE64[(l & BITS_6)];\n\t\t\tl >>= SHIFT_6;\n\t\t\tvalue[2] = BASE64[(l & BITS_6)];\n\n\t\t\tString res = new String(value);\n\n\t\t\t// increment LOW\n\t\t\tlow++;\n\t\t\tif (low == LOW_MAX) {\n\t\t\t\tlow = 0;\n\t\t\t}\n\t\t\tif (low == lowLast) {\n\t\t\t\ttime = System.currentTimeMillis();\n\t\t\t\tcompleteToken();\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t}", "public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Use this API to fetch aaagroup_aaauser_binding resources of given name .
[ "public static aaagroup_aaauser_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_aaauser_binding obj = new aaagroup_aaauser_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_aaauser_binding response[] = (aaagroup_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "private static JSONArray parseOutgoings(ArrayList<Shape> outgoings) throws JSONException {\n if (outgoings != null) {\n JSONArray outgoingsArray = new JSONArray();\n\n for (Shape outgoing : outgoings) {\n JSONObject outgoingObject = new JSONObject();\n\n outgoingObject.put(\"resourceId\",\n outgoing.getResourceId().toString());\n outgoingsArray.put(outgoingObject);\n }\n\n return outgoingsArray;\n }\n\n return new JSONArray();\n }", "public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}", "synchronized void bulkRegisterSingleton() {\n for (Map.Entry<Class<? extends AppService>, AppService> entry : registry.entrySet()) {\n if (isSingletonService(entry.getKey())) {\n app.registerSingleton(entry.getKey(), entry.getValue());\n }\n }\n }", "public int getPathId(String pathName, int profileId) {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n // first get the pathId for the pathName/profileId\n int pathId = -1;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.PATH_PROFILE_PATHNAME + \"= ? \"\n + \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n queryStatement.setString(1, pathName);\n queryStatement.setInt(2, profileId);\n results = queryStatement.executeQuery();\n if (results.next()) {\n pathId = 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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return pathId;\n }", "public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }", "public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }", "private void writeNewLineIndent() throws IOException\n {\n if (m_pretty)\n {\n if (!m_indent.isEmpty())\n {\n m_writer.write('\\n');\n m_writer.write(m_indent);\n }\n }\n }", "public long number(ImapRequestLineReader request) throws ProtocolException {\n String digits = consumeWord(request, new DigitCharValidator());\n return Long.parseLong(digits);\n }", "public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }" ]
This method returns the existing folder, and if it does not exist, the method generates it. @param path @param dest_dir @return the folder @throws BeastException
[ "public static File createFolder(String path, String dest_dir)\n throws BeastException {\n File f = new File(dest_dir);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n logger.severe(\"Problem creating directory: \" + path\n + File.separator + dest_dir);\n }\n }\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n String message = \"Problem creating directory: \" + path\n + File.separator + dest_dir;\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n\n return f;\n }" ]
[ "private void writeActivity(Task mpxj)\n {\n ActivityType xml = m_factory.createActivityType();\n m_project.getActivity().add(xml);\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setAtCompletionDuration(getDuration(mpxj.getDuration()));\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getCalendar()));\n xml.setDurationPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setDurationType(DURATION_TYPE_MAP.get(mpxj.getType()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(getActivityID(mpxj));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setPercentCompleteType(\"Duration\");\n xml.setPrimaryConstraintType(CONSTRAINT_TYPE_MAP.get(mpxj.getConstraintType()));\n xml.setPrimaryConstraintDate(mpxj.getConstraintDate());\n xml.setPlannedDuration(getDuration(mpxj.getDuration()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRemainingDuration(getDuration(mpxj.getRemainingDuration()));\n xml.setRemainingEarlyFinishDate(mpxj.getEarlyFinish());\n xml.setRemainingEarlyStartDate(mpxj.getResume());\n xml.setRemainingLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setStartDate(mpxj.getStart());\n xml.setStatus(getActivityStatus(mpxj));\n xml.setType(extractAndConvertTaskType(mpxj));\n xml.setWBSObjectId(parentObjectID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.TASK, mpxj));\n\n writePredecessors(mpxj);\n }", "@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 }", "public static java.util.Date getDateTime(Object value) {\n try {\n return toDateTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "public String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\n }", "protected void add(Widget child, Element container) {\n\n // Detach new child.\n child.removeFromParent();\n\n // Logical attach.\n getChildren().add(child);\n\n // Physical attach.\n DOM.appendChild(container, child.getElement());\n\n // Adopt.\n adopt(child);\n }", "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 Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\n }", "public Set<ConstraintViolation> validate(DataSetInfo info) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\ttry {\r\n\t\t\tif (info.isMandatory() && get(info.getDataSetNumber()) == null) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));\r\n\t\t\t}\r\n\t\t\tif (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));\r\n\t\t\t}\r\n\t\t} catch (SerializationException e) {\r\n\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}", "public void process()\n {\n if (m_data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length (repeated twice)\n int length = MPPUtility.getInt(m_data, offset);\n offset += 8;\n // Then the number of custom columns\n int numberOfAliases = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n // Then the aliases themselves\n while (index < numberOfAliases && offset < length)\n {\n // Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the\n // offset to the string (4 bytes)\n\n // Get the Field ID\n int fieldID = MPPUtility.getInt(m_data, offset);\n offset += 4;\n // Get the alias offset (offset + 4 for some reason).\n int aliasOffset = MPPUtility.getInt(m_data, offset) + 4;\n offset += 4;\n // Read the alias itself\n if (aliasOffset < m_data.length)\n {\n String alias = MPPUtility.getUnicodeString(m_data, aliasOffset);\n m_fields.getCustomField(FieldTypeHelper.getInstance(fieldID)).setAlias(alias);\n }\n index++;\n }\n }\n }" ]
Publish the bundle resources directly.
[ "public void publish() {\n\n CmsDirectPublishDialogAction action = new CmsDirectPublishDialogAction();\n List<CmsResource> resources = getBundleResources();\n I_CmsDialogContext context = new A_CmsDialogContext(\"\", ContextType.appToolbar, resources) {\n\n public void focus(CmsUUID structureId) {\n\n //Nothing to do.\n }\n\n public List<CmsUUID> getAllStructureIdsInView() {\n\n return null;\n }\n\n public void updateUserInfo() {\n\n //Nothing to do.\n }\n };\n action.executeAction(context);\n updateLockInformation();\n\n }" ]
[ "public String getKeySchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String keySchema = schema.getField(keyFieldName).schema().toString();\n return keySchema;\n }", "@Override\n\tpublic boolean retainAll(Collection<?> collection) {\n\t\tif (dao == null) {\n\t\t\treturn false;\n\t\t}\n\t\tboolean changed = false;\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tT data = iterator.next();\n\t\t\t\tif (!collection.contains(data)) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn changed;\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "private void initDurationButtonGroup() {\n\n m_groupDuration = new CmsRadioButtonGroup();\n\n m_endsAfterRadioButton = new CmsRadioButton(\n EndType.TIMES.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_0));\n m_endsAfterRadioButton.setGroup(m_groupDuration);\n m_endsAtRadioButton = new CmsRadioButton(\n EndType.DATE.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_DATE_0));\n m_endsAtRadioButton.setGroup(m_groupDuration);\n m_groupDuration.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (null != value) {\n m_controller.setEndType(value);\n }\n }\n }\n });\n\n }", "@Override public Object instantiateItem(ViewGroup parent, int position) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n View view = renderer.getRootView();\n parent.addView(view);\n return view;\n }", "public void logout() {\n String userIdentifier = session.get(config().sessionKeyUsername());\n SessionManager sessionManager = app().sessionManager();\n sessionManager.logout(session);\n if (S.notBlank(userIdentifier)) {\n app().eventBus().trigger(new LogoutEvent(userIdentifier));\n }\n }", "private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }", "public PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }", "public static service_dospolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tservice_dospolicy_binding obj = new service_dospolicy_binding();\n\t\tobj.set_name(name);\n\t\tservice_dospolicy_binding response[] = (service_dospolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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 }" ]
Initialize the container for the current application deployment @param deploymentManager @param deploymentServices
[ "public static void initialize(BeanManagerImpl deploymentManager, ServiceRegistry deploymentServices) {\n Container instance = new Container(RegistrySingletonProvider.STATIC_INSTANCE, deploymentManager, deploymentServices);\n Container.instance.set(RegistrySingletonProvider.STATIC_INSTANCE, instance);\n }" ]
[ "public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n checkSchemeAndPort(scheme, port);\r\n StringBuilder buffer = new StringBuilder();\r\n if (!host.startsWith(scheme + \"://\")) {\r\n buffer.append(scheme).append(\"://\");\r\n }\r\n buffer.append(host);\r\n if (port > 0) {\r\n buffer.append(':');\r\n buffer.append(port);\r\n }\r\n if (path == null) {\r\n path = \"/\";\r\n }\r\n buffer.append(path);\r\n\r\n if (!parameters.isEmpty()) {\r\n buffer.append('?');\r\n }\r\n int size = parameters.size();\r\n for (Map.Entry<String, String> entry : parameters.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append('=');\r\n Object value = entry.getValue();\r\n if (value != null) {\r\n String string = value.toString();\r\n try {\r\n string = URLEncoder.encode(string, UTF8);\r\n } catch (UnsupportedEncodingException e) {\r\n // Should never happen, but just in case\r\n }\r\n buffer.append(string);\r\n }\r\n if (--size != 0) {\r\n buffer.append('&');\r\n }\r\n }\r\n\r\n /*\r\n * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&\r\n * !ignoreMethod(getMethod(parameters))) { buffer.append(\"&api_sig=\"); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }\r\n */\r\n\r\n return new URL(buffer.toString());\r\n }", "public static String insertDumpInformation(String pattern,\n\t\t\tString dateStamp, String project) {\n\t\tif (pattern == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn pattern.replace(\"{DATE}\", dateStamp).replace(\"{PROJECT}\",\n\t\t\t\t\tproject);\n\t\t}\n\t}", "public List<Action> getRootActions() {\n\t\tfinal List<Action> rootActions = srcUpdTrees.stream().map(t -> originalActionsSrc.get(t))\n\t\t\t\t.collect(Collectors.toList());\n\n\t\trootActions.addAll(srcDelTrees.stream() //\n\t\t\t\t.filter(t -> !srcDelTrees.contains(t.getParent()) && !srcUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsSrc.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstAddTrees.stream() //\n\t\t\t\t.filter(t -> !dstAddTrees.contains(t.getParent()) && !dstUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstMvTrees.stream() //\n\t\t\t\t.filter(t -> !dstMvTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.removeAll(Collections.singleton(null));\n\t\treturn rootActions;\n\t}", "SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }", "private void validate() {\n if (Strings.emptyToNull(random) == null) {\n random = Strings.emptyToNull(getProject().getProperty(SYSPROP_RANDOM_SEED())); \n }\n \n if (random == null) {\n throw new BuildException(\"Required attribute 'seed' must not be empty. Look at <junit4:pickseed>.\");\n }\n \n long[] seeds = SeedUtils.parseSeedChain(random);\n if (seeds.length < 1) {\n throw new BuildException(\"Random seed is required.\");\n }\n \n if (values.isEmpty() && !allowUndefined) {\n throw new BuildException(\"No values to pick from and allowUndefined=false.\");\n }\n }", "protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {\n final String parameterString = servletContext.getInitParameter(parameterName);\n if(parameterString != null && parameterString.trim().length() > 0) {\n try {\n return Integer.parseInt(parameterString);\n }\n catch (NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return defaultValue;\n }", "public static base_responses update(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat updateresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new inat();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].privateip = resources[i].privateip;\n\t\t\t\tupdateresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].tftp = resources[i].tftp;\n\t\t\t\tupdateresources[i].usip = resources[i].usip;\n\t\t\t\tupdateresources[i].usnip = resources[i].usnip;\n\t\t\t\tupdateresources[i].proxyip = resources[i].proxyip;\n\t\t\t\tupdateresources[i].mode = resources[i].mode;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException {\n // verify that the resource exist before removing it\n context.readResource(PathAddress.EMPTY_ADDRESS, false);\n Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS);\n recordCapabilitiesAndRequirements(context, operation, resource);\n }", "public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Returns the field definition with the specified name. @param name The name of the desired field @return The field definition or <code>null</code> if there is no such field
[ "public FieldDescriptorDef getField(String name)\r\n {\r\n FieldDescriptorDef fieldDef = null;\r\n\r\n for (Iterator it = _fields.iterator(); it.hasNext(); )\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n if (fieldDef.getName().equals(name))\r\n {\r\n return fieldDef;\r\n }\r\n }\r\n return null;\r\n }" ]
[ "public void deployApplication(String applicationName, URL... urls) throws IOException {\n this.applicationName = applicationName;\n\n for (URL url : urls) {\n try (InputStream inputStream = url.openStream()) {\n deploy(inputStream);\n }\n }\n }", "public static boolean isRegularQueue(final Jedis jedis, final String key) {\n return LIST.equalsIgnoreCase(jedis.type(key));\n }", "public Map<String, Table> process(File directory, String prefix) throws IOException\n {\n String filePrefix = prefix.toUpperCase();\n Map<String, Table> tables = new HashMap<String, Table>();\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n String name = file.getName().toUpperCase();\n if (!name.startsWith(filePrefix))\n {\n continue;\n }\n\n int typeIndex = name.lastIndexOf('.') - 3;\n String type = name.substring(typeIndex, typeIndex + 3);\n TableDefinition definition = TABLE_DEFINITIONS.get(type);\n if (definition != null)\n {\n Table table = new Table();\n TableReader reader = new TableReader(definition);\n reader.read(file, table);\n tables.put(type, table);\n //dumpCSV(type, definition, table);\n }\n }\n }\n return tables;\n }", "public static nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private Map<UUID, List<DateRange>> processDayTypes(List<MapRow> types)\n {\n Map<UUID, List<DateRange>> map = new HashMap<UUID, List<DateRange>>();\n for (MapRow row : types)\n {\n List<DateRange> ranges = new ArrayList<DateRange>();\n for (MapRow range : row.getRows(\"TIME_RANGES\"))\n {\n ranges.add(new DateRange(range.getDate(\"START\"), range.getDate(\"END\")));\n }\n map.put(row.getUUID(\"UUID\"), ranges);\n }\n\n return map;\n }", "public void put(String key, Object object, Envelope envelope) {\n\t\tindex.put(key, envelope);\n\t\tcache.put(key, object);\n\t}", "public Eval<UploadResult> putAsync(String key, Object value) {\n return Eval.later(() -> put(key, value))\n .map(t -> t.orElse(null))\n .map(FluentFunctions.ofChecked(up -> up.waitForUploadResult()));\n\n }", "public void configure(Configuration pConfig) throws ConfigurationException\r\n {\r\n if (pConfig instanceof PBPoolConfiguration)\r\n {\r\n PBPoolConfiguration conf = (PBPoolConfiguration) pConfig;\r\n this.setMaxActive(conf.getMaxActive());\r\n this.setMaxIdle(conf.getMaxIdle());\r\n this.setMaxWait(conf.getMaxWaitMillis());\r\n this.setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis());\r\n this.setTimeBetweenEvictionRunsMillis(conf.getTimeBetweenEvictionRunsMilli());\r\n this.setWhenExhaustedAction(conf.getWhenExhaustedAction());\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass().getName() +\r\n \" cannot read configuration properties, use default.\");\r\n }\r\n }", "public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n float angle = (float) Math.acos(getFloat(\"outer_cone_angle\")) * 2.0f;\n GVRCamera shadowCam = GVRShadowMap.makePerspShadowCamera(getGVRContext().getMainScene().getMainCameraRig().getCenterCamera(), angle);\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n mChanged.set(true);\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }" ]
Remove a descriptor. @param validKey This could be the {@link JdbcConnectionDescriptor} itself, or the associated {@link JdbcConnectionDescriptor#getPBKey PBKey}.
[ "public void removeDescriptor(Object validKey)\r\n {\r\n PBKey pbKey;\r\n if (validKey instanceof PBKey)\r\n {\r\n pbKey = (PBKey) validKey;\r\n }\r\n else if (validKey instanceof JdbcConnectionDescriptor)\r\n {\r\n pbKey = ((JdbcConnectionDescriptor) validKey).getPBKey();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Could not remove descriptor, given object was no vaild key: \" +\r\n validKey);\r\n }\r\n Object removed = null;\r\n synchronized (jcdMap)\r\n {\r\n removed = jcdMap.remove(pbKey);\r\n jcdAliasToPBKeyMap.remove(pbKey.getAlias());\r\n }\r\n log.info(\"Remove descriptor: \" + removed);\r\n }" ]
[ "public Integer getBlockMaskPrefixLength(boolean network) {\n\t\tInteger prefixLen;\n\t\tif(network) {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.networkMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t} else {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.hostMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setHostMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t}\n\t\tif(prefixLen < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn prefixLen;\n\t}", "protected CmsAccessControlEntry getImportAccessControlEntry(\n CmsResource res,\n String id,\n String allowed,\n String denied,\n String flags) {\n\n return new CmsAccessControlEntry(\n res.getResourceId(),\n new CmsUUID(id),\n Integer.parseInt(allowed),\n Integer.parseInt(denied),\n Integer.parseInt(flags));\n }", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }", "public static List<String> getLayersDigests(String manifestContent) throws IOException {\n List<String> dockerLayersDependencies = new ArrayList<String>();\n\n JsonNode manifest = Utils.mapper().readTree(manifestContent);\n JsonNode schemaVersion = manifest.get(\"schemaVersion\");\n if (schemaVersion == null) {\n throw new IllegalStateException(\"Could not find 'schemaVersion' in manifest\");\n }\n\n boolean isSchemeVersion1 = schemaVersion.asInt() == 1;\n JsonNode fsLayers = getFsLayers(manifest, isSchemeVersion1);\n for (JsonNode fsLayer : fsLayers) {\n JsonNode blobSum = getBlobSum(isSchemeVersion1, fsLayer);\n dockerLayersDependencies.add(blobSum.asText());\n }\n dockerLayersDependencies.add(getConfigDigest(manifestContent));\n\n //Add manifest sha1\n String manifestSha1 = Hashing.sha1().hashString(manifestContent, Charsets.UTF_8).toString();\n dockerLayersDependencies.add(\"sha1:\" + manifestSha1);\n\n return dockerLayersDependencies;\n }", "public Bundler put(String key, CharSequence[] value) {\n delegate.putCharSequenceArray(key, value);\n return this;\n }", "public static void writeShortString(ByteBuffer buffer, String s) {\n if (s == null) {\n buffer.putShort((short) -1);\n } else if (s.length() > Short.MAX_VALUE) {\n throw new IllegalArgumentException(\"String exceeds the maximum size of \" + Short.MAX_VALUE + \".\");\n } else {\n byte[] data = getBytes(s); //topic support non-ascii character\n buffer.putShort((short) data.length);\n buffer.put(data);\n }\n }", "public static boolean isListLiteralWithOnlyConstantValues(Expression expression) {\r\n if (expression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) expression).getExpressions();\r\n for (Expression e : expressions) {\r\n if (!isConstantOrConstantLiteral(e)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }", "public PhotoList<Photo> getNotInSet(int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", PhotosInterface.METHOD_GET_NOT_IN_SET);\r\n\r\n RequestContext requestContext = RequestContext.getRequestContext();\r\n\r\n List<String> extras = requestContext.getExtras();\r\n if (extras.size() > 0) {\r\n parameters.put(\"extras\", StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoElements = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "protected void eigenvalue2by2( int x1 ) {\n double a = diag[x1];\n double b = off[x1];\n double c = diag[x1+1];\n\n // normalize to reduce overflow\n double absA = Math.abs(a);\n double absB = Math.abs(b);\n double absC = Math.abs(c);\n\n double scale = absA > absB ? absA : absB;\n if( absC > scale ) scale = absC;\n\n // see if it is a pathological case. the diagonal must already be zero\n // and the eigenvalues are all zero. so just return\n if( scale == 0 ) {\n off[x1] = 0;\n diag[x1] = 0;\n diag[x1+1] = 0;\n return;\n }\n\n a /= scale;\n b /= scale;\n c /= scale;\n\n eigenSmall.symm2x2_fast(a,b,c);\n\n off[x1] = 0;\n diag[x1] = scale*eigenSmall.value0.real;\n diag[x1+1] = scale*eigenSmall.value1.real;\n }" ]
This method extracts data for a single calendar from a Planner file. @param plannerCalendar Calendar data @param parentMpxjCalendar parent of derived calendar
[ "private void readCalendar(net.sf.mpxj.planner.schema.Calendar plannerCalendar, ProjectCalendar parentMpxjCalendar) throws MPXJException\n {\n //\n // Create a calendar instance\n //\n ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();\n\n //\n // Populate basic details\n //\n mpxjCalendar.setUniqueID(getInteger(plannerCalendar.getId()));\n mpxjCalendar.setName(plannerCalendar.getName());\n mpxjCalendar.setParent(parentMpxjCalendar);\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = plannerCalendar.getDefaultWeek();\n setWorkingDay(mpxjCalendar, Day.MONDAY, dw.getMon());\n setWorkingDay(mpxjCalendar, Day.TUESDAY, dw.getTue());\n setWorkingDay(mpxjCalendar, Day.WEDNESDAY, dw.getWed());\n setWorkingDay(mpxjCalendar, Day.THURSDAY, dw.getThu());\n setWorkingDay(mpxjCalendar, Day.FRIDAY, dw.getFri());\n setWorkingDay(mpxjCalendar, Day.SATURDAY, dw.getSat());\n setWorkingDay(mpxjCalendar, Day.SUNDAY, dw.getSun());\n\n //\n // Set working hours\n //\n processWorkingHours(mpxjCalendar, plannerCalendar);\n\n //\n // Process exception days\n //\n processExceptionDays(mpxjCalendar, plannerCalendar);\n\n m_eventManager.fireCalendarReadEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n for (net.sf.mpxj.planner.schema.Calendar cal : calendarList)\n {\n readCalendar(cal, mpxjCalendar);\n }\n }" ]
[ "private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }", "public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }", "public static BuildRetention createBuildRetention(Run build, boolean discardOldArtifacts) {\n BuildRetention buildRetention = new BuildRetention(discardOldArtifacts);\n LogRotator rotator = null;\n BuildDiscarder buildDiscarder = build.getParent().getBuildDiscarder();\n if (buildDiscarder != null && buildDiscarder instanceof LogRotator) {\n rotator = (LogRotator) buildDiscarder;\n }\n if (rotator == null) {\n return buildRetention;\n }\n if (rotator.getNumToKeep() > -1) {\n buildRetention.setCount(rotator.getNumToKeep());\n }\n if (rotator.getDaysToKeep() > -1) {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.DAY_OF_YEAR, -rotator.getDaysToKeep());\n buildRetention.setMinimumBuildDate(new Date(calendar.getTimeInMillis()));\n }\n List<String> notToBeDeleted = ExtractorUtils.getBuildNumbersNotToBeDeleted(build);\n buildRetention.setBuildNumbersNotToBeDiscarded(notToBeDeleted);\n return buildRetention;\n }", "private RecurrenceType getRecurrenceType(int value)\n {\n RecurrenceType result;\n if (value < 0 || value >= RECURRENCE_TYPES.length)\n {\n result = null;\n }\n else\n {\n result = RECURRENCE_TYPES[value];\n }\n\n return result;\n }", "public void bindBundleToSceneObject(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject)\n throws IOException, GVRScriptException\n {\n bindHelper(scriptBundle, rootSceneObject, BIND_MASK_SCENE_OBJECTS);\n }", "private void populateLeaf(String parentName, Row row, Task task)\n {\n if (row.getInteger(\"TASKID\") != null)\n {\n populateTask(row, task);\n }\n else\n {\n populateMilestone(row, task);\n }\n\n String name = task.getName();\n if (name == null || name.isEmpty())\n {\n task.setName(parentName);\n }\n }", "public DiscreteInterval plus(DiscreteInterval other) {\n return new DiscreteInterval(this.min + other.min, this.max + other.max);\n }", "public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }", "public static final void setBounds(UIObject o, Rect bounds) {\n setPosition(o, bounds);\n setSize(o, bounds);\n }" ]
Gets the global and adds it ot the BatchExecutionresults using the alternative outIdentifier. @param identifier The identifier of the global @param outIdentifier The identifier used in the ExecutionResults to store the global. @return
[ "public static Command newGetGlobal(String identifier,\n String outIdentifier) {\n return getCommandFactoryProvider().newGetGlobal( identifier,\n outIdentifier );\n }" ]
[ "public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }", "public void setAll() {\n\tshowAttributes = true;\n\tshowEnumerations = true;\n\tshowEnumConstants = true;\n\tshowOperations = true;\n\tshowConstructors = true;\n\tshowVisibility = true;\n\tshowType = true;\n }", "static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}", "public static Deployment of(final URL url) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"url\", url));\n return new Deployment(deploymentContent, null);\n }", "public static sslcertkey_crldistribution_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public ItemRequest<Tag> delete(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"DELETE\");\n }", "private HiveShellContainer createHiveServerContainer(final List<? extends Script> scripts, final Object testCase, TemporaryFolder baseDir) \n throws IOException {\n\n HiveServerContext context = new StandaloneHiveServerContext(baseDir, config);\n\n final HiveServerContainer hiveTestHarness = new HiveServerContainer(context);\n\n HiveShellBuilder hiveShellBuilder = new HiveShellBuilder();\n hiveShellBuilder.setCommandShellEmulation(config.getCommandShellEmulator());\n\n HiveShellField shellSetter = loadScriptUnderTest(testCase, hiveShellBuilder);\n if (scripts != null) {\n hiveShellBuilder.overrideScriptsUnderTest(scripts);\n }\n\n hiveShellBuilder.setHiveServerContainer(hiveTestHarness);\n\n loadAnnotatedResources(testCase, hiveShellBuilder);\n\n loadAnnotatedProperties(testCase, hiveShellBuilder);\n\n loadAnnotatedSetupScripts(testCase, hiveShellBuilder);\n\n // Build shell\n final HiveShellContainer shell = hiveShellBuilder.buildShell();\n\n // Set shell\n shellSetter.setShell(shell);\n\n if (shellSetter.isAutoStart()) {\n shell.start();\n }\n\n return shell;\n }", "public static ipset[] get(nitro_service service) throws Exception{\n\t\tipset obj = new ipset();\n\t\tipset[] response = (ipset[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public boolean classifySentenceStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n while ((line = is.readLine()) != null) {\r\n \t\r\n if (line.trim().equals(\"\")) {\r\n \t text += sentence + eol;\r\n \t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n classifyAndWriteAnswers(documents, readerWriter);\r\n text = \"\";\r\n } else {\r\n \t text += line + eol;\r\n }\r\n }\r\n if (text.trim().equals(\"\")) {\r\n \treturn false;\r\n }\r\n return true;\r\n }" ]
Get a writer implementation to push data into Canvas. @param type Interface type you wish to get an implementation for @param oauthToken An OAuth token to use for authentication when making API calls @param <T> A writer implementation @return A writer implementation class
[ "public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken) {\n return getWriter(type, oauthToken, false);\n }" ]
[ "private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\n }\n }", "public boolean hasUppercaseVariations(int base, boolean lowerOnly) {\n\t\tif(base > 10) {\n\t\t\tint count = getSegmentCount();\n\t\t\tfor(int i = 0; i < count; i++) {\n\t\t\t\tIPv6AddressSegment seg = getSegment(i);\n\t\t\t\tif(seg.hasUppercaseVariations(base, lowerOnly)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\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 }", "public static base_response add(nitro_service client, inat resource) throws Exception {\n\t\tinat addresource = new inat();\n\t\taddresource.name = resource.name;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.privateip = resource.privateip;\n\t\taddresource.tcpproxy = resource.tcpproxy;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.tftp = resource.tftp;\n\t\taddresource.usip = resource.usip;\n\t\taddresource.usnip = resource.usnip;\n\t\taddresource.proxyip = resource.proxyip;\n\t\taddresource.mode = resource.mode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public static aaaparameter get(nitro_service service) throws Exception{\n\t\taaaparameter obj = new aaaparameter();\n\t\taaaparameter[] response = (aaaparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public Map<DeckReference, TrackMetadata> getLoadedTracks() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, TrackMetadata>(hotCache));\n }", "public Stats getPhotoStats(String photoId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTO_STATS, \"photo_id\", photoId, date);\n }", "private void addDirectSubTypes(XClass type, ArrayList subTypes)\r\n {\r\n if (type.isInterface())\r\n {\r\n if (type.getExtendingInterfaces() != null)\r\n {\r\n subTypes.addAll(type.getExtendingInterfaces());\r\n }\r\n // we have to traverse the implementing classes as these array contains all classes that\r\n // implement the interface, not only those who have an \"implement\" declaration\r\n // note that for whatever reason the declared interfaces are not exported via the XClass interface\r\n // so we have to get them via the underlying class which is hopefully a subclass of AbstractClass\r\n if (type.getImplementingClasses() != null)\r\n {\r\n Collection declaredInterfaces = null;\r\n XClass subType;\r\n\r\n for (Iterator it = type.getImplementingClasses().iterator(); it.hasNext(); )\r\n {\r\n subType = (XClass)it.next();\r\n if (subType instanceof AbstractClass)\r\n {\r\n declaredInterfaces = ((AbstractClass)subType).getDeclaredInterfaces();\r\n if ((declaredInterfaces != null) && declaredInterfaces.contains(type))\r\n {\r\n subTypes.add(subType);\r\n }\r\n }\r\n else\r\n {\r\n // Otherwise we have to live with the bug\r\n subTypes.add(subType);\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n subTypes.addAll(type.getDirectSubclasses());\r\n }\r\n }" ]
Injects bound fields @param instance The instance to inject into
[ "public static <T> void injectBoundFields(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends FieldInjectionPoint<?, ?>> injectableFields) {\n for (FieldInjectionPoint<?, ?> injectableField : injectableFields) {\n injectableField.inject(instance, manager, creationalContext);\n }\n }" ]
[ "public T removeBundle(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createBundleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }", "@Pure\n\tpublic static <T> List<T> reverseView(List<T> list) {\n\t\treturn Lists.reverse(list);\n\t}", "public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void splitSpan(int n) {\n\t\tint x = (xKnots[n] + xKnots[n+1])/2;\n\t\taddKnot(x, getColor(x/256.0f), knotTypes[n]);\n\t\trebuildGradient();\n\t}", "public Tree determineHead(Tree t, Tree parent) {\r\n if (nonTerminalInfo == null) {\r\n throw new RuntimeException(\"Classes derived from AbstractCollinsHeadFinder must\" + \" create and fill HashMap nonTerminalInfo.\");\r\n }\r\n if (t == null || t.isLeaf()) {\r\n return null;\r\n }\r\n if (DEBUG) {\r\n System.err.println(\"determineHead for \" + t.value());\r\n }\r\n \r\n Tree[] kids = t.children();\r\n\r\n Tree theHead;\r\n // first check if subclass found explicitly marked head\r\n if ((theHead = findMarkedHead(t)) != null) {\r\n if (DEBUG) {\r\n System.err.println(\"Find marked head method returned \" +\r\n theHead.label() + \" as head of \" + t.label());\r\n }\r\n return theHead;\r\n }\r\n\r\n // if the node is a unary, then that kid must be the head\r\n // it used to special case preterminal and ROOT/TOP case\r\n // but that seemed bad (especially hardcoding string \"ROOT\")\r\n if (kids.length == 1) {\r\n if (DEBUG) {\r\n System.err.println(\"Only one child determines \" +\r\n kids[0].label() + \" as head of \" + t.label());\r\n }\r\n return kids[0];\r\n }\r\n\r\n return determineNonTrivialHead(t, parent);\r\n }", "private void readNetscapeExt() {\n do {\n readBlock();\n if (block[0] == 1) {\n // Loop count sub-block.\n int b1 = ((int) block[1]) & 0xff;\n int b2 = ((int) block[2]) & 0xff;\n header.loopCount = (b2 << 8) | b1;\n if(header.loopCount == 0) {\n header.loopCount = GifDecoder.LOOP_FOREVER;\n }\n }\n } while ((blockSize > 0) && !err());\n }", "public static final Double parseCurrency(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() / 100));\n }", "public static tunnelip_stats[] get(nitro_service service) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\ttunnelip_stats[] response = (tunnelip_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public ClassNode annotatedWith(String name) {\n ClassNode anno = infoBase.node(name);\n this.annotations.add(anno);\n anno.annotated.add(this);\n return this;\n }" ]
Calculate start dates for a daily recurrence. @param calendar current date @param frequency frequency @param dates array of start dates
[ "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 }" ]
[ "boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));\n }", "public void add(StatementRank rank, Resource subject) {\n\t\tif (this.bestRank == rank) {\n\t\t\tsubjects.add(subject);\n\t\t} else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) {\n\t\t\t//We found a preferred statement\n\t\t\tsubjects.clear();\n\t\t\tbestRank = StatementRank.PREFERRED;\n\t\t\tsubjects.add(subject);\n\t\t}\n\t}", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "public static void main(String[] args) throws LoginFailedException,\n\t\t\tIOException, MediaWikiApiErrorException {\n\t\tExampleHelpers.configureLogging();\n\t\tprintDocumentation();\n\n\t\tSetLabelsForNumbersBot bot = new SetLabelsForNumbersBot();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(bot);\n\t\tbot.finish();\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}", "public static void compress(File dir, File zipFile) throws IOException {\n\n FileOutputStream fos = new FileOutputStream(zipFile);\n ZipOutputStream zos = new ZipOutputStream(fos);\n\n recursiveAddZip(dir, zos, dir);\n\n zos.finish();\n zos.close();\n\n }", "protected I_CmsSearchConfigurationFacetField parseFieldFacet(JSONObject fieldFacetObject) {\n\n try {\n String field = fieldFacetObject.getString(JSON_KEY_FACET_FIELD);\n String name = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_MINCOUNT);\n Integer limit = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_LIMIT);\n String prefix = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_PREFIX);\n String sorder = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (Exception e) {\n order = null;\n }\n String filterQueryModifier = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_FILTERQUERYMODIFIER);\n Boolean isAndFacet = parseOptionalBooleanValue(fieldFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(fieldFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreFilterAllFacetFilters = parseOptionalBooleanValue(\n fieldFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreFilterAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1, JSON_KEY_FACET_FIELD),\n e);\n return null;\n }\n }", "private boolean setNextIterator()\r\n {\r\n boolean retval = false;\r\n // first, check if the activeIterator is null, and set it.\r\n if (m_activeIterator == null)\r\n {\r\n if (m_rsIterators.size() > 0)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n }\r\n }\r\n else if (!m_activeIterator.hasNext())\r\n {\r\n if (m_rsIterators.size() > (m_activeIteratorIndex + 1))\r\n {\r\n // we still have iterators in the collection, move to the\r\n // next one, increment the counter, and set the active\r\n // iterator.\r\n m_activeIteratorIndex++;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n retval = true;\r\n }\r\n }\r\n\r\n return retval;\r\n }", "private ProjectFile readFile(File file) throws MPXJException\n {\n try\n {\n String url = \"jdbc:sqlite:\" + file.getAbsolutePath();\n Properties props = new Properties();\n m_connection = org.sqlite.JDBC.createConnection(url, props);\n\n m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n m_dayTimeIntervals = xpath.compile(\"/array/dayTimeInterval\");\n m_entityMap = new HashMap<String, Integer>();\n return read();\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT, ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n\n m_documentBuilder = null;\n m_dayTimeIntervals = null;\n m_entityMap = null;\n }\n }", "private void enforceSrid(Object feature) throws LayerException {\n\t\tGeometry geom = getFeatureModel().getGeometry(feature);\n\t\tif (null != geom) {\n\t\t\tgeom.setSRID(srid);\n\t\t\tgetFeatureModel().setGeometry(feature, geom);\n\t\t}\n\t}" ]
Returns the bit at the specified index. @param index The index of the bit to look-up (0 is the least-significant bit). @return A boolean indicating whether the bit is set or not. @throws IndexOutOfBoundsException If the specified index is not a bit position in this bit string.
[ "public boolean getBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n return (data[word] & (1 << offset)) != 0;\n }" ]
[ "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }", "public Conditionals ifModifiedSince(LocalDateTime time) {\n Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));\n Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE));\n time = time.withNano(0);\n return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty());\n }", "protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "private void updateDates(Task parentTask)\n {\n if (parentTask.hasChildTasks())\n {\n Date plannedStartDate = null;\n Date plannedFinishDate = null;\n\n for (Task task : parentTask.getChildTasks())\n {\n updateDates(task);\n plannedStartDate = DateHelper.min(plannedStartDate, task.getStart());\n plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish());\n }\n\n parentTask.setStart(plannedStartDate);\n parentTask.setFinish(plannedFinishDate);\n }\n }", "@Nullable\n public static LocationEngineResult extractResult(Intent intent) {\n LocationEngineResult result = null;\n if (isOnClasspath(GOOGLE_PLAY_LOCATION_RESULT)) {\n result = extractGooglePlayResult(intent);\n }\n return result == null ? extractAndroidResult(intent) : result;\n }", "@Override\n\tpublic void set(String headerName, String headerValue) {\n\t\tList<String> headerValues = new LinkedList<String>();\n\t\theaderValues.add(headerValue);\n\t\theaders.put(headerName, headerValues);\n\t}", "public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding)\n throws JMException, UnsupportedEncodingException {\n return new WebMBeanAdapter(mBeanServer, mBeanName, encoding);\n }", "protected String classOf(List<IN> lineInfos, int pos) {\r\n Datum<String, String> d = makeDatum(lineInfos, pos, featureFactory);\r\n return classifier.classOf(d);\r\n }", "public static final String printDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }" ]
Returns the compact task records for all tasks with the given tag. Tasks can have more than one tag at a time. @param tag The tag to fetch tasks from. @return Request object
[ "public CollectionRequest<Task> getTasksWithTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }" ]
[ "public void beforeCompletion()\r\n {\r\n // avoid redundant calls\r\n if(beforeCompletionCall) return;\r\n\r\n log.info(\"Method beforeCompletion was called\");\r\n int status = Status.STATUS_UNKNOWN;\r\n try\r\n {\r\n JTATxManager mgr = (JTATxManager) getImplementation().getTxManager();\r\n status = mgr.getJTATransaction().getStatus();\r\n // ensure proper work, check all possible status\r\n // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary\r\n if(status == Status.STATUS_MARKED_ROLLBACK\r\n || status == Status.STATUS_ROLLEDBACK\r\n || status == Status.STATUS_ROLLING_BACK\r\n || status == Status.STATUS_UNKNOWN\r\n || status == Status.STATUS_NO_TRANSACTION)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Can't prepare for commit, because tx status was \"\r\n + TxUtil.getStatusString(status) + \". Do internal cleanup only.\");\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Synchronization#beforeCompletion: Prepare for commit\");\r\n }\r\n // write objects to database\r\n prepareCommit();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Error while prepare for commit\", e);\r\n if(e instanceof LockNotGrantedException)\r\n {\r\n throw (LockNotGrantedException) e;\r\n }\r\n else if(e instanceof TransactionAbortedException)\r\n {\r\n throw (TransactionAbortedException) e;\r\n }\r\n else if(e instanceof ODMGRuntimeException)\r\n {\r\n throw (ODMGRuntimeException) e;\r\n }\r\n else\r\n { \r\n throw new ODMGRuntimeException(\"Method beforeCompletion() fails, status of JTA-tx was \"\r\n + TxUtil.getStatusString(status) + \", message: \" + e.getMessage());\r\n }\r\n\r\n }\r\n finally\r\n {\r\n beforeCompletionCall = true;\r\n setInExternTransaction(false);\r\n internalCleanup();\r\n }\r\n }", "public final void save(final PrintJobStatusExtImpl entry) {\n getSession().merge(entry);\n getSession().flush();\n getSession().evict(entry);\n }", "public static double huntKennedyCMSAdjustedRate(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tdouble a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble rateUnadjusted\t= forwardSwaprate;\n\t\tdouble rateAdjusted\t\t= forwardSwaprate * convexityAdjustment;\n\n\t\treturn (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;\n\t}", "@PostConstruct\n\tprotected void checkPluginDependencies() throws GeomajasException {\n\t\tif (\"true\".equals(System.getProperty(\"skipPluginDependencyCheck\"))) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\n\t\t// start by going through all plug-ins to build a map of versions for plug-in keys\n\t\t// includes verification that each key is only used once\n\t\tMap<String, String> versions = new HashMap<String, String>();\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tString version = plugin.getVersion().getVersion();\n\t\t\t// check for multiple plugin with same name but different versions (duplicates allowed for jar+source dep)\n\t\t\tif (null != version) {\n\t\t\t\tString otherVersion = versions.get(name);\n\t\t\t\tif (null != otherVersion) {\n\t\t\t\t\tif (!version.startsWith(EXPR_START)) {\n\t\t\t\t\t\tif (!otherVersion.startsWith(EXPR_START) && !otherVersion.equals(version)) {\n\t\t\t\t\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_INVALID_DUPLICATE,\n\t\t\t\t\t\t\t\t\tname, version, versions.get(name));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tversions.put(name, version);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tversions.put(name, version);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check dependencies\n\t\tStringBuilder message = new StringBuilder();\n\t\tString backendVersion = versions.get(\"Geomajas\");\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tString name = plugin.getVersion().getName();\n\t\t\tmessage.append(checkVersion(name, \"Geomajas back-end\", plugin.getBackendVersion(), backendVersion));\n\t\t\tList<PluginVersionInfo> dependencies = plugin.getDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : plugin.getDependencies()) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t}\n\t\t\t}\n\t\t\tdependencies = plugin.getOptionalDependencies();\n\t\t\tif (null != dependencies) {\n\t\t\t\tfor (PluginVersionInfo dependency : dependencies) {\n\t\t\t\t\tString depName = dependency.getName();\n\t\t\t\t\tString availableVersion = versions.get(depName);\n\t\t\t\t\tif (null != availableVersion) {\n\t\t\t\t\t\tmessage.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (message.length() > 0) {\n\t\t\tthrow new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_FAILED, message.toString());\n\t\t}\n\n\t\trecorder.record(GROUP, VALUE);\n\t}", "public AsciiTable setTextAlignment(TextAlignment textAlignment){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static float noise1(float x) {\n int bx0, bx1;\n float rx0, rx1, sx, t, u, v;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n sx = sCurve(rx0);\n\n u = rx0 * g1[p[bx0]];\n v = rx1 * g1[p[bx1]];\n return 2.3f*lerp(sx, u, v);\n }", "protected void recordContentLoader(final String patchID, final PatchContentLoader contentLoader) {\n if (contentLoaders.containsKey(patchID)) {\n throw new IllegalStateException(\"Content loader already registered for patch \" + patchID); // internal wrong usage, no i18n\n }\n contentLoaders.put(patchID, contentLoader);\n }", "public static long getVisibilityCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\n \"Cache size must be positive for \" + VISIBILITY_CACHE_WEIGHT);\n }\n return size;\n }", "private void add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }" ]
Specify additional query parameters to be passed to the filter function. @param queryParams map of key-value parameters @return this Replication instance to set more options or trigger the replication
[ "public Replication queryParams(Map<String, Object> queryParams) {\r\n this.replication = replication.queryParams(queryParams);\r\n return this;\r\n }" ]
[ "public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)\n\tthrows CertificateEncodingException,\n\tInvalidKeyException,\n\tCertificateException,\n\tCertificateNotYetValidException,\n\tNoSuchAlgorithmException,\n\tNoSuchProviderException,\n\tSignatureException,\n\tKeyStoreException,\n\tUnrecoverableKeyException\n\t{\n\n\t\tString thumbprint = ThumbprintUtil.getThumbprint(cert);\n\n\t\tString mappedCertThumbprint = _certMap.get(thumbprint);\n\n\t\tif(mappedCertThumbprint == null)\n\t\t{\n\n\t\t\t// Check if we've already mapped this public key from a KeyValue\n\t\t\tPublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());\n\t\t\tPrivateKey privKey;\n\n\t\t\tif(mappedPk == null)\n\t\t\t{\n\t\t\t\tPublicKey pk = cert.getPublicKey();\n\n\t\t\t\tString algo = pk.getAlgorithm();\n\n\t\t\t\tKeyPair kp;\n\n\t\t\t\tif(algo.equals(\"RSA\")) {\n\t\t\t\t\tkp = getRSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse if(algo.equals(\"DSA\")) {\n\t\t\t\t\tkp = getDSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthrow new InvalidKeyException(\"Key algorithm \" + algo + \" not supported.\");\n\t\t\t\t}\n\t\t\t\tmappedPk = kp.getPublic();\n\t\t\t\tprivKey = kp.getPrivate();\n\n\t\t\t\tmapPublicKeys(cert.getPublicKey(), mappedPk);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprivKey = getPrivateKey(mappedPk);\n\t\t\t}\n\n\n\t\t\tX509Certificate replacementCert =\n\t\t\t\tCertificateCreator.mitmDuplicateCertificate(\n\t\t\t\t\t\tcert,\n\t\t\t\t\t\tmappedPk,\n\t\t\t\t\t\tgetSigningCert(),\n\t\t\t\t\t\tgetSigningPrivateKey());\n\n\t\t\taddCertAndPrivateKey(null, replacementCert, privKey);\n\n\t\t\tmappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);\n\n\t\t\t_certMap.put(thumbprint, mappedCertThumbprint);\n\t\t\t_certMap.put(mappedCertThumbprint, thumbprint);\n\t\t\t_subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\t\t\treturn replacementCert;\n\t\t}\n return getCertificateByAlias(mappedCertThumbprint);\n\n\t}", "public UUID getUUID(FastTrackField type)\n {\n String value = getString(type);\n UUID result = null;\n if (value != null && !value.isEmpty() && value.length() >= 36)\n {\n if (value.startsWith(\"{\"))\n {\n value = value.substring(1, value.length() - 1);\n }\n if (value.length() > 16)\n {\n value = value.substring(0, 36);\n }\n result = UUID.fromString(value);\n }\n return result;\n }", "public static void pow(ComplexPolar_F64 a , int N , ComplexPolar_F64 result )\n {\n result.r = Math.pow(a.r,N);\n result.theta = N*a.theta;\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> TypeConverter<E> typeConverterFor(Class<E> cls) throws NoSuchTypeConverterException {\n TypeConverter<E> typeConverter = TYPE_CONVERTERS.get(cls);\n if (typeConverter == null) {\n throw new NoSuchTypeConverterException(cls);\n }\n return typeConverter;\n }", "public User findByEmail(String email) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_FIND_BY_EMAIL);\r\n\r\n parameters.put(\"find_email\", email);\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 userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n user.setUsername(XMLUtilities.getChildValue(userElement, \"username\"));\r\n return user;\r\n }", "public WindupConfiguration setOptionValue(String name, Object value)\n {\n configurationOptions.put(name, value);\n return this;\n }", "protected boolean cannotInstantiate(Class<?> actionClass) {\n\t\treturn actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum()\n\t\t\t\t|| (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass();\n\t}", "private long getWeightedMatchScore(Iterable<String> requestUriParts, Iterable<String> destUriParts) {\n // The score calculated below is a base 5 number\n // The score will have one digit for one part of the URI\n // This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13\n // We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during\n // score calculation\n long score = 0;\n for (Iterator<String> rit = requestUriParts.iterator(), dit = destUriParts.iterator();\n rit.hasNext() && dit.hasNext(); ) {\n String requestPart = rit.next();\n String destPart = dit.next();\n if (requestPart.equals(destPart)) {\n score = (score * 5) + 4;\n } else if (PatternPathRouterWithGroups.GROUP_PATTERN.matcher(destPart).matches()) {\n score = (score * 5) + 3;\n } else {\n score = (score * 5) + 2;\n }\n }\n return score;\n }", "public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}" ]
Checks the orderby attribute. @param collDef The collection descriptor @param checkLevel The current check level (this constraint is checked in basic and strict) @exception ConstraintException If the value for orderby is invalid (unknown field or ordering)
[ "private void checkOrderby(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String orderbySpec = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ORDERBY);\r\n\r\n if ((orderbySpec == null) || (orderbySpec.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.');\r\n ClassDescriptorDef elementClass = ((ModelDef)ownerClass.getOwner()).getClass(elementClassName);\r\n FieldDescriptorDef fieldDef;\r\n String token;\r\n String fieldName;\r\n String ordering;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(orderbySpec); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos == -1)\r\n {\r\n fieldName = token;\r\n ordering = null;\r\n }\r\n else\r\n {\r\n fieldName = token.substring(0, pos);\r\n ordering = token.substring(pos + 1);\r\n }\r\n fieldDef = elementClass.getField(fieldName);\r\n if (fieldDef == null)\r\n {\r\n throw new ConstraintException(\"The field \"+fieldName+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" hasn't been found in the element class \"+elementClass.getName());\r\n }\r\n if ((ordering != null) && (ordering.length() > 0) &&\r\n !\"ASC\".equals(ordering) && !\"DESC\".equals(ordering))\r\n {\r\n throw new ConstraintException(\"The ordering \"+ordering+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" is invalid\");\r\n }\r\n }\r\n }" ]
[ "protected X509Certificate wireUpSslWithCyberVilliansCAOdo(String host, SslListener listener) {\n host = requestOriginalHostName.get();\n\n // Add cybervillians CA(from browsermob)\n try {\n // see https://github.com/webmetrics/browsermob-proxy/issues/105\n String escapedHost = host.replace('*', '_');\n\n KeyStoreManager keyStoreManager = Utils.getKeyStoreManager(escapedHost);\n keyStoreManager.getKeyStore().deleteEntry(KeyStoreManager._caPrivKeyAlias);\n keyStoreManager.persist();\n listener.setKeystore(new File(\"seleniumSslSupport\" + File.separator + escapedHost + File.separator + \"cybervillainsCA.jks\").getAbsolutePath());\n\n return keyStoreManager.getCertificateByAlias(escapedHost);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "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}", "protected String findPath(String start, String end) {\n if (start.equals(end)) {\n return start;\n } else {\n return findPath(start, parent.get(end)) + \" -> \" + end;\n }\n }", "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 List<File> getInactiveOverlays() throws PatchingException {\n if (referencedOverlayDirectories == null) {\n walk();\n }\n List<File> inactiveDirs = null;\n for (Layer layer : installedIdentity.getLayers()) {\n final File overlaysDir = new File(layer.getDirectoryStructure().getModuleRoot(), Constants.OVERLAYS);\n final File[] inactiveLayerDirs = overlaysDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isDirectory() && !referencedOverlayDirectories.contains(pathname);\n }\n });\n if (inactiveLayerDirs != null && inactiveLayerDirs.length > 0) {\n if (inactiveDirs == null) {\n inactiveDirs = new ArrayList<File>();\n }\n inactiveDirs.addAll(Arrays.asList(inactiveLayerDirs));\n }\n }\n return inactiveDirs == null ? Collections.<File>emptyList() : inactiveDirs;\n }", "public ActionContext applyContentType(Result result) {\n if (!result.status().isError()) {\n return applyContentType();\n }\n return applyContentType(contentTypeForErrorResult(req()));\n }", "public TaskMode getTaskMode()\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;\n }", "public static void resize(GVRMesh mesh, float xsize, float ysize, float zsize) {\n float dim[] = getBoundingSize(mesh);\n\n scale(mesh, xsize / dim[0], ysize / dim[1], zsize / dim[2]);\n }", "public int scrollToPage(int pageNumber) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToPage pageNumber = %d mPageCount = %d\",\n pageNumber, mPageCount);\n\n if (mSupportScrollByPage &&\n (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) {\n scrollToItem(getFirstItemIndexOnPage(pageNumber));\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n return mCurrentItemIndex;\n\t}" ]
Associate an input stream with the operation. Closing the input stream is the responsibility of the caller. @param in the input stream. Cannot be {@code null} @return a builder than can be used to continue building the operation
[ "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 }" ]
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public UTMDetail getUTMDetails() {\n UTMDetail ud = new UTMDetail();\n ud.setSource(source);\n ud.setMedium(medium);\n ud.setCampaign(campaign);\n return ud;\n }", "private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {\n if(response == null) {\n logger.warn(\"RoutingTimedout on waiting for async ops; parallelResponseToWait: \"\n + numNodesPendingResponse + \"; preferred-1: \" + (preferred - 1)\n + \"; quorumOK: \" + quorumSatisfied + \"; zoneOK: \" + zonesSatisfied);\n } else {\n numNodesPendingResponse = numNodesPendingResponse - 1;\n numResponsesGot = numResponsesGot + 1;\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handling async put error\");\n }\n if(response.getValue() instanceof QuotaExceededException) {\n /**\n * TODO Not sure if we need to count this Exception for\n * stats or silently ignore and just log a warning. While\n * QuotaExceededException thrown from other places mean the\n * operation failed, this one does not fail the operation\n * but instead stores slops. Introduce a new Exception in\n * client side to just monitor how mamy Async writes fail on\n * exceeding Quota?\n * \n */\n if(logger.isDebugEnabled()) {\n logger.debug(\"Received quota exceeded exception after a successful \"\n + pipeline.getOperation().getSimpleName() + \" call on node \"\n + response.getNode().getId() + \", store '\"\n + pipelineData.getStoreName() + \"', master-node '\"\n + pipelineData.getMaster().getId() + \"'\");\n }\n } else if(handleResponseError(response, pipeline, failureDetector)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key\n + \"} severe async put error, exiting parallel put stage\");\n }\n\n return;\n }\n if(PipelineRoutedStore.isSlopableFailure(response.getValue())\n || response.getValue() instanceof QuotaExceededException) {\n /**\n * We want to slop ParallelPuts which fail due to\n * QuotaExceededException.\n * \n * TODO Though this is not the right way of doing things, in\n * order to avoid inconsistencies and data loss, we chose to\n * slop the quota failed parallel puts.\n * \n * As a long term solution - 1) either Quota management\n * should be hidden completely in a routing layer like\n * Coordinator or 2) the Server should be able to\n * distinguish between serial and parallel puts and should\n * only quota for serial puts\n * \n */\n pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());\n }\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handled async put error\");\n }\n\n } else {\n pipelineData.incrementSuccesses();\n failureDetector.recordSuccess(response.getNode(), response.getRequestTime());\n pipelineData.getZoneResponses().add(response.getNode().getZoneId());\n }\n }\n }", "@Deprecated public Duration getDuration(Date startDate, Date endDate) throws MPXJException\n {\n return (getDuration(\"Standard\", startDate, endDate));\n }", "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }", "@Override\n public List<ConfigIssue> init(Service.Context context) {\n this.context = context;\n return init();\n }", "public List<IssueCategory> getIssueCategories()\n {\n return this.issueCategories.values().stream()\n .sorted((category1, category2) -> category1.getPriority() - category2.getPriority())\n .collect(Collectors.toList());\n }", "public void originalClass(String template, Properties attributes) throws XDocletException\r\n {\r\n pushCurrentClass(_curClassDef.getOriginalClass());\r\n generate(template);\r\n popCurrentClass();\r\n }", "public static BoxCollaborationWhitelistExemptTarget.Info create(final BoxAPIConnection api, String userID) {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"user\", new JsonObject()\n .add(\"type\", \"user\")\n .add(\"id\", userID));\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelistExemptTarget userWhitelist = new BoxCollaborationWhitelistExemptTarget(api,\n responseJSON.get(\"id\").asString());\n\n return userWhitelist.new Info(responseJSON);\n }", "private Method getPropertySourceMethod(Object sourceObject,\r\n\t\t\tObject destinationObject, String destinationProperty) {\r\n\t\tBeanToBeanMapping beanToBeanMapping = beanToBeanMappings.get(ClassPair\r\n\t\t\t\t.get(sourceObject.getClass(), destinationObject\r\n\t\t\t\t\t\t.getClass()));\r\n\t\tString sourceProperty = null;\r\n\t\tif (beanToBeanMapping != null) {\r\n\t\t\tsourceProperty = beanToBeanMapping\r\n\t\t\t\t\t.getSourceProperty(destinationProperty);\r\n\t\t}\r\n\t\tif (sourceProperty == null) {\r\n\t\t\tsourceProperty = destinationProperty;\r\n\t\t}\r\n\r\n\t\treturn BeanUtils.getGetterPropertyMethod(sourceObject.getClass(),\r\n\t\t\t\tsourceProperty);\r\n\t}" ]
By the time we reach this method, we should be looking at the SQLite database file itself. @param file SQLite database file @return ProjectFile instance
[ "private ProjectFile readFile(File file) throws MPXJException\n {\n try\n {\n String url = \"jdbc:sqlite:\" + file.getAbsolutePath();\n Properties props = new Properties();\n m_connection = org.sqlite.JDBC.createConnection(url, props);\n\n m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n m_dayTimeIntervals = xpath.compile(\"/array/dayTimeInterval\");\n m_entityMap = new HashMap<String, Integer>();\n return read();\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT, ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n\n m_documentBuilder = null;\n m_dayTimeIntervals = null;\n m_entityMap = null;\n }\n }" ]
[ "public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }", "public void setKnotBlend(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~BLEND_MASK) | type);\n\t\trebuildGradient();\n\t}", "public static appqoepolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }", "private final boolean parseBoolean(String value)\n {\n return value != null && (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"y\") || value.equalsIgnoreCase(\"yes\"));\n }", "public static Chart getMSDLineWithPowerModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double a, double D) {\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] = 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^alpha\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }" ]
Multiply scalar value to a complex number. @param z1 Complex Number. @param scalar Scalar value. @return Returns new ComplexNumber instance containing the multiply of specified complex number with the scalar value.
[ "public static ComplexNumber Multiply(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real * scalar, z1.imaginary * scalar);\r\n }" ]
[ "public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) {\n try {\n Configuration conf = new Configuration();\n conf.setInt(\"io.file.buffer.size\", 4096);\n SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration());\n SequenceFile.Metadata meta = reader.getMetadata();\n reader.close();\n TreeMap<Text, Text> map = meta.getMetadata();\n Map<String, String> values = new HashMap<String, String>();\n for(Map.Entry<Text, Text> entry: map.entrySet())\n values.put(entry.getKey().toString(), entry.getValue().toString());\n\n return values;\n } catch(IOException e) {\n throw new RuntimeException(e);\n }\n }", "private ModelNode createJVMNode() throws OperationFailedException {\n ModelNode jvm = new ModelNode().setEmptyObject();\n jvm.get(NAME).set(getProperty(\"java.vm.name\"));\n jvm.get(JAVA_VERSION).set(getProperty(\"java.vm.specification.version\"));\n jvm.get(JVM_VERSION).set(getProperty(\"java.version\"));\n jvm.get(JVM_VENDOR).set(getProperty(\"java.vm.vendor\"));\n jvm.get(JVM_HOME).set(getProperty(\"java.home\"));\n return jvm;\n }", "public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) {\n return rootDir.listFiles(new FileFilter() {\n\n public boolean accept(File pathName) {\n if(checkVersionDirName(pathName)) {\n long versionId = getVersionId(pathName);\n if(versionId != -1 && versionId <= maxId && versionId >= minId) {\n return true;\n }\n }\n return false;\n }\n });\n }", "public void growMaxLength( int arrayLength , boolean preserveValue ) {\n if( arrayLength < 0 )\n throw new IllegalArgumentException(\"Negative array length. Overflow?\");\n // see if multiplying numRows*numCols will cause an overflow. If it won't then pick the smaller of the two\n if( numRows != 0 && numCols <= Integer.MAX_VALUE / numRows ) {\n // save the user from themselves\n arrayLength = Math.min(numRows*numCols, arrayLength);\n }\n if( nz_values == null || arrayLength > this.nz_values.length ) {\n double[] data = new double[ arrayLength ];\n int[] row_idx = new int[ arrayLength ];\n\n if( preserveValue ) {\n if( nz_values == null )\n throw new IllegalArgumentException(\"Can't preserve values when uninitialized\");\n System.arraycopy(this.nz_values, 0, data, 0, this.nz_length);\n System.arraycopy(this.nz_rows, 0, row_idx, 0, this.nz_length);\n }\n\n this.nz_values = data;\n this.nz_rows = row_idx;\n }\n }", "final void end() {\n final Thread thread = this.threadRef;\n this.keepRunning.set(false);\n if (thread != null) {\n // thread.interrupt();\n try {\n thread.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n this.threadRef = null;\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 }", "private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate();\n for (net.sf.mpxj.ganttproject.schema.Date date : dates)\n {\n addException(mpxjCalendar, date);\n }\n }", "public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }", "public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception {\n HeaderMap headers = exchange.getRequestHeaders();\n String[] origins = headers.get(Headers.ORIGIN).toArray();\n if (allowedOrigins != null && !allowedOrigins.isEmpty()) {\n for (String allowedOrigin : allowedOrigins) {\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n }\n }\n String allowedOrigin = defaultOrigin(exchange);\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n ROOT_LOGGER.debug(\"Request rejected due to HOST/ORIGIN mis-match.\");\n ResponseCodeHandler.HANDLE_403.handleRequest(exchange);\n return null;\n }" ]
Closes off all connections in all partitions.
[ "public void terminateAllConnections(){\r\n\t\tthis.terminationLock.lock();\r\n\t\ttry{\r\n\t\t\t// close off all connections.\r\n\t\t\tfor (int i=0; i < this.pool.partitionCount; i++) {\r\n\t\t\t\tthis.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\t\t\t\tList<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); \r\n\t\t\t\tthis.pool.partitions[i].getFreeConnections().drainTo(clist);\r\n\t\t\t\tfor (ConnectionHandle c: clist){\r\n\t\t\t\t\tthis.pool.destroyConnection(c);\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t} finally {\r\n\t\t\tthis.terminationLock.unlock();\r\n\t\t}\r\n\t}" ]
[ "private ChildTaskContainer getParentTask(String wbs)\n {\n ChildTaskContainer result;\n String parentWbs = getParentWBS(wbs);\n if (parentWbs == null)\n {\n result = m_projectFile;\n }\n else\n {\n result = m_taskMap.get(parentWbs);\n }\n return result;\n }", "public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }", "public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}", "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 }", "protected static boolean isMaskCompatibleWithRange(long value, long upperValue, long maskValue, long maxValue) {\n\t\tif(value == upperValue || maskValue == maxValue || maskValue == 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\t//algorithm:\n\t\t//here we find the highest bit that is part of the range, highestDifferingBitInRange (ie changes from lower to upper)\n\t\t//then we find the highest bit in the mask that is 1 that is the same or below highestDifferingBitInRange (if such a bit exists)\n\t\t\n\t\t//this gives us the highest bit that is part of the masked range (ie changes from lower to upper after applying the mask)\n\t\t//if this latter bit exists, then any bit below it in the mask must be 1 to include the entire range.\n\t\t\n\t\tlong differing = value ^ upperValue;\n\t\tboolean foundDiffering = (differing != 0);\n\t\tboolean differingIsLowestBit = (differing == 1);\n\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\tint highestDifferingBitInRange = Long.numberOfLeadingZeros(differing);\n\t\t\tlong maskMask = ~0L >>> highestDifferingBitInRange;\n\t\t\tlong differingMasked = maskValue & maskMask;\n\t\t\tfoundDiffering = (differingMasked != 0);\n\t\t\tdifferingIsLowestBit = (differingMasked == 1);\n\t\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\t\t//anything below highestDifferingBitMasked in the mask must be ones\n\t\t\t\t//Also, if we have masked out any 1 bit in the original, then anything that we do not mask out that follows must be all 1s\n\t\t\t\tint highestDifferingBitMasked = Long.numberOfLeadingZeros(differingMasked);\n\t\t\t\tlong hostMask = ~0L >>> (highestDifferingBitMasked + 1);//for the first mask bit that is 1, all bits that follow must also be 1\n\t\t\t\tif((maskValue & hostMask) != hostMask) { //check if all ones below\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(highestDifferingBitMasked > highestDifferingBitInRange) {\n\t\t\t\t\t//We have masked out a 1 bit, so we need to check that all bits in upper value that we do not mask out are also 1 bits, otherwise we end up missing values in the masked range\n\t\t\t\t\t//This check is unnecessary for prefix-length subnets, only non-standard ranges might fail this check.\n\t\t\t\t\t//For instance, if we have range 0000 to 1010\n\t\t\t\t\t//and we mask upper and lower with 0111\n\t\t\t\t\t//we get 0000 to 0010, but 0111 was in original range, and the mask of that value retains that value\n\t\t\t\t\t//so that value needs to be in final range, and it's not.\n\t\t\t\t\t//What went wrong is that we masked out the top bit, and any other bit that is not masked out must be 1.\n\t\t\t\t\t//To work, our original range needed to be 0000 to 1111, with the three 1s following the first masked-out 1\n\t\t\t\t\tlong hostMaskUpper = ~0L >>> highestDifferingBitMasked;\n\t\t\t\t\tif((upperValue & hostMaskUpper) != hostMaskUpper) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "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 }", "private void putToSessionCache(Identity oid, CacheEntry entry, boolean onlyIfNew)\r\n {\r\n if(onlyIfNew)\r\n {\r\n // no synchronization needed, because session cache was used per broker instance\r\n if(!sessionCache.containsKey(oid)) sessionCache.put(oid, entry);\r\n }\r\n else\r\n {\r\n sessionCache.put(oid, entry);\r\n }\r\n }", "public void updateInfo(BoxTermsOfServiceUserStatus.Info info) {\n URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n info.update(responseJSON);\n }", "private Map<String, String> fillInitialVariables() {\r\n Map<String, TransitionTarget> targets = model.getChildren();\n\r\n Set<String> variables = new HashSet<>();\r\n for (TransitionTarget target : targets.values()) {\r\n OnEntry entry = target.getOnEntry();\r\n List<Action> actions = entry.getActions();\r\n for (Action action : actions) {\r\n if (action instanceof Assign) {\r\n String variable = ((Assign) action).getName();\r\n variables.add(variable);\r\n } else if (action instanceof SetAssignExtension.SetAssignTag) {\r\n String variable = ((SetAssignExtension.SetAssignTag) action).getName();\r\n variables.add(variable);\r\n }\r\n }\r\n }\n\r\n Map<String, String> result = new HashMap<>();\r\n for (String variable : variables) {\r\n result.put(variable, \"\");\r\n }\n\r\n return result;\r\n }" ]
Get the ver @param id @return
[ "public Versioned<E> getVersionedById(int id) {\n Versioned<VListNode<E>> listNode = getListNode(id);\n if(listNode == null)\n throw new IndexOutOfBoundsException();\n return new Versioned<E>(listNode.getValue().getValue(), listNode.getVersion());\n }" ]
[ "@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 String dir = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean verbose = false;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET);\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);\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 metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_DIR)) {\n dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);\n }\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(OPT_VERBOSE)) {\n verbose = true;\n }\n\n // execute command\n File directory = AdminToolUtils.createDir(dir);\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 for(Object key: MetadataStore.METADATA_KEYS) {\n metaKeys.add((String) key);\n }\n }\n\n doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);\n }", "public static sslcertkey[] get(nitro_service service) throws Exception{\n\t\tsslcertkey obj = new sslcertkey();\n\t\tsslcertkey[] response = (sslcertkey[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String convertToSQL92(char escape, char multi, char single, String pattern)\n\t\t\tthrows IllegalArgumentException {\n\t\tif ((escape == '\\'') || (multi == '\\'') || (single == '\\'')) {\n\t\t\tthrow new IllegalArgumentException(\"do not use single quote (') as special char!\");\n\t\t}\n\t\t\n\t\tStringBuilder result = new StringBuilder(pattern.length() + 5);\n\t\tint i = 0;\n\t\twhile (i < pattern.length()) {\n\t\t\tchar chr = pattern.charAt(i);\n\t\t\tif (chr == escape) {\n\t\t\t\t// emit the next char and skip it\n\t\t\t\tif (i != (pattern.length() - 1)) {\n\t\t\t\t\tresult.append(pattern.charAt(i + 1));\n\t\t\t\t}\n\t\t\t\ti++; // skip next char\n\t\t\t} else if (chr == single) {\n\t\t\t\tresult.append('_');\n\t\t\t} else if (chr == multi) {\n\t\t\t\tresult.append('%');\n\t\t\t} else if (chr == '\\'') {\n\t\t\t\tresult.append('\\'');\n\t\t\t\tresult.append('\\'');\n\t\t\t} else {\n\t\t\t\tresult.append(chr);\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\n\t\treturn result.toString();\n\t}", "private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }", "public static String getEncoding(CmsObject cms, CmsResource file) {\n\n CmsProperty encodingProperty = CmsProperty.getNullProperty();\n try {\n encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n return CmsEncoder.lookupEncoding(encodingProperty.getValue(\"\"), OpenCms.getSystemInfo().getDefaultEncoding());\n }", "@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 }", "public double nextDouble(double lo, double hi) {\n if (lo < 0) {\n if (nextInt(2) == 0)\n return -nextDouble(0, -lo);\n else\n return nextDouble(0, hi);\n } else {\n return (lo + (hi - lo) * nextDouble());\n }\n }", "public static final String printTimestamp(Date value)\n {\n return (value == null ? null : TIMESTAMP_FORMAT.get().format(value));\n }", "public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\n }" ]
For running queries embebed in the report design @param dr @param layoutManager @param con @param _parameters @return @throws JRException
[ "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n if (_parameters == null)\n _parameters = new HashMap<String, Object>();\n\n visitSubreports(dr, _parameters);\n compileOrLoadSubreports(dr, _parameters, \"r\");\n\n DynamicJasperDesign jd = generateJasperDesign(dr);\n Map<String, Object> params = new HashMap<String, Object>();\n if (!_parameters.isEmpty()) {\n registerParams(jd, _parameters);\n params.putAll(_parameters);\n }\n registerEntities(jd, dr, layoutManager);\n layoutManager.applyLayout(jd, dr);\n JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n //JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n JasperReport jr = JasperCompileManager.compileReport(jd);\n params.putAll(jd.getParametersWithValues());\n jp = JasperFillManager.fillReport(jr, params, con);\n\n return jp;\n }" ]
[ "public static base_responses delete(nitro_service client, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = resources[i].hostname;\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public void addEvent(Event event) {\n if(event == null)\n throw new IllegalStateException(\"event must be non-null\");\n\n if(logger.isTraceEnabled())\n logger.trace(\"Adding event \" + event);\n\n eventQueue.add(event);\n }", "public Set<String> postProcessingFields() {\n Set<String> fields = new LinkedHashSet<>();\n query.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n sort.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n return fields;\n }", "public RowColumn following() {\n if (row.equals(Bytes.EMPTY)) {\n return RowColumn.EMPTY;\n } else if (col.equals(Column.EMPTY)) {\n return new RowColumn(followingBytes(row));\n } else if (!col.isQualifierSet()) {\n return new RowColumn(row, new Column(followingBytes(col.getFamily())));\n } else if (!col.isVisibilitySet()) {\n return new RowColumn(row, new Column(col.getFamily(), followingBytes(col.getQualifier())));\n } else {\n return new RowColumn(row,\n new Column(col.getFamily(), col.getQualifier(), followingBytes(col.getVisibility())));\n }\n }", "private void setCalendarToOrdinalRelativeDay(Calendar calendar, int dayNumber)\n {\n int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n int requiredDayOfWeek = getDayOfWeek().getValue();\n int dayOfWeekOffset = 0;\n if (requiredDayOfWeek > currentDayOfWeek)\n {\n dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek;\n }\n else\n {\n if (requiredDayOfWeek < currentDayOfWeek)\n {\n dayOfWeekOffset = 7 - (currentDayOfWeek - requiredDayOfWeek);\n }\n }\n\n if (dayOfWeekOffset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset);\n }\n\n if (dayNumber > 1)\n {\n calendar.add(Calendar.DAY_OF_YEAR, (7 * (dayNumber - 1)));\n }\n }", "public static InetAddress getLocalHost() throws UnknownHostException {\n InetAddress addr;\n try {\n addr = InetAddress.getLocalHost();\n } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404\n addr = InetAddress.getByName(null);\n }\n return addr;\n }", "public static ModelNode getOperationAddress(final ModelNode op) {\n return op.hasDefined(OP_ADDR) ? op.get(OP_ADDR) : new ModelNode();\n }", "public static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public static nsrpcnode[] get(nitro_service service, String ipaddress[]) throws Exception{\n\t\tif (ipaddress !=null && ipaddress.length>0) {\n\t\t\tnsrpcnode response[] = new nsrpcnode[ipaddress.length];\n\t\t\tnsrpcnode obj[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++) {\n\t\t\t\tobj[i] = new nsrpcnode();\n\t\t\t\tobj[i].set_ipaddress(ipaddress[i]);\n\t\t\t\tresponse[i] = (nsrpcnode) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
Reverses all the TransitionControllers managed by this TransitionManager
[ "public void reverse() {\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).reverse();\n }\n }" ]
[ "private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }", "public static vlan[] get(nitro_service service) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tvlan[] response = (vlan[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n\tpublic void processItemDocument(ItemDocument itemDocument) {\n\t\tthis.countItems++;\n\n\t\t// Do some printing for demonstration/debugging.\n\t\t// Only print at most 50 items (or it would get too slow).\n\t\tif (this.countItems < 10) {\n\t\t\tSystem.out.println(itemDocument);\n\t\t} else if (this.countItems == 10) {\n\t\t\tSystem.out.println(\"*** I won't print any further items.\\n\"\n\t\t\t\t\t+ \"*** We will never finish if we print all the items.\\n\"\n\t\t\t\t\t+ \"*** Maybe remove this debug output altogether.\");\n\t\t}\n\t}", "public RedwoodConfiguration collapseExact(){\r\n tasks.add(new Runnable() { public void run() { Redwood.spliceHandler(VisibilityHandler.class, new RepeatedRecordHandler(RepeatedRecordHandler.EXACT), OutputHandler.class); } });\r\n return this;\r\n }", "public void setPlaying(boolean playing) {\n\n if (this.playing.get() == playing) {\n return;\n }\n\n this.playing.set(playing);\n\n if (playing) {\n metronome.jumpToBeat(whereStopped.get().getBeat());\n if (isSendingStatus()) { // Need to also start the beat sender.\n beatSender.set(new BeatSender(metronome));\n }\n } else {\n final BeatSender activeSender = beatSender.get();\n if (activeSender != null) { // We have a beat sender we need to stop.\n activeSender.shutDown();\n beatSender.set(null);\n }\n whereStopped.set(metronome.getSnapshot());\n }\n }", "private boolean keyAlreadyExists(String newKey) {\n\n Collection<?> itemIds = m_table.getItemIds();\n for (Object itemId : itemIds) {\n if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {\n return true;\n }\n }\n return false;\n }", "public void runOnInvariantViolationPlugins(Invariant invariant,\n\t\t\tCrawlerContext context) {\n\t\tLOGGER.debug(\"Running OnInvariantViolationPlugins...\");\n\t\tcounters.get(OnInvariantViolationPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {\n\t\t\tif (plugin instanceof OnInvariantViolationPlugin) {\n\t\t\t\ttry {\n\t\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\t\t((OnInvariantViolationPlugin) plugin).onInvariantViolation(\n\t\t\t\t\t\t\tinvariant, context);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public static final Boolean parseExtendedAttributeBoolean(String value)\n {\n return ((value.equals(\"1\") ? Boolean.TRUE : Boolean.FALSE));\n }", "protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }" ]
Scans a single class for Swagger annotations - does not invoke ReaderListeners
[ "public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }" ]
[ "@UiHandler(\"m_everyDay\")\r\n void onEveryDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setInterval(m_everyDay.getFormValueAsString());\r\n }\r\n\r\n }", "protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }", "public boolean find() {\r\n if (findIterator == null) {\r\n findIterator = root.iterator();\r\n }\r\n if (findCurrent != null && matches()) {\r\n return true;\r\n }\r\n while (findIterator.hasNext()) {\r\n findCurrent = findIterator.next();\r\n resetChildIter(findCurrent);\r\n if (matches()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "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 }", "public static clusternodegroup get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tobj.set_name(name);\n\t\tclusternodegroup response = (clusternodegroup) obj.get_resource(service);\n\t\treturn response;\n\t}", "public List<IssueCategory> getIssueCategories()\n {\n return this.issueCategories.values().stream()\n .sorted((category1, category2) -> category1.getPriority() - category2.getPriority())\n .collect(Collectors.toList());\n }", "private Class[] getInterfaces(Class clazz) {\r\n Class superClazz = clazz;\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n // clazz can be an interface itself and when getInterfaces()\r\n // is called on an interface it returns only the extending\r\n // interfaces, not the interface itself.\r\n if (clazz.isInterface()) {\r\n Class[] tempInterfaces = new Class[interfaces.length + 1];\r\n tempInterfaces[0] = clazz;\r\n\r\n System.arraycopy(interfaces, 0, tempInterfaces, 1, interfaces.length);\r\n interfaces = tempInterfaces;\r\n }\r\n\r\n // add all interfaces implemented by superclasses to the interfaces array\r\n while ((superClazz = superClazz.getSuperclass()) != null) {\r\n Class[] superInterfaces = superClazz.getInterfaces();\r\n Class[] combInterfaces = new Class[interfaces.length + superInterfaces.length];\r\n System.arraycopy(interfaces, 0, combInterfaces, 0, interfaces.length);\r\n System.arraycopy(superInterfaces, 0, combInterfaces, interfaces.length, superInterfaces.length);\r\n interfaces = combInterfaces;\r\n }\r\n\r\n /**\r\n * Must remove duplicate interfaces before calling Proxy.getProxyClass().\r\n * Duplicates can occur if a subclass re-declares that it implements\r\n * the same interface as one of its ancestor classes.\r\n **/\r\n HashMap unique = new HashMap();\r\n for (int i = 0; i < interfaces.length; i++) {\r\n unique.put(interfaces[i].getName(), interfaces[i]);\r\n }\r\n /* Add the OJBProxy interface as well */\r\n unique.put(OJBProxy.class.getName(), OJBProxy.class);\r\n\r\n interfaces = (Class[])unique.values().toArray(new Class[unique.size()]);\r\n\r\n return interfaces;\r\n }", "public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }", "private String searchForPersistentSubType(XClass type)\r\n {\r\n ArrayList queue = new ArrayList();\r\n XClass subType;\r\n\r\n queue.add(type);\r\n while (!queue.isEmpty())\r\n {\r\n subType = (XClass)queue.get(0);\r\n queue.remove(0);\r\n if (_model.hasClass(subType.getQualifiedName()))\r\n {\r\n return subType.getQualifiedName();\r\n }\r\n addDirectSubTypes(subType, queue);\r\n }\r\n return null;\r\n }" ]
create a new instance of the class represented by the no-argument constructor provided @param constructor the zero argument constructor for the class @return a new instance of the class @throws InstantiationException @throws ClassNotPersistenceCapableException if the constructor is null or there is an exception while trying to create a new instance
[ "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }" ]
[ "public static int convertBytesToInt(byte[] bytes, int offset)\n {\n return (BITWISE_BYTE_TO_INT & bytes[offset + 3])\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8)\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16)\n | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24);\n }", "public void strokeEllipse(Rectangle rect, Color color, float linewidth) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),\n\t\t\t\torigY + rect.getTop());\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}", "private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) {\n\t\tif (fieldType.isEscapedDefaultValue()) {\n\t\t\tappendEscapedWord(sb, defaultValue.toString());\n\t\t} else {\n\t\t\tsb.append(defaultValue);\n\t\t}\n\t}", "private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }", "public static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }", "protected void checkActiveState(Widget child) {\n // Check if this widget has a valid href\n String href = child.getElement().getAttribute(\"href\");\n String url = Window.Location.getHref();\n int pos = url.indexOf(\"#\");\n String location = pos >= 0 ? url.substring(pos, url.length()) : \"\";\n\n if (!href.isEmpty() && location.startsWith(href)) {\n ListItem li = findListItemParent(child);\n if (li != null) {\n makeActive(li);\n }\n } else if (child instanceof HasWidgets) {\n // Recursive check\n for (Widget w : (HasWidgets) child) {\n checkActiveState(w);\n }\n }\n }", "public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n\n boolean suppressLoad = false;\n ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy();\n final boolean isReloaded = environment.getRunningModeControl().isReloaded();\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) {\n throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName());\n }\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) {\n suppressLoad = true;\n }\n\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"domain\"), domainXml, domainXml, suppressLoad);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"domain\"), domainXml);\n }\n }\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }", "public static <T extends DMatrix> boolean decomposeSafe(DecompositionInterface<T> decomp, T M ) {\n if( decomp.inputModified() ) {\n return decomp.decompose(M.<T>copy());\n } else {\n return decomp.decompose(M);\n }\n }", "private void addCalendarException(MpxjTreeNode parentNode, final ProjectCalendarException exception)\n {\n MpxjTreeNode exceptionNode = new MpxjTreeNode(exception, CALENDAR_EXCEPTION_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return m_dateFormat.format(exception.getFromDate());\n }\n };\n parentNode.add(exceptionNode);\n addHours(exceptionNode, exception);\n }" ]
Method will be executed asynchronously.
[ "public void sendEventsFromQueue() {\n if (null == queue || stopSending) {\n return;\n }\n LOG.fine(\"Scheduler called for sending events\");\n\n int packageSize = getEventsPerMessageCall();\n\n while (!queue.isEmpty()) {\n final List<Event> list = new ArrayList<Event>();\n int i = 0;\n while (i < packageSize && !queue.isEmpty()) {\n Event event = queue.remove();\n if (event != null && !filter(event)) {\n list.add(event);\n i++;\n }\n }\n if (list.size() > 0) {\n executor.execute(new Runnable() {\n public void run() {\n try {\n sendEvents(list);\n } catch (MonitoringException e) {\n e.logException(Level.SEVERE);\n }\n }\n });\n\n }\n }\n\n }" ]
[ "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }", "public T[] toArray(T[] tArray) {\n List<T> array = new ArrayList<T>(100);\n for (Iterator<T> it = iterator(); it.hasNext();) {\n T val = it.next();\n if (val != null) array.add(val);\n }\n return array.toArray(tArray);\n }", "public void remove(int profileId) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //also want to delete what is in the server redirect table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //also want to delete the path_profile table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //and the enabled overrides table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //and delete all the clients associated with this profile including the default client\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\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 void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) {\n\n if (CmsXmlUtils.isDeepXpath(xmlPath)) {\n String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath);\n if (null == xmlContent.getValue(parentPath, l)) {\n createParentXmlElements(xmlContent, parentPath, l);\n xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1);\n }\n }\n\n }", "@Override\n public final long getLong(final String key) {\n Long result = optLong(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }", "public static base_response update(nitro_service client, snmpoption resource) throws Exception {\n\t\tsnmpoption updateresource = new snmpoption();\n\t\tupdateresource.snmpset = resource.snmpset;\n\t\tupdateresource.snmptraplogging = resource.snmptraplogging;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void clearHistory(int profileId, String clientUUID) {\n PreparedStatement query = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"DELETE FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is null or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId;\n }\n\n // see if clientUUID is null or not\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \" AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"'\";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n query = sqlConnection.prepareStatement(sqlQuery);\n query.executeUpdate();\n } catch (Exception e) {\n } finally {\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static String dump(final int displayOffset, final byte[] data, final int offset, final int len)\n {\n StringBuilder sb = new StringBuilder();\n Formatter formatter = new Formatter(sb);\n StringBuilder ascii = new StringBuilder();\n\n int dataNdx = offset;\n final int maxDataNdx = offset + len;\n final int lines = (len + 16) / 16;\n for (int i = 0; i < lines; i++) {\n ascii.append(\" |\");\n formatter.format(\"%08x \", displayOffset + (i * 16));\n\n for (int j = 0; j < 16; j++) {\n if (dataNdx < maxDataNdx) {\n byte b = data[dataNdx++];\n formatter.format(\"%02x \", b);\n ascii.append((b > MIN_VISIBLE && b < MAX_VISIBLE) ? (char) b : ' ');\n }\n else {\n sb.append(\" \");\n }\n\n if (j == 7) {\n sb.append(' ');\n }\n }\n\n ascii.append('|');\n sb.append(ascii).append('\\n');\n ascii.setLength(0);\n }\n\n formatter.close();\n return sb.toString();\n }" ]
Delivers the correct JSON Object for properties @param properties @throws org.json.JSONException
[ "private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }" ]
[ "public Conditionals ifModifiedSince(LocalDateTime time) {\n Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));\n Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE));\n time = time.withNano(0);\n return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty());\n }", "public static String generateQuery(final Map<String,Object> params){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tboolean newEntry = false;\n\t\t\n\t\tsb.append(\"{\");\n\t\tfor(final Entry<String,Object> param: params.entrySet()){\n\t\t\tif(newEntry){\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\n\t\t\tsb.append(param.getKey());\n\t\t\tsb.append(\": \");\n\t\t\tsb.append(getParam(param.getValue()));\n\t\t\tnewEntry = true;\n\t\t}\n\t\tsb.append(\"}\");\n\t\t\n\t\treturn sb.toString();\n\t}", "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 AT_Row setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (PreparedStatement) Proxy.newProxyInstance(\n\t\t\t\tPreparedStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {PreparedStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "private void processDestructionQueue(HttpServletRequest request) {\n Object contextsAttribute = request.getAttribute(DESTRUCTION_QUEUE_ATTRIBUTE_NAME);\n if (contextsAttribute instanceof Map) {\n Map<String, List<ContextualInstance<?>>> contexts = cast(contextsAttribute);\n synchronized (contexts) {\n FastEvent<String> beforeDestroyedEvent = FastEvent.of(String.class, beanManager, BeforeDestroyed.Literal.CONVERSATION);\n FastEvent<String> destroyedEvent = FastEvent.of(String.class, beanManager, Destroyed.Literal.CONVERSATION);\n for (Iterator<Entry<String, List<ContextualInstance<?>>>> iterator = contexts.entrySet().iterator(); iterator.hasNext();) {\n Entry<String, List<ContextualInstance<?>>> entry = iterator.next();\n beforeDestroyedEvent.fire(entry.getKey());\n for (ContextualInstance<?> contextualInstance : entry.getValue()) {\n destroyContextualInstance(contextualInstance);\n }\n // Note that for the attached/current conversation we fire the destroyed event twice because we can't reliably identify such a conversation\n destroyedEvent.fire(entry.getKey());\n iterator.remove();\n }\n }\n }\n }", "private static DumpContentType guessDumpContentType(String fileName) {\n\t\tString lcDumpName = fileName.toLowerCase();\n\t\tif (lcDumpName.contains(\".json.gz\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".json.bz2\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".sql.gz\")) {\n\t\t\treturn DumpContentType.SITES;\n\t\t} else if (lcDumpName.contains(\".xml.bz2\")) {\n\t\t\tif (lcDumpName.contains(\"daily\")) {\n\t\t\t\treturn DumpContentType.DAILY;\n\t\t\t} else if (lcDumpName.contains(\"current\")) {\n\t\t\t\treturn DumpContentType.CURRENT;\n\t\t\t} else {\n\t\t\t\treturn DumpContentType.FULL;\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.warn(\"Could not guess type of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to json.gz.\");\n\t\t\treturn DumpContentType.JSON;\n\t\t}\n\t}", "void scan() {\n if (acquireScanLock()) {\n boolean scheduleRescan = false;\n try {\n scheduleRescan = scan(false, deploymentOperations);\n } finally {\n try {\n if (scheduleRescan) {\n synchronized (this) {\n if (scanEnabled) {\n rescanIncompleteTask = scheduledExecutor.schedule(scanRunnable, 200, TimeUnit.MILLISECONDS);\n }\n }\n }\n } finally {\n releaseScanLock();\n }\n }\n }\n }", "public static appfwprofile_safeobject_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_safeobject_binding obj = new appfwprofile_safeobject_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_safeobject_binding response[] = (appfwprofile_safeobject_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Decide which donor node to steal from. This is a policy implementation. I.e., in the future, additional policies could be considered. At that time, this method should be overridden in a sub-class, or a policy object ought to implement this algorithm. Current policy: 1) If possible, a stealer node that is the zone n-ary in the finalCluster steals from the zone n-ary in the currentCluster in the same zone. 2) If there are no partition-stores to steal in the same zone (i.e., this is the "zone expansion" use case), then a differnt policy must be used. The stealer node that is the zone n-ary in the finalCluster determines which pre-existing zone in the currentCluster hosts the primary partition id for the partition-store. The stealer then steals the zone n-ary from that pre-existing zone. This policy avoids unnecessary cross-zone moves and distributes the load of cross-zone moves approximately-uniformly across pre-existing zones. Other policies to consider: - For zone expansion, steal all partition-stores from one specific pre-existing zone. - Replace heuristic to approximately uniformly distribute load among existing zones to something more concrete (i.e. track steals from each pre-existing zone and forcibly balance them). - Select a single donor for all replicas in a new zone. This will require donor-based rebalancing to be run (at least for this specific part of the plan). This would reduce the number of donor-side scans of data. (But still send replication factor copies over the WAN.) This would require apparatus in the RebalanceController to work. - Set up some sort of chain-replication in which a single stealer in the new zone steals some replica from a pre-exising zone, and then other n-aries in the new zone steal from the single cross-zone stealer in the zone. This would require apparatus in the RebalanceController to work. @param currentSRP @param finalSRP @param stealerZoneId @param stealerNodeId @param stealerPartitionId @return the node id of the donor for this partition Id.
[ "protected int getDonorId(StoreRoutingPlan currentSRP,\n StoreRoutingPlan finalSRP,\n int stealerZoneId,\n int stealerNodeId,\n int stealerPartitionId) {\n int stealerZoneNAry = finalSRP.getZoneNaryForNodesPartition(stealerZoneId,\n stealerNodeId,\n stealerPartitionId);\n\n int donorZoneId;\n if(currentSRP.zoneNAryExists(stealerZoneId, stealerZoneNAry, stealerPartitionId)) {\n // Steal from local n-ary (since one exists).\n donorZoneId = stealerZoneId;\n } else {\n // Steal from zone that hosts primary partition Id.\n int currentMasterNodeId = currentSRP.getNodeIdForPartitionId(stealerPartitionId);\n donorZoneId = currentCluster.getNodeById(currentMasterNodeId).getZoneId();\n }\n\n return currentSRP.getNodeIdForZoneNary(donorZoneId, stealerZoneNAry, stealerPartitionId);\n\n }" ]
[ "public boolean evaluate(Object feature) {\n\t\t// Checks to ensure that the attribute has been set\n\t\tif (attribute == null) {\n\t\t\treturn false;\n\t\t}\n\t\t// Note that this converts the attribute to a string\n\t\t// for comparison. Unlike the math or geometry filters, which\n\t\t// require specific types to function correctly, this filter\n\t\t// using the mandatory string representation in Java\n\t\t// Of course, this does not guarantee a meaningful result, but it\n\t\t// does guarantee a valid result.\n\t\t// LOGGER.finest(\"pattern: \" + pattern);\n\t\t// LOGGER.finest(\"string: \" + attribute.getValue(feature));\n\t\t// return attribute.getValue(feature).toString().matches(pattern);\n\t\tObject value = attribute.evaluate(feature);\n\n\t\tif (null == value) {\n\t\t\treturn false;\n\t\t}\n\n\t\tMatcher matcher = getMatcher();\n\t\tmatcher.reset(value.toString());\n\n\t\treturn matcher.matches();\n\t}", "protected String sp_createSequenceQuery(String sequenceName, long maxKey)\r\n {\r\n return \"insert into \" + SEQ_TABLE_NAME + \" (\"\r\n + SEQ_NAME_STRING + \",\" + SEQ_ID_STRING +\r\n \") values ('\" + sequenceName + \"',\" + maxKey + \")\";\r\n }", "public void put(final String key, final Object value) {\n if (TASK_DIRECTORY_KEY.equals(key) && this.values.keySet().contains(TASK_DIRECTORY_KEY)) {\n // ensure that no one overwrites the task directory\n throw new IllegalArgumentException(\"Invalid key: \" + key);\n }\n\n if (value == null) {\n throw new IllegalArgumentException(\n \"A null value was attempted to be put into the values object under key: \" + key);\n }\n this.values.put(key, value);\n }", "public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {\n\t\tLOGGER.debug(\"Running OnBrowserCreatedPlugins...\");\n\t\tcounters.get(OnBrowserCreatedPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {\n\t\t\tif (plugin instanceof OnBrowserCreatedPlugin) {\n\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\ttry {\n\t\t\t\t\t((OnBrowserCreatedPlugin) plugin)\n\t\t\t\t\t\t\t.onBrowserCreated(newBrowser);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldResponse(fromPlayer, yielded);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield response to listener\", t);\n }\n }\n }", "private static long scanForLocSig(FileChannel channel) throws IOException {\n\n channel.position(0);\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long end = channel.size();\n while (channel.position() <= end) {\n\n read(bb, channel);\n\n int bufferPos = 0;\n while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the size of the pattern is static\n // b) the pattern is static and has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Outer switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid local file record\n long startLocRecord = channel.position() - bb.limit() + bufferPos;\n long currentPos = channel.position();\n if (validateLocalFileRecord(channel, startLocRecord, -1)) {\n return startLocRecord;\n }\n // Restore position in case it shifted\n channel.position(currentPos);\n\n // wasn't a valid local file record; continue scan\n bufferPos += 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos + patternPos) - Byte.MIN_VALUE;\n bufferPos += LOC_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos += 4;\n }\n }\n }\n\n return -1;\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}", "protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{\r\n\t\tconnectionHandle.setOriginatingPartition(this);\r\n\t\t// assume success to avoid racing where we insert an item in a queue and having that item immediately\r\n\t\t// taken and closed off thus decrementing the created connection count.\r\n\t\tupdateCreatedConnections(1);\r\n\t\tif (!this.disableTracking){\r\n\t\t\ttrackConnectionFinalizer(connectionHandle); \r\n\t\t}\r\n\t\t\r\n\t\t// the instant the following line is executed, consumers can start making use of this \r\n\t\t// connection.\r\n\t\tif (!this.freeConnections.offer(connectionHandle)){\r\n\t\t\t// we failed. rollback.\r\n\t\t\tupdateCreatedConnections(-1); // compensate our createdConnection count.\r\n\t\t\t\r\n\t\t\tif (!this.disableTracking){\r\n\t\t\t\tthis.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection());\r\n\t\t\t}\r\n\t\t\t// terminate the internal handle.\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}", "public static List<String> getArgumentNames(MethodCallExpression methodCall) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n Expression arguments = methodCall.getArguments();\r\n List<Expression> argExpressions = null;\r\n if (arguments instanceof ArrayExpression) {\r\n argExpressions = ((ArrayExpression) arguments).getExpressions();\r\n } else if (arguments instanceof ListExpression) {\r\n argExpressions = ((ListExpression) arguments).getExpressions();\r\n } else if (arguments instanceof TupleExpression) {\r\n argExpressions = ((TupleExpression) arguments).getExpressions();\r\n } else {\r\n LOG.warn(\"getArgumentNames arguments is not an expected type\");\r\n }\r\n\r\n if (argExpressions != null) {\r\n for (Expression exp : argExpressions) {\r\n if (exp instanceof VariableExpression) {\r\n result.add(((VariableExpression) exp).getName());\r\n }\r\n }\r\n }\r\n return result;\r\n }" ]
Performs a Versioned put operation with the specified composite request object @param requestWrapper Composite request object containing the key and the versioned object @return Version of the value for the successful put @throws ObsoleteVersionException
[ "public Version putVersionedWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper)\n throws ObsoleteVersionException {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {\n try {\n String keyHexString = \"\";\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"PUT_VERSION\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n keyHexString);\n }\n store.put(requestWrapper);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"PUT_VERSION\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n return requestWrapper.getValue().getVersion();\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during put [ \" + e.getMessage()\n + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n }" ]
[ "private TableAlias getTableAliasForPath(String aPath, List hintClasses)\r\n {\r\n return (TableAlias) m_pathToAlias.get(buildAliasKey(aPath, hintClasses));\r\n }", "private float MIN(float first, float second, float third) {\r\n\r\n float min = Integer.MAX_VALUE;\r\n if (first < min) {\r\n min = first;\r\n }\r\n if (second < min) {\r\n min = second;\r\n }\r\n if (third < min) {\r\n min = third;\r\n }\r\n return min;\r\n }", "private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }", "public static base_response delete(nitro_service client, String labelname) throws Exception {\n\t\tdnspolicylabel deleteresource = new dnspolicylabel();\n\t\tdeleteresource.labelname = labelname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "void setState(final WidgetState.State state) {\n Log.d(TAG, \"setState(%s): state is %s, setting to %s\", mWidget.getName(), mState, state);\n if (state != mState) {\n final WidgetState.State nextState = getNextState(state);\n Log.d(TAG, \"setState(%s): next state '%s'\", mWidget.getName(), nextState);\n if (nextState != mState) {\n Log.d(TAG, \"setState(%s): setting state to '%s'\", mWidget.getName(), nextState);\n setCurrentState(false);\n mState = nextState;\n setCurrentState(true);\n }\n }\n }", "public boolean isExit() {\n if (currentRow > finalRow) { //request new block of work\n String newBlock = this.sendRequestSync(\"this/request/block\");\n LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0);\n\n if (newBlock.contains(\"exit\")) {\n getExitFlag().set(true);\n makeReport(true);\n return true;\n } else {\n block.buildFromResponse(newBlock);\n }\n\n currentRow = block.getStart();\n finalRow = block.getStop();\n } else { //report the number of lines written\n makeReport(false);\n\n if (exit.get()) {\n getExitFlag().set(true);\n return true;\n }\n }\n\n return false;\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 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}", "private void readAssignments(Project plannerProject)\n {\n Allocations allocations = plannerProject.getAllocations();\n List<Allocation> allocationList = allocations.getAllocation();\n Set<Task> tasksWithAssignments = new HashSet<Task>();\n\n for (Allocation allocation : allocationList)\n {\n Integer taskID = getInteger(allocation.getTaskId());\n Integer resourceID = getInteger(allocation.getResourceId());\n Integer units = getInteger(allocation.getUnits());\n\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n\n if (task != null && resource != null)\n {\n Duration work = task.getWork();\n int percentComplete = NumberHelper.getInt(task.getPercentageComplete());\n\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setUnits(units);\n assignment.setWork(work);\n\n if (percentComplete != 0)\n {\n Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());\n assignment.setActualWork(actualWork);\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n else\n {\n assignment.setRemainingWork(work);\n }\n\n assignment.setStart(task.getStart());\n assignment.setFinish(task.getFinish());\n\n tasksWithAssignments.add(task);\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n\n //\n // Adjust work per assignment for tasks with multiple assignments\n //\n for (Task task : tasksWithAssignments)\n {\n List<ResourceAssignment> assignments = task.getResourceAssignments();\n if (assignments.size() > 1)\n {\n double maxUnits = 0;\n for (ResourceAssignment assignment : assignments)\n {\n maxUnits += assignment.getUnits().doubleValue();\n }\n\n for (ResourceAssignment assignment : assignments)\n {\n Duration work = assignment.getWork();\n double factor = assignment.getUnits().doubleValue() / maxUnits;\n\n work = Duration.getInstance(work.getDuration() * factor, work.getUnits());\n assignment.setWork(work);\n Duration actualWork = assignment.getActualWork();\n if (actualWork != null)\n {\n actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits());\n assignment.setActualWork(actualWork);\n }\n\n Duration remainingWork = assignment.getRemainingWork();\n if (remainingWork != null)\n {\n remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits());\n assignment.setRemainingWork(remainingWork);\n }\n }\n }\n }\n }" ]
Reads numBytes bytes, and returns the corresponding string
[ "public String read(int numBytes) throws IOException {\n Preconditions.checkArgument(numBytes >= 0);\n Preconditions.checkArgument(numBytes <= MAX_ALLOWABLE_BUFFER_SIZE);\n int numBytesRemaining = numBytes;\n // first read whatever we need from our buffer\n if (!isReadBufferEmpty()) {\n int length = Math.min(end - offset, numBytesRemaining);\n copyToStrBuffer(buffer, offset, length);\n offset += length;\n numBytesRemaining -= length;\n }\n\n // next read the remaining chars directly into our strBuffer\n if (numBytesRemaining > 0) {\n readAmountToStrBuffer(numBytesRemaining);\n }\n\n if (strBufferIndex > 0 && strBuffer[strBufferIndex - 1] != LF) {\n // the last byte doesn't correspond to lf\n return readLine(false);\n }\n\n int strBufferLength = strBufferIndex;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strBufferLength, charset);\n }" ]
[ "@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }", "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 }", "public static final void decodeBuffer(byte[] data, byte encryptionCode)\n {\n for (int i = 0; i < data.length; i++)\n {\n data[i] = (byte) (data[i] ^ encryptionCode);\n }\n }", "public boolean classifyDocumentStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n int blankLines = 0;\r\n while ((line = is.readLine()) != null) {\r\n if (line.trim().equals(\"\")) {\r\n \t ++blankLines;\r\n \t if (blankLines > 3) {\r\n \t\t return false;\r\n \t } else if (blankLines > 2) {\r\n\t\t\t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n\t \t classifyAndWriteAnswers(documents, readerWriter);\r\n \t\t text = \"\";\r\n \t } else {\r\n \t\t text += sentence + eol;\r\n \t }\r\n } else {\r\n \t text += line + eol;\r\n \t blankLines = 0;\r\n }\r\n }\r\n // Classify last document before input stream end\r\n if (text.trim() != \"\") {\r\n ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n \t classifyAndWriteAnswers(documents, readerWriter);\r\n }\r\n return (line == null); // reached eol\r\n }", "public static void log(String label, byte[] data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(ByteArrayHelper.hexdump(data, true));\n LOG.flush();\n }\n }", "public static lbvserver_rewritepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_rewritepolicy_binding obj = new lbvserver_rewritepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_rewritepolicy_binding response[] = (lbvserver_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }", "public <X> X invokeOnInstance(Object instance, Object... parameters) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n final Map<Class<?>, Method> methods = this.methods;\n Method method = methods.get(instance.getClass());\n if (method == null) {\n // the same method may be written to the map twice, but that is ok\n // lookupMethod is very slow\n Method delegate = annotatedMethod.getJavaMember();\n method = SecurityActions.lookupMethod(instance.getClass(), delegate.getName(), delegate.getParameterTypes());\n SecurityActions.ensureAccessible(method);\n synchronized (this) {\n final Map<Class<?>, Method> newMethods = new HashMap<Class<?>, Method>(methods);\n newMethods.put(instance.getClass(), method);\n this.methods = WeldCollections.immutableMapView(newMethods);\n }\n }\n return cast(method.invoke(instance, parameters));\n }", "protected boolean hasContentType() {\n\n boolean result = false;\n if(this.request.getHeader(RestMessageHeaders.CONTENT_TYPE) != null) {\n result = true;\n } else {\n logger.error(\"Error when validating put request. Missing Content-Type header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Type header\");\n }\n return result;\n }" ]
Parses the provided file, using the given libraryPaths and sourcePaths as context. The libraries may be either jar files or references to directories containing class files. The sourcePaths must be a reference to the top level directory for sources (eg, for a file src/main/java/org/example/Foo.java, the source path would be src/main/java). The wildcard resolver provides a fallback for processing wildcard imports that the underlying parser was unable to resolve.
[ "public static List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths,\n Path sourceFile)\n {\n ASTParser parser = ASTParser.newParser(AST.JLS11);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n String fileName = sourceFile.getFileName().toString();\n parser.setUnitName(fileName);\n try\n {\n parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray());\n }\n catch (IOException e)\n {\n throw new ASTException(\"Failed to get source for file: \" + sourceFile.toString() + \" due to: \" + e.getMessage(), e);\n }\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n CompilationUnit cu = (CompilationUnit) parser.createAST(null);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString());\n cu.accept(visitor);\n return visitor.getJavaClassReferences();\n }" ]
[ "public static List<String> enableJMX(List<String> jvmArgs) {\n final String arg = \"-D\" + OPT_JMX_REMOTE;\n if (jvmArgs.contains(arg))\n return jvmArgs;\n final List<String> cmdLine2 = new ArrayList<>(jvmArgs);\n cmdLine2.add(arg);\n return cmdLine2;\n }", "private PersistentResourceXMLDescription getSimpleMapperParser() {\n if (version.equals(Version.VERSION_1_0)) {\n return simpleMapperParser_1_0;\n } else if (version.equals(Version.VERSION_1_1)) {\n return simpleMapperParser_1_1;\n }\n return simpleMapperParser;\n }", "protected byte[] getBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache() || (cached = valueCache.lowerBytes) == null) {\n\t\t\tvalueCache.lowerBytes = cached = getBytesImpl(true);\n\t\t}\n\t\treturn cached;\n\t}", "public static cacheselector[] get(nitro_service service, options option) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tcacheselector[] response = (cacheselector[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }", "public static String getTemplateAsString(String fileName) throws IOException {\n // in .jar file\n String fNameJar = getFileNameInPath(fileName);\n InputStream inStream = DomUtils.class.getResourceAsStream(\"/\"\n + fNameJar);\n if (inStream == null) {\n // try to find file normally\n File f = new File(fileName);\n if (f.exists()) {\n inStream = new FileInputStream(f);\n } else {\n throw new IOException(\"Cannot find \" + fileName + \" or \"\n + fNameJar);\n }\n }\n\n BufferedReader bufferedReader = new BufferedReader(\n new InputStreamReader(inStream));\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line).append(\"\\n\");\n }\n\n bufferedReader.close();\n return stringBuilder.toString();\n }", "static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }", "public final boolean hasReturnValues()\r\n {\r\n if (this.hasReturnValue())\r\n {\r\n return true;\r\n }\r\n else\r\n {\r\n // TODO: We may be able to 'pre-calculate' the results\r\n // of this loop by just checking arguments as they are added\r\n // The only problem is that the 'isReturnedbyProcedure' property\r\n // can be modified once the argument is added to this procedure.\r\n // If that occurs, then 'pre-calculated' results will be inacccurate.\r\n Iterator iter = this.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "public static double Sin(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x - (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n double sign = 1;\r\n int factS = 5;\r\n double result = x - mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }" ]
Return the trimmed source line corresponding to the specified AST node @param node - the Groovy AST node
[ "protected String sourceLineTrimmed(ASTNode node) {\r\n return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }" ]
[ "private List<MapRow> sort(List<MapRow> rows, final String attribute)\n {\n Collections.sort(rows, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n String value1 = o1.getString(attribute);\n String value2 = o2.getString(attribute);\n return value1.compareTo(value2);\n }\n });\n return rows;\n }", "@Pure\n\tpublic static <T> Iterable<T> filterNull(Iterable<T> unfiltered) {\n\t\treturn Iterables.filter(unfiltered, Predicates.notNull());\n\t}", "@PostConstruct\n public void checkUniqueSchemes() {\n Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();\n\n for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {\n schemeToPluginMap.put(plugin.getUriScheme(), plugin);\n }\n\n StringBuilder violations = new StringBuilder();\n for (String scheme: schemeToPluginMap.keySet()) {\n final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);\n if (plugins.size() > 1) {\n violations.append(\"\\n\\n* \").append(\"There are has multiple \")\n .append(ConfigFileLoaderPlugin.class.getSimpleName())\n .append(\" plugins that support the scheme: '\").append(scheme).append('\\'')\n .append(\":\\n\\t\").append(plugins);\n }\n }\n\n if (violations.length() > 0) {\n throw new IllegalStateException(violations.toString());\n }\n }", "public static Module unserializeModule(final String module) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(module, Module.class);\n }", "public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags)\n {\n Map<Set<String>, Vertex> cache = getCache(event);\n Vertex vertex = cache.get(tags);\n if (vertex == null)\n {\n TagSetModel model = create();\n model.setTags(tags);\n cache.put(tags, model.getElement());\n return model;\n }\n else\n {\n return frame(vertex);\n }\n }", "public void pause()\n {\n if (mAudioListener != null)\n {\n int sourceId = getSourceId();\n if (sourceId != GvrAudioEngine.INVALID_ID)\n {\n mAudioListener.getAudioEngine().pauseSound(sourceId);\n }\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 }", "public String getResourceFilename() {\n switch (resourceType) {\n case ANDROID_ASSETS:\n return assetPath\n .substring(assetPath.lastIndexOf(File.separator) + 1);\n\n case ANDROID_RESOURCE:\n return resourceFilePath.substring(\n resourceFilePath.lastIndexOf(File.separator) + 1);\n\n case LINUX_FILESYSTEM:\n return filePath.substring(filePath.lastIndexOf(File.separator) + 1);\n\n case NETWORK:\n return url.getPath().substring(url.getPath().lastIndexOf(\"/\") + 1);\n\n case INPUT_STREAM:\n return inputStreamName;\n\n default:\n return null;\n }\n }", "public BoundRequestBuilder createRequest()\n throws HttpRequestCreateException {\n BoundRequestBuilder builder = null;\n\n getLogger().debug(\"AHC completeUrl \" + requestUrl);\n\n try {\n\n switch (httpMethod) {\n case GET:\n builder = client.prepareGet(requestUrl);\n break;\n case POST:\n builder = client.preparePost(requestUrl);\n break;\n case PUT:\n builder = client.preparePut(requestUrl);\n break;\n case HEAD:\n builder = client.prepareHead(requestUrl);\n break;\n case OPTIONS:\n builder = client.prepareOptions(requestUrl);\n break;\n case DELETE:\n builder = client.prepareDelete(requestUrl);\n break;\n default:\n break;\n }\n\n PcHttpUtils.addHeaders(builder, this.httpHeaderMap);\n if (!Strings.isNullOrEmpty(postData)) {\n builder.setBody(postData);\n String charset = \"\";\n if (null!=this.httpHeaderMap) {\n charset = this.httpHeaderMap.get(\"charset\");\n }\n if(!Strings.isNullOrEmpty(charset)) {\n builder.setBodyEncoding(charset);\n }\n }\n\n } catch (Exception t) {\n throw new HttpRequestCreateException(\n \"Error in creating request in Httpworker. \"\n + \" If BoundRequestBuilder is null. Then fail to create.\",\n t);\n }\n\n return builder;\n\n }" ]
Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd, while reporting the progress to a ProgressListener. @param output the stream to where the file will be written. @param rangeStart the byte offset at which to start the download. @param rangeEnd the byte offset at which to stop the download. @param listener a listener for monitoring the download's progress.
[ "public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n if (rangeEnd > 0) {\n request.addHeader(\"Range\", String.format(\"bytes=%s-%s\", Long.toString(rangeStart),\n Long.toString(rangeEnd)));\n } else {\n request.addHeader(\"Range\", String.format(\"bytes=%s-\", Long.toString(rangeStart)));\n }\n\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n } finally {\n response.disconnect();\n }\n }" ]
[ "public CollectionRequest<Project> findByTeam(String team) {\n \n String path = String.format(\"/teams/%s/projects\", team);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static Optional<Variable> freshBuilder(SourceBuilder code, Datatype datatype) {\n if (!datatype.getBuilderFactory().isPresent()) {\n return Optional.empty();\n }\n return Optional.of(code.scope().computeIfAbsent(Declaration.FRESH_BUILDER, () -> {\n Variable defaults = new Variable(\"defaults\");\n code.addLine(\"%s %s = %s;\",\n datatype.getGeneratedBuilder(),\n defaults,\n datatype.getBuilderFactory().get()\n .newBuilder(datatype.getBuilder(), TypeInference.INFERRED_TYPES));\n return defaults;\n }));\n }", "public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "private int deleteSegments(Log log, List<LogSegment> segments) {\n int total = 0;\n for (LogSegment segment : segments) {\n boolean deleted = false;\n try {\n try {\n segment.getMessageSet().close();\n } catch (IOException e) {\n logger.warn(e.getMessage(), e);\n }\n if (!segment.getFile().delete()) {\n deleted = true;\n } else {\n total += 1;\n }\n } finally {\n logger.warn(String.format(\"DELETE_LOG[%s] %s => %s\", log.name, segment.getFile().getAbsolutePath(),\n deleted));\n }\n }\n return total;\n }", "public int getLeadingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong front = network ? getDivision(0).getMaxValue() : 0;\n\t\tint prefixLen = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != front) {\n\t\t\t\treturn prefixLen + seg.getLeadingBitCount(network);\n\t\t\t}\n\t\t\tprefixLen += seg.getBitCount();\n\t\t}\n\t\treturn prefixLen;\n\t}", "public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {\n\t\tdocument.writeElement(\"vml:shape\", asChild);\n\t\tPoint p = (Point) o;\n\t\tString adj = document.getFormatter().format(p.getX()) + \",\"\n\t\t\t\t+ document.getFormatter().format(p.getY());\n\t\tdocument.writeAttribute(\"adj\", adj);\n\t}", "@Inline(value = \"$1.put($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\treturn map.put(entry.getKey(), entry.getValue());\n\t}", "public void showTrajectoryAndSpline(){\n\t\t\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[rotatedTrajectory.size()];\n\t\t double[] yData = new double[rotatedTrajectory.size()];\n\t\t for(int i = 0; i < rotatedTrajectory.size(); i++){\n\t\t \txData[i] = rotatedTrajectory.get(i).x;\n\t\t \tyData[i] = rotatedTrajectory.get(i).y;\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(\"Spline+Track\", \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\t \n\t\t //Add spline support points\n\t\t double[] subxData = new double[splineSupportPoints.size()];\n\t\t double[] subyData = new double[splineSupportPoints.size()];\n\t\t \n\t\t for(int i = 0; i < splineSupportPoints.size(); i++){\n\t\t \tsubxData[i] = splineSupportPoints.get(i).x;\n\t\t \tsubyData[i] = splineSupportPoints.get(i).y;\n\t\t }\n\t\t Series s = chart.addSeries(\"Spline Support Points\", subxData, subyData);\n\t\t s.setLineStyle(SeriesLineStyle.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t //ADd spline points\n\t\t int numberInterpolatedPointsPerSegment = 20;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] sxData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t \n\t\t double[] syData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/numberInterpolatedPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < numberInterpolatedPointsPerSegment; j++){\n\n\t\t \t\tsxData[i*numberInterpolatedPointsPerSegment+j] = x;\n\t\t \t\tsyData[i*numberInterpolatedPointsPerSegment+j] = spline.value(x);\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t s = chart.addSeries(\"Spline\", sxData, syData);\n\t\t s.setLineStyle(SeriesLineStyle.DASH_DASH);\n\t\t s.setMarker(SeriesMarker.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t \n\t\t //Show it\n\t\t new SwingWrapper(chart).displayChart();\n\t\t} \n\t}" ]
Gets any previous versions of this file. Note that only users with premium accounts will be able to retrieve previous versions of their files. @return a list of previous file versions.
[ "public Collection<BoxFileVersion> getVersions() {\n URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n JsonArray entries = jsonObject.get(\"entries\").asArray();\n Collection<BoxFileVersion> versions = new ArrayList<BoxFileVersion>();\n for (JsonValue entry : entries) {\n versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID()));\n }\n\n return versions;\n }" ]
[ "public static Method getSAMMethod(Class<?> c) {\n // SAM = single public abstract method\n // if the class is not abstract there is no abstract method\n if (!Modifier.isAbstract(c.getModifiers())) return null;\n if (c.isInterface()) {\n Method[] methods = c.getMethods();\n // res stores the first found abstract method\n Method res = null;\n for (Method mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (mi.getAnnotation(Traits.Implemented.class)!=null) continue;\n try {\n Object.class.getMethod(mi.getName(), mi.getParameterTypes());\n continue;\n } catch (NoSuchMethodException e) {/*ignore*/}\n\n // we have two methods, so no SAM\n if (res!=null) return null;\n res = mi;\n }\n return res;\n\n } else {\n\n LinkedList<Method> methods = new LinkedList();\n getAbstractMethods(c, methods);\n if (methods.isEmpty()) return null;\n ListIterator<Method> it = methods.listIterator();\n while (it.hasNext()) {\n Method m = it.next();\n if (hasUsableImplementation(c, m)) it.remove();\n }\n return getSingleNonDuplicateMethod(methods);\n }\n }", "public static CmsSearchConfigurationSorting create(\n final String sortParam,\n final List<I_CmsSearchConfigurationSortOption> options,\n final I_CmsSearchConfigurationSortOption defaultOption) {\n\n return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption)\n ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption)\n : null;\n }", "@Override\n\tpublic void add(String headerName, String headerValue) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\tif (headerValues == null) {\n\t\t\theaderValues = new LinkedList<String>();\n\t\t\tthis.headers.put(headerName, headerValues);\n\t\t}\n\t\theaderValues.add(headerValue);\n\t}", "public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }", "public boolean isIPv4Mapped() {\n\t\t//::ffff:x:x/96 indicates IPv6 address mapped to IPv4\n\t\tif(getSegment(5).matches(IPv6Address.MAX_VALUE_PER_SEGMENT)) {\n\t\t\tfor(int i = 0; i < 5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public ConnectionRepository readConnectionRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readConnectionRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository from \" + inst, e);\r\n }\r\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 }", "public void addChannel(String boneName, GVRAnimationChannel channel)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n mBoneChannels[boneId] = channel;\n mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);\n Log.d(\"BONE\", \"Adding animation channel %d %s \", boneId, boneName);\n }\n }" ]
Arbitrarily resolve the inconsistency by choosing the first object if there is one. @param values The list of objects @return A single value, if one exists, taken from the input list.
[ "public List<T> resolveConflicts(List<T> values) {\n if(values.size() > 1)\n return values;\n else\n return Collections.singletonList(values.get(0));\n }" ]
[ "public Integer getInteger(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "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 static String getOjbClassName(ResultSet rs)\r\n {\r\n try\r\n {\r\n return rs.getString(OJB_CLASS_COLUMN);\r\n }\r\n catch (SQLException e)\r\n {\r\n return null;\r\n }\r\n }", "public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}", "public Scale getNearestScale(\n final ZoomLevels zoomLevels,\n final double tolerance,\n final ZoomLevelSnapStrategy zoomLevelSnapStrategy,\n final boolean geodetic,\n final Rectangle paintArea,\n final double dpi) {\n\n final Scale scale = getScale(paintArea, dpi);\n final Scale correctedScale;\n final double scaleRatio;\n if (geodetic) {\n final double currentScaleDenominator = scale.getGeodeticDenominator(\n getProjection(), dpi, getCenter());\n scaleRatio = scale.getDenominator(dpi) / currentScaleDenominator;\n correctedScale = scale.toResolution(scale.getResolution() / scaleRatio);\n } else {\n scaleRatio = 1;\n correctedScale = scale;\n }\n\n DistanceUnit unit = DistanceUnit.fromProjection(getProjection());\n final ZoomLevelSnapStrategy.SearchResult result = zoomLevelSnapStrategy.search(\n correctedScale, tolerance, zoomLevels);\n final Scale newScale;\n\n if (geodetic) {\n newScale = new Scale(\n result.getScale(unit).getDenominator(PDF_DPI) * scaleRatio,\n getProjection(), dpi);\n } else {\n newScale = result.getScale(unit);\n }\n\n return newScale;\n }", "public final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }", "public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }", "public QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}", "public static final String printResourceType(ResourceType value)\n {\n return (Integer.toString(value == null ? ResourceType.WORK.getValue() : value.getValue()));\n }" ]
Return all tenors for which data exists. @return The tenors in months.
[ "public int[] getTenors() {\r\n\t\tSet<Integer> setTenors\t= new HashSet<>();\r\n\r\n\t\tfor(int moneyness : getGridNodesPerMoneyness().keySet()) {\r\n\t\t\tsetTenors.addAll(Arrays.asList((IntStream.of(keyMap.get(moneyness)[1]).boxed().toArray(Integer[]::new))));\r\n\t\t}\r\n\t\treturn setTenors.stream().sorted().mapToInt(Integer::intValue).toArray();\r\n\t}" ]
[ "public Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }", "void forcedUndeployScan() {\n\n if (acquireScanLock()) {\n try {\n ROOT_LOGGER.tracef(\"Performing a post-boot forced undeploy scan for scan directory %s\", deploymentDir.getAbsolutePath());\n ScanContext scanContext = new ScanContext(deploymentOperations);\n\n // Add remove actions to the plan for anything we count as\n // deployed that we didn't find on the scan\n for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) {\n // remove successful deployment and left will be removed\n if (scanContext.registeredDeployments.containsKey(missing.getKey())) {\n scanContext.registeredDeployments.remove(missing.getKey());\n }\n }\n Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet());\n scannedDeployments.removeAll(scanContext.persistentDeployments);\n\n List<ScannerTask> scannerTasks = scanContext.scannerTasks;\n for (String toUndeploy : scannedDeployments) {\n scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true));\n }\n try {\n executeScannerTasks(scannerTasks, deploymentOperations, true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n\n ROOT_LOGGER.tracef(\"Forced undeploy scan complete\");\n } catch (Exception e) {\n ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath());\n } finally {\n releaseScanLock();\n }\n }\n }", "public static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) {\n Map<String, List<String>> ret = new HashMap<String, List<String>>();\n for (String topic : topics) {\n List<String> partList = new ArrayList<String>();\n List<String> brokers = getChildrenParentMayNotExist(zkClient, BrokerTopicsPath + \"/\" + topic);\n if (brokers != null) {\n for (String broker : brokers) {\n final String parts = readData(zkClient, BrokerTopicsPath + \"/\" + topic + \"/\" + broker);\n int nParts = Integer.parseInt(parts);\n for (int i = 0; i < nParts; i++) {\n partList.add(broker + \"-\" + i);\n }\n }\n }\n Collections.sort(partList);\n ret.put(topic, partList);\n }\n return ret;\n }", "public static Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }", "public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }", "public boolean checkXpathStartsWithXpathEventableCondition(Document dom,\n\t\t\tEventableCondition eventableCondition, String xpath) throws XPathExpressionException {\n\t\tif (eventableCondition == null || Strings\n\t\t\t\t.isNullOrEmpty(eventableCondition.getInXPath())) {\n\t\t\tthrow new CrawljaxException(\"Eventable has no XPath condition\");\n\t\t}\n\t\tList<String> expressions =\n\t\t\t\tXPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());\n\n\t\treturn checkXPathUnderXPaths(xpath, expressions);\n\t}", "private void readTasks(Document cdp)\n {\n //\n // Sort the projects into the correct order\n //\n List<Project> projects = new ArrayList<Project>(cdp.getProjects().getProject());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(projects, new Comparator<Project>()\n {\n @Override public int compare(Project o1, Project o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n for (Project project : cdp.getProjects().getProject())\n {\n readProject(project);\n }\n }", "public void stop()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"stopping audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().stopSound(getSourceId());\n }\n }", "public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }" ]
Append the html-code to finish a html mail message to the given buffer. @param buffer The StringBuffer to add the html code to.
[ "protected void appenHtmlFooter(StringBuffer buffer) {\n\n if (m_configuredFooter != null) {\n buffer.append(m_configuredFooter);\n } else {\n buffer.append(\" </body>\\r\\n\" + \"</html>\");\n }\n }" ]
[ "public void linkMtoN(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkMtoN(true, obj, cod, referencedObjects, insert);\n }", "public Capsule newCapsule(String mode, Path wrappedJar) {\n final String oldMode = properties.getProperty(PROP_MODE);\n final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();\n Thread.currentThread().setContextClassLoader(capsuleClass.getClassLoader());\n try {\n setProperty(PROP_MODE, mode);\n\n final Constructor<?> ctor = accessible(capsuleClass.getDeclaredConstructor(Path.class));\n final Object capsule = ctor.newInstance(jarFile);\n\n if (wrappedJar != null) {\n final Method setTarget = accessible(capsuleClass.getDeclaredMethod(\"setTarget\", Path.class));\n setTarget.invoke(capsule, wrappedJar);\n }\n\n return wrap(capsule);\n } catch (ReflectiveOperationException e) {\n throw new RuntimeException(\"Could not create capsule instance.\", e);\n } finally {\n setProperty(PROP_MODE, oldMode);\n Thread.currentThread().setContextClassLoader(oldCl);\n }\n }", "public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public void reset(int profileId, String clientUUID) throws Exception {\n PreparedStatement statement = null;\n\n // TODO: need a better way to do this than brute force.. but the iterative approach is too slow\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n // first remove all enabled overrides with this client uuid\n String queryString = \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n statement.close();\n\n // clean up request response table for this uuid\n queryString = \"UPDATE \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" SET \" + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + \"=?, \"\n + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + \"=?, \"\n + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + \"=-1, \"\n + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + \"=0, \"\n + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + \"=0 \"\n + \"WHERE \" + Constants.GENERIC_CLIENT_UUID + \"=? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, \"\");\n statement.setString(2, \"\");\n statement.setString(3, clientUUID);\n statement.setInt(4, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n this.updateActive(profileId, clientUUID, false);\n }", "private void loadLocalizationFromXmlBundle(Locale locale) {\n\n CmsXmlContentValueSequence messages = m_xmlBundle.getValueSequence(\"Message\", locale);\n SortedProperties props = new SortedProperties();\n if (null != messages) {\n for (I_CmsXmlContentValue msg : messages.getValues()) {\n String msgpath = msg.getPath();\n props.put(\n m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", locale),\n m_xmlBundle.getStringValue(m_cms, msgpath + \"/Value\", locale));\n }\n }\n m_localizations.put(locale, props);\n }", "protected Element createTextElement(String data, float width)\n {\n Element el = createTextElement(width);\n Text text = doc.createTextNode(data);\n el.appendChild(text);\n return el;\n }", "public Set<DeviceAnnouncement> findUnreachablePlayers() {\n ensureRunning();\n Set<DeviceAnnouncement> result = new HashSet<DeviceAnnouncement>();\n for (DeviceAnnouncement candidate: DeviceFinder.getInstance().getCurrentDevices()) {\n if (!Util.sameNetwork(matchedAddress.getNetworkPrefixLength(), matchedAddress.getAddress(), candidate.getAddress())) {\n result.add(candidate);\n }\n }\n return Collections.unmodifiableSet(result);\n }", "public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) {\n\n\t\t/*\n\t\t * Cacluate average log returns\n\t\t */\n\t\tdouble[] averageLogReturn = new double[12];\n\t\tArrays.fill(averageLogReturn, 0.0);\n\t\tfor(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){\n\n\t\t\tint month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12));\n\n\t\t\tdouble logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]);\n\t\t\taverageLogReturn[month] += logReturn/numberOfYearsToAverage;\n\t\t}\n\n\t\t/*\n\t\t * Normalize\n\t\t */\n\t\tdouble sum = 0.0;\n\t\tfor(int index = 0; index < averageLogReturn.length; index++){\n\t\t\tsum += averageLogReturn[index];\n\t\t}\n\t\tdouble averageSeasonal = sum / averageLogReturn.length;\n\n\t\tdouble[] seasonalAdjustments = new double[averageLogReturn.length];\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal;\n\t\t}\n\n\t\t// Annualize seasonal adjustments\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = seasonalAdjustments[index] * 12;\n\t\t}\n\n\t\treturn seasonalAdjustments;\n\t}", "public static ComplexNumber Function2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) {\n\n double X = x * Math.cos(orientation) + y * Math.sin(orientation);\n double Y = -x * Math.sin(orientation) + y * Math.cos(orientation);\n\n double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance)));\n double real = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset);\n double imaginary = Math.sin(2 * Math.PI * (X / wavelength) + phaseOffset);\n\n return new ComplexNumber(envelope * real, envelope * imaginary);\n }" ]
Plots the trajectory @param title Title of the plot @param t Trajectory to be plotted
[ "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}" ]
[ "void stop() {\n try {\n dm.stop(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to stop \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory, e);\n }\n declarationsFiles.clear();\n declarationRegistrationManager.unregisterAll();\n }", "public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private PoolingHttpClientConnectionManager createConnectionMgr() {\n PoolingHttpClientConnectionManager connectionMgr;\n\n // prepare SSLContext\n SSLContext sslContext = buildSslContext();\n ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();\n // we allow to disable host name verification against CA certificate,\n // notice: in general this is insecure and should be avoided in production,\n // (this type of configuration is useful for development purposes)\n boolean noHostVerification = false;\n LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(\n sslContext,\n noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()\n );\n Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()\n .register(\"http\", plainsf)\n .register(\"https\", sslsf)\n .build();\n connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,\n null, connectionPoolTimeToLive, TimeUnit.SECONDS);\n\n connectionMgr.setMaxTotal(maxConnectionsTotal);\n connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);\n HttpHost localhost = new HttpHost(\"localhost\", 80);\n connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);\n return connectionMgr;\n }", "@Override\n public PersistentResourceXMLDescription getParserDescription() {\n return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())\n .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)\n .addAttribute(ElytronDefinition.INITIAL_PROVIDERS)\n .addAttribute(ElytronDefinition.FINAL_PROVIDERS)\n .addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)\n .addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))\n .addChild(getAuthenticationClientParser())\n .addChild(getProviderParser())\n .addChild(getAuditLoggingParser())\n .addChild(getDomainParser())\n .addChild(getRealmParser())\n .addChild(getCredentialSecurityFactoryParser())\n .addChild(getMapperParser())\n .addChild(getHttpParser())\n .addChild(getSaslParser())\n .addChild(getTlsParser())\n .addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))\n .addChild(getDirContextParser())\n .addChild(getPolicyParser())\n .build();\n }", "private void setBelief(String bName, Object value) {\n introspector.setBeliefValue(this.getLocalName(), bName, value, null);\n }", "void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }", "public void setFirstOccurence(int min, int max) throws ParseException {\n if (fullCondition == null) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n firstOptional = true;\n }\n firstMinimumOccurence = Math.max(1, min);\n firstMaximumOccurence = max;\n } else {\n throw new ParseException(\"fullCondition already generated\");\n }\n }", "public static appfwprofile_xmlvalidationurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_xmlvalidationurl_binding obj = new appfwprofile_xmlvalidationurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_xmlvalidationurl_binding response[] = (appfwprofile_xmlvalidationurl_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Integer getVarDataKey(FieldType type)\n {\n Integer result = null;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getVarDataKey();\n }\n return result;\n }" ]
Use this API to add nsacl6.
[ "public static base_response add(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 addresource = new nsacl6();\n\t\taddresource.acl6name = resource.acl6name;\n\t\taddresource.acl6action = resource.acl6action;\n\t\taddresource.td = resource.td;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.ttl = resource.ttl;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.established = resource.established;\n\t\taddresource.icmptype = resource.icmptype;\n\t\taddresource.icmpcode = resource.icmpcode;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public static Object getFieldValue(Object object, String fieldName) {\n try {\n return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }", "private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)\n {\n try\n {\n try (ZipFile zip = new ZipFile(archive))\n {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n \n while (entries.hasMoreElements())\n {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (filter.accept(name))\n discoveredFiles.add(name);\n }\n }\n }\n catch (IOException e)\n {\n throw new RuntimeException(\"Error handling file \" + archive, e);\n }\n }", "private Class getDynamicProxyClass(Class baseClass) {\r\n Class[] m_dynamicProxyClassInterfaces;\r\n if (foundInterfaces.containsKey(baseClass)) {\r\n m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);\r\n } else {\r\n m_dynamicProxyClassInterfaces = getInterfaces(baseClass);\r\n foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);\r\n }\r\n\r\n // return dynymic Proxy Class implementing all interfaces\r\n Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);\r\n return proxyClazz;\r\n }", "public void printInterceptorChain(InterceptorChain chain) {\n Iterator<Interceptor<? extends Message>> it = chain.iterator();\n String phase = \"\";\n StringBuilder builder = null;\n while (it.hasNext()) {\n Interceptor<? extends Message> interceptor = it.next();\n if (interceptor instanceof DemoInterceptor) {\n continue;\n }\n if (interceptor instanceof PhaseInterceptor) {\n PhaseInterceptor pi = (PhaseInterceptor)interceptor;\n if (!phase.equals(pi.getPhase())) {\n if (builder != null) {\n System.out.println(builder.toString());\n } else {\n builder = new StringBuilder(100);\n }\n builder.setLength(0);\n builder.append(\" \");\n builder.append(pi.getPhase());\n builder.append(\": \");\n phase = pi.getPhase();\n }\n String id = pi.getId();\n int idx = id.lastIndexOf('.');\n if (idx != -1) {\n id = id.substring(idx + 1);\n }\n builder.append(id);\n builder.append(' ');\n }\n }\n\n }", "private static String qualifiedName(Options opt, String r) {\n\tif (opt.hideGenerics)\n\t r = removeTemplate(r);\n\t// Fast path - nothing to do:\n\tif (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0))\n\t return r;\n\tStringBuilder buf = new StringBuilder(r.length());\n\tqualifiedNameInner(opt, r, buf, 0, !opt.showQualified);\n\treturn buf.toString();\n }", "@Pure\n\tpublic static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure1<P2>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p) {\n\t\t\t\tprocedure.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}", "public static base_response flush(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup flushresource = new cachecontentgroup();\n\t\tflushresource.name = resource.name;\n\t\tflushresource.query = resource.query;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.selectorvalue = resource.selectorvalue;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "private JsonObject getPendingJSONObject() {\n for (Map.Entry<String, BoxJSONObject> entry : this.children.entrySet()) {\n BoxJSONObject child = entry.getValue();\n JsonObject jsonObject = child.getPendingJSONObject();\n if (jsonObject != null) {\n if (this.pendingChanges == null) {\n this.pendingChanges = new JsonObject();\n }\n\n this.pendingChanges.set(entry.getKey(), jsonObject);\n }\n }\n return this.pendingChanges;\n }", "public static base_responses export(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata exportresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new appfwlearningdata();\n\t\t\t\texportresources[i].profilename = resources[i].profilename;\n\t\t\t\texportresources[i].securitycheck = resources[i].securitycheck;\n\t\t\t\texportresources[i].target = resources[i].target;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}" ]
Subtract a complex number. @param z1 Complex Number. @param scalar Scalar value. @return Returns new ComplexNumber instance containing the subtract of specified complex number with a scalar value.
[ "public static ComplexNumber Subtract(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real - scalar, z1.imaginary);\r\n }" ]
[ "private Table getTable(String name)\n {\n Table table = m_tables.get(name);\n if (table == null)\n {\n table = EMPTY_TABLE;\n }\n return table;\n }", "public static appfwjsoncontenttype[] get(nitro_service service, options option) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tappfwjsoncontenttype[] response = (appfwjsoncontenttype[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public static appqoepolicy get(nitro_service service, String name) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tobj.set_name(name);\n\t\tappqoepolicy response = (appqoepolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "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 }", "public void moveUp(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index > 0) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index - 1);\n }\n updateButtonBars();\n }", "public static nspbr6_stats get(nitro_service service, String name) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tobj.set_name(name);\n\t\tnspbr6_stats response = (nspbr6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public List<T> parseList(JsonParser jsonParser) throws IOException {\n List<T> list = new ArrayList<>();\n if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n list.add(parse(jsonParser));\n }\n }\n return list;\n }", "public static appfwsignatures get(nitro_service service) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tappfwsignatures[] response = (appfwsignatures[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public Launcher addEnvironmentVariable(final String key, final String value) {\n env.put(key, value);\n return this;\n }" ]
Return true if the expression is a constructor call on any of the named classes, with any number of parameters. @param expression - the expression @param classNames - the possible List of class names @return as described
[ "public static boolean isConstructorCall(Expression expression, List<String> classNames) {\r\n return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName());\r\n }" ]
[ "public final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }", "public boolean addSsextension(String ssExt) {\n if (this.ssextensions == null) {\n this.ssextensions = new ArrayList<String>();\n }\n return this.ssextensions.add(ssExt);\n }", "private void WebPageCloseOnClick(GVRViewSceneObject gvrWebViewSceneObject, GVRSceneObject gvrSceneObjectAnchor, String url) {\n final String urlFinal = url;\n\n webPagePlusUISceneObject = new GVRSceneObject(gvrContext);\n webPagePlusUISceneObject.getTransform().setPosition(webPagePlusUIPosition[0], webPagePlusUIPosition[1], webPagePlusUIPosition[2]);\n\n GVRScene mainScene = gvrContext.getMainScene();\n\n Sensor webPageSensor = new Sensor(urlFinal, Sensor.Type.TOUCH, gvrWebViewSceneObject, true);\n final GVRSceneObject gvrSceneObjectAnchorFinal = gvrSceneObjectAnchor;\n final GVRSceneObject gvrWebViewSceneObjectFinal = gvrWebViewSceneObject;\n final GVRSceneObject webPagePlusUISceneObjectFinal = webPagePlusUISceneObject;\n\n webPagePlusUISceneObjectFinal.addChildObject(gvrWebViewSceneObjectFinal);\n gvrSceneObjectAnchorFinal.addChildObject(webPagePlusUISceneObjectFinal);\n\n\n webPageSensor.addISensorEvents(new ISensorEvents() {\n boolean uiObjectIsActive = false;\n boolean clickDown = true;\n\n @Override\n public void onSensorEvent(SensorEvent event) {\n if (event.isActive()) {\n clickDown = !clickDown;\n if (clickDown) {\n // Delete the WebView page\n gvrSceneObjectAnchorFinal.removeChildObject(webPagePlusUISceneObjectFinal);\n webPageActive = false;\n webPagePlusUISceneObject = null;\n webPageClosed = true; // Make sure click up doesn't open web page behind it\n }\n }\n }\n });\n }", "protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException\r\n {\r\n /*\r\n arminw:\r\n if broker isn't in PB-tx, start tx\r\n */\r\n if (!getBroker().isInTransaction())\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"call beginTransaction() on PB instance\");\r\n broker.beginTransaction();\r\n }\r\n\r\n // Notify objects of impending commits.\r\n performTransactionAwareBeforeCommit();\r\n\r\n // Now perfom the real work\r\n objectEnvelopeTable.writeObjects(isFlush);\r\n // now we have to perform the named objects\r\n namedRootsMap.performDeletion();\r\n namedRootsMap.performInsert();\r\n namedRootsMap.afterWriteCleanup();\r\n }", "@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withTag(String key, String value) {\n if (this.inner().getTags() == null) {\n this.inner().withTags(new HashMap<String, String>());\n }\n this.inner().getTags().put(key, value);\n return (FluentModelImplT) this;\n }", "public static String regexFindFirst(String pattern, String str) {\n return regexFindFirst(Pattern.compile(pattern), str, 1);\n }", "public static String getTokenText(INode node) {\n\t\tif (node instanceof ILeafNode)\n\t\t\treturn ((ILeafNode) node).getText();\n\t\telse {\n\t\t\tStringBuilder builder = new StringBuilder(Math.max(node.getTotalLength(), 1));\n\t\t\tboolean hiddenSeen = false;\n\t\t\tfor (ILeafNode leaf : node.getLeafNodes()) {\n\t\t\t\tif (!leaf.isHidden()) {\n\t\t\t\t\tif (hiddenSeen && builder.length() > 0)\n\t\t\t\t\t\tbuilder.append(' ');\n\t\t\t\t\tbuilder.append(leaf.getText());\n\t\t\t\t\thiddenSeen = false;\n\t\t\t\t} else {\n\t\t\t\t\thiddenSeen = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn builder.toString();\n\t\t}\n\t}", "public static List<String> getValueList(List<String> valuePairs, String delim) {\n List<String> valueList = Lists.newArrayList();\n for(String valuePair: valuePairs) {\n String[] value = valuePair.split(delim, 2);\n if(value.length != 2)\n throw new VoldemortException(\"Invalid argument pair: \" + valuePair);\n valueList.add(value[0]);\n valueList.add(value[1]);\n }\n return valueList;\n }", "public void alias( double value , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character. '\"+name+\"'\");\n\n VariableDouble old = (VariableDouble)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableDouble(value));\n }else {\n old.value = value;\n }\n }" ]
Process the graphical indicator criteria for a single column. @param type field type @return indicator criteria data
[ "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 }" ]
[ "public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}", "private String getCachedETag(HttpHost host, String file) {\n Map<String, Object> cachedETags = readCachedETags();\n\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> hostMap =\n (Map<String, Object>)cachedETags.get(host.toURI());\n if (hostMap == null) {\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n Map<String, String> etagMap = (Map<String, String>)hostMap.get(file);\n if (etagMap == null) {\n return null;\n }\n\n return etagMap.get(\"ETag\");\n }", "public void reset() {\n state = BreakerState.CLOSED;\n isHardTrip = false;\n byPass = false;\n isAttemptLive = false;\n\n notifyBreakerStateChange(getStatus());\n }", "private static String getUnexpectedTypeMessage(final Class<?> expectedType, final Object actualValue) {\n\t\tif( expectedType == null ) {\n\t\t\tthrow new NullPointerException(\"expectedType should not be null\");\n\t\t}\n\t\tString expectedClassName = expectedType.getName();\n\t\tString actualClassName = (actualValue != null) ? actualValue.getClass().getName() : \"null\";\n\t\treturn String.format(\"the input value should be of type %s but is %s\", expectedClassName, actualClassName);\n\t}", "public ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {\n Objects.requireNonNull(rateTypes);\n if (rateTypes.isEmpty()) {\n throw new IllegalArgumentException(\"At least one RateType is required.\");\n }\n Set<RateType> rtSet = new HashSet<>(rateTypes);\n set(ProviderContext.KEY_RATE_TYPES, rtSet);\n return this;\n }", "public static void processEntitiesFromWikidataDump(\n\t\t\tEntityDocumentProcessor entityDocumentProcessor) {\n\n\t\t// Controller object for processing dumps:\n\t\tDumpProcessingController dumpProcessingController = new DumpProcessingController(\n\t\t\t\t\"wikidatawiki\");\n\t\tdumpProcessingController.setOfflineMode(OFFLINE_MODE);\n\n\t\t// // Optional: Use another download directory:\n\t\t// dumpProcessingController.setDownloadDirectory(System.getProperty(\"user.dir\"));\n\n\t\t// Should we process historic revisions or only current ones?\n\t\tboolean onlyCurrentRevisions;\n\t\tswitch (DUMP_FILE_MODE) {\n\t\tcase ALL_REVS:\n\t\tcase ALL_REVS_WITH_DAILIES:\n\t\t\tonlyCurrentRevisions = false;\n\t\t\tbreak;\n\t\tcase CURRENT_REVS:\n\t\tcase CURRENT_REVS_WITH_DAILIES:\n\t\tcase JSON:\n\t\tcase JUST_ONE_DAILY_FOR_TEST:\n\t\tdefault:\n\t\t\tonlyCurrentRevisions = true;\n\t\t}\n\n\t\t// Subscribe to the most recent entity documents of type wikibase item:\n\t\tdumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\tentityDocumentProcessor, null, onlyCurrentRevisions);\n\n\t\t// Also add a timer that reports some basic progress information:\n\t\tEntityTimerProcessor entityTimerProcessor = new EntityTimerProcessor(\n\t\t\t\tTIMEOUT_SEC);\n\t\tdumpProcessingController.registerEntityDocumentProcessor(\n\t\t\t\tentityTimerProcessor, null, onlyCurrentRevisions);\n\n\t\tMwDumpFile dumpFile = null;\n\t\ttry {\n\t\t\t// Start processing (may trigger downloads where needed):\n\t\t\tswitch (DUMP_FILE_MODE) {\n\t\t\tcase ALL_REVS:\n\t\t\tcase CURRENT_REVS:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.FULL);\n\t\t\t\tbreak;\n\t\t\tcase ALL_REVS_WITH_DAILIES:\n\t\t\tcase CURRENT_REVS_WITH_DAILIES:\n\t\t\t\tMwDumpFile fullDumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.FULL);\n\t\t\t\tMwDumpFile incrDumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.DAILY);\n\t\t\t\tlastDumpFileName = fullDumpFile.getProjectName() + \"-\"\n\t\t\t\t\t\t+ incrDumpFile.getDateStamp() + \".\"\n\t\t\t\t\t\t+ fullDumpFile.getDateStamp();\n\t\t\t\tdumpProcessingController.processAllRecentRevisionDumps();\n\t\t\t\tbreak;\n\t\t\tcase JSON:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.JSON);\n\t\t\t\tbreak;\n\t\t\tcase JUST_ONE_DAILY_FOR_TEST:\n\t\t\t\tdumpFile = dumpProcessingController\n\t\t\t\t\t\t.getMostRecentDump(DumpContentType.DAILY);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new RuntimeException(\"Unsupported dump processing type \"\n\t\t\t\t\t\t+ DUMP_FILE_MODE);\n\t\t\t}\n\n\t\t\tif (dumpFile != null) {\n\t\t\t\tlastDumpFileName = dumpFile.getProjectName() + \"-\"\n\t\t\t\t\t\t+ dumpFile.getDateStamp();\n\t\t\t\tdumpProcessingController.processDump(dumpFile);\n\t\t\t}\n\t\t} catch (TimeoutException e) {\n\t\t\t// The timer caused a time out. Continue and finish normally.\n\t\t}\n\n\t\t// Print final timer results:\n\t\tentityTimerProcessor.close();\n\t}", "public static synchronized FormInputValueHelper getInstance(\n\t\t\tInputSpecification inputSpecification, FormFillMode formFillMode) {\n\t\tif (instance == null)\n\t\t\tinstance = new FormInputValueHelper(inputSpecification,\n\t\t\t\t\tformFillMode);\n\t\treturn instance;\n\t}", "private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\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}" ]
Makes a DocumentReaderAndWriter based on flags.plainTextReaderAndWriter. Useful for reading in untokenized text documents or reading plain text from the command line. An example of a way to use this would be to return a edu.stanford.nlp.wordseg.Sighan2005DocumentReaderAndWriter for the Chinese Segmenter.
[ "public DocumentReaderAndWriter<IN> makePlainTextReaderAndWriter() {\r\n String readerClassName = flags.plainTextDocumentReaderAndWriter;\r\n // We set this default here if needed because there may be models\r\n // which don't have the reader flag set\r\n if (readerClassName == null) {\r\n readerClassName = SeqClassifierFlags.DEFAULT_PLAIN_TEXT_READER;\r\n }\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>) Class.forName(readerClassName).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.plainTextDocumentReaderAndWriter: '%s'\", flags.plainTextDocumentReaderAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }" ]
[ "public ServerRedirect addServerMapping(String sourceHost, String destinationHost, String hostHeader) {\n JSONObject response = null;\n\n ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();\n params.add(new BasicNameValuePair(\"srcUrl\", sourceHost));\n params.add(new BasicNameValuePair(\"destUrl\", destinationHost));\n params.add(new BasicNameValuePair(\"profileIdentifier\", this._profileName));\n if (hostHeader != null) {\n params.add(new BasicNameValuePair(\"hostHeader\", hostHeader));\n }\n\n try {\n BasicNameValuePair paramArray[] = new BasicNameValuePair[params.size()];\n params.toArray(paramArray);\n response = new JSONObject(doPost(BASE_SERVER, paramArray));\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return getServerRedirectFromJSON(response);\n }", "public boolean merge(AbstractTransition another) {\n if (!isCompatible(another)) {\n return false;\n }\n if (another.mId != null) {\n if (mId == null) {\n mId = another.mId;\n } else {\n StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());\n sb.append(mId);\n sb.append(\"_MERGED_\");\n sb.append(another.mId);\n mId = sb.toString();\n }\n }\n mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;\n mSetupList.addAll(another.mSetupList);\n Collections.sort(mSetupList, new Comparator<S>() {\n @Override\n public int compare(S lhs, S rhs) {\n if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {\n AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;\n AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;\n float startLeft = left.mReverse ? left.mEnd : left.mStart;\n float startRight = right.mReverse ? right.mEnd : right.mStart;\n return (int) ((startRight - startLeft) * 1000);\n }\n return 0;\n }\n });\n\n return true;\n }", "public byte[] getValueAsArray() {\n ByteBuffer buffer = getValue();\n byte[] result = new byte[buffer.remaining()];\n buffer.get(result);\n return result;\n }", "protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {\n CompletableFuture<T> futureValue = getValue();\n\n if (futureValue == null) {\n logger.error(\"Could not retrieve value \" + this.getClass().getName());\n return null;\n }\n\n return futureValue\n .exceptionally(\n t -> {\n logger.error(\"Could not retrieve value \" + this.getClass().getName(), t);\n return null;\n })\n .thenApply(\n value -> {\n JsonArrayBuilder perms = Json.createArrayBuilder();\n if (isWritable) {\n perms.add(\"pw\");\n }\n if (isReadable) {\n perms.add(\"pr\");\n }\n if (isEventable) {\n perms.add(\"ev\");\n }\n JsonObjectBuilder builder =\n Json.createObjectBuilder()\n .add(\"iid\", instanceId)\n .add(\"type\", shortType)\n .add(\"perms\", perms.build())\n .add(\"format\", format)\n .add(\"ev\", false)\n .add(\"description\", description);\n setJsonValue(builder, value);\n return builder;\n });\n }", "public Optional<URL> getRoute(String routeName) {\n Route route = getClient().routes()\n .inNamespace(namespace).withName(routeName).get();\n\n return route != null ? Optional.ofNullable(createUrlFromRoute(route)) : Optional.empty();\n }", "protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }", "public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }", "public int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public static NotificationInfo getNotificationInfo(final Bundle extras) {\n if (extras == null) return new NotificationInfo(false, false);\n\n boolean fromCleverTap = extras.containsKey(Constants.NOTIFICATION_TAG);\n boolean shouldRender = fromCleverTap && extras.containsKey(\"nm\");\n return new NotificationInfo(fromCleverTap, shouldRender);\n }" ]
Ensures that the primary keys required by the given reference are present in the referenced class. @param modelDef The model @param refDef The reference @throws ConstraintException If there is a conflict between the primary keys
[ "private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException\r\n {\r\n String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);\r\n ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);\r\n\r\n ensurePKsFromHierarchy(targetClassDef);\r\n }" ]
[ "public static boolean checkDuplicateElements(DMatrixSparseCSC A ) {\n A = A.copy(); // create a copy so that it doesn't modify A\n A.sortIndices(null);\n return !checkSortedFlag(A);\n }", "private List<DomainControllerData> readFromFile(String directoryName) {\n List<DomainControllerData> data = new ArrayList<DomainControllerData>();\n if (directoryName == null) {\n return data;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n directoryName = parsedPut.getPrefix();\n }\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n GetResponse val = conn.get(location, key, null);\n if (val.object != null) {\n byte[] buf = val.object.data;\n if (buf != null && buf.length > 0) {\n try {\n data = S3Util.domainControllerDataFromByteBuffer(buf);\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData();\n }\n }\n }\n return data;\n } catch (IOException e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3File(e.getLocalizedMessage());\n }\n }", "public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }", "public void setDefaultCalendarName(String calendarName)\n {\n if (calendarName == null || calendarName.length() == 0)\n {\n calendarName = DEFAULT_CALENDAR_NAME;\n }\n\n set(ProjectField.DEFAULT_CALENDAR_NAME, calendarName);\n }", "private void processAssignments() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zproject=? and z_ent=? order by zorderinactivity\", m_projectID, m_entityMap.get(\"Assignment\"));\n for (Row row : rows)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(\"ZACTIVITY_\"));\n Resource resource = m_project.getResourceByUniqueID(row.getInteger(\"ZRESOURCE\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setGUID(row.getUUID(\"ZUNIQUEID\"));\n assignment.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n assignment.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n\n assignment.setWork(assignmentDuration(task, row.getWork(\"ZGIVENWORK_\")));\n assignment.setOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENWORKOVERTIME_\")));\n assignment.setActualWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORK_\")));\n assignment.setActualOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORKOVERTIME_\")));\n assignment.setRemainingWork(assignmentDuration(task, row.getWork(\"ZGIVENREMAININGWORK_\")));\n\n assignment.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n\n if (assignment.getRemainingWork() == null)\n {\n assignment.setRemainingWork(assignment.getWork());\n }\n\n if (resource.getType() == ResourceType.WORK)\n {\n assignment.setUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZRESOURCEUNITS_\")) * 100.0));\n }\n }\n }\n }", "private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }", "public static dnsview[] get(nitro_service service) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tdnsview[] response = (dnsview[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {\n Set<String> orderedChildTypes = resource.getOrderedChildTypes();\n if (orderedChildTypes.size() > 0) {\n orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());\n }\n }", "public static List<File> listFiles(File[] directories, IOFileFilter fileFilter, IOFileFilter dirFilter) {\n List<File> files = new ArrayList<>();\n for (File directory : directories) {\n if (!directory.isDirectory()) {\n continue;\n }\n Collection<File> filesInDirectory = FileUtils.listFiles(directory,\n fileFilter,\n dirFilter);\n files.addAll(filesInDirectory);\n }\n return files;\n }" ]
Prints some basic documentation about this program.
[ "public static void printDocumentation() {\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t\tSystem.out.println(\"*** Wikidata Toolkit: GenderRatioProcessor\");\n\t\tSystem.out.println(\"*** \");\n\t\tSystem.out\n\t\t\t\t.println(\"*** This program will download and process dumps from Wikidata.\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** It will compute the numbers of articles about humans across\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** Wikimedia projects, and in particular it will count the articles\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** for each sex/gender. Results will be stored in a CSV file.\");\n\t\tSystem.out.println(\"*** See source code for further details.\");\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t}" ]
[ "private static <D, T> D createDaoFromConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\t// no loaded configs\n\t\tif (configMap == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDatabaseTableConfig<T> config = (DatabaseTableConfig<T>) configMap.get(clazz);\n\t\t// if we don't config information cached return null\n\t\tif (config == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// else create a DAO using configuration\n\t\tDao<T, ?> configedDao = doCreateDao(connectionSource, config);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) configedDao;\n\t\treturn castDao;\n\t}", "public static base_responses delete(nitro_service client, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = resources[i].hostname;\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public void clearRequestSettings(int pathId, String clientUUID) throws Exception {\n this.setRequestEnabled(pathId, false, clientUUID);\n OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_REQUEST);\n EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_REQUEST, pathId, clientUUID);\n }", "protected DateTimeException _peelDTE(DateTimeException e) {\n while (true) {\n Throwable t = e.getCause();\n if (t != null && t instanceof DateTimeException) {\n e = (DateTimeException) t;\n continue;\n }\n break;\n }\n return e;\n }", "protected static List<StackTraceElement> filterStackTrace(StackTraceElement[] stack) {\r\n List<StackTraceElement> filteredStack = new ArrayList<StackTraceElement>();\r\n\r\n int i = 2; // we can skip the first two (first is getStackTrace(), second is this method)\r\n while (i < stack.length) {\r\n boolean isLoggingClass = false;\r\n for (String loggingClass : loggingClasses) {\r\n String className = stack[i].getClassName();\r\n if (className.startsWith(loggingClass)) {\r\n isLoggingClass = true;\r\n break;\r\n }\r\n }\r\n if (!isLoggingClass) {\r\n filteredStack.add(stack[i]);\r\n }\r\n\r\n i += 1;\r\n }\r\n\r\n // if we didn't find anything, keep the full stack\r\n if (filteredStack.size() == 0) {\r\n return Arrays.asList(stack);\r\n }\r\n return filteredStack;\r\n }", "public static byte[] concat(Bytes... listOfBytes) {\n int offset = 0;\n int size = 0;\n\n for (Bytes b : listOfBytes) {\n size += b.length() + checkVlen(b.length());\n }\n\n byte[] data = new byte[size];\n for (Bytes b : listOfBytes) {\n offset = writeVint(data, offset, b.length());\n b.copyTo(0, b.length(), data, offset);\n offset += b.length();\n }\n return data;\n }", "public static Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }", "public void clearSources()\n {\n synchronized (mAudioSources)\n {\n for (GVRAudioSource source : mAudioSources)\n {\n source.setListener(null);\n }\n mAudioSources.clear();\n }\n }", "public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {\n List<Versioned<V>> versionedValues;\n\n validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());\n boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;\n String keyHexString = \"\";\n if(!hasVersion) {\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"DELETE without version requested for key: \" + keyHexString\n + \" , for store: \" + this.storeName + \" at time(in ms): \"\n + startTimeInMs + \" . Nested GET and DELETE requests to follow ---\");\n }\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent delete might be faster all the\n // steps might finish within the allotted time\n deleteRequestObject.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(deleteRequestObject);\n Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),\n null,\n versionedValues);\n\n if(versioned == null) {\n return false;\n }\n\n long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()\n - (System.currentTimeMillis() - startTimeInMs);\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n if(timeLeft < 0) {\n throw new StoreTimeoutException(\"DELETE request timed out\");\n }\n\n // Update the version and the new timeout\n deleteRequestObject.setVersion(versioned.getVersion());\n deleteRequestObject.setRoutingTimeoutInMs(timeLeft);\n\n }\n long deleteVersionStartTimeInNs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n keyHexString);\n }\n boolean result = store.delete(deleteRequestObject);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n if(!hasVersion && logger.isDebugEnabled()) {\n logger.debug(\"DELETE without version response received for key: \" + keyHexString\n + \", for store: \" + this.storeName + \" at time(in ms): \"\n + System.currentTimeMillis());\n }\n return result;\n }" ]
Creates the server setup, depending on the protocol flags. @return the configured server setups.
[ "private ServerSetup[] createServerSetup() {\n List<ServerSetup> setups = new ArrayList<>();\n if (smtpProtocol) {\n smtpServerSetup = createTestServerSetup(ServerSetup.SMTP);\n setups.add(smtpServerSetup);\n }\n if (smtpsProtocol) {\n smtpsServerSetup = createTestServerSetup(ServerSetup.SMTPS);\n setups.add(smtpsServerSetup);\n }\n if (pop3Protocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3));\n }\n if (pop3sProtocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3S));\n }\n if (imapProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAP));\n }\n if (imapsProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAPS));\n }\n return setups.toArray(new ServerSetup[setups.size()]);\n }" ]
[ "public static FileOutputStream openResultFileOuputStream(\n\t\t\tPath resultDirectory, String filename) throws IOException {\n\t\tPath filePath = resultDirectory.resolve(filename);\n\t\treturn new FileOutputStream(filePath.toFile());\n\t}", "private int slopSize(Versioned<Slop> slopVersioned) {\n int nBytes = 0;\n Slop slop = slopVersioned.getValue();\n nBytes += slop.getKey().length();\n nBytes += ((VectorClock) slopVersioned.getVersion()).sizeInBytes();\n switch(slop.getOperation()) {\n case PUT: {\n nBytes += slop.getValue().length;\n break;\n }\n case DELETE: {\n break;\n }\n default:\n logger.error(\"Unknown slop operation: \" + slop.getOperation());\n }\n return nBytes;\n }", "private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {\n final Set<WaveformListener> listeners = getWaveformListeners();\n if (!listeners.isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);\n for (final WaveformListener listener : listeners) {\n try {\n listener.previewChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform preview update to listener\", t);\n }\n }\n }\n });\n }\n }", "public ReplyObject getReplyList(String topicId, int perPage, int page) throws FlickrException {\r\n ReplyList<Reply> reply = new ReplyList<Reply>();\r\n TopicList<Topic> topic = new TopicList<Topic>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_LIST);\r\n\r\n parameters.put(\"topic_id\", topicId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element replyElements = response.getPayload();\r\n ReplyObject ro = new ReplyObject();\r\n NodeList replyNodes = replyElements.getElementsByTagName(\"reply\");\r\n for (int i = 0; i < replyNodes.getLength(); i++) {\r\n Element replyNodeElement = (Element) replyNodes.item(i);\r\n // Element replyElement = XMLUtilities.getChild(replyNodeElement, \"reply\");\r\n reply.add(parseReply(replyNodeElement));\r\n ro.setReplyList(reply);\r\n\r\n }\r\n NodeList topicNodes = replyElements.getElementsByTagName(\"topic\");\r\n for (int i = 0; i < topicNodes.getLength(); i++) {\r\n Element replyNodeElement = (Element) replyNodes.item(i);\r\n // Element topicElement = XMLUtilities.getChild(replyNodeElement, \"topic\");\r\n topic.add(parseTopic(replyNodeElement));\r\n ro.setTopicList(topic);\r\n }\r\n\r\n return ro;\r\n }", "public static void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }", "public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\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 }", "private void clearDeck(TrackMetadataUpdate update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverBeatGridUpdate(update.player, null);\n }\n }", "private void readResourceCustomFields(net.sf.mpxj.ganttproject.schema.Resource gpResource, Resource mpxjResource)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_resourcePropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomResourceProperty property : gpResource.getCustomProperty())\n {\n Pair<FieldType, String> definition = m_resourcePropertyDefinitions.get(property.getDefinitionId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_localeDateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjResource.set(item.getKey(), item.getValue());\n }\n }\n }", "protected boolean inViewPort(final int dataIndex) {\n boolean inViewPort = true;\n\n for (Layout layout: mLayouts) {\n inViewPort = inViewPort && (layout.inViewPort(dataIndex) || !layout.isClippingEnabled());\n }\n return inViewPort;\n }" ]
Takes a model and an SCXMLFrontier and decomposes the Frontier into a Map of Strings to Strings These strings can be sent over a network to get a Frontier past a 'gap' @param frontier the Frontier @param modelText the model @return the map of strings representing a decomposition
[ "public Map<String, String> decompose(Frontier frontier, String modelText) {\r\n if (!(frontier instanceof SCXMLFrontier)) {\r\n return null;\r\n }\n\r\n TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState;\r\n Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables;\n\r\n Map<String, String> decomposition = new HashMap<String, String>();\r\n decomposition.put(\"target\", target.getId());\n\r\n StringBuilder packedVariables = new StringBuilder();\r\n for (Map.Entry<String, String> variable : variables.entrySet()) {\r\n packedVariables.append(variable.getKey());\r\n packedVariables.append(\"::\");\r\n packedVariables.append(variable.getValue());\r\n packedVariables.append(\";\");\r\n }\n\r\n decomposition.put(\"variables\", packedVariables.toString());\r\n decomposition.put(\"model\", modelText);\n\r\n return decomposition;\r\n }" ]
[ "public void pause(ServerActivityCallback requestCountListener) {\n if (paused) {\n throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();\n }\n this.paused = true;\n listenerUpdater.set(this, requestCountListener);\n if (activeRequestCountUpdater.get(this) == 0) {\n if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {\n requestCountListener.done();\n }\n }\n }", "public void setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(charTranslator!=null){\r\n\t\t\tthis.charTranslator = charTranslator;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}", "public static ResourceResolutionContext context(ResourceResolutionComponent[] components,\n Map<String, Object> messageParams) {\n return new ResourceResolutionContext(components, messageParams);\n }", "@Override\n public DMatrixRMaj getV(DMatrixRMaj V , boolean transpose , boolean compact ) {\n V = handleV(V, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(V);\n\n// UBV.print();\n\n // todo the very first multiplication can be avoided by setting to the rank1update output\n for( int j = min-1; j >= 0; j-- ) {\n u[j+1] = 1;\n for( int i = j+2; i < n; i++ ) {\n u[i] = UBV.get(j,i);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);\n }\n\n return V;\n }", "public long remove(final String... fields) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.hdel(getKey(), fields);\n }\n });\n }", "@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}", "public void setSpeed(float newValue) {\n if (newValue < 0) newValue = 0;\n this.pitch.setValue( newValue );\n this.speed.setValue( newValue );\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 }", "public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\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 if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\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 photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }" ]
In case we cannot delete a directory create a marker to recheck whether we can garbage collect some not referenced directories and files. @param file the directory
[ "protected void failedToCleanupDir(final File file) {\n checkForGarbageOnRestart = true;\n PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath());\n }" ]
[ "public GroovyMethodDoc[] methods() {\n Collections.sort(methods);\n return methods.toArray(new GroovyMethodDoc[methods.size()]);\n }", "public boolean hasValue(String fieldName) {\n\t\treturn resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null;\n\t}", "protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }", "public static void validate(final Module module) {\n if (null == module) {\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module cannot be null!\")\n .build());\n }\n if(module.getName() == null ||\n module.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module name cannot be null or empty!\")\n .build());\n }\n if(module.getVersion()== null ||\n module.getVersion().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module version cannot be null or empty!\")\n .build());\n }\n\n // Check artifacts\n for(final Artifact artifact: DataUtils.getAllArtifacts(module)){\n validate(artifact);\n }\n\n // Check dependencies\n for(final Dependency dependency: DataUtils.getAllDependencies(module)){\n validate(dependency.getTarget());\n }\n }", "private void sortFields()\r\n {\r\n HashMap fields = new HashMap();\r\n ArrayList fieldsWithId = new ArrayList();\r\n ArrayList fieldsWithoutId = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext(); )\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n fields.put(fieldDef.getName(), fieldDef);\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_ID))\r\n {\r\n fieldsWithId.add(fieldDef.getName());\r\n }\r\n else\r\n {\r\n fieldsWithoutId.add(fieldDef.getName());\r\n }\r\n }\r\n\r\n Collections.sort(fieldsWithId, new FieldWithIdComparator(fields));\r\n\r\n ArrayList result = new ArrayList();\r\n\r\n for (Iterator it = fieldsWithId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n for (Iterator it = fieldsWithoutId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n\r\n _fields = result;\r\n }", "public void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) {\n int dayOfWeekInt = Integer.parseInt(dayOfWeek);\n int seekAmountInt = Integer.parseInt(seekAmount);\n assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT));\n assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK));\n assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7);\n \n markDateInvocation();\n \n int sign = direction.equals(DIR_RIGHT) ? 1 : -1;\n if(seekType.equals(SEEK_BY_WEEK)) {\n // set our calendar to this weeks requested day of the week,\n // then add or subtract the week(s)\n _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt);\n _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign);\n }\n \n else if(seekType.equals(SEEK_BY_DAY)) {\n // find the closest day\n do {\n _calendar.add(Calendar.DAY_OF_YEAR, sign);\n } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt);\n \n // now add/subtract any additional days\n if(seekAmountInt > 0) {\n _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign);\n }\n }\n }", "private static MonolingualTextValue toTerm(MonolingualTextValue term) {\n\t\treturn term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText());\n\t}", "public void removeLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference serviceReference : declaration.getStatus().getServiceReferencesBounded()) {\n // FIXME : In case of multiples Linker, we will remove the link of all the ServiceReference\n // FIXME : event the ones which dun know nothing about\n linkerManagement.unlink(declaration, serviceReference);\n }\n }", "public void createResourceFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RESOURCE_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultResourceData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }" ]
Checks if a property's type is valid to be included in the report. @param _property the property. @return true if the property is is of a valid type.
[ "private static boolean isValidPropertyClass(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n return Number.class.isAssignableFrom(type) || type == String.class || Date.class.isAssignableFrom(type) || type == Boolean.class;\n }" ]
[ "public static String getStateKey(CmsResourceState state) {\n\n StringBuffer sb = new StringBuffer(STATE_PREFIX);\n sb.append(state);\n sb.append(STATE_POSTFIX);\n return sb.toString();\n\n }", "public static base_response add(nitro_service client, sslcipher resource) throws Exception {\n\t\tsslcipher addresource = new sslcipher();\n\t\taddresource.ciphergroupname = resource.ciphergroupname;\n\t\taddresource.ciphgrpalias = resource.ciphgrpalias;\n\t\treturn addresource.add_resource(client);\n\t}", "public Where<T, ID> reset() {\n\t\tfor (int i = 0; i < clauseStackLevel; i++) {\n\t\t\t// help with gc\n\t\t\tclauseStack[i] = null;\n\t\t}\n\t\tclauseStackLevel = 0;\n\t\treturn this;\n\t}", "public ClosableIterator<Tuple> callStoredProcedure(EmbeddedCacheManager embeddedCacheManager, String storedProcedureName, ProcedureQueryParameters queryParameters, ClassLoaderService classLoaderService ) {\n\t\tvalidate( queryParameters );\n\t\tCache<String, String> cache = embeddedCacheManager.getCache( STORED_PROCEDURES_CACHE_NAME, true );\n\t\tString className = cache.getOrDefault( storedProcedureName, storedProcedureName );\n\t\tCallable<?> callable = instantiate( storedProcedureName, className, classLoaderService );\n\t\tsetParams( storedProcedureName, queryParameters, callable );\n\t\tObject res = execute( storedProcedureName, embeddedCacheManager, callable );\n\t\treturn extractResultSet( storedProcedureName, res );\n\t}", "public void print( String equation ) {\n // first assume it's just a variable\n Variable v = lookupVariable(equation);\n if( v == null ) {\n Sequence sequence = compile(equation,false,false);\n sequence.perform();\n v = sequence.output;\n }\n\n if( v instanceof VariableMatrix ) {\n ((VariableMatrix)v).matrix.print();\n } else if(v instanceof VariableScalar ) {\n System.out.println(\"Scalar = \"+((VariableScalar)v).getDouble() );\n } else {\n System.out.println(\"Add support for \"+v.getClass().getSimpleName());\n }\n }", "public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }", "public void onDrawFrame(float frameTime) {\n final GVRSceneObject owner = getOwnerObject();\n if (owner == null) {\n return;\n }\n\n final int size = mRanges.size();\n final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();\n\n for (final Object[] range : mRanges) {\n ((GVRSceneObject)range[1]).setEnable(false);\n }\n\n for (int i = size - 1; i >= 0; --i) {\n final Object[] range = mRanges.get(i);\n final GVRSceneObject child = (GVRSceneObject) range[1];\n if (child.getParent() != owner) {\n Log.w(TAG, \"the scene object for distance greater than \" + range[0] + \" is not a child of the owner; skipping it\");\n continue;\n }\n\n final float[] values = child.getBoundingVolumeRawValues();\n mCenter.set(values[0], values[1], values[2], 1.0f);\n mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);\n\n mVector.sub(mCenter);\n mVector.negate();\n\n float distance = mVector.dot(mVector);\n\n if (distance >= (Float) range[0]) {\n child.setEnable(true);\n break;\n }\n }\n }", "private void processCalendarDays(ProjectCalendar calendar, Record root)\n {\n // Retrieve working hours ...\n Record daysOfWeek = root.getChild(\"DaysOfWeek\");\n if (daysOfWeek != null)\n {\n for (Record dayRecord : daysOfWeek.getChildren())\n {\n processCalendarHours(calendar, dayRecord);\n }\n }\n }", "protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }" ]
Delete a file ignoring failures. @param file file to delete
[ "public static final void deleteQuietly(File file)\n {\n if (file != null)\n {\n if (file.isDirectory())\n {\n File[] children = file.listFiles();\n if (children != null)\n {\n for (File child : children)\n {\n deleteQuietly(child);\n }\n }\n }\n file.delete();\n }\n }" ]
[ "private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }", "protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {\r\n MethodNode setter = new MethodNode(\r\n setterName,\r\n propertyNode.getModifiers(),\r\n ClassHelper.VOID_TYPE,\r\n params(param(propertyNode.getType(), \"value\")),\r\n ClassNode.EMPTY_ARRAY,\r\n setterBlock);\r\n setter.setSynthetic(true);\r\n // add it to the class\r\n declaringClass.addMethod(setter);\r\n }", "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 int scrollToNextPage() {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToNextPage getCurrentPage() = %d currentIndex = %d\",\n getCurrentPage(), mCurrentItemIndex);\n\n if (mSupportScrollByPage) {\n scrollToPage(getCurrentPage() + 1);\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n\n return mCurrentItemIndex;\n\t}", "public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }", "private FieldDescriptor[] getExtentFieldDescriptors(TableAlias extAlias, FieldDescriptor[] fds)\r\n {\r\n FieldDescriptor[] result = new FieldDescriptor[fds.length];\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n result[i] = extAlias.cld.getFieldDescriptorByName(fds[i].getAttributeName());\r\n }\r\n\r\n return result;\r\n }", "public static Thread newThread(String name, Runnable runnable, boolean daemon) {\n Thread thread = new Thread(runnable, name);\n thread.setDaemon(daemon);\n return thread;\n }", "public void processDefaultCurrency(Row row)\n {\n ProjectProperties properties = m_project.getProjectProperties();\n properties.setCurrencySymbol(row.getString(\"curr_symbol\"));\n properties.setSymbolPosition(CURRENCY_SYMBOL_POSITION_MAP.get(row.getString(\"pos_curr_fmt_type\")));\n properties.setCurrencyDigits(row.getInteger(\"decimal_digit_cnt\"));\n properties.setThousandsSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n properties.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n }", "public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Binds a script bundle to a scene. @param scriptBundle The {@code GVRScriptBundle} object containing script binding information. @param scene The scene to bind to. @throws IOException if script bundle file cannot be read. @throws GVRScriptException if script processing error occurs.
[ "public void bindScriptBundleToScene(GVRScriptBundle scriptBundle, GVRScene scene) throws IOException, GVRScriptException {\n for (GVRSceneObject sceneObject : scene.getSceneObjects()) {\n bindBundleToSceneObject(scriptBundle, sceneObject);\n }\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 }", "protected void setProperty(String propertyName, JavascriptObject propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getJSObject());\n }", "public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException {\n try {\n T result = action.call(self);\n\n Closeable temp = self;\n self = null;\n temp.close();\n\n return result;\n } finally {\n DefaultGroovyMethodsSupport.closeWithWarning(self);\n }\n }", "protected I_CmsSearchConfigurationFacetField parseFieldFacet(final String pathPrefix) {\n\n try {\n final String field = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_FACET_FIELD);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final Integer limit = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_LIMIT);\n final String prefix = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_PREFIX);\n final String sorder = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (@SuppressWarnings(\"unused\") final Exception e) {\n order = null;\n }\n final String filterQueryModifier = parseOptionalStringValue(\n pathPrefix + XML_ELEMENT_FACET_FILTERQUERYMODIFIER);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_FACET_FIELD),\n e);\n return null;\n }\n }", "private String getWorkingDayString(ProjectCalendar mpxjCalendar, Day day)\n {\n String result = null;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = \"0\";\n break;\n }\n\n case NON_WORKING:\n {\n result = \"1\";\n break;\n }\n\n case DEFAULT:\n {\n result = \"2\";\n break;\n }\n }\n\n return (result);\n }", "private static QName convertString(String str) {\n if (str != null) {\n return QName.valueOf(str);\n } else {\n return null;\n }\n }", "public static base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup addresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new clusternodegroup();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "protected long preConnection() throws SQLException{\r\n\t\tlong statsObtainTime = 0;\r\n\t\t\r\n\t\tif (this.pool.poolShuttingDown){\r\n\t\t\tthrow new SQLException(this.pool.shutdownStackTrace);\r\n\t\t}\r\n\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tstatsObtainTime = System.nanoTime();\r\n\t\t\tthis.pool.statistics.incrementConnectionsRequested();\r\n\t\t}\r\n\t\t\r\n\t\treturn statsObtainTime;\r\n\t}", "protected void removeInvalidChildren() {\n\n if (getLoadState() == LoadState.LOADED) {\n List<CmsSitemapTreeItem> toDelete = new ArrayList<CmsSitemapTreeItem>();\n for (int i = 0; i < getChildCount(); i++) {\n CmsSitemapTreeItem item = (CmsSitemapTreeItem)getChild(i);\n CmsUUID id = item.getEntryId();\n if ((id != null) && (CmsSitemapView.getInstance().getController().getEntryById(id) == null)) {\n toDelete.add(item);\n }\n }\n for (CmsSitemapTreeItem deleteItem : toDelete) {\n m_children.removeItem(deleteItem);\n }\n }\n }" ]
Delete a database for a given path and userId. @param appInfo the info for this application @param serviceName the name of the associated service @param clientFactory the associated factory that creates clients @param userId the id of the user's to delete @return true if successfully deleted, false if not
[ "public static boolean deleteDatabase(final StitchAppClientInfo appInfo,\n final String serviceName,\n final EmbeddedMongoClientFactory clientFactory,\n final String userId) {\n final String dataDir = appInfo.getDataDirectory();\n if (dataDir == null) {\n throw new IllegalArgumentException(\"StitchAppClient not configured with a data directory\");\n }\n\n final String instanceKey = String.format(\n \"%s-%s_sync_%s_%s\", appInfo.getClientAppId(), dataDir, serviceName, userId);\n final String dbPath = String.format(\n \"%s/%s/sync_mongodb_%s/%s/0/\", dataDir, appInfo.getClientAppId(), serviceName, userId);\n final MongoClient client =\n clientFactory.getClient(instanceKey, dbPath, appInfo.getCodecRegistry());\n\n for (final String listDatabaseName : client.listDatabaseNames()) {\n try {\n client.getDatabase(listDatabaseName).drop();\n } catch (Exception e) {\n // do nothing\n }\n }\n\n client.close();\n clientFactory.removeClient(instanceKey);\n\n return new File(dbPath).delete();\n }" ]
[ "private static boolean isAssignableFrom(Type from, GenericArrayType to) {\n\t\tType toGenericComponentType = to.getGenericComponentType();\n\t\tif (toGenericComponentType instanceof ParameterizedType) {\n\t\t\tType t = from;\n\t\t\tif (from instanceof GenericArrayType) {\n\t\t\t\tt = ((GenericArrayType) from).getGenericComponentType();\n\t\t\t} else if (from instanceof Class) {\n\t\t\t\tClass<?> classType = (Class<?>) from;\n\t\t\t\twhile (classType.isArray()) {\n\t\t\t\t\tclassType = classType.getComponentType();\n\t\t\t\t}\n\t\t\t\tt = classType;\n\t\t\t}\n\t\t\treturn isAssignableFrom(t,\n\t\t\t\t\t(ParameterizedType) toGenericComponentType,\n\t\t\t\t\tnew HashMap<String, Type>());\n\t\t}\n\t\t// No generic defined on \"to\"; therefore, return true and let other\n\t\t// checks determine assignability\n\t\treturn true;\n\t}", "public 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 }", "private void processProperties() {\n state = true;\n try {\n exporterServiceFilter = getFilter(exporterServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n exportDeclarationFilter = getFilter(exportDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }", "public static List<StoreDefinition> filterStores(List<StoreDefinition> storeDefs,\n final boolean isReadOnly) {\n List<StoreDefinition> filteredStores = Lists.newArrayList();\n for(StoreDefinition storeDef: storeDefs) {\n if(storeDef.getType().equals(ReadOnlyStorageConfiguration.TYPE_NAME) == isReadOnly) {\n filteredStores.add(storeDef);\n }\n }\n return filteredStores;\n }", "public static base_response update(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup updateresource = new cachecontentgroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\tupdateresource.heurexpiryparam = resource.heurexpiryparam;\n\t\tupdateresource.relexpiry = resource.relexpiry;\n\t\tupdateresource.relexpirymillisec = resource.relexpirymillisec;\n\t\tupdateresource.absexpiry = resource.absexpiry;\n\t\tupdateresource.absexpirygmt = resource.absexpirygmt;\n\t\tupdateresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\tupdateresource.hitparams = resource.hitparams;\n\t\tupdateresource.invalparams = resource.invalparams;\n\t\tupdateresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\tupdateresource.matchcookies = resource.matchcookies;\n\t\tupdateresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\tupdateresource.polleverytime = resource.polleverytime;\n\t\tupdateresource.ignorereloadreq = resource.ignorereloadreq;\n\t\tupdateresource.removecookies = resource.removecookies;\n\t\tupdateresource.prefetch = resource.prefetch;\n\t\tupdateresource.prefetchperiod = resource.prefetchperiod;\n\t\tupdateresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\tupdateresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\tupdateresource.flashcache = resource.flashcache;\n\t\tupdateresource.expireatlastbyte = resource.expireatlastbyte;\n\t\tupdateresource.insertvia = resource.insertvia;\n\t\tupdateresource.insertage = resource.insertage;\n\t\tupdateresource.insertetag = resource.insertetag;\n\t\tupdateresource.cachecontrol = resource.cachecontrol;\n\t\tupdateresource.quickabortsize = resource.quickabortsize;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.maxressize = resource.maxressize;\n\t\tupdateresource.memlimit = resource.memlimit;\n\t\tupdateresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\tupdateresource.minhits = resource.minhits;\n\t\tupdateresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\tupdateresource.persist = resource.persist;\n\t\tupdateresource.pinned = resource.pinned;\n\t\tupdateresource.lazydnsresolve = resource.lazydnsresolve;\n\t\tupdateresource.hitselector = resource.hitselector;\n\t\tupdateresource.invalselector = resource.invalselector;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void remove(Object pKey)\r\n {\r\n Identity id;\r\n if(pKey instanceof Identity)\r\n {\r\n id = (Identity) pKey;\r\n }\r\n else\r\n {\r\n id = transaction.getBroker().serviceIdentity().buildIdentity(pKey);\r\n }\r\n mhtObjectEnvelopes.remove(id);\r\n mvOrderOfIds.remove(id);\r\n }", "public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) {\n return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName);\n }", "public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }", "public Map<String, SetAndCount> getAggregateResultFullSummary() {\n\n Map<String, SetAndCount> summaryMap = new ConcurrentHashMap<String, SetAndCount>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), new SetAndCount(entry.getValue()));\n }\n\n return summaryMap;\n }" ]
Use this API to change responderhtmlpage.
[ "public static base_response change(nitro_service client, responderhtmlpage resource) throws Exception {\n\t\tresponderhtmlpage updateresource = new responderhtmlpage();\n\t\tupdateresource.name = resource.name;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}" ]
[ "public void setTimewarpInt(String timewarp) {\n\n try {\n m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue());\n } catch (Exception e) {\n m_userSettings.setTimeWarp(-1);\n }\n }", "public static String encodeHost(String host, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4);\n\t}", "public long remove(final String... fields) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.hdel(getKey(), fields);\n }\n });\n }", "protected void boot(final BootContext context) throws ConfigurationPersistenceException {\n List<ModelNode> bootOps = configurationPersister.load();\n ModelNode op = registerModelControllerServiceInitializationBootStep(context);\n if (op != null) {\n bootOps.add(op);\n }\n boot(bootOps, false);\n finishBoot();\n }", "protected void copyStream(File outputDirectory,\n InputStream stream,\n String targetFileName) throws IOException\n {\n File resourceFile = new File(outputDirectory, targetFileName);\n BufferedReader reader = null;\n Writer writer = null;\n try\n {\n reader = new BufferedReader(new InputStreamReader(stream, ENCODING));\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));\n\n String line = reader.readLine();\n while (line != null)\n {\n writer.write(line);\n writer.write('\\n');\n line = reader.readLine();\n }\n writer.flush();\n }\n finally\n {\n if (reader != null)\n {\n reader.close();\n }\n if (writer != null)\n {\n writer.close();\n }\n }\n }", "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addPluginPath(Model model, Plugin add) throws Exception {\n PluginManager.getInstance().addPluginPath(add.getPath());\n\n return pluginInformation();\n }", "public void setProxyClass(Class newProxyClass)\r\n {\r\n proxyClass = newProxyClass;\r\n if (proxyClass == null)\r\n {\r\n setProxyClassName(null);\r\n }\r\n else\r\n {\r\n proxyClassName = proxyClass.getName();\r\n }\r\n }", "public boolean getHidden() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_HIDDEN);\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(\"hidden\").equals(\"1\") ? true : false;\r\n }", "public ItemDocument updateTermsStatements(ItemIdValue itemIdValue,\n\t\t\tList<MonolingualTextValue> addLabels,\n\t\t\tList<MonolingualTextValue> addDescriptions,\n\t\t\tList<MonolingualTextValue> addAliases,\n\t\t\tList<MonolingualTextValue> deleteAliases,\n\t\t\tList<Statement> addStatements,\n\t\t\tList<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\t\tItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(itemIdValue.getId());\n\t\t\n\t\treturn updateTermsStatements(currentDocument, addLabels,\n\t\t\t\taddDescriptions, addAliases, deleteAliases,\n\t\t\t\taddStatements, deleteStatements, summary);\n\t}" ]
Reads, stems, and prints the trees in the file. @param args Usage: WordStemmer file
[ "public static void main(String[] args) {\r\n Treebank treebank = new DiskTreebank();\r\n treebank.loadPath(args[0]);\r\n WordStemmer ls = new WordStemmer();\r\n for (Tree tree : treebank) {\r\n ls.visitTree(tree);\r\n System.out.println(tree);\r\n }\r\n }" ]
[ "private List<T> computePagedList(List<T> result, HeaderAndBody httpResponse, JSONObject where, Pipe<T> requestingPipe) {\n ReadFilter previousRead = null;\n ReadFilter nextRead = null;\n\n if (PageConfig.MetadataLocations.WEB_LINKING.equals(pageConfig.getMetadataLocation())) {\n String webLinksRaw = \"\";\n final String relHeader = \"rel\";\n final String nextIdentifier = pageConfig.getNextIdentifier();\n final String prevIdentifier = pageConfig.getPreviousIdentifier();\n try {\n webLinksRaw = getWebLinkHeader(httpResponse);\n if (webLinksRaw == null) { // no paging, return result\n return result;\n }\n List<WebLink> webLinksParsed = WebLinkParser.parse(webLinksRaw);\n for (WebLink link : webLinksParsed) {\n if (nextIdentifier.equals(link.getParameters().get(relHeader))) {\n nextRead = new ReadFilter();\n nextRead.setLinkUri(new URI(link.getUri()));\n } else if (prevIdentifier.equals(link.getParameters().get(relHeader))) {\n previousRead = new ReadFilter();\n previousRead.setLinkUri(new URI(link.getUri()));\n }\n\n }\n } catch (URISyntaxException ex) {\n Log.e(TAG, webLinksRaw + \" did not contain a valid context URI\", ex);\n throw new RuntimeException(ex);\n } catch (ParseException ex) {\n Log.e(TAG, webLinksRaw + \" could not be parsed as a web link header\", ex);\n throw new RuntimeException(ex);\n }\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.HEADERS)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.BODY)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else {\n throw new IllegalStateException(\"Not supported\");\n }\n if (nextRead != null) {\n nextRead.setWhere(where);\n }\n\n if (previousRead != null) {\n previousRead.setWhere(where);\n }\n\n return new WrappingPagedList<T>(requestingPipe, result, nextRead, previousRead);\n }", "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 }", "private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "private void checkInitializationMethod(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String initMethodName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_INITIALIZATION_METHOD);\r\n\r\n if (initMethodName == null)\r\n {\r\n return;\r\n }\r\n\r\n Class initClass;\r\n Method initMethod;\r\n\r\n try\r\n {\r\n initClass = InheritanceHelper.getClass(classDef.getName());\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" was not found on the classpath\");\r\n }\r\n try\r\n {\r\n initMethod = initClass.getDeclaredMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n initMethod = null;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n if (initMethod == null)\r\n { \r\n try\r\n {\r\n initMethod = initClass.getMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n throw new ConstraintException(\"No suitable initialization-method \"+initMethodName+\" found in class \"+classDef.getName());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n }\r\n\r\n // checking modifiers\r\n int mods = initMethod.getModifiers();\r\n\r\n if (Modifier.isStatic(mods) || Modifier.isAbstract(mods))\r\n {\r\n throw new ConstraintException(\"The initialization-method \"+initMethodName+\" in class \"+classDef.getName()+\" must be a concrete instance method\");\r\n }\r\n }", "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}", "public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }", "public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }", "public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)\n\tthrows CertificateEncodingException,\n\tInvalidKeyException,\n\tCertificateException,\n\tCertificateNotYetValidException,\n\tNoSuchAlgorithmException,\n\tNoSuchProviderException,\n\tSignatureException,\n\tKeyStoreException,\n\tUnrecoverableKeyException\n\t{\n\n\t\tString thumbprint = ThumbprintUtil.getThumbprint(cert);\n\n\t\tString mappedCertThumbprint = _certMap.get(thumbprint);\n\n\t\tif(mappedCertThumbprint == null)\n\t\t{\n\n\t\t\t// Check if we've already mapped this public key from a KeyValue\n\t\t\tPublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());\n\t\t\tPrivateKey privKey;\n\n\t\t\tif(mappedPk == null)\n\t\t\t{\n\t\t\t\tPublicKey pk = cert.getPublicKey();\n\n\t\t\t\tString algo = pk.getAlgorithm();\n\n\t\t\t\tKeyPair kp;\n\n\t\t\t\tif(algo.equals(\"RSA\")) {\n\t\t\t\t\tkp = getRSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse if(algo.equals(\"DSA\")) {\n\t\t\t\t\tkp = getDSAKeyPair();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthrow new InvalidKeyException(\"Key algorithm \" + algo + \" not supported.\");\n\t\t\t\t}\n\t\t\t\tmappedPk = kp.getPublic();\n\t\t\t\tprivKey = kp.getPrivate();\n\n\t\t\t\tmapPublicKeys(cert.getPublicKey(), mappedPk);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprivKey = getPrivateKey(mappedPk);\n\t\t\t}\n\n\n\t\t\tX509Certificate replacementCert =\n\t\t\t\tCertificateCreator.mitmDuplicateCertificate(\n\t\t\t\t\t\tcert,\n\t\t\t\t\t\tmappedPk,\n\t\t\t\t\t\tgetSigningCert(),\n\t\t\t\t\t\tgetSigningPrivateKey());\n\n\t\t\taddCertAndPrivateKey(null, replacementCert, privKey);\n\n\t\t\tmappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);\n\n\t\t\t_certMap.put(thumbprint, mappedCertThumbprint);\n\t\t\t_certMap.put(mappedCertThumbprint, thumbprint);\n\t\t\t_subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);\n\n\t\t\tif(persistImmediately) {\n\t\t\t\tpersist();\n\t\t\t}\n\t\t\treturn replacementCert;\n\t\t}\n return getCertificateByAlias(mappedCertThumbprint);\n\n\t}", "public static DeploymentUnit getTopDeploymentUnit(DeploymentUnit unit) {\n Assert.checkNotNullParam(\"unit\", unit);\n\n DeploymentUnit parent = unit.getParent();\n while (parent != null) {\n unit = parent;\n parent = unit.getParent();\n }\n return unit;\n }" ]
Leave a group. @see <a href="http://www.flickr.com/services/api/flickr.groups.leave.html">lickr.groups.leave</a> for a description of the various behaviors possible when a user leaves a group. @param groupId - the id of the group to leave @param deletePhotos - delete photos by this user from group
[ "public void leave(String groupId, Boolean deletePhotos) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LEAVE);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"delete_photos\", deletePhotos);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
[ "public static linkset get(nitro_service service, String id) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tobj.set_id(id);\n\t\tlinkset response = (linkset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void addCell(TableLayoutCell cell) {\n GridBagConstraints constraints = cell.getConstraints();\n constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding);\n add(cell.getComponent(), constraints);\n }", "public GroovyFieldDoc[] fields() {\n Collections.sort(fields);\n return fields.toArray(new GroovyFieldDoc[fields.size()]);\n }", "public static CurrencySymbolPosition getSymbolPosition(int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:\n default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }", "private void getYearlyRelativeDates(Calendar calendar, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.set(Calendar.MONTH, NumberHelper.getInt(m_monthNumber) - 1);\n\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.YEAR, 1);\n }\n }", "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }", "protected boolean exportWithMinimalMetaData(String path) {\n\n String checkPath = path.startsWith(\"/\") ? path + \"/\" : \"/\" + path + \"/\";\n for (String p : m_parameters.getResourcesToExportWithMetaData()) {\n if (checkPath.startsWith(p)) {\n return false;\n }\n }\n return true;\n }", "public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}", "protected boolean checkExcludePackages(String classPackageName) {\n\t\tif (excludePackages != null && excludePackages.length > 0) {\n\t\t\tWildcardHelper wildcardHelper = new WildcardHelper();\n\n\t\t\t// we really don't care about the results, just the boolean\n\t\t\tMap<String, String> matchMap = new HashMap<String, String>();\n\n\t\t\tfor (String packageExclude : excludePackages) {\n\t\t\t\tint[] packagePattern = wildcardHelper.compilePattern(packageExclude);\n\t\t\t\tif (wildcardHelper.match(matchMap, classPackageName, packagePattern)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}" ]
Locates a task within a child task container which matches the supplied UUID. @param parent child task container @param uuid required UUID @return Task instance or null if the task is not found
[ "private Task findChildTaskByUUID(ChildTaskContainer parent, UUID uuid)\n {\n Task result = null;\n\n for (Task task : parent.getChildTasks())\n {\n if (uuid.equals(task.getGUID()))\n {\n result = task;\n break;\n }\n }\n\n return result;\n }" ]
[ "public synchronized boolean undoRoleMappingRemove(final Object removalKey) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n RoleMappingImpl toRestore = removedRoles.remove(removalKey);\n if (toRestore != null && newRoles.containsKey(toRestore.getName()) == false) {\n newRoles.put(toRestore.getName(), toRestore);\n roleMappings = Collections.unmodifiableMap(newRoles);\n return true;\n }\n\n return false;\n }", "private static boolean typeEquals(ParameterizedType from,\n\t\t\tParameterizedType to, Map<String, Type> typeVarMap) {\n\t\tif (from.getRawType().equals(to.getRawType())) {\n\t\t\tType[] fromArgs = from.getActualTypeArguments();\n\t\t\tType[] toArgs = to.getActualTypeArguments();\n\t\t\tfor (int i = 0; i < fromArgs.length; i++) {\n\t\t\t\tif (!matches(fromArgs[i], toArgs[i], typeVarMap)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}", "void flushLogQueue() {\n Set<String> problems = new LinkedHashSet<String>();\n synchronized (messageQueue) {\n Iterator<LogEntry> i = messageQueue.iterator();\n while (i.hasNext()) {\n problems.add(\"\\t\\t\" + i.next().getMessage() + \"\\n\");\n i.remove();\n }\n }\n if (!problems.isEmpty()) {\n logger.transformationWarnings(target.getHostName(), problems);\n }\n }", "public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }", "public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }", "@Override\n public synchronized void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n while (!taskQueue.isEmpty() && (activeRequestCount < maxRequestCount || maxRequestCount < 0)) {\n runQueuedTask(false);\n }\n }", "private List<Key> getScatterKeys(\n int numSplits, Query query, PartitionId partition, Datastore datastore)\n throws DatastoreException {\n Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);\n\n List<Key> keySplits = new ArrayList<Key>();\n\n QueryResultBatch batch;\n do {\n RunQueryRequest scatterRequest =\n RunQueryRequest.newBuilder()\n .setPartitionId(partition)\n .setQuery(scatterPointQuery)\n .build();\n batch = datastore.runQuery(scatterRequest).getBatch();\n for (EntityResult result : batch.getEntityResultsList()) {\n keySplits.add(result.getEntity().getKey());\n }\n scatterPointQuery.setStartCursor(batch.getEndCursor());\n scatterPointQuery.getLimitBuilder().setValue(\n scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());\n } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);\n Collections.sort(keySplits, DatastoreHelper.getKeyComparator());\n return keySplits;\n }", "public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }" ]
Get info for a given topic @param topicId Unique identifier of a topic for a given group {@link Topic}. @return A group topic @throws FlickrException @see <a href="http://www.flickr.com/services/api/flickr.groups.discuss.topics.getInfo.html">API Documentation</a>
[ "public Topic getTopicInfo(String topicId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_TOPICS_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\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 topicElement = response.getPayload();\r\n\r\n return parseTopic(topicElement);\r\n }" ]
[ "private String resolveExpressionString(final String unresolvedString) throws OperationFailedException {\n\n // parseAndResolve should only be providing expressions with no leading or trailing chars\n assert unresolvedString.startsWith(\"${\") && unresolvedString.endsWith(\"}\");\n\n // Default result is no change from input\n String result = unresolvedString;\n\n ModelNode resolveNode = new ModelNode(new ValueExpression(unresolvedString));\n\n // Try plug-in resolution; i.e. vault\n resolvePluggableExpression(resolveNode);\n\n if (resolveNode.getType() == ModelType.EXPRESSION ) {\n // resolvePluggableExpression did nothing. Try standard resolution\n String resolvedString = resolveStandardExpression(resolveNode);\n if (!unresolvedString.equals(resolvedString)) {\n // resolveStandardExpression made progress\n result = resolvedString;\n } // else there is nothing more we can do with this string\n } else {\n // resolvePluggableExpression made progress\n result = resolveNode.asString();\n }\n\n return result;\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}", "private static Class getClassForClassNode(ClassNode type) {\r\n // todo hamlet - move to a different \"InferenceUtil\" object\r\n Class primitiveType = getPrimitiveType(type);\r\n if (primitiveType != null) {\r\n return primitiveType;\r\n } else if (classNodeImplementsType(type, String.class)) {\r\n return String.class;\r\n } else if (classNodeImplementsType(type, ReentrantLock.class)) {\r\n return ReentrantLock.class;\r\n } else if (type.getName() != null && type.getName().endsWith(\"[]\")) {\r\n return Object[].class; // better type inference could be done, but oh well\r\n }\r\n return null;\r\n }", "public static Status from(Set<ServiceReference> serviceReferencesBound, Set<ServiceReference> serviceReferencesHandled) {\n if (serviceReferencesBound == null && serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\" +\n \"and serviceReferencesHandled == null\");\n } else if (serviceReferencesBound == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesBound == null\");\n } else if (serviceReferencesHandled == null) {\n throw new IllegalArgumentException(\"Cannot create a status with serviceReferencesHandled == null\");\n }\n return new Status(serviceReferencesBound, serviceReferencesHandled);\n }", "public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}", "private D createAndRegisterDeclaration(Map<String, Object> metadata) {\n D declaration;\n if (klass.equals(ImportDeclaration.class)) {\n declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();\n } else if (klass.equals(ExportDeclaration.class)) {\n declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();\n } else {\n throw new IllegalStateException(\"\");\n }\n declarationRegistrationManager.registerDeclaration(declaration);\n return declaration;\n }", "public static authenticationldappolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationldappolicy_authenticationvserver_binding obj = new authenticationldappolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationldappolicy_authenticationvserver_binding response[] = (authenticationldappolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "synchronized public void completeTask(int taskId, int partitionStoresMigrated) {\n tasksInFlight.remove(taskId);\n\n numTasksCompleted++;\n numPartitionStoresMigrated += partitionStoresMigrated;\n\n updateProgressBar();\n }", "public void restoreSecurityContext(CacheContext context) {\n\t\tSavedAuthorization cached = context.get(CacheContext.SECURITY_CONTEXT_KEY, SavedAuthorization.class);\n\t\tif (cached != null) {\n\t\t\tlog.debug(\"Restoring security context {}\", cached);\n\t\t\tsecurityManager.restoreSecurityContext(cached);\n\t\t} else {\n\t\t\tsecurityManager.clearSecurityContext();\n\t\t}\n\t}" ]
Get a property as a string or throw an exception. @param key the property name
[ "@Override\n public final String getString(final String key) {\n String result = optString(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }" ]
[ "private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }", "public String getHostAddress() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostAddress();\n }\n return ((InetAddress)addr).getHostAddress();\n }", "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 }", "private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }", "public boolean matches(PathAddress address) {\n if (address == null) {\n return false;\n }\n if (equals(address)) {\n return true;\n }\n if (size() != address.size()) {\n return false;\n }\n for (int i = 0; i < size(); i++) {\n PathElement pe = getElement(i);\n PathElement other = address.getElement(i);\n if (!pe.matches(other)) {\n // Could be a multiTarget with segments\n if (pe.isMultiTarget() && !pe.isWildcard()) {\n boolean matched = false;\n for (String segment : pe.getSegments()) {\n if (segment.equals(other.getValue())) {\n matched = true;\n break;\n }\n }\n if (!matched) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }", "synchronized void processFinished() {\n final InternalState required = this.requiredState;\n final InternalState state = this.internalState;\n // If the server was not stopped\n if(required == InternalState.STOPPED && state == InternalState.PROCESS_STOPPING) {\n finishTransition(InternalState.PROCESS_STOPPING, InternalState.PROCESS_STOPPED);\n } else {\n this.requiredState = InternalState.STOPPED;\n if ( !(internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), internalState, InternalState.PROCESS_STOPPING)\n && internalSetState(getTransitionTask(InternalState.PROCESS_REMOVING), internalState, InternalState.PROCESS_REMOVING)\n && internalSetState(getTransitionTask(InternalState.STOPPED), internalState, InternalState.STOPPED)) ){\n this.requiredState = InternalState.FAILED;\n internalSetState(null, internalState, InternalState.PROCESS_STOPPED);\n }\n }\n }", "public static String createFolderPath(String path) {\n\n String[] pathParts = path.split(\"\\\\.\");\n String path2 = \"\";\n for (String part : pathParts) {\n if (path2.equals(\"\")) {\n path2 = part;\n } else {\n path2 = path2 + File.separator\n + changeFirstLetterToLowerCase(createClassName(part));\n }\n }\n\n return path2;\n }", "public static boolean oracleExists(CuratorFramework curator) {\n boolean exists = false;\n try {\n exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null\n && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty();\n } catch (Exception nne) {\n if (nne instanceof KeeperException.NoNodeException) {\n // you'll do nothing\n } else {\n throw new RuntimeException(nne);\n }\n }\n return exists;\n }", "public String get(final long index) {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.lindex(getKey(), index);\n }\n });\n }" ]
Scan all the class path and look for all classes that have the Format Annotations.
[ "public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}" ]
[ "public Stats getPhotostreamStats(Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSTREAM_STATS, null, null, date);\n }", "public static JRDesignExpression getReportConnectionExpression() {\n JRDesignExpression connectionExpression = new JRDesignExpression();\n connectionExpression.setText(\"$P{\" + JRDesignParameter.REPORT_CONNECTION + \"}\");\n connectionExpression.setValueClass(Connection.class);\n return connectionExpression;\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 }", "private static int findTrackIdAtOffset(SlotReference slot, Client client, int offset) throws IOException {\n Message entry = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot.slot, CdjStatus.TrackType.REKORDBOX, offset, 1).get(0);\n if (entry.getMenuItemType() == Message.MenuItemType.UNKNOWN) {\n logger.warn(\"Encountered unrecognized track list entry item type: {}\", entry);\n }\n return (int)((NumberField)entry.arguments.get(1)).getValue();\n }", "public static final String printResourceUID(Integer value)\n {\n ProjectFile file = PARENT_FILE.get();\n if (file != null)\n {\n file.getEventManager().fireResourceWrittenEvent(file.getResourceByUniqueID(value));\n }\n return (value.toString());\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void enableKeyboardAutoHiding() {\n keyboardListener = new OnScrollListener() {\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n if (dx != 0 || dy != 0) {\n imeManager.hideSoftInputFromWindow(\n Hits.this.getWindowToken(),\n InputMethodManager.HIDE_NOT_ALWAYS);\n }\n super.onScrolled(recyclerView, dx, dy);\n }\n };\n addOnScrollListener(keyboardListener);\n }", "public 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 void getYearlyAbsoluteDates(Calendar calendar, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.set(Calendar.MONTH, NumberHelper.getInt(m_monthNumber) - 1);\n int requiredDayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n int useDayNumber = requiredDayNumber;\n int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n if (useDayNumber > maxDayNumber)\n {\n useDayNumber = maxDayNumber;\n }\n\n calendar.set(Calendar.DAY_OF_MONTH, useDayNumber);\n if (calendar.getTimeInMillis() < startDate)\n {\n calendar.add(Calendar.YEAR, 1);\n }\n\n dates.add(calendar.getTime());\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.YEAR, 1);\n }\n }", "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}" ]
Creates a ServiceCall from a paging operation. @param first the observable to the first page @param next the observable to poll subsequent pages @param callback the client-side callback @param <E> the element type @return the future based ServiceCall
[ "public static <E> ServiceFuture<List<E>> fromPageResponse(Observable<ServiceResponse<Page<E>>> first, final Func1<String, Observable<ServiceResponse<Page<E>>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, next, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }" ]
[ "public void setBody(String body) {\n byte[] bytes = body.getBytes(StandardCharsets.UTF_8);\n this.bodyLength = bytes.length;\n this.body = new ByteArrayInputStream(bytes);\n }", "private void populateCurrencySettings(Record record, ProjectProperties properties)\n {\n properties.setCurrencySymbol(record.getString(0));\n properties.setSymbolPosition(record.getCurrencySymbolPosition(1));\n properties.setCurrencyDigits(record.getInteger(2));\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setThousandsSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setDecimalSeparator(c.charValue());\n }\n }", "@Deprecated\n public static RemoteProxyController create(final ManagementChannelHandler channelAssociation, final PathAddress pathAddress, final ProxyOperationAddressTranslator addressTranslator) {\n final TransactionalProtocolClient client = TransactionalProtocolHandlers.createClient(channelAssociation);\n // the remote proxy\n return create(client, pathAddress, addressTranslator, ModelVersion.CURRENT);\n }", "private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_HEIGHT, \"\" + this.getHeight());\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_WIDTH, \"\" + this.getWidth());\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_POSX, \"\" + this.getBounds().x);\r\n Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_POSY, \"\" + this.getBounds().y);\r\n Main.getProperties().storeProperties(\"\");\r\n System.exit(0);\r\n }", "public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }", "static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {\n AzureAsyncOperation asyncOperation = null;\n String rawString = null;\n if (response.body() != null) {\n try {\n rawString = response.body().string();\n asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);\n } catch (IOException exception) {\n // Exception will be handled below\n } finally {\n response.body().close();\n }\n }\n if (asyncOperation == null || asyncOperation.status() == null) {\n throw new CloudException(\"polling response does not contain a valid body: \" + rawString, response);\n }\n else {\n asyncOperation.rawString = rawString;\n }\n return asyncOperation;\n }", "public static final Bytes of(String s, Charset c) {\n Objects.requireNonNull(s);\n Objects.requireNonNull(c);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(c);\n return new Bytes(data);\n }", "public E setById(final int id, final E element) {\n VListKey<K> key = new VListKey<K>(_key, id);\n UpdateElementById<K, E> updateElementAction = new UpdateElementById<K, E>(key, element);\n\n if(!_storeClient.applyUpdate(updateElementAction))\n throw new ObsoleteVersionException(\"update failed\");\n\n return updateElementAction.getResult();\n }" ]
Adds a new child widget to the panel, attaching its Element to the specified container Element. @param child the child widget to be added @param container the element within which the child will be contained
[ "protected void add(Widget child, Element container) {\n\n // Detach new child.\n child.removeFromParent();\n\n // Logical attach.\n getChildren().add(child);\n\n // Physical attach.\n DOM.appendChild(container, child.getElement());\n\n // Adopt.\n adopt(child);\n }" ]
[ "public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }", "public Map<String, MBeanAttributeInfo> getAttributeMetadata() {\n\n MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes();\n\n Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>();\n for (MBeanAttributeInfo attribute: attributeList) {\n attributeMap.put(attribute.getName(), attribute);\n }\n return attributeMap;\n }", "public static String readFlowId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String flowId = null;\n Header hdFlowId = ((SoapMessage)message).getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n if (hdFlowId.getObject() instanceof String) {\n flowId = (String)hdFlowId.getObject();\n } else if (hdFlowId.getObject() instanceof Node) {\n Node headerNode = (Node)hdFlowId.getObject();\n flowId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found FlowId soap header but value is not a String or a Node! Value: \"\n + hdFlowId.getObject().toString());\n }\n }\n return flowId;\n }", "public void delete() {\n URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.DELETE);\n\n request.send();\n }", "protected Object[] idsOf(final List<?> idsOrValues) {\n // convert list to array that we can mutate\n final Object[] ids = idsOrValues.toArray();\n\n // mutate array to contain only non-empty ids\n int length = 0;\n for (int i = 0; i < ids.length;) {\n final Object p = ids[i++];\n if (p instanceof HasId) {\n // only use values with ids that are non-empty\n final String id = ((HasId) p).getId();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p instanceof String) {\n // only use ids that are non-empty\n final String id = p.toString();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p != null) {\n throw new StoreException(\"Invalid id or value of type \" + p);\n }\n }\n\n // no ids in array\n if (length == 0) {\n return null;\n }\n\n // some ids in array\n if (length != ids.length) {\n final Object[] tmp = new Object[length];\n System.arraycopy(ids, 0, tmp, 0, length);\n return tmp;\n }\n\n // array was full\n return ids;\n }", "protected int mapGanttBarHeight(int height)\n {\n switch (height)\n {\n case 0:\n {\n height = 6;\n break;\n }\n\n case 1:\n {\n height = 8;\n break;\n }\n\n case 2:\n {\n height = 10;\n break;\n }\n\n case 3:\n {\n height = 12;\n break;\n }\n\n case 4:\n {\n height = 14;\n break;\n }\n\n case 5:\n {\n height = 18;\n break;\n }\n\n case 6:\n {\n height = 24;\n break;\n }\n }\n\n return (height);\n }", "public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }", "public static base_responses add(nitro_service client, dnspolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnspolicylabel addresources[] = new dnspolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnspolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].transform = resources[i].transform;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private void addStatement(RecordImpl record,\n String subject,\n String property,\n String object) {\n Collection<Column> cols = columns.get(property);\n if (cols == null) {\n if (property.equals(RDF_TYPE) && !types.isEmpty())\n addValue(record, subject, property, object);\n return;\n }\n \n for (Column col : cols) {\n String cleaned = object;\n if (col.getCleaner() != null)\n cleaned = col.getCleaner().clean(object);\n if (cleaned != null && !cleaned.equals(\"\"))\n addValue(record, subject, col.getProperty(), cleaned);\n }\n }" ]
This method reads a two byte integer from the input stream. @param is the input stream @return integer value @throws IOException on file read error or EOF
[ "protected int readShort(InputStream is) throws IOException\n {\n byte[] data = new byte[2];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getShort(data, 0));\n }" ]
[ "public int getPartition(byte[] key,\n byte[] value,\n int numReduceTasks) {\n try {\n /**\n * {@link partitionId} is the Voldemort primary partition that this\n * record belongs to.\n */\n int partitionId = ByteUtils.readInt(value, ByteUtils.SIZE_OF_INT);\n\n /**\n * This is the base number we will ultimately mod by {@link numReduceTasks}\n * to determine which reduce task to shuffle to.\n */\n int magicNumber = partitionId;\n\n if (getSaveKeys() && !buildPrimaryReplicasOnly) {\n /**\n * When saveKeys is enabled (which also implies we are generating\n * READ_ONLY_V2 format files), then we are generating files with\n * a replica type, with one file per replica.\n *\n * Each replica is sent to a different reducer, and thus the\n * {@link magicNumber} is scaled accordingly.\n *\n * The downside to this is that it is pretty wasteful. The files\n * generated for each replicas are identical to one another, so\n * there's no point in generating them independently in many\n * reducers.\n *\n * This is one of the reasons why buildPrimaryReplicasOnly was\n * written. In this mode, we only generate the files for the\n * primary replica, which means the number of reducers is\n * minimized and {@link magicNumber} does not need to be scaled.\n */\n int replicaType = (int) ByteUtils.readBytes(value,\n 2 * ByteUtils.SIZE_OF_INT,\n ByteUtils.SIZE_OF_BYTE);\n magicNumber = magicNumber * getStoreDef().getReplicationFactor() + replicaType;\n }\n\n if (!getReducerPerBucket()) {\n /**\n * Partition files can be split in many chunks in order to limit the\n * maximum file size downloaded and handled by Voldemort servers.\n *\n * {@link chunkId} represents which chunk of partition then current\n * record belongs to.\n */\n int chunkId = ReadOnlyUtils.chunk(key, getNumChunks());\n\n /**\n * When reducerPerBucket is disabled, all chunks are sent to a\n * different reducer. This increases parallelism at the expense\n * of adding more load on Hadoop.\n *\n * {@link magicNumber} is thus scaled accordingly, in order to\n * leverage the extra reducers available to us.\n */\n magicNumber = magicNumber * getNumChunks() + chunkId;\n }\n\n /**\n * Finally, we mod {@link magicNumber} by {@link numReduceTasks},\n * since the MapReduce framework expects the return of this function\n * to be bounded by the number of reduce tasks running in the job.\n */\n return magicNumber % numReduceTasks;\n } catch (Exception e) {\n throw new VoldemortException(\"Caught exception in getPartition()!\" +\n \" key: \" + ByteUtils.toHexString(key) +\n \", value: \" + ByteUtils.toHexString(value) +\n \", numReduceTasks: \" + numReduceTasks, e);\n }\n }", "public static aaauser_auditsyslogpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_auditsyslogpolicy_binding obj = new aaauser_auditsyslogpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_auditsyslogpolicy_binding response[] = (aaauser_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected BlockBox createBlock(BlockBox parent, Element n, boolean replaced)\n {\n BlockBox root;\n if (replaced)\n {\n BlockReplacedBox rbox = new BlockReplacedBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n rbox.setViewport(viewport);\n rbox.setContentObj(new ReplacedImage(rbox, rbox.getVisualContext(), baseurl, n.getAttribute(\"src\")));\n root = rbox;\n }\n else\n {\n root = new BlockBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n root.setViewport(viewport);\n }\n root.setBase(baseurl);\n root.setParent(parent);\n root.setContainingBlockBox(parent);\n root.setClipBlock(viewport);\n root.setOrder(next_order++);\n return root;\n }", "public IPv4AddressSection mask(IPv4AddressSection mask, boolean retainPrefix) throws IncompatibleAddressException, PrefixLenException, SizeMismatchException {\n\t\tcheckMaskSectionCount(mask);\n\t\treturn getSubnetSegments(\n\t\t\t\tthis,\n\t\t\t\tretainPrefix ? getPrefixLength() : null,\n\t\t\t\tgetAddressCreator(),\n\t\t\t\ttrue,\n\t\t\t\tthis::getSegment,\n\t\t\t\ti -> mask.getSegment(i).getSegmentValue(),\n\t\t\t\tfalse);\n\t}", "@SuppressWarnings(\"unchecked\")\n\tpublic <T extends TermedStatementDocument> T updateTermsStatements(T currentDocument,\n\t\t\tList<MonolingualTextValue> addLabels,\n\t\t\tList<MonolingualTextValue> addDescriptions,\n\t\t\tList<MonolingualTextValue> addAliases,\n\t\t\tList<MonolingualTextValue> deleteAliases,\n\t\t\tList<Statement> addStatements, List<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\t\t\n\t\tTermStatementUpdate termStatementUpdate = new TermStatementUpdate(\n\t\t\t\tcurrentDocument,\n\t\t\t\taddStatements, deleteStatements,\n\t\t\t\taddLabels, addDescriptions, addAliases, deleteAliases);\n\t\ttermStatementUpdate.setGuidGenerator(guidGenerator);\n\t\t\n\t\treturn (T) termStatementUpdate.performEdit(wbEditingAction, editAsBot, summary);\n\t}", "public void read(byte[] holder) throws ProtocolException {\r\n int readTotal = 0;\r\n try {\r\n while (readTotal < holder.length) {\r\n int count = input.read(holder, readTotal, holder.length - readTotal);\r\n if (count == -1) {\r\n throw new ProtocolException(\"Unexpected end of stream.\");\r\n }\r\n readTotal += count;\r\n }\r\n // Unset the next char.\r\n nextSeen = false;\r\n nextChar = 0;\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Error reading from stream.\", e);\r\n }\r\n }", "public static void log(byte[] data)\n {\n if (LOG != null)\n {\n LOG.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n LOG.flush();\n }\n }", "public static double computeRowMax( ZMatrixRMaj A ,\n int row , int col0 , int col1 ) {\n double max = 0;\n\n int indexA = A.getIndex(row,col0);\n double h[] = A.data;\n\n for (int i = col0; i < col1; i++) {\n double realVal = h[indexA++];\n double imagVal = h[indexA++];\n\n double magVal = realVal*realVal + imagVal*imagVal;\n if( max < magVal ) {\n max = magVal;\n }\n }\n return Math.sqrt(max);\n }", "private boolean addType(TypeDefinition type) {\n\n if (type == null) {\n return false;\n }\n\n if (type.getBaseTypeId() == null) {\n return false;\n }\n\n // find base type\n TypeDefinition baseType = null;\n if (type.getBaseTypeId() == BaseTypeId.CMIS_DOCUMENT) {\n baseType = copyTypeDefintion(m_types.get(DOCUMENT_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) {\n baseType = copyTypeDefintion(m_types.get(FOLDER_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_RELATIONSHIP) {\n baseType = copyTypeDefintion(m_types.get(RELATIONSHIP_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_POLICY) {\n baseType = copyTypeDefintion(m_types.get(POLICY_TYPE_ID).getTypeDefinition());\n } else {\n return false;\n }\n\n AbstractTypeDefinition newType = (AbstractTypeDefinition)copyTypeDefintion(type);\n\n // copy property definition\n for (PropertyDefinition<?> propDef : baseType.getPropertyDefinitions().values()) {\n ((AbstractPropertyDefinition<?>)propDef).setIsInherited(Boolean.TRUE);\n newType.addPropertyDefinition(propDef);\n }\n\n // add it\n addTypeInternal(newType);\n return true;\n }" ]
Checks if ranges contain the uid @param idRanges the id ranges @param uid the uid @return true, if ranges contain given uid
[ "public static boolean containsUid(IdRange[] idRanges, long uid) {\r\n if (null != idRanges && idRanges.length > 0) {\r\n for (IdRange range : idRanges) {\r\n if (range.includes(uid)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }" ]
[ "private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }", "public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }", "public static Path getRootFolderForSource(Path sourceFilePath, String packageName)\n {\n if (packageName == null || packageName.trim().isEmpty())\n {\n return sourceFilePath.getParent();\n }\n String[] packageNameComponents = packageName.split(\"\\\\.\");\n Path currentPath = sourceFilePath.getParent();\n for (int i = packageNameComponents.length; i > 0; i--)\n {\n String packageComponent = packageNameComponents[i - 1];\n if (!StringUtils.equals(packageComponent, currentPath.getFileName().toString()))\n {\n return null;\n }\n currentPath = currentPath.getParent();\n }\n return currentPath;\n }", "private I_CmsSearchIndex getIndex() {\n\n I_CmsSearchIndex index = null;\n // get the configured index or the selected index\n if (isInitialCall()) {\n // the search form is in the initial state\n // get the configured index\n index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName());\n } else {\n // the search form is not in the inital state, the submit button was used already or the\n // search index was changed already\n // get the selected index in the search dialog\n index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter(\"indexName.0\"));\n }\n return index;\n }", "public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }", "public void addNotBetween(Object attribute, Object value1, Object value2)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }", "private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }", "public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){\n\t\tfinal Artifact artifact = new Artifact();\n\n\t\tartifact.setGroupId(groupId);\n\t\tartifact.setArtifactId(artifactId);\n\t\tartifact.setVersion(version);\n\n\t\tif(classifier != null){\n\t\t\tartifact.setClassifier(classifier);\n\t\t}\n\n\t\tif(type != null){\n\t\t\tartifact.setType(type);\n\t\t}\n\n\t\tif(extension != null){\n\t\t\tartifact.setExtension(extension);\n\t\t}\n\n\t\tartifact.setOrigin(origin == null ? \"maven\" : origin);\n\n\t\treturn artifact;\n\t}", "public void setBREE(String bree) {\n\t\tString old = mainAttributes.get(BUNDLE_REQUIREDEXECUTIONENVIRONMENT);\n\t\tif (!bree.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_REQUIREDEXECUTIONENVIRONMENT, bree);\n\t\t\tthis.modified = true;\n\t\t\tthis.bree = bree;\n\t\t}\n\t}" ]
Returns the number of key-value mappings in this map for the third key. @param firstKey the first key @param secondKey the second key @return Returns the number of key-value mappings in this map for the third key.
[ "public int size(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t// existence check on inner map1\n\t\tfinal HashMap<K3, V> innerMap2 = innerMap1.get(secondKey);\n\t\tif( innerMap2 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap2.size();\n\t}" ]
[ "public static String replaceParameters(final InputStream stream) {\n String content = IOUtil.asStringPreservingNewLines(stream);\n return resolvePlaceholders(content);\n }", "public static dnstxtrec[] get(nitro_service service, dnstxtrec_args args) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public static Configuration loadFromString(String config)\n throws IOException, SAXException {\n ConfigurationImpl cfg = new ConfigurationImpl();\n\n XMLReader parser = XMLReaderFactory.createXMLReader();\n parser.setContentHandler(new ConfigHandler(cfg, null));\n Reader reader = new StringReader(config);\n parser.parse(new InputSource(reader));\n return cfg;\n }", "protected void postDestroyConnection(ConnectionHandle handle){\r\n\t\tConnectionPartition partition = handle.getOriginatingPartition();\r\n\r\n\t\tif (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety\r\n\t\t\tthis.finalizableRefs.remove(handle.getInternalConnection());\r\n\t\t\t//\t\t\tassert o != null : \"Did not manage to remove connection from finalizable ref queue\";\r\n\t\t}\r\n\r\n\t\tpartition.updateCreatedConnections(-1);\r\n\t\tpartition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\r\n\r\n\t\t// \"Destroying\" for us means: don't put it back in the pool.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onDestroy(handle);\r\n\t\t}\r\n\r\n\t}", "protected void associateBatched(Collection owners, Collection children)\r\n {\r\n ObjectReferenceDescriptor ord = getObjectReferenceDescriptor();\r\n ClassDescriptor cld = getOwnerClassDescriptor();\r\n Object owner;\r\n Object relatedObject;\r\n Object fkValues[];\r\n Identity id;\r\n PersistenceBroker pb = getBroker();\r\n PersistentField field = ord.getPersistentField();\r\n Class topLevelClass = pb.getTopLevelClass(ord.getItemClass());\r\n HashMap childrenMap = new HashMap(children.size());\r\n\r\n\r\n for (Iterator it = children.iterator(); it.hasNext(); )\r\n {\r\n relatedObject = it.next();\r\n childrenMap.put(pb.serviceIdentity().buildIdentity(relatedObject), relatedObject);\r\n }\r\n\r\n for (Iterator it = owners.iterator(); it.hasNext(); )\r\n {\r\n owner = it.next();\r\n fkValues = ord.getForeignKeyValues(owner,cld);\r\n if (isNull(fkValues))\r\n {\r\n field.set(owner, null);\r\n continue;\r\n }\r\n id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues);\r\n relatedObject = childrenMap.get(id);\r\n field.set(owner, relatedObject);\r\n }\r\n }", "@Override\n public boolean invokeFunction(String funcName, Object[] params) {\n // Run script if it is dirty. This makes sure the script is run\n // on the same thread as the caller (suppose the caller is always\n // calling from the same thread).\n checkDirty();\n\n // Skip bad functions\n if (isBadFunction(funcName)) {\n return false;\n }\n\n String statement = getInvokeStatementCached(funcName, params);\n\n synchronized (mEngineLock) {\n localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE);\n if (localBindings == null) {\n localBindings = mLocalEngine.createBindings();\n mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE);\n }\n }\n\n fillBindings(localBindings, params);\n\n try {\n mLocalEngine.eval(statement);\n } catch (ScriptException e) {\n // The function is either undefined or throws, avoid invoking it later\n addBadFunction(funcName);\n mLastError = e.getMessage();\n return false;\n } finally {\n removeBindings(localBindings, params);\n }\n\n return true;\n }", "public <T> T get(URI uri, Class<T> classType) {\n HttpConnection connection = Http.GET(uri);\n InputStream response = executeToInputStream(connection);\n try {\n return getResponse(response, classType, getGson());\n } finally {\n close(response);\n }\n }", "@UiHandler({\"m_atMonth\", \"m_everyMonth\"})\r\n void onMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setMonth(event.getValue());\r\n }\r\n }", "public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }" ]
If X == null then the solution is written into B. Otherwise the solution is copied from B into X.
[ "@Override\n public void solve(DMatrixRBlock B, DMatrixRBlock X) {\n if( B.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in B.\");\n\n DSubmatrixD1 L = new DSubmatrixD1(decomposer.getT(null));\n\n if( X != null ) {\n if( X.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in X.\");\n if( X.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in X\");\n }\n \n if( B.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in B\");\n\n // L * L^T*X = B\n\n // Solve for Y: L*Y = B\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),false);\n\n // L^T * X = Y\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),true);\n\n if( X != null ) {\n // copy the solution from B into X\n MatrixOps_DDRB.extractAligned(B,X);\n }\n\n }" ]
[ "public 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 }", "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n Boolean lastExpandedState = savedLastExpansionState.get(parent);\n boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState;\n\n generateParentWrapper(flatItemList, parent, shouldExpand);\n }\n\n return flatItemList;\n }", "private List<Variable> parseAssignRange(Sequence sequence, TokenList tokens, TokenList.Token t0) {\n // find assignment symbol\n TokenList.Token tokenAssign = t0.next;\n while( tokenAssign != null && tokenAssign.symbol != Symbol.ASSIGN ) {\n tokenAssign = tokenAssign.next;\n }\n\n if( tokenAssign == null )\n throw new ParseError(\"Can't find assignment operator\");\n\n // see if it is a sub matrix before\n if( tokenAssign.previous.symbol == Symbol.PAREN_RIGHT ) {\n TokenList.Token start = t0.next;\n if( start.symbol != Symbol.PAREN_LEFT )\n throw new ParseError((\"Expected left param for assignment\"));\n TokenList.Token end = tokenAssign.previous;\n TokenList subTokens = tokens.extractSubList(start,end);\n subTokens.remove(subTokens.getFirst());\n subTokens.remove(subTokens.getLast());\n\n handleParentheses(subTokens,sequence);\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(subTokens, sequence);\n\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n\n List<Variable> range = new ArrayList<>();\n addSubMatrixVariables(inputs, range);\n if( range.size() != 1 && range.size() != 2 ) {\n throw new ParseError(\"Unexpected number of range variables. 1 or 2 expected\");\n }\n return range;\n }\n\n return null;\n }", "public static java.util.Date newDateTime() {\n return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);\n }", "protected Method resolveTargetMethod(Message message,\n FieldDescriptor payloadField) {\n Method targetMethod = fieldToMethod.get(payloadField);\n\n if (targetMethod == null) {\n // look up and cache target method; this block is called only once\n // per target method, so synchronized is ok\n synchronized (this) {\n targetMethod = fieldToMethod.get(payloadField);\n if (targetMethod == null) {\n String name = payloadField.getName();\n for (Method method : service.getClass().getMethods()) {\n if (method.getName().equals(name)) {\n try {\n method.setAccessible(true);\n } catch (Exception ex) {\n log.log(Level.SEVERE,\"Error accessing RPC method\",ex);\n }\n\n targetMethod = method;\n fieldToMethod.put(payloadField, targetMethod);\n break;\n }\n }\n }\n }\n }\n\n if (targetMethod != null) {\n return targetMethod;\n } else {\n throw new RuntimeException(\"No matching method found by the name '\"\n + payloadField.getName() + \"'\");\n }\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 CollectionRequest<Project> tasks(String project) {\n \n String path = String.format(\"/projects/%s/tasks\", project);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public static int secondsDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));\n }", "public void resolveLazyCrossReferences(final CancelIndicator mon) {\n\t\tfinal CancelIndicator monitor = mon == null ? CancelIndicator.NullImpl : mon;\n\t\tTreeIterator<Object> iterator = EcoreUtil.getAllContents(this, true);\n\t\twhile (iterator.hasNext()) {\n\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\tInternalEObject source = (InternalEObject) iterator.next();\n\t\t\tEStructuralFeature[] eStructuralFeatures = ((EClassImpl.FeatureSubsetSupplier) source.eClass()\n\t\t\t\t\t.getEAllStructuralFeatures()).crossReferences();\n\t\t\tif (eStructuralFeatures != null) {\n\t\t\t\tfor (EStructuralFeature crossRef : eStructuralFeatures) {\n\t\t\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\t\t\tresolveLazyCrossReference(source, crossRef);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
Detect if the given object has a PK field represents a 'null' value.
[ "public boolean hasNullPKField(ClassDescriptor cld, Object obj)\r\n {\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n boolean hasNull = false;\r\n // an unmaterialized proxy object can never have nullified PK's\r\n IndirectionHandler handler = ProxyHelper.getIndirectionHandler(obj);\r\n if(handler == null || handler.alreadyMaterialized())\r\n {\r\n if(handler != null) obj = handler.getRealSubject();\r\n FieldDescriptor fld;\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n fld = fields[i];\r\n hasNull = representsNull(fld, fld.getPersistentField().get(obj));\r\n if(hasNull) break;\r\n }\r\n }\r\n return hasNull;\r\n }" ]
[ "private void createTimephasedData(ProjectFile file, ResourceAssignment assignment, List<TimephasedWork> timephasedPlanned, List<TimephasedWork> timephasedComplete)\n {\n if (timephasedPlanned.isEmpty() && timephasedComplete.isEmpty())\n {\n Duration totalMinutes = assignment.getWork().convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n\n Duration workPerDay;\n\n if (assignment.getResource() == null || assignment.getResource().getType() == ResourceType.WORK)\n {\n workPerDay = totalMinutes.getDuration() == 0 ? totalMinutes : ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n int units = NumberHelper.getInt(assignment.getUnits());\n if (units != 100)\n {\n workPerDay = Duration.getInstance((workPerDay.getDuration() * units) / 100.0, workPerDay.getUnits());\n }\n }\n else\n {\n if (assignment.getVariableRateUnits() == null)\n {\n Duration workingDays = assignment.getCalendar().getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.DAYS);\n double units = NumberHelper.getDouble(assignment.getUnits());\n double unitsPerDayAsMinutes = (units * 60) / (workingDays.getDuration() * 100);\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n else\n {\n double unitsPerHour = NumberHelper.getDouble(assignment.getUnits());\n workPerDay = ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n Duration hoursPerDay = workPerDay.convertUnits(TimeUnit.HOURS, file.getProjectProperties());\n double unitsPerDayAsHours = (unitsPerHour * hoursPerDay.getDuration()) / 100;\n double unitsPerDayAsMinutes = unitsPerDayAsHours * 60;\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n }\n\n Duration overtimeWork = assignment.getOvertimeWork();\n if (overtimeWork != null && overtimeWork.getDuration() != 0)\n {\n Duration totalOvertimeMinutes = overtimeWork.convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n totalMinutes = Duration.getInstance(totalMinutes.getDuration() - totalOvertimeMinutes.getDuration(), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(assignment.getStart());\n tra.setAmountPerDay(workPerDay);\n tra.setModified(false);\n tra.setFinish(assignment.getFinish());\n tra.setTotalAmount(totalMinutes);\n timephasedPlanned.add(tra);\n }\n }", "static DisplayMetrics getDisplayMetrics(final Context context) {\n final WindowManager\n windowManager =\n (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n final DisplayMetrics metrics = new DisplayMetrics();\n windowManager.getDefaultDisplay().getMetrics(metrics);\n return metrics;\n }", "public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }", "private void updateDb(String dbName, String webapp) {\n\n m_mainLayout.removeAllComponents();\n m_setupBean.setDatabase(dbName);\n CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);\n m_panel[0] = panel;\n panel.initFromSetupBean(webapp);\n m_mainLayout.addComponent(panel);\n }", "public static int rank(SingularValueDecomposition_F64 svd , double threshold ) {\n int numRank=0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] > threshold)\n numRank++;\n }\n\n return numRank;\n }", "public void resolveLazyCrossReferences(final CancelIndicator mon) {\n\t\tfinal CancelIndicator monitor = mon == null ? CancelIndicator.NullImpl : mon;\n\t\tTreeIterator<Object> iterator = EcoreUtil.getAllContents(this, true);\n\t\twhile (iterator.hasNext()) {\n\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\tInternalEObject source = (InternalEObject) iterator.next();\n\t\t\tEStructuralFeature[] eStructuralFeatures = ((EClassImpl.FeatureSubsetSupplier) source.eClass()\n\t\t\t\t\t.getEAllStructuralFeatures()).crossReferences();\n\t\t\tif (eStructuralFeatures != null) {\n\t\t\t\tfor (EStructuralFeature crossRef : eStructuralFeatures) {\n\t\t\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\t\t\tresolveLazyCrossReference(source, crossRef);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public void run(Configuration configuration, InjectableStepsFactory stepsFactory, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n RunContext context = new RunContext(configuration, stepsFactory, story.getPath(), filter);\n if (beforeStories != null) {\n context.stateIs(beforeStories);\n }\n Map<String, String> storyParameters = new HashMap<>();\n run(context, story, storyParameters);\n }", "public static crvserver_policymap_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcrvserver_policymap_binding obj = new crvserver_policymap_binding();\n\t\tobj.set_name(name);\n\t\tcrvserver_policymap_binding response[] = (crvserver_policymap_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String multiply(CharSequence self, Number factor) {\n String s = self.toString();\n int size = factor.intValue();\n if (size == 0)\n return \"\";\n else if (size < 0) {\n throw new IllegalArgumentException(\"multiply() should be called with a number of 0 or greater not: \" + size);\n }\n StringBuilder answer = new StringBuilder(s);\n for (int i = 1; i < size; i++) {\n answer.append(s);\n }\n return answer.toString();\n }" ]
List details of all calendars in the file. @param file ProjectFile instance
[ "private static void listCalendars(ProjectFile file)\n {\n for (ProjectCalendar cal : file.getCalendars())\n {\n System.out.println(cal.toString());\n }\n }" ]
[ "public Metadata add(String path, List<String> values) {\n JsonArray arr = new JsonArray();\n for (String value : values) {\n arr.add(value);\n }\n this.values.add(this.pathToProperty(path), arr);\n this.addOp(\"add\", path, arr);\n return this;\n }", "private void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) {\r\n String getterName = \"get\" + MetaClassHelper.capitalize(propertyName);\r\n MethodNode setter = classNode.getSetterMethod(\"set\" + MetaClassHelper.capitalize(propertyName));\r\n\r\n if (setter != null) {\r\n // Get the existing code block\r\n Statement code = setter.getCode();\r\n\r\n Expression oldValue = varX(\"$oldValue\");\r\n Expression newValue = varX(\"$newValue\");\r\n Expression proposedValue = varX(setter.getParameters()[0].getName());\r\n BlockStatement block = new BlockStatement();\r\n\r\n // create a local variable to hold the old value from the getter\r\n block.addStatement(declS(oldValue, callThisX(getterName)));\r\n\r\n // add the fireVetoableChange method call\r\n block.addStatement(stmt(callThisX(\"fireVetoableChange\", args(\r\n constX(propertyName), oldValue, proposedValue))));\r\n\r\n // call the existing block, which will presumably set the value properly\r\n block.addStatement(code);\r\n\r\n if (bindable) {\r\n // get the new value to emit in the event\r\n block.addStatement(declS(newValue, callThisX(getterName)));\r\n\r\n // add the firePropertyChange method call\r\n block.addStatement(stmt(callThisX(\"firePropertyChange\", args(constX(propertyName), oldValue, newValue))));\r\n }\r\n\r\n // replace the existing code block with our new one\r\n setter.setCode(block);\r\n }\r\n }", "GVRSceneObject makeParticleMesh(float[] vertices, float[] velocities,\n float[] particleTimeStamps )\n {\n mParticleMesh = new GVRMesh(mGVRContext);\n\n //pass the particle positions as vertices, velocities as normals, and\n //spawning times as texture coordinates.\n mParticleMesh.setVertices(vertices);\n mParticleMesh.setNormals(velocities);\n mParticleMesh.setTexCoords(particleTimeStamps);\n\n particleID = new GVRShaderId(ParticleShader.class);\n material = new GVRMaterial(mGVRContext, particleID);\n\n material.setVec4(\"u_color\", mColorMultiplier.x, mColorMultiplier.y,\n mColorMultiplier.z, mColorMultiplier.w);\n material.setFloat(\"u_particle_age\", mAge);\n material.setVec3(\"u_acceleration\", mAcceleration.x, mAcceleration.y, mAcceleration.z);\n material.setFloat(\"u_particle_size\", mSize);\n material.setFloat(\"u_size_change_rate\", mParticleSizeRate);\n material.setFloat(\"u_fade\", mFadeWithAge);\n material.setFloat(\"u_noise_factor\", mNoiseFactor);\n\n GVRRenderData renderData = new GVRRenderData(mGVRContext);\n renderData.setMaterial(material);\n renderData.setMesh(mParticleMesh);\n material.setMainTexture(mTexture);\n\n GVRSceneObject meshObject = new GVRSceneObject(mGVRContext);\n meshObject.attachRenderData(renderData);\n meshObject.getRenderData().setMaterial(material);\n\n // Set the draw mode to GL_POINTS, disable writing to depth buffer, enable depth testing\n // and set the rendering order to transparent.\n // Disabling writing to depth buffer ensure that the particles blend correctly\n // and keeping the depth test on along with rendering them\n // after the geometry queue makes sure they occlude, and are occluded, correctly.\n\n meshObject.getRenderData().setDrawMode(GL_POINTS);\n meshObject.getRenderData().setDepthTest(true);\n meshObject.getRenderData().setDepthMask(false);\n meshObject.getRenderData().setRenderingOrder(GVRRenderData.GVRRenderingOrder.TRANSPARENT);\n\n return meshObject;\n }", "public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}", "public String addPostRunDependent(FunctionalTaskItem dependent) {\n Objects.requireNonNull(dependent);\n return this.taskGroup().addPostRunDependent(dependent);\n }", "public URL buildWithQuery(String base, String queryString, Object... values) {\n String urlString = String.format(base + this.template, values) + queryString;\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n assert false : \"An invalid URL template indicates a bug in the SDK.\";\n }\n\n return url;\n }", "protected I_CmsFacetQueryItem parseFacetQueryItem(JSONObject item) {\n\n String query;\n try {\n query = item.getString(JSON_KEY_QUERY_FACET_QUERY_QUERY);\n } catch (JSONException e) {\n // TODO: Log\n return null;\n }\n String label = parseOptionalStringValue(item, JSON_KEY_QUERY_FACET_QUERY_LABEL);\n return new CmsFacetQueryItem(query, label);\n }", "protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) {\n this.valid = false;\n for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) {\n if (annotatedAnnotation.isAnnotationPresent(annotationType)) {\n this.valid = true;\n }\n }\n }", "public float getBitangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_bitangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }" ]
Transfer the ownership of an application to another user. @param appName App name. See {@link #listApps} for a list of apps that can be used. @param to Username of the person to transfer the app to. This is usually in the form of "[email protected]".
[ "public void transferApp(String appName, String to) {\n connection.execute(new SharingTransfer(appName, to), apiKey);\n }" ]
[ "private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }", "private ProjectFile handleDirectory(File directory) throws Exception\n {\n ProjectFile result = handleDatabaseInDirectory(directory);\n if (result == null)\n {\n result = handleFileInDirectory(directory);\n }\n return result;\n }", "public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)\n {\n String extension = StringUtils.substringAfterLast(filePath, \".\");\n\n if (!StringUtils.equalsIgnoreCase(extension, \"jar\"))\n return false;\n\n ZipFile archive;\n try\n {\n archive = new ZipFile(filePath);\n } catch (IOException e)\n {\n return false;\n }\n\n WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());\n\n // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)\n boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();\n\n // this should only be true if:\n // 1) the package does not contain *any* customer packages.\n // 2) the package contains \"known\" vendor packages.\n boolean exclusivelyKnown = false;\n\n String organization = null;\n Enumeration<?> e = archive.entries();\n\n // go through all entries...\n ZipEntry entry;\n while (e.hasMoreElements())\n {\n entry = (ZipEntry) e.nextElement();\n String entryName = entry.getName();\n\n if (entry.isDirectory() || !StringUtils.endsWith(entryName, \".class\"))\n continue;\n\n String classname = PathUtil.classFilePathToClassname(entryName);\n // if the package isn't current \"known\", try to match against known packages for this entry.\n if (!exclusivelyKnown)\n {\n organization = getOrganizationForPackage(event, classname);\n if (organization != null)\n {\n exclusivelyKnown = true;\n } else\n {\n // we couldn't find a package definitively, so ignore the archive\n exclusivelyKnown = false;\n break;\n }\n }\n\n // If the user specified package names and this is in those package names, then scan it anyway\n if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))\n {\n return false;\n }\n }\n\n if (exclusivelyKnown)\n LOG.info(\"Known Package: \" + archive.getName() + \"; Organization: \" + organization);\n\n // Return the evaluated exclusively known value.\n return exclusivelyKnown;\n }", "@SuppressWarnings(\"unchecked\") public Relation addPredecessor(Task targetTask, RelationType type, Duration lag)\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = (List<Relation>) getCachedValue(TaskField.PREDECESSORS);\n\n //\n // Ensure that there is only one predecessor relationship between\n // these two tasks.\n //\n Relation predecessorRelation = null;\n Iterator<Relation> iter = predecessorList.iterator();\n while (iter.hasNext() == true)\n {\n predecessorRelation = iter.next();\n if (predecessorRelation.getTargetTask() == targetTask)\n {\n if (predecessorRelation.getType() != type || predecessorRelation.getLag().compareTo(lag) != 0)\n {\n predecessorRelation = null;\n }\n break;\n }\n predecessorRelation = null;\n }\n\n //\n // If necessary, create a new predecessor relationship\n //\n if (predecessorRelation == null)\n {\n predecessorRelation = new Relation(this, targetTask, type, lag);\n predecessorList.add(predecessorRelation);\n }\n\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = (List<Relation>) targetTask.getCachedValue(TaskField.SUCCESSORS);\n\n //\n // Ensure that there is only one successor relationship between\n // these two tasks.\n //\n Relation successorRelation = null;\n iter = successorList.iterator();\n while (iter.hasNext() == true)\n {\n successorRelation = iter.next();\n if (successorRelation.getTargetTask() == this)\n {\n if (successorRelation.getType() != type || successorRelation.getLag().compareTo(lag) != 0)\n {\n successorRelation = null;\n }\n break;\n }\n successorRelation = null;\n }\n\n //\n // If necessary, create a new successor relationship\n //\n if (successorRelation == null)\n {\n successorRelation = new Relation(targetTask, this, type, lag);\n successorList.add(successorRelation);\n }\n\n return (predecessorRelation);\n }", "public static void log(byte[] data)\n {\n if (LOG != null)\n {\n LOG.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n LOG.flush();\n }\n }", "public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }", "@Override\n public void close() throws IOException {\n // Notify encoder of EOF (-1).\n if (doEncode) {\n baseNCodec.encode(singleByte, 0, EOF, context);\n } else {\n baseNCodec.decode(singleByte, 0, EOF, context);\n }\n flush();\n out.close();\n }", "private static List<Path> expandMultiAppInputDirs(List<Path> input)\n {\n List<Path> expanded = new LinkedList<>();\n for (Path path : input)\n {\n if (Files.isRegularFile(path))\n {\n expanded.add(path);\n continue;\n }\n if (!Files.isDirectory(path))\n {\n String pathString = (path == null) ? \"\" : path.toString(); \n log.warning(\"Neither a file or directory found in input: \" + pathString);\n continue;\n }\n\n try\n {\n try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))\n {\n for (Path subpath : directoryStream)\n {\n\n if (isJavaArchive(subpath))\n {\n expanded.add(subpath);\n }\n }\n }\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to read directory contents of: \" + path);\n }\n }\n return expanded;\n }", "private void verityLicenseIsConflictFree(final DbLicense newComer) {\n if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) {\n return;\n }\n\n final DbLicense existing = repoHandler.getLicense(newComer.getName());\n final List<DbLicense> licenses = repoHandler.getAllLicenses();\n\n if(null == existing) {\n licenses.add(newComer);\n } else {\n existing.setRegexp(newComer.getRegexp());\n }\n\n\n final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS);\n if (reportOp.isPresent()) {\n final Report reportDef = reportOp.get();\n ReportRequest reportRequest = new ReportRequest();\n reportRequest.setReportId(reportDef.getId());\n\n Map<String, String> params = new HashMap<>();\n\n //\n // TODO: Make the organization come as an external parameter from the client side.\n // This may have impact on the UI, as when the user will update a license he will\n // have to specify which organization he's editing the license for (in case there\n // are more organizations defined in the collection).\n //\n params.put(\"organization\", \"Axway\");\n reportRequest.setParamValues(params);\n\n final RepositoryHandler wrapped = wrapperBuilder\n .start(repoHandler)\n .replaceGetMethod(\"getAllLicenses\", licenses)\n .build();\n\n final ReportExecution execution = reportDef.execute(wrapped, reportRequest);\n\n List<String[]> data = execution.getData();\n\n final Optional<String[]> first = data\n .stream()\n .filter(strings -> strings[2].contains(newComer.getName()))\n .findFirst();\n\n if(first.isPresent()) {\n final String[] strings = first.get();\n final String message = String.format(\n \"Pattern conflict for string entry %s matching multiple licenses: %s\",\n strings[1], strings[2]);\n LOG.info(message);\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(message)\n .build());\n } else {\n if(!data.isEmpty() && !data.get(0)[2].isEmpty()) {\n LOG.info(\"There are remote conflicts between existing licenses and artifact strings\");\n }\n }\n } else {\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"Cannot find report by id %s\", MULTIPLE_LICENSE_MATCHING_STRINGS));\n }\n }\n }" ]
Obtain override ID @param overrideIdentifier can be the override ID or class name @return @throws Exception
[ "public static Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception {\n Integer overrideId = -1;\n\n try {\n // there is an issue with parseInt where it does not parse negative values correctly\n boolean isNegative = false;\n if (overrideIdentifier.startsWith(\"-\")) {\n isNegative = true;\n overrideIdentifier = overrideIdentifier.substring(1);\n }\n overrideId = Integer.parseInt(overrideIdentifier);\n\n if (isNegative) {\n overrideId = 0 - overrideId;\n }\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n\n // split into two parts\n String className = null;\n String methodName = null;\n int lastDot = overrideIdentifier.lastIndexOf(\".\");\n className = overrideIdentifier.substring(0, lastDot);\n methodName = overrideIdentifier.substring(lastDot + 1);\n\n overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName);\n }\n\n return overrideId;\n }" ]
[ "private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}", "private static boolean hasSelfPermissions(Context context, String... permissions) {\n for (String permission : permissions) {\n if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {\n return true;\n }\n }\n return false;\n }", "private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception\n {\n long start = System.currentTimeMillis();\n reader.setProjectID(projectID);\n ProjectFile projectFile = reader.read();\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading database completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }", "public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\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 }", "public static InstalledIdentity load(final File jbossHome, final ProductConfig productConfig, final File... repoRoots) throws IOException {\n final InstalledImage installedImage = installedImage(jbossHome);\n return load(installedImage, productConfig, Arrays.<File>asList(repoRoots), Collections.<File>emptyList());\n }", "public LuaPreparedScript endPreparedScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n ArrayList<LuaKeyArgument> keyList = new ArrayList<>(keyArg2AstArg.keySet());\n ArrayList<LuaValueArgument> argvList = new ArrayList<>(valueArg2AstArg.keySet());\n if (config.isThreadSafe()) {\n return new ThreadSafeLuaPreparedScript(scriptText, keyList, argvList, config);\n } else {\n return new BasicLuaPreparedScript(scriptText, keyList, argvList, config);\n }\n }", "public static Set<Dependency> getAllDependencies(final Module module, final List<String> producedArtifacts) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n\n for(final Dependency dependency: module.getDependencies()){\n if(!producedArtifacts.contains(dependency.getTarget().getGavc())){\n dependencies.add(dependency);\n }\n }\n\n for(final Module subModule: module.getSubmodules()){\n dependencies.addAll(getAllDependencies(subModule, producedArtifacts));\n }\n\n return dependencies;\n }", "private void addClasses(XMLStreamWriter writer, File jarFile, boolean mapClassMethods) throws IOException, ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();\n\n URLClassLoader loader = new URLClassLoader(new URL[]\n {\n jarFile.toURI().toURL()\n }, currentThreadClassLoader);\n\n JarFile jar = new JarFile(jarFile);\n Enumeration<JarEntry> enumeration = jar.entries();\n while (enumeration.hasMoreElements())\n {\n JarEntry jarEntry = enumeration.nextElement();\n if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(\".class\"))\n {\n addClass(loader, jarEntry, writer, mapClassMethods);\n }\n }\n jar.close();\n }", "public static vpnglobal_appcontroller_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_appcontroller_binding obj = new vpnglobal_appcontroller_binding();\n\t\tvpnglobal_appcontroller_binding response[] = (vpnglobal_appcontroller_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Use this API to fetch appfwhtmlerrorpage resource of given name .
[ "public static appfwhtmlerrorpage get(nitro_service service, String name) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tobj.set_name(name);\n\t\tappfwhtmlerrorpage response = (appfwhtmlerrorpage) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action) {\r\n return createRetentionPolicy(api, name, type, length, action, null);\r\n }", "public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }", "private void addSuperClasses(Integer directSuperClass,\n\t\t\tClassRecord subClassRecord) {\n\t\tif (subClassRecord.superClasses.contains(directSuperClass)) {\n\t\t\treturn;\n\t\t}\n\t\tsubClassRecord.superClasses.add(directSuperClass);\n\t\tClassRecord superClassRecord = getClassRecord(directSuperClass);\n\t\tif (superClassRecord == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (Integer superClass : superClassRecord.directSuperClasses) {\n\t\t\taddSuperClasses(superClass, subClassRecord);\n\t\t}\n\t}", "private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }", "public void registerDatatype(Class<? extends GVRHybridObject> textureClass,\n AsyncLoaderFactory<? extends GVRHybridObject, ?> asyncLoaderFactory) {\n mFactories.put(textureClass, asyncLoaderFactory);\n }", "public static base_response update(nitro_service client, snmpalarm resource) throws Exception {\n\t\tsnmpalarm updateresource = new snmpalarm();\n\t\tupdateresource.trapname = resource.trapname;\n\t\tupdateresource.thresholdvalue = resource.thresholdvalue;\n\t\tupdateresource.normalvalue = resource.normalvalue;\n\t\tupdateresource.time = resource.time;\n\t\tupdateresource.state = resource.state;\n\t\tupdateresource.severity = resource.severity;\n\t\tupdateresource.logging = resource.logging;\n\t\treturn updateresource.update_resource(client);\n\t}", "@Override\n public double get( int row , int col ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds: \"+row+\" \"+col);\n }\n\n return data[ row * numCols + col ];\n }", "public final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }", "CueList getCueList(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.CUE_LIST_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.CUE_LIST) {\n return new CueList(response);\n }\n logger.error(\"Unexpected response type when requesting cue list: {}\", response);\n return null;\n }" ]
Suite end.
[ "private void emitSuiteEnd(AggregatedSuiteResultEvent e, int suitesCompleted) throws IOException {\n assert showSuiteSummary;\n\n final StringBuilder b = new StringBuilder();\n final int totalErrors = this.totalErrors.addAndGet(e.isSuccessful() ? 0 : 1);\n b.append(String.format(Locale.ROOT, \"%sCompleted [%d/%d%s]%s in %.2fs, \",\n shortTimestamp(e.getStartTimestamp() + e.getExecutionTime()),\n suitesCompleted,\n totalSuites,\n totalErrors == 0 ? \"\" : \" (\" + totalErrors + \"!)\",\n e.getSlave().slaves > 1 ? \" on J\" + e.getSlave().id : \"\",\n e.getExecutionTime() / 1000.0d));\n b.append(e.getTests().size()).append(Pluralize.pluralize(e.getTests().size(), \" test\"));\n\n int failures = e.getFailureCount();\n if (failures > 0) {\n b.append(\", \").append(failures).append(Pluralize.pluralize(failures, \" failure\"));\n }\n\n int errors = e.getErrorCount();\n if (errors > 0) {\n b.append(\", \").append(errors).append(Pluralize.pluralize(errors, \" error\"));\n }\n\n int ignored = e.getIgnoredCount();\n if (ignored > 0) {\n b.append(\", \").append(ignored).append(\" skipped\");\n }\n\n if (!e.isSuccessful()) {\n b.append(FAILURE_STRING);\n }\n\n b.append(\"\\n\");\n logShort(b, false);\n }" ]
[ "public void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }", "public SerialMessage getValueMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_GET };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "public Permissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element permissionsElement = response.getPayload();\r\n Permissions permissions = new Permissions();\r\n permissions.setId(permissionsElement.getAttribute(\"id\"));\r\n permissions.setPublicFlag(\"1\".equals(permissionsElement.getAttribute(\"ispublic\")));\r\n permissions.setFamilyFlag(\"1\".equals(permissionsElement.getAttribute(\"isfamily\")));\r\n permissions.setFriendFlag(\"1\".equals(permissionsElement.getAttribute(\"isfriend\")));\r\n permissions.setComment(permissionsElement.getAttribute(\"permcomment\"));\r\n permissions.setAddmeta(permissionsElement.getAttribute(\"permaddmeta\"));\r\n return permissions;\r\n }", "public static java.sql.Timestamp getTimestamp(Object value) {\n try {\n return toTimestamp(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "public static servicegroup_stats[] get(nitro_service service, options option) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tservicegroup_stats[] response = (servicegroup_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }", "public static void directoryCheck(String dir) throws IOException {\n\t\tfinal File file = new File(dir);\n\n\t\tif (!file.exists()) {\n\t\t\tFileUtils.forceMkdir(file);\n\t\t}\n\t}", "private String getLogRequestIdentifier() {\n if (logIdentifier == null) {\n logIdentifier = String.format(\"%s-%s %s %s\", Integer.toHexString(hashCode()),\n numberOfRetries, connection.getRequestMethod(), connection.getURL());\n }\n return logIdentifier;\n }", "public long getTimeFor(int player) {\n TrackPositionUpdate update = positions.get(player);\n if (update != null) {\n return interpolateTimeSinceUpdate(update, System.nanoTime());\n }\n return -1; // We don't know.\n }" ]
Sets the top padding character for all cells in the row. @param paddingTopChar new padding character, ignored if null @return this to allow chaining
[ "public AT_Row setPaddingTopChar(Character paddingTopChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public static Set<Map<String, Object>> setify(ObjectMapper mapper, Object source) {\n return (Set<Map<String, Object>>) collectify(mapper, source, Set.class);\n }", "public static BoxAPIConnection getTransactionConnection(String accessToken, String scope) {\n return BoxTransactionalAPIConnection.getTransactionConnection(accessToken, scope, null);\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 Map<String, String> listConfig(String appName) {\n return connection.execute(new ConfigList(appName), apiKey);\n }", "private List<Key> getScatterKeys(\n int numSplits, Query query, PartitionId partition, Datastore datastore)\n throws DatastoreException {\n Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);\n\n List<Key> keySplits = new ArrayList<Key>();\n\n QueryResultBatch batch;\n do {\n RunQueryRequest scatterRequest =\n RunQueryRequest.newBuilder()\n .setPartitionId(partition)\n .setQuery(scatterPointQuery)\n .build();\n batch = datastore.runQuery(scatterRequest).getBatch();\n for (EntityResult result : batch.getEntityResultsList()) {\n keySplits.add(result.getEntity().getKey());\n }\n scatterPointQuery.setStartCursor(batch.getEndCursor());\n scatterPointQuery.getLimitBuilder().setValue(\n scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());\n } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);\n Collections.sort(keySplits, DatastoreHelper.getKeyComparator());\n return keySplits;\n }", "public void setIndexBuffer(GVRIndexBuffer ibuf)\n {\n mIndices = ibuf;\n NativeMesh.setIndexBuffer(getNative(), (ibuf != null) ? ibuf.getNative() : 0L);\n }", "private int collectCandidates(Map<Long, Score> candidates,\n List<Bucket> buckets,\n int threshold) {\n int ix;\n for (ix = 0; ix < threshold &&\n candidates.size() < (CUTOFF_FACTOR_1 * max_search_hits); ix++) {\n Bucket b = buckets.get(ix);\n long[] ids = b.records;\n double score = b.getScore();\n \n for (int ix2 = 0; ix2 < b.nextfree; ix2++) {\n Score s = candidates.get(ids[ix2]);\n if (s == null) {\n s = new Score(ids[ix2]);\n candidates.put(ids[ix2], s);\n }\n s.score += score;\n }\n if (DEBUG)\n System.out.println(\"Bucket \" + b.nextfree + \" -> \" + candidates.size());\n }\n return ix;\n }", "public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }", "public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD;\r\n }" ]
Use this context as prototype for a new mutable builder. The new builder is pre-populated with the current settings of this context instance.
[ "public ContentAssistContext.Builder copy() {\n\t\tBuilder result = builderProvider.get();\n\t\tresult.copyFrom(this);\n\t\treturn result;\n\t}" ]
[ "public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private Map<UUID, FieldType> populateCustomFieldMap()\n {\n byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);\n int length = MPPUtility.getInt(data, 0);\n int index = length + 36;\n\n // 4 byte record count\n int recordCount = MPPUtility.getInt(data, index);\n index += 4;\n\n // 8 bytes per record\n index += (8 * recordCount);\n \n Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();\n while (index < data.length)\n {\n int blockLength = MPPUtility.getInt(data, index); \n if (blockLength <= 0 || index + blockLength > data.length)\n {\n break;\n }\n \n int fieldID = MPPUtility.getInt(data, index + 4);\n FieldType field = FieldTypeHelper.getInstance(fieldID);\n UUID guid = MPPUtility.getGUID(data, index + 160);\n map.put(guid, field);\n index += blockLength;\n }\n return map;\n }", "public LogStreamResponse getLogs(String appName, Boolean tail) {\n return connection.execute(new Log(appName, tail), apiKey);\n }", "public void transferApp(String appName, String to) {\n connection.execute(new SharingTransfer(appName, to), apiKey);\n }", "public void setJdbcLevel(String jdbcLevel)\r\n {\r\n if (jdbcLevel != null)\r\n {\r\n try\r\n {\r\n double intLevel = Double.parseDouble(jdbcLevel);\r\n setJdbcLevel(intLevel);\r\n }\r\n catch(NumberFormatException nfe)\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was not numeric (Value=\" + jdbcLevel + \"), used default jdbc level of 2.0 \");\r\n }\r\n }\r\n else\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was null, used default jdbc level of 2.0 \");\r\n }\r\n }", "public static boolean isSuccess(JsonRtn jsonRtn) {\n if (jsonRtn == null) {\n return false;\n }\n\n String errCode = jsonRtn.getErrCode();\n if (StringUtils.isEmpty(errCode) || StringUtils.equals(WECHAT_JSON_RTN_SUCCESS_CODE, errCode)) {\n return true;\n }\n\n return false;\n }", "public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }", "public static cmppolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_policybinding_binding obj = new cmppolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_policybinding_binding response[] = (cmppolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void ensureXPathNotNull(Node node, String expression) {\n if (node == null) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }" ]
Returns a OkHttpClient that ignores SSL cert errors @return
[ "private static OkHttpClient getUnsafeOkHttpClient() {\n try {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] {\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }\n };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new java.security.SecureRandom());\n // Create an ssl socket factory with our all-trusting manager\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n\n OkHttpClient okHttpClient = new OkHttpClient();\n okHttpClient.setSslSocketFactory(sslSocketFactory);\n okHttpClient.setHostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n return okHttpClient;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public static hanode_routemonitor6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor6_binding obj = new hanode_routemonitor6_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor6_binding response[] = (hanode_routemonitor6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\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 FileModel getChildFile(ArchiveModel archiveModel, String filePath)\n {\n filePath = FilenameUtils.separatorsToUnix(filePath);\n StringTokenizer stk = new StringTokenizer(filePath, \"/\");\n\n FileModel currentFileModel = archiveModel;\n while (stk.hasMoreTokens() && currentFileModel != null)\n {\n String pathElement = stk.nextToken();\n\n currentFileModel = findFileModel(currentFileModel, pathElement);\n }\n return currentFileModel;\n }", "public String processNested(Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n NestedDef nestedDef = _curClassDef.getNested(name);\r\n\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_NESTED,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n ClassDescriptorDef nestedTypeDef = _model.getClass(type.getQualifiedName());\r\n\r\n if (nestedTypeDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (nestedDef == null)\r\n {\r\n nestedDef = new NestedDef(name, nestedTypeDef);\r\n _curClassDef.addNested(nestedDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processNested\", \" Processing nested object \"+nestedDef.getName()+\" of type \"+nestedTypeDef.getName());\r\n\r\n String attrName;\r\n \r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n nestedDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\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 }", "@TargetApi(VERSION_CODES.KITKAT)\n public static void showSystemUI(Activity activity) {\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n );\n }", "public Module getModule(final String name, final String version) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module details\", name, version);\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(Module.class);\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 }" ]
Additional bean deployment archives are used for extentions, synthetic annotated types and beans which do not come from a bean archive. @param beanClass @return the additional bean deployment archive
[ "protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(ADDITIONAL_BDA_ID, Collections.synchronizedSet(new HashSet<String>()), null);\n additionalBda.getServices().addAll(getServices().entrySet());\n beanDeploymentArchives.add(additionalBda);\n setBeanDeploymentArchivesAccessibility();\n return additionalBda;\n }" ]
[ "public BoxAPIResponse send(ProgressListener listener) {\n if (this.api == null) {\n this.backoffCounter.reset(BoxGlobalSettings.getMaxRequestAttempts());\n } else {\n this.backoffCounter.reset(this.api.getMaxRequestAttempts());\n }\n\n while (this.backoffCounter.getAttemptsRemaining() > 0) {\n try {\n return this.trySend(listener);\n } catch (BoxAPIException apiException) {\n if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {\n throw apiException;\n }\n\n try {\n this.resetBody();\n } catch (IOException ioException) {\n throw apiException;\n }\n\n try {\n this.backoffCounter.waitBackoff();\n } catch (InterruptedException interruptedException) {\n Thread.currentThread().interrupt();\n throw apiException;\n }\n }\n }\n\n throw new RuntimeException();\n }", "public static boolean isDelayedQueue(final Jedis jedis, final String key) {\n return ZSET.equalsIgnoreCase(jedis.type(key));\n }", "protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException {\n final ManagementResponseHeader response = ManagementResponseHeader.create(header, error);\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }", "public static base_response update(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup updateresource = new clusternodegroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.strict = resource.strict;\n\t\treturn updateresource.update_resource(client);\n\t}", "private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}", "private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }", "public int getMinutesPerWeek()\n {\n return m_minutesPerWeek == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerWeek()) : m_minutesPerWeek.intValue();\n }", "protected int readInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getInt(data, 0));\n }", "public static int checkVlen(int i) {\n int count = 0;\n if (i >= -112 && i <= 127) {\n return 1;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n count++;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n while (len != 0) {\n count++;\n len--;\n }\n\n return count;\n }\n }" ]
Create the metadata which gets send to the DC when registering. @param hostInfo the local host info @param productConfig the product config @param ignoredResourceRegistry registry of ignored resources @return the host info
[ "public static ModelNode createLocalHostHostInfo(final LocalHostControllerInfo hostInfo, final ProductConfig productConfig,\n final IgnoredDomainResourceRegistry ignoredResourceRegistry, final Resource hostModelResource) {\n final ModelNode info = new ModelNode();\n info.get(NAME).set(hostInfo.getLocalHostName());\n info.get(RELEASE_VERSION).set(Version.AS_VERSION);\n info.get(RELEASE_CODENAME).set(Version.AS_RELEASE_CODENAME);\n info.get(MANAGEMENT_MAJOR_VERSION).set(Version.MANAGEMENT_MAJOR_VERSION);\n info.get(MANAGEMENT_MINOR_VERSION).set(Version.MANAGEMENT_MINOR_VERSION);\n info.get(MANAGEMENT_MICRO_VERSION).set(Version.MANAGEMENT_MICRO_VERSION);\n final String productName = productConfig.getProductName();\n final String productVersion = productConfig.getProductVersion();\n if(productName != null) {\n info.get(PRODUCT_NAME).set(productName);\n }\n if(productVersion != null) {\n info.get(PRODUCT_VERSION).set(productVersion);\n }\n ModelNode ignoredModel = ignoredResourceRegistry.getIgnoredResourcesAsModel();\n if (ignoredModel.hasDefined(IGNORED_RESOURCE_TYPE)) {\n info.get(IGNORED_RESOURCES).set(ignoredModel.require(IGNORED_RESOURCE_TYPE));\n }\n boolean ignoreUnaffectedServerGroups = hostInfo.isRemoteDomainControllerIgnoreUnaffectedConfiguration();\n IgnoredNonAffectedServerGroupsUtil.addCurrentServerGroupsToHostInfoModel(ignoreUnaffectedServerGroups, hostModelResource, info);\n return info;\n }" ]
[ "private TableAlias getTableAliasForPath(String aPath, String aUserAlias, List hintClasses)\r\n {\r\n if (aUserAlias == null)\r\n {\r\n return getTableAliasForPath(aPath, hintClasses);\r\n }\r\n else\r\n {\r\n\t\t\treturn getTableAliasForPath(aUserAlias + ALIAS_SEPARATOR + aPath, hintClasses);\r\n }\r\n }", "@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 int positionOf(char value, char[] array) {\n for (int i = 0; i < array.length; i++) {\n if (value == array[i]) {\n return i;\n }\n }\n throw new OkapiException(\"Unable to find character '\" + value + \"' in character array.\");\n }", "public static base_response add(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance addresource = new clusterinstance();\n\t\taddresource.clid = resource.clid;\n\t\taddresource.deadinterval = resource.deadinterval;\n\t\taddresource.hellointerval = resource.hellointerval;\n\t\taddresource.preemption = resource.preemption;\n\t\treturn addresource.add_resource(client);\n\t}", "public static AiScene importFile(String filename) throws IOException {\n \n return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class));\n }", "public static WidgetLib init(GVRContext gvrContext, String customPropertiesAsset)\n throws InterruptedException, JSONException, NoSuchMethodException {\n if (mInstance == null) {\n // Constructor sets mInstance to ensure the initialization order\n new WidgetLib(gvrContext, customPropertiesAsset);\n }\n return mInstance.get();\n }", "private void addContentInfo() {\n\n if (!m_cms.getRequestContext().getCurrentProject().isOnlineProject()\n && (null == m_searchController.getCommon().getConfig().getSolrIndex())\n && (null != m_addContentInfoForEntries)) {\n CmsSolrQuery query = new CmsSolrQuery();\n m_searchController.addQueryParts(query, m_cms);\n query.setStart(Integer.valueOf(0));\n query.setRows(m_addContentInfoForEntries);\n CmsContentLoadCollectorInfo info = new CmsContentLoadCollectorInfo();\n info.setCollectorClass(this.getClass().getName());\n info.setCollectorParams(query.getQuery());\n info.setId((new CmsUUID()).getStringValue());\n if (CmsJspTagEditable.getDirectEditProvider(pageContext) != null) {\n try {\n CmsJspTagEditable.getDirectEditProvider(pageContext).insertDirectEditListMetadata(\n pageContext,\n info);\n } catch (JspException e) {\n LOG.error(\"Could not write content info.\", e);\n }\n }\n }\n }", "public void populateFromAttributes(\n @Nonnull final Template template,\n @Nonnull final Map<String, Attribute> attributes,\n @Nonnull final PObject requestJsonAttributes) {\n if (requestJsonAttributes.has(JSON_REQUEST_HEADERS) &&\n requestJsonAttributes.getObject(JSON_REQUEST_HEADERS).has(JSON_REQUEST_HEADERS) &&\n !attributes.containsKey(JSON_REQUEST_HEADERS)) {\n attributes.put(JSON_REQUEST_HEADERS, new HttpRequestHeadersAttribute());\n }\n for (Map.Entry<String, Attribute> attribute: attributes.entrySet()) {\n try {\n put(attribute.getKey(),\n attribute.getValue().getValue(template, attribute.getKey(), requestJsonAttributes));\n } catch (ObjectMissingException | IllegalArgumentException e) {\n throw e;\n } catch (Throwable e) {\n String templateName = \"unknown\";\n for (Map.Entry<String, Template> entry: template.getConfiguration().getTemplates()\n .entrySet()) {\n if (entry.getValue() == template) {\n templateName = entry.getKey();\n break;\n }\n }\n\n String defaults = \"\";\n\n if (attribute instanceof ReflectiveAttribute<?>) {\n ReflectiveAttribute<?> reflectiveAttribute = (ReflectiveAttribute<?>) attribute;\n defaults = \"\\n\\n The attribute defaults are: \" + reflectiveAttribute.getDefaultValue();\n }\n\n String errorMsg = \"An error occurred when creating a value from the '\" + attribute.getKey() +\n \"' attribute for the '\" +\n templateName + \"' template.\\n\\nThe JSON is: \\n\" + requestJsonAttributes + defaults +\n \"\\n\" +\n e.toString();\n\n throw new AttributeParsingException(errorMsg, e);\n }\n }\n\n if (template.getConfiguration().isThrowErrorOnExtraParameters()) {\n final List<String> extraProperties = new ArrayList<>();\n for (Iterator<String> it = requestJsonAttributes.keys(); it.hasNext(); ) {\n final String attributeName = it.next();\n if (!attributes.containsKey(attributeName)) {\n extraProperties.add(attributeName);\n }\n }\n\n if (!extraProperties.isEmpty()) {\n throw new ExtraPropertyException(\"Extra properties found in the request attributes\",\n extraProperties, attributes.keySet());\n }\n }\n }", "public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n boolean retval;\r\n if (supportsAdvancedJDBCCursorControl())\r\n {\r\n retval = absoluteAdvanced(row);\r\n }\r\n else\r\n {\r\n retval = absoluteBasic(row);\r\n }\r\n return retval;\r\n }" ]
Peeks the current top of the stack or returns null if the stack is empty @return the current top of the stack or returns null if the stack is empty
[ "public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }" ]
[ "public int getBoneIndex(String bonename)\n {\n for (int i = 0; i < getNumBones(); ++i)\n\n if (mBoneNames[i].equals(bonename))\n return i;\n return -1;\n }", "public Set<ConstraintViolation> validate() {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int record = 1; record <= 3; ++record) {\r\n\t\t\terrors.addAll(validate(record));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}", "private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }", "public static float gain(float a, float b) {\n/*\n\t\tfloat p = (float)Math.log(1.0 - b) / (float)Math.log(0.5);\n\n\t\tif (a < .001)\n\t\t\treturn 0.0f;\n\t\telse if (a > .999)\n\t\t\treturn 1.0f;\n\t\tif (a < 0.5)\n\t\t\treturn (float)Math.pow(2 * a, p) / 2;\n\t\telse\n\t\t\treturn 1.0f - (float)Math.pow(2 * (1. - a), p) / 2;\n*/\n\t\tfloat c = (1.0f/b-2.0f) * (1.0f-2.0f*a);\n\t\tif (a < 0.5)\n\t\t\treturn a/(c+1.0f);\n\t\telse\n\t\t\treturn (c-a)/(c-1.0f);\n\t}", "@Override\n public void checkin(K key, V resource) {\n super.checkin(key, resource);\n // NB: Blocking checkout calls for synchronous requests get the resource\n // checked in above before processQueueLoop() attempts checkout below.\n // There is therefore a risk that asynchronous requests will be starved.\n processQueueLoop(key);\n }", "public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }", "public static Map<String, IDiagramPlugin>\n getLocalPluginsRegistry(ServletContext context) {\n if (LOCAL == null) {\n LOCAL = initializeLocalPlugins(context);\n }\n return LOCAL;\n }", "public static void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\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}" ]
Clear history for a client @param profileId ID of profile @param clientUUID UUID of client
[ "public void clearHistory(int profileId, String clientUUID) {\n PreparedStatement query = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"DELETE FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is null or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId;\n }\n\n // see if clientUUID is null or not\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \" AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"'\";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n query = sqlConnection.prepareStatement(sqlQuery);\n query.executeUpdate();\n } catch (Exception e) {\n } finally {\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
[ "public void useNewRESTServiceWithOldClient() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/new-rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n \n // The outgoing old Customer data needs to be transformed for \n // the new service to understand it and the response from the new service\n // needs to be transformed for this old client to understand it.\n ClientConfiguration config = WebClient.getConfig(customerService);\n addTransformInterceptors(config.getInInterceptors(),\n config.getOutInterceptors(),\n false);\n \n \n System.out.println(\"Using new RESTful CustomerService with old Client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old to New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old to New REST\");\n printOldCustomerDetails(customer);\n }", "public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}", "protected final void addPathTo(final StringBuilder result) {\n if (this.parent != null) {\n this.parent.addPathTo(result);\n if (!(this.parent instanceof PJsonArray)) {\n result.append(\".\");\n }\n }\n result.append(getPathElement(this.contextName));\n }", "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 }", "String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }", "public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }", "private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\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 static base_response update(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy updateresource = new transformpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.logaction = resource.logaction;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Creates an object instance from the Scala class name @param className the Scala class name @return An Object instance
[ "public Object newInstance(String className) {\n try {\n return classLoader.loadClass(className).newInstance();\n } catch (Exception e) {\n throw new ScalaInstanceNotFound(className);\n }\n }" ]
[ "public RedwoodConfiguration loggingClass(final Class<?> classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces.getName()); } });\r\n return this;\r\n }", "void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}", "public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "protected float computeUniformPadding(final CacheDataSet cache) {\n float axisSize = getViewPortSize(getOrientationAxis());\n float totalPadding = axisSize - cache.getTotalSize();\n float uniformPadding = totalPadding > 0 && cache.count() > 1 ?\n totalPadding / (cache.count() - 1) : 0;\n return uniformPadding;\n }", "@Override\n\tpublic List<String> contentTypes() {\n\t\tList<String> contentTypes = null;\n\t\tfinal HttpServletRequest request = getHttpRequest();\n\n\t\tif (favorParameterOverAcceptHeader) {\n\t\t\tcontentTypes = getFavoredParameterValueAsList(request);\n\t\t} else {\n\t\t\tcontentTypes = getAcceptHeaderValues(request);\n\t\t}\n\n\t\tif (isEmpty(contentTypes)) {\n\t\t\tlogger.debug(\"Setting content types to default: {}.\", DEFAULT_SUPPORTED_CONTENT_TYPES);\n\n\t\t\tcontentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES;\n\t\t}\n\n\t\treturn unmodifiableList(contentTypes);\n\t}", "public final OutputFormat getOutputFormat(final PJsonObject specJson) {\n final String format = specJson.getString(MapPrinterServlet.JSON_OUTPUT_FORMAT);\n final boolean mapExport =\n this.configuration.getTemplate(specJson.getString(Constants.JSON_LAYOUT_KEY)).isMapExport();\n final String beanName =\n format + (mapExport ? MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING : OUTPUT_FORMAT_BEAN_NAME_ENDING);\n\n if (!this.outputFormat.containsKey(beanName)) {\n throw new RuntimeException(\"Format '\" + format + \"' with mapExport '\" + mapExport\n + \"' is not supported.\");\n }\n\n return this.outputFormat.get(beanName);\n }", "static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\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 void extract( DMatrixRMaj src,\n int rows[] , int rowsSize ,\n int cols[] , int colsSize , DMatrixRMaj dst ) {\n if( rowsSize != dst.numRows || colsSize != dst.numCols )\n throw new MatrixDimensionException(\"Unexpected number of rows and/or columns in dst matrix\");\n\n int indexDst = 0;\n for (int i = 0; i < rowsSize; i++) {\n int indexSrcRow = src.numCols*rows[i];\n for (int j = 0; j < colsSize; j++) {\n dst.data[indexDst++] = src.data[indexSrcRow + cols[j]];\n }\n }\n }" ]
returns the abstract method from a SAM type, if it is a SAM type. @param c the SAM class @return null if nothing was found, the method otherwise
[ "public static Method getSAMMethod(Class<?> c) {\n // SAM = single public abstract method\n // if the class is not abstract there is no abstract method\n if (!Modifier.isAbstract(c.getModifiers())) return null;\n if (c.isInterface()) {\n Method[] methods = c.getMethods();\n // res stores the first found abstract method\n Method res = null;\n for (Method mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (mi.getAnnotation(Traits.Implemented.class)!=null) continue;\n try {\n Object.class.getMethod(mi.getName(), mi.getParameterTypes());\n continue;\n } catch (NoSuchMethodException e) {/*ignore*/}\n\n // we have two methods, so no SAM\n if (res!=null) return null;\n res = mi;\n }\n return res;\n\n } else {\n\n LinkedList<Method> methods = new LinkedList();\n getAbstractMethods(c, methods);\n if (methods.isEmpty()) return null;\n ListIterator<Method> it = methods.listIterator();\n while (it.hasNext()) {\n Method m = it.next();\n if (hasUsableImplementation(c, m)) it.remove();\n }\n return getSingleNonDuplicateMethod(methods);\n }\n }" ]
[ "private void computeUnnamedParams() {\n unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList()));\n }", "public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }", "public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }", "public static void applyHyperLinkToElement(DynamicJasperDesign design, DJHyperLink djlink, JRDesignChart chart, String name) {\n\t\tJRDesignExpression hlpe = ExpressionUtils.createAndRegisterExpression(design, name, djlink.getExpression());\n\t\tchart.setHyperlinkReferenceExpression(hlpe);\n\t\tchart.setHyperlinkType( HyperlinkTypeEnum.REFERENCE ); //FIXME Should this be a parameter in the future?\n\t\t\t\t\n\t\tif (djlink.getTooltip() != null){\t\t\t\n\t\t\tJRDesignExpression tooltipExp = ExpressionUtils.createAndRegisterExpression(design, \"tooltip_\" + name, djlink.getTooltip());\n\t\t\tchart.setHyperlinkTooltipExpression(tooltipExp);\n\t\t}\n\t}", "public static sslciphersuite[] get(nitro_service service, String ciphername[]) throws Exception{\n\t\tif (ciphername !=null && ciphername.length>0) {\n\t\t\tsslciphersuite response[] = new sslciphersuite[ciphername.length];\n\t\t\tsslciphersuite obj[] = new sslciphersuite[ciphername.length];\n\t\t\tfor (int i=0;i<ciphername.length;i++) {\n\t\t\t\tobj[i] = new sslciphersuite();\n\t\t\t\tobj[i].set_ciphername(ciphername[i]);\n\t\t\t\tresponse[i] = (sslciphersuite) 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(String strKey, Object value)\r\n {\r\n this.propertyChangeDelegate.firePropertyChange(strKey,\r\n hmAttributes.put(strKey, value), value);\r\n }", "public RedwoodConfiguration stderr(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.err();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\n }", "public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }", "public Set<URI> collectOutgoingReferences(IResourceDescription description) {\n\t\tURI resourceURI = description.getURI();\n\t\tSet<URI> result = null;\n\t\tfor(IReferenceDescription reference: description.getReferenceDescriptions()) {\n\t\t\tURI targetResource = reference.getTargetEObjectUri().trimFragment();\n\t\t\tif (!resourceURI.equals(targetResource)) {\n\t\t\t\tif (result == null)\n\t\t\t\t\tresult = Sets.newHashSet(targetResource);\n\t\t\t\telse\n\t\t\t\t\tresult.add(targetResource);\n\t\t\t}\n\t\t}\n\t\tif (result != null)\n\t\t\treturn result;\n\t\treturn Collections.emptySet();\n\t}" ]
Generates and writes the sql for inserting the currently contained data objects. @param model The database model @param platform The platform @param writer The output stream
[ "public void createInsertionSql(Database model, Platform platform, Writer writer) throws IOException\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n writer.write(platform.getInsertSql(model, (DynaBean)it.next()));\r\n if (it.hasNext())\r\n {\r\n writer.write(\"\\n\");\r\n }\r\n }\r\n }" ]
[ "private void setExpressionForPrecalculatedTotalValue(\n\t\t\tDJCrosstabColumn[] auxCols, DJCrosstabRow[] auxRows, JRDesignExpression measureExp, DJCrosstabMeasure djmeasure,\n\t\t\tDJCrosstabColumn crosstabColumn, DJCrosstabRow crosstabRow, String meausrePrefix) {\n\n\t\tString rowValuesExp = \"new Object[]{\";\n\t\tString rowPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxRows.length; i++) {\n\t\t\tif (auxRows[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\trowValuesExp += \"$V{\" + auxRows[i].getProperty().getProperty() +\"}\";\n\t\t\trowPropsExp += \"\\\"\" + auxRows[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxRows.length && auxRows[i+1].getProperty()!= null){\n\t\t\t\trowValuesExp += \", \";\n\t\t\t\trowPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\trowValuesExp += \"}\";\n\t\trowPropsExp += \"}\";\n\n\t\tString colValuesExp = \"new Object[]{\";\n\t\tString colPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxCols.length; i++) {\n\t\t\tif (auxCols[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\tcolValuesExp += \"$V{\" + auxCols[i].getProperty().getProperty() +\"}\";\n\t\t\tcolPropsExp += \"\\\"\" + auxCols[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxCols.length && auxCols[i+1].getProperty()!= null){\n\t\t\t\tcolValuesExp += \", \";\n\t\t\t\tcolPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\tcolValuesExp += \"}\";\n\t\tcolPropsExp += \"}\";\n\n\t\tString measureProperty = meausrePrefix + djmeasure.getProperty().getProperty();\n\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_totalProvider}).getValueFor( \"\n\t\t+ colPropsExp +\", \"\n\t\t+ colValuesExp +\", \"\n\t\t+ rowPropsExp\n\t\t+ \", \"\n\t\t+ rowValuesExp\n\t\t+\" ))\";\n\n\t\tif (djmeasure.getValueFormatter() != null){\n\n\t\t\tString fieldsMap = ExpressionUtils.getTextForFieldsFromScriptlet();\n\t\t\tString parametersMap = ExpressionUtils.getTextForParametersFromScriptlet();\n\t\t\tString variablesMap = ExpressionUtils.getTextForVariablesFromScriptlet();\n\n\t\t\tString stringExpression = \"(((\"+DJValueFormatter.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_vf}).evaluate( \"\n\t\t\t\t+ \"(\"+expText+\"), \" + fieldsMap +\", \" + variablesMap + \", \" + parametersMap +\" ))\";\n\n\t\t\tmeasureExp.setText(stringExpression);\n\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t} else {\n\n//\t\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+djmeasure.getProperty().getProperty()+\"_totalProvider}).getValueFor( \"\n//\t\t\t+ colPropsExp +\", \"\n//\t\t\t+ colValuesExp +\", \"\n//\t\t\t+ rowPropsExp\n//\t\t\t+ \", \"\n//\t\t\t+ rowValuesExp\n//\t\t\t+\" ))\";\n//\n\t\t\tlog.debug(\"text for crosstab total provider is: \" + expText);\n\n\t\t\tmeasureExp.setText(expText);\n//\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t\tString valueClassNameForOperation = ExpressionUtils.getValueClassNameForOperation(djmeasure.getOperation(),djmeasure.getProperty());\n\t\t\tmeasureExp.setValueClassName(valueClassNameForOperation);\n\t\t}\n\n\t}", "public static vlan_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_nsip_binding obj = new vlan_nsip_binding();\n\t\tobj.set_id(id);\n\t\tvlan_nsip_binding response[] = (vlan_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }", "public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void registerInterceptor(Node source,\n String beanName,\n BeanDefinitionRegistry registry) {\n List<String> methodList = buildMethodList(source);\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(SingleServiceWrapperInterceptor.class);\n initializer.addPropertyValue(\"methods\", methodList);\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n initializer.addPropertyReference(\"serviceWrapper\", perfMonitorName);\n\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n registry.registerBeanDefinition(interceptorName, initializer.getBeanDefinition());\n }", "public Integer next() {\n\t\tfor(int i = currentIndex; i < t.size(); i++){\n\t\t\tif(i+timelag>=t.size()){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif((t.get(i) != null) && (t.get(i+timelag) != null)){\n\t\t\t\tif(overlap){\n\t\t\t\t\tcurrentIndex = i+1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcurrentIndex = i+timelag;\n\t\t\t\t}\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}", "public static int checkVlen(int i) {\n int count = 0;\n if (i >= -112 && i <= 127) {\n return 1;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n count++;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n while (len != 0) {\n count++;\n len--;\n }\n\n return count;\n }\n }", "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 }", "protected PersistenceBrokerInternal createNewBrokerInstance(PBKey key) throws PBFactoryException\r\n {\r\n if (key == null) throw new PBFactoryException(\"Could not create new broker with PBkey argument 'null'\");\r\n // check if the given key really exists\r\n if (MetadataManager.getInstance().connectionRepository().getDescriptor(key) == null)\r\n {\r\n throw new PBFactoryException(\"Given PBKey \" + key + \" does not match in metadata configuration\");\r\n }\r\n if (log.isEnabledFor(Logger.INFO))\r\n {\r\n // only count created instances when INFO-Log-Level\r\n log.info(\"Create new PB instance for PBKey \" + key +\r\n \", already created persistence broker instances: \" + instanceCount);\r\n // useful for testing\r\n ++this.instanceCount;\r\n }\r\n\r\n PersistenceBrokerInternal instance = null;\r\n Class[] types = {PBKey.class, PersistenceBrokerFactoryIF.class};\r\n Object[] args = {key, this};\r\n try\r\n {\r\n instance = (PersistenceBrokerInternal) ClassHelper.newInstance(implementationClass, types, args);\r\n OjbConfigurator.getInstance().configure(instance);\r\n instance = (PersistenceBrokerInternal) InterceptorFactory.getInstance().createInterceptorFor(instance);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Creation of a new PB instance failed\", e);\r\n throw new PBFactoryException(\"Creation of a new PB instance failed\", e);\r\n }\r\n return instance;\r\n }" ]
Retrieves list of inbox messages based on given userId @param userId String userid @return ArrayList of {@link CTMessageDAO}
[ "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 }" ]
[ "private static void writeToLog(Logger logger, Level level, String pattern, Exception exception) {\n if (level == Level.ERROR) {\n logger.error(pattern, exception);\n } else if (level == Level.INFO) {\n logger.info(pattern);\n } else if (level == Level.DEBUG) {\n logger.debug(pattern);\n }\n }", "public static void pushClassType(CodeAttribute b, String classType) {\n if (classType.length() != 1) {\n if (classType.startsWith(\"L\") && classType.endsWith(\";\")) {\n classType = classType.substring(1, classType.length() - 1);\n }\n b.loadClass(classType);\n } else {\n char type = classType.charAt(0);\n switch (type) {\n case 'I':\n b.getstatic(Integer.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'J':\n b.getstatic(Long.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'S':\n b.getstatic(Short.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'F':\n b.getstatic(Float.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'D':\n b.getstatic(Double.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'B':\n b.getstatic(Byte.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'C':\n b.getstatic(Character.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'Z':\n b.getstatic(Boolean.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n default:\n throw new RuntimeException(\"Cannot handle primitive type: \" + type);\n }\n }\n }", "public GVRAnimator animate(int animIndex, float timeInSec)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n anim.animate(timeInSec);\n return anim;\n }", "public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }", "public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException {\r\n\r\n // Use TreeMap so keys are automatically sorted alphabetically\r\n Map<String, String> parameters = new TreeMap<String, String>();\r\n parameters.put(\"method\", METHOD_EXCHANGE_TOKEN);\r\n parameters.put(Flickr.API_KEY, apiKey);\r\n // This method call must be signed using Flickr (not OAuth) style signing\r\n parameters.put(\"api_sig\", getSignature(sharedSecret, parameters));\r\n\r\n Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n OAuth1RequestToken accessToken = constructToken(response);\r\n\r\n return accessToken;\r\n }", "public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }", "private Integer getIntegerTimeInMinutes(Date date)\n {\n Integer result = null;\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n int time = cal.get(Calendar.HOUR_OF_DAY) * 60;\n time += cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n result = Integer.valueOf(time); \n }\n return (result);\n }", "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}", "public static AliasOperationTransformer replaceLastElement(final PathElement element) {\n return create(new AddressTransformer() {\n @Override\n public PathAddress transformAddress(final PathAddress original) {\n final PathAddress address = original.subAddress(0, original.size() -1);\n return address.append(element);\n }\n });\n }" ]
Print rate. @param rate Rate instance @return rate value
[ "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 }" ]
[ "public void setInRGB(IntRange inRGB) {\r\n this.inRed = inRGB;\r\n this.inGreen = inRGB;\r\n this.inBlue = inRGB;\r\n\r\n CalculateMap(inRGB, outRed, mapRed);\r\n CalculateMap(inRGB, outGreen, mapGreen);\r\n CalculateMap(inRGB, outBlue, mapBlue);\r\n }", "private List<String> parseRssFeedForeCast(String feed) {\n String[] result = feed.split(\"<br />\");\n List<String> returnList = new ArrayList<String>();\n String[] result2 = result[2].split(\"<BR />\");\n\n returnList.add(result2[3] + \"\\n\");\n returnList.add(result[3] + \"\\n\");\n returnList.add(result[4] + \"\\n\");\n returnList.add(result[5] + \"\\n\");\n returnList.add(result[6] + \"\\n\");\n\n return returnList;\n }", "public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }", "public static base_response update(nitro_service client, nsspparams resource) throws Exception {\n\t\tnsspparams updateresource = new nsspparams();\n\t\tupdateresource.basethreshold = resource.basethreshold;\n\t\tupdateresource.throttle = resource.throttle;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public void setDialect(String dialect) {\n String[] scripts = createScripts.get(dialect);\n createSql = scripts[0];\n createSqlInd = scripts[1];\n }", "protected Class getPrototypeClass(T content) {\n if (prototypes.size() == 1) {\n return prototypes.get(0).getClass();\n } else {\n return binding.get(content.getClass());\n }\n }", "private void writeCalendars(List<ProjectCalendar> records)\n {\n\n //\n // Write project calendars\n //\n for (ProjectCalendar record : records)\n {\n m_buffer.setLength(0);\n m_buffer.append(\"CLDR \");\n m_buffer.append(SDEFmethods.lset(record.getUniqueID().toString(), 2)); // 2 character used, USACE allows 1\n String workDays = SDEFmethods.workDays(record); // custom line, like NYYYYYN for a week\n m_buffer.append(SDEFmethods.lset(workDays, 8));\n m_buffer.append(SDEFmethods.lset(record.getName(), 30));\n m_writer.println(m_buffer);\n }\n }", "private static Query buildQuery(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n Criteria crit = new Criteria();\r\n\r\n for(int i = 0; i < pkFields.length; i++)\r\n {\r\n crit.addEqualTo(pkFields[i].getAttributeName(), null);\r\n }\r\n return new QueryByCriteria(cld.getClassOfObject(), crit);\r\n }" ]
Produces all tuples of size n chosen from a list of variable names @param variables the list of variable names to make tuples of @param nWise the size of the desired tuples @return all tuples of size nWise
[ "public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) {\r\n List<Set<String>> completeTuples = new ArrayList<>();\r\n makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise);\n\r\n return completeTuples;\r\n }" ]
[ "static void tryAutoAttaching(final SlotReference slot) {\n if (!MetadataFinder.getInstance().getMountedMediaSlots().contains(slot)) {\n logger.error(\"Unable to auto-attach cache to empty slot {}\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getMetadataCache(slot) != null) {\n logger.info(\"Not auto-attaching to slot {}; already has a cache attached.\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getAutoAttachCacheFiles().isEmpty()) {\n logger.debug(\"No auto-attach files configured.\");\n return;\n }\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5); // Give us a chance to find out what type of media is in the new mount.\n final MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null && details.mediaType == CdjStatus.TrackType.REKORDBOX) {\n // First stage attempt: See if we can match based on stored media details, which is both more reliable and\n // less disruptive than trying to sample the player database to compare entries.\n boolean attached = false;\n for (File file : MetadataFinder.getInstance().getAutoAttachCacheFiles()) {\n final MetadataCache cache = new MetadataCache(file);\n try {\n if (cache.sourceMedia != null && cache.sourceMedia.hashKey().equals(details.hashKey())) {\n // We found a solid match, no need to probe tracks.\n final boolean changed = cache.sourceMedia.hasChanged(details);\n logger.info(\"Auto-attaching metadata cache \" + cache.getName() + \" to slot \" + slot +\n \" based on media details \" + (changed? \"(changed since created)!\" : \"(unchanged).\"));\n MetadataFinder.getInstance().attachMetadataCacheInternal(slot, cache);\n attached = true;\n return;\n }\n } finally {\n if (!attached) {\n cache.close();\n }\n }\n }\n\n // Could not match based on media details; fall back to older method based on probing track metadata.\n ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {\n @Override\n public Object useClient(Client client) throws Exception {\n tryAutoAttachingWithConnection(slot, client);\n return null;\n }\n };\n ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, \"trying to auto-attach metadata cache\");\n }\n } catch (Exception e) {\n logger.error(\"Problem trying to auto-attach metadata cache for slot \" + slot, e);\n }\n\n }\n }, \"Metadata cache file auto-attachment attempt\").start();\n }", "private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}", "public void setFieldByAlias(String alias, Object value)\n {\n set(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias), value);\n }", "protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {\n try {\n // Add special methods for interceptors\n for (Method method : LifecycleMixin.class.getMethods()) {\n BeanLogger.LOG.addingMethodToProxy(method);\n MethodInformation methodInfo = new RuntimeMethodInformation(method);\n createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor);\n }\n Method getInstanceMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetInstance\");\n Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetClass\");\n generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod));\n generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod));\n\n Method setMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_setHandler\", MethodHandler.class);\n generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));\n\n Method getMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_getHandler\");\n generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }", "private static <D, T> D createDaoFromConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\t// no loaded configs\n\t\tif (configMap == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDatabaseTableConfig<T> config = (DatabaseTableConfig<T>) configMap.get(clazz);\n\t\t// if we don't config information cached return null\n\t\tif (config == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// else create a DAO using configuration\n\t\tDao<T, ?> configedDao = doCreateDao(connectionSource, config);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) configedDao;\n\t\treturn castDao;\n\t}", "private static String toColumnName(String fieldName) {\n int lastDot = fieldName.indexOf('.');\n if (lastDot > -1) {\n return fieldName.substring(lastDot + 1);\n } else {\n return fieldName;\n }\n }", "private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }", "private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException {\n\t\tList<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>();\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read next field from config file\", e);\n\t\t\t}\n\t\t\tif (line == null || line.equals(CONFIG_FILE_FIELDS_END)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader);\n\t\t\tif (fieldConfig == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfields.add(fieldConfig);\n\t\t}\n\t\tconfig.setFieldConfigs(fields);\n\t}", "public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }" ]
Get the class name without the qualified package name. @param className the className to get the short name for @return the class name of the class without the package name @throws IllegalArgumentException if the className is empty
[ "public static String getShortName(String className) {\n\t\tAssert.hasLength(className, \"Class name must not be empty\");\n\t\tint lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);\n\t\tint nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);\n\t\tif (nameEndIndex == -1) {\n\t\t\tnameEndIndex = className.length();\n\t\t}\n\t\tString shortName = className.substring(lastDotIndex + 1, nameEndIndex);\n\t\tshortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);\n\t\treturn shortName;\n\t}" ]
[ "public static vpnclientlessaccesspolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }", "public DesignDocument get(String id) {\r\n assertNotEmpty(id, \"id\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id));\r\n }", "private File makeDestFile(URL src) {\n if (dest == null) {\n throw new IllegalArgumentException(\"Please provide a download destination\");\n }\n\n File destFile = dest;\n if (destFile.isDirectory()) {\n //guess name from URL\n String name = src.toString();\n if (name.endsWith(\"/\")) {\n name = name.substring(0, name.length() - 1);\n }\n name = name.substring(name.lastIndexOf('/') + 1);\n destFile = new File(dest, name);\n } else {\n //create destination directory\n File parent = destFile.getParentFile();\n if (parent != null) {\n parent.mkdirs();\n }\n }\n return destFile;\n }", "public static byte[] copy(byte[] array, int from, int to) {\n if(to - from < 0) {\n return new byte[0];\n } else {\n byte[] a = new byte[to - from];\n System.arraycopy(array, from, a, 0, to - from);\n return a;\n }\n }", "public void prepare(Properties p, Connection cnx)\n {\n this.tablePrefix = p.getProperty(\"com.enioka.jqm.jdbc.tablePrefix\", \"\");\n queries.putAll(DbImplBase.queries);\n for (Map.Entry<String, String> entry : DbImplBase.queries.entrySet())\n {\n queries.put(entry.getKey(), this.adaptSql(entry.getValue()));\n }\n }", "public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "public static base_responses update(nitro_service client, inat resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tinat updateresources[] = new inat[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new inat();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].privateip = resources[i].privateip;\n\t\t\t\tupdateresources[i].tcpproxy = resources[i].tcpproxy;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].tftp = resources[i].tftp;\n\t\t\t\tupdateresources[i].usip = resources[i].usip;\n\t\t\t\tupdateresources[i].usnip = resources[i].usnip;\n\t\t\t\tupdateresources[i].proxyip = resources[i].proxyip;\n\t\t\t\tupdateresources[i].mode = resources[i].mode;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) {\n\t\tif (fieldType.isEscapedDefaultValue()) {\n\t\t\tappendEscapedWord(sb, defaultValue.toString());\n\t\t} else {\n\t\t\tsb.append(defaultValue);\n\t\t}\n\t}" ]
Extract where the destination is reshaped to match the extracted region @param src The original matrix which is to be copied. Not modified. @param srcX0 Start column. @param srcX1 Stop column+1. @param srcY0 Start row. @param srcY1 Stop row+1. @param dst Where the submatrix are stored. Modified.
[ "public static void extract( DMatrix src,\n int srcY0, int srcY1,\n int srcX0, int srcX1,\n DMatrix dst ) {\n ((ReshapeMatrix)dst).reshape(srcY1-srcY0,srcX1-srcX0);\n extract(src,srcY0,srcY1,srcX0,srcX1,dst,0,0);\n }" ]
[ "public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }", "private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList)\n {\n if (isWorkingDay(mpxjCalendar, day))\n {\n ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day);\n if (mpxjHours != null)\n {\n OverriddenDayType odt = m_factory.createOverriddenDayType();\n typeList.add(odt);\n odt.setId(getIntegerString(uniqueID.next()));\n List<Interval> intervalList = odt.getInterval();\n for (DateRange mpxjRange : mpxjHours)\n {\n Date rangeStart = mpxjRange.getStart();\n Date rangeEnd = mpxjRange.getEnd();\n\n if (rangeStart != null && rangeEnd != null)\n {\n Interval interval = m_factory.createInterval();\n intervalList.add(interval);\n interval.setStart(getTimeString(rangeStart));\n interval.setEnd(getTimeString(rangeEnd));\n }\n }\n }\n }\n }", "public static void objectToXML(Object object, String fileName) throws FileNotFoundException {\r\n\t\tFileOutputStream fo = new FileOutputStream(fileName);\r\n\t\tXMLEncoder encoder = new XMLEncoder(fo);\r\n\t\tencoder.writeObject(object);\r\n\t\tencoder.close();\r\n\t}", "@Nullable\n public final Credentials toCredentials(final AuthScope authscope) {\n try {\n\n if (!matches(MatchInfo.fromAuthScope(authscope))) {\n return null;\n }\n } catch (UnknownHostException | MalformedURLException | SocketException e) {\n throw new RuntimeException(e);\n }\n if (this.username == null) {\n return null;\n }\n\n final String passwordString;\n if (this.password != null) {\n passwordString = new String(this.password);\n } else {\n passwordString = null;\n }\n return new UsernamePasswordCredentials(this.username, passwordString);\n }", "public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}", "private void writeResources(Project project)\n {\n Project.Resources resources = m_factory.createProjectResources();\n project.setResources(resources);\n List<Project.Resources.Resource> list = resources.getResource();\n\n for (Resource resource : m_projectFile.getResources())\n {\n list.add(writeResource(resource));\n }\n }", "public static base_response add(nitro_service client, dnssuffix resource) throws Exception {\n\t\tdnssuffix addresource = new dnssuffix();\n\t\taddresource.Dnssuffix = resource.Dnssuffix;\n\t\treturn addresource.add_resource(client);\n\t}", "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}", "@Override\n\tprotected void doLinking() {\n\t\tIParseResult parseResult = getParseResult();\n\t\tif (parseResult == null || parseResult.getRootASTElement() == null)\n\t\t\treturn;\n\n\t\tXtextLinker castedLinker = (XtextLinker) getLinker();\n\t\tcastedLinker.discardGeneratedPackages(parseResult.getRootASTElement());\n\t}" ]
Returns the u component of a coordinate from a texture coordinate set. @param vertex the vertex index @param coords the texture coordinate set @return the u component
[ "public float getTexCoordU(int vertex, int coords) {\n if (!hasTexCoords(coords)) {\n throw new IllegalStateException(\n \"mesh has no texture coordinate set \" + coords);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for coords are done by java for us */\n \n return m_texcoords[coords].getFloat(\n vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);\n }" ]
[ "private boolean compareBytes(byte[] lhs, byte[] rhs, int rhsOffset)\n {\n boolean result = true;\n for (int loop = 0; loop < lhs.length; loop++)\n {\n if (lhs[loop] != rhs[rhsOffset + loop])\n {\n result = false;\n break;\n }\n }\n return (result);\n }", "protected <T> T getProperty(String key, Class<T> type) {\n Object returnValue = getProperty(key);\n if (returnValue != null) {\n return (T) returnValue;\n } else {\n return null;\n }\n }", "public static base_response rename(nitro_service client, responderpolicy resource, String new_name) throws Exception {\n\t\tresponderpolicy renameresource = new responderpolicy();\n\t\trenameresource.name = resource.name;\n\t\treturn renameresource.rename_resource(client,new_name);\n\t}", "protected void notifyBufferChange(char[] newData, int numChars) {\n synchronized(bufferChangeLoggers) {\n Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator();\n while (iterator.hasNext()) {\n iterator.next().bufferChanged(newData, numChars);\n }\n }\n }", "private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) {\n if(requestQueue != null) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n destroyRequest(resourceRequest);\n resourceRequest = requestQueue.poll();\n }\n }\n }", "public static void addLoadInstruction(CodeAttribute code, String type, int variable) {\n char tp = type.charAt(0);\n if (tp != 'L' && tp != '[') {\n // we have a primitive type\n switch (tp) {\n case 'J':\n code.lload(variable);\n break;\n case 'D':\n code.dload(variable);\n break;\n case 'F':\n code.fload(variable);\n break;\n default:\n code.iload(variable);\n }\n } else {\n code.aload(variable);\n }\n }", "public Collection<V> put(K key, Collection<V> collection) {\r\n return map.put(key, collection);\r\n }", "public static <E> Collection<E> sampleWithoutReplacement(Collection<E> c, int n) {\r\n return sampleWithoutReplacement(c, n, new Random());\r\n }", "public static <E, V> ServiceFuture<List<E>> fromHeaderPageResponse(Observable<ServiceResponseWithHeaders<Page<E>, V>> first, final Func1<String, Observable<ServiceResponseWithHeaders<Page<E>, V>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, new Func1<String, Observable<ServiceResponse<Page<E>>>>() {\n @Override\n public Observable<ServiceResponse<Page<E>>> call(String s) {\n return next.call(s)\n .map(new Func1<ServiceResponseWithHeaders<Page<E>, V>, ServiceResponse<Page<E>>>() {\n @Override\n public ServiceResponse<Page<E>> call(ServiceResponseWithHeaders<Page<E>, V> pageVServiceResponseWithHeaders) {\n return pageVServiceResponseWithHeaders;\n }\n });\n }\n }, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }" ]
Set an enterprise text value. @param index text index (1-40) @param value text value
[ "public void setEnterpriseText(int index, String value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_TEXT, index), value);\n }" ]
[ "@Override\n protected void addBuildInfoProperties(BuildInfoBuilder builder) {\n if (envVars != null) {\n for (Map.Entry<String, String> entry : envVars.entrySet()) {\n builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + entry.getKey(), entry.getValue());\n }\n }\n\n if (sysVars != null) {\n for (Map.Entry<String, String> entry : sysVars.entrySet()) {\n builder.addProperty(entry.getKey(), entry.getValue());\n }\n }\n }", "protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }", "public ItemRequest<CustomField> findById(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }", "private void processProjectID()\n {\n if (m_projectID == null)\n {\n List<Row> rows = getRows(\"project\", null, null);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_projectID = row.getInteger(\"proj_id\");\n }\n }\n }", "private void readTextsCompressed(File dir, HashMap results) throws IOException\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (files[idx].isDirectory())\r\n {\r\n continue;\r\n }\r\n results.put(files[idx].getName(), readTextCompressed(files[idx]));\r\n }\r\n }\r\n }", "public Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }", "public static void validateUserStoreNamesOnNode(AdminClient adminClient,\n Integer nodeId,\n List<String> storeNames) {\n List<StoreDefinition> storeDefList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, Boolean> existingStoreNames = new HashMap<String, Boolean>();\n for(StoreDefinition storeDef: storeDefList) {\n existingStoreNames.put(storeDef.getName(), true);\n }\n for(String storeName: storeNames) {\n if(!Boolean.TRUE.equals(existingStoreNames.get(storeName))) {\n Utils.croak(\"Store \" + storeName + \" does not exist!\");\n }\n }\n }", "protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) {\r\n if (argType==null || fieldType==null || fullyQualifiedMethodName==null) {\r\n throw new IllegalArgumentException(\"All parameters must be supplied - no nulls\");\r\n }\r\n String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(\".\"));\r\n String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(\".\")+1);\r\n\r\n \r\n String desc = null;\r\n try {\r\n if (MethodIs.aConstructor(methodName)) {\r\n Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType);\r\n desc = Type.getConstructorDescriptor(ctor);\r\n } else {\r\n Method method = Class.forName(className).getMethod(methodName, argType);\r\n desc = Type.getMethodDescriptor(method);\r\n }\r\n } catch (NoSuchMethodException e) {\r\n rethrow(\"No such method\", e);\r\n } catch (SecurityException e) {\r\n rethrow(\"Security error\", e);\r\n } catch (ClassNotFoundException e) {\r\n rethrow(\"Class not found\", e);\r\n }\r\n CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc);\r\n hardcodeValidCopyMethod(fieldType, copyMethod);\r\n }", "static void populateFileCreationRecord(Record record, ProjectProperties properties)\n {\n properties.setMpxProgramName(record.getString(0));\n properties.setMpxFileVersion(FileVersion.getInstance(record.getString(1)));\n properties.setMpxCodePage(record.getCodePage(2));\n }" ]
Checks the available space and sets max-height to the details field-set.
[ "private void onShow() {\n\n if (m_detailsFieldset != null) {\n m_detailsFieldset.getContentPanel().getElement().getStyle().setPropertyPx(\n \"maxHeight\",\n getAvailableHeight(m_messageWidget.getOffsetHeight()));\n }\n }" ]
[ "public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }", "public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }", "private List<I_CmsSearchFieldMapping> getMappings() {\n\n CmsSearchManager manager = OpenCms.getSearchManager();\n I_CmsSearchFieldConfiguration fieldConfig = manager.getFieldConfiguration(getParamFieldconfiguration());\n CmsLuceneField field;\n List<I_CmsSearchFieldMapping> result = null;\n Iterator<CmsSearchField> itFields;\n if (fieldConfig != null) {\n itFields = fieldConfig.getFields().iterator();\n while (itFields.hasNext()) {\n field = (CmsLuceneField)itFields.next();\n if (field.getName().equals(getParamField())) {\n result = field.getMappings();\n }\n }\n } else {\n result = Collections.emptyList();\n if (LOG.isErrorEnabled()) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SEARCHINDEX_EDIT_MISSING_PARAM_1,\n A_CmsFieldConfigurationDialog.PARAM_FIELDCONFIGURATION));\n }\n }\n return result;\n }", "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }", "public AnnotationVisitor visitLocalVariableAnnotation(int typeRef,\n TypePath typePath, Label[] start, Label[] end, int[] index,\n String desc, boolean visible) {\n if (mv != null) {\n return mv.visitLocalVariableAnnotation(typeRef, typePath, start,\n end, index, desc, visible);\n }\n return null;\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}", "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 }", "private IndexedContainer createContainerForBundleWithoutDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n Set<Object> keySet = m_keyset.getKeySet();\n for (Object key : keySet) {\n\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object translation = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n }\n\n return container;\n }", "public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }" ]
Get the permission information for the specified photo. This method requires authentication with 'read' permission. @param photoId The photo id @return The Permissions object @throws FlickrException
[ "public Permissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element permissionsElement = response.getPayload();\r\n Permissions permissions = new Permissions();\r\n permissions.setId(permissionsElement.getAttribute(\"id\"));\r\n permissions.setPublicFlag(\"1\".equals(permissionsElement.getAttribute(\"ispublic\")));\r\n permissions.setFamilyFlag(\"1\".equals(permissionsElement.getAttribute(\"isfamily\")));\r\n permissions.setFriendFlag(\"1\".equals(permissionsElement.getAttribute(\"isfriend\")));\r\n permissions.setComment(permissionsElement.getAttribute(\"permcomment\"));\r\n permissions.setAddmeta(permissionsElement.getAttribute(\"permaddmeta\"));\r\n return permissions;\r\n }" ]
[ "protected void mergeSameWork(LinkedList<TimephasedWork> list)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n TimephasedWork previousAssignment = null;\n for (TimephasedWork assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Duration previousAssignmentWork = previousAssignment.getAmountPerDay();\n Duration assignmentWork = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentWork.getDuration(), assignmentWork.getDuration(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().getDuration();\n total += assignmentWork.getDuration();\n Duration totalWork = Duration.getInstance(total, TimeUnit.MINUTES);\n\n TimephasedWork merged = new TimephasedWork();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentWork);\n merged.setTotalAmount(totalWork);\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }", "public Task<Long> count() {\n return dispatcher.dispatchTask(new Callable<Long>() {\n @Override\n public Long call() {\n return proxy.count();\n }\n });\n }", "private void checkObjectCache(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n ObjectCacheDef objCacheDef = classDef.getObjectCache();\r\n\r\n if (objCacheDef == null)\r\n {\r\n return;\r\n }\r\n\r\n String objectCacheName = objCacheDef.getName();\r\n\r\n if ((objectCacheName == null) || (objectCacheName.length() == 0))\r\n {\r\n throw new ConstraintException(\"No class specified for the object-cache of class \"+classDef.getName());\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(objectCacheName, OBJECT_CACHE_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+objectCacheName+\" specified as object-cache of class \"+classDef.getName()+\" does not implement the interface \"+OBJECT_CACHE_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the object-cache class \"+objectCacheName+\" of class \"+classDef.getName());\r\n }\r\n }", "private static int getTrimmedWidth(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int trimmedWidth = 0;\n\n for (int i = 0; i < height; i++) {\n for (int j = width - 1; j >= 0; j--) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {\n trimmedWidth = j;\n break;\n }\n }\n }\n\n return trimmedWidth;\n }", "public static void validateAllAvroSchemas(SerializerDefinition avroSerDef) {\n Map<Integer, String> schemaVersions = avroSerDef.getAllSchemaInfoVersions();\n if(schemaVersions.size() < 1) {\n throw new VoldemortException(\"No schema specified\");\n }\n for(Map.Entry<Integer, String> entry: schemaVersions.entrySet()) {\n Integer schemaVersionNumber = entry.getKey();\n String schemaStr = entry.getValue();\n try {\n Schema.parse(schemaStr);\n } catch(Exception e) {\n throw new VoldemortException(\"Unable to parse Avro schema version :\"\n + schemaVersionNumber + \", schema string :\"\n + schemaStr);\n }\n }\n }", "public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }", "boolean callbackUnregistered(final TransactionalProtocolClient old, final boolean shuttingDown) {\n // Disconnect the remote connection.\n // WFCORE-196 Do this out of the sync block to avoid deadlocks where in-flight requests can't\n // be informed that the channel has closed\n protocolClient.disconnected(old);\n\n synchronized (this) {\n // If the connection dropped without us stopping the process ask for reconnection\n if (!shuttingDown && requiredState == InternalState.SERVER_STARTED) {\n final InternalState state = internalState;\n if (state == InternalState.PROCESS_STOPPED\n || state == InternalState.PROCESS_STOPPING\n || state == InternalState.STOPPED) {\n // In case it stopped we don't reconnect\n return true;\n }\n // In case we are reloading, it will reconnect automatically\n if (state == InternalState.RELOADING) {\n return true;\n }\n try {\n ROOT_LOGGER.logf(DEBUG_LEVEL, \"trying to reconnect to %s current-state (%s) required-state (%s)\", serverName, state, requiredState);\n internalSetState(new ReconnectTask(), state, InternalState.SEND_STDIN);\n } catch (Exception e) {\n ROOT_LOGGER.logf(DEBUG_LEVEL, e, \"failed to send reconnect task\");\n }\n return false;\n } else {\n return true;\n }\n }\n }", "public int scrollToPage(int pageNumber) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToPage pageNumber = %d mPageCount = %d\",\n pageNumber, mPageCount);\n\n if (mSupportScrollByPage &&\n (mScrollOver || (pageNumber >= 0 && pageNumber <= mPageCount - 1))) {\n scrollToItem(getFirstItemIndexOnPage(pageNumber));\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n return mCurrentItemIndex;\n\t}", "public List<Message> requestArtistMenuFrom(final SlotReference slotReference, final int sortOrder)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Artist menu.\");\n Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n new NumberField(sortOrder));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting artist menu\");\n }" ]
Substitute the variables in the given expression with the values from the resolver @param pResolver @param pExpression
[ "public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) {\n final char[] open = pOpen.toCharArray();\n final char[] close = pClose.toCharArray();\n\n final StringBuilder out = new StringBuilder();\n StringBuilder sb = new StringBuilder();\n char[] last = null;\n int wo = 0;\n int wc = 0;\n int level = 0;\n for (char c : pExpression.toCharArray()) {\n if (c == open[wo]) {\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n wc = 0;\n wo++;\n if (open.length == wo) {\n // found open\n if (last == open) {\n out.append(open);\n }\n level++;\n out.append(sb);\n sb = new StringBuilder();\n wo = 0;\n last = open;\n }\n } else if (c == close[wc]) {\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n wo = 0;\n wc++;\n if (close.length == wc) {\n // found close\n if (last == open) {\n final String variable = pResolver.get(sb.toString());\n if (variable != null) {\n out.append(variable);\n } else {\n out.append(open);\n out.append(sb);\n out.append(close);\n }\n } else {\n out.append(sb);\n out.append(close);\n }\n sb = new StringBuilder();\n level--;\n wc = 0;\n last = close;\n }\n } else {\n\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n\n sb.append(c);\n\n wo = wc = 0;\n }\n }\n\n if (wo > 0) {\n sb.append(open, 0, wo);\n }\n\n if (wc > 0) {\n sb.append(close, 0, wc);\n }\n\n if (level > 0) {\n out.append(open);\n }\n out.append(sb);\n\n return out.toString();\n }" ]
[ "public static<T> Vendor<T> vendor(Callable<T> f) {\n\treturn j.vendor(f);\n }", "public static String toSafeFileName(String name) {\n int size = name.length();\n StringBuilder builder = new StringBuilder(size * 2);\n for (int i = 0; i < size; i++) {\n char c = name.charAt(i);\n boolean valid = c >= 'a' && c <= 'z';\n valid = valid || (c >= 'A' && c <= 'Z');\n valid = valid || (c >= '0' && c <= '9');\n valid = valid || (c == '_') || (c == '-') || (c == '.');\n\n if (valid) {\n builder.append(c);\n } else {\n // Encode the character using hex notation\n builder.append('x');\n builder.append(Integer.toHexString(i));\n }\n }\n return builder.toString();\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 }", "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}", "void processBeat(Beat beat) {\n if (isRunning() && beat.isTempoMaster()) {\n setMasterTempo(beat.getEffectiveTempo());\n deliverBeatAnnouncement(beat);\n }\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 }", "public static int queryForInt(Statement stmt, String sql, int nullvalue) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n if (!rs.next())\n return nullvalue;\n \n return rs.getInt(1);\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }", "public int[] argb(int x, int y) {\n Pixel p = pixel(x, y);\n return new int[]{p.alpha(), p.red(), p.green(), p.blue()};\n }", "private static Data loadLeapSeconds(URL url) throws ClassNotFoundException, IOException {\n List<String> lines;\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {\n lines = reader.lines().collect(Collectors.toList());\n }\n List<Long> dates = new ArrayList<>();\n List<Integer> offsets = new ArrayList<>();\n for (String line : lines) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\")) {\n continue;\n }\n Matcher matcher = LEAP_FILE_FORMAT.matcher(line);\n if (matcher.matches() == false) {\n throw new StreamCorruptedException(\"Invalid leap second file\");\n }\n dates.add(LocalDate.parse(matcher.group(1)).getLong(JulianFields.MODIFIED_JULIAN_DAY));\n offsets.add(Integer.valueOf(matcher.group(2)));\n }\n long[] datesData = new long[dates.size()];\n int[] offsetsData = new int[dates.size()];\n long[] taiData = new long[dates.size()];\n for (int i = 0; i < datesData.length; i++) {\n datesData[i] = dates.get(i);\n offsetsData[i] = offsets.get(i);\n taiData[i] = tai(datesData[i], offsetsData[i]);\n }\n return new Data(datesData, offsetsData, taiData);\n }" ]
Returns a description String based on the defined command and options. Useful when printing "help" info etc.
[ "public String printHelp(String commandName) {\n int maxLength = 0;\n int width = 80;\n List<ProcessedOption> opts = getOptions();\n for (ProcessedOption o : opts) {\n if(o.getFormattedLength() > maxLength)\n maxLength = o.getFormattedLength();\n }\n\n StringBuilder sb = new StringBuilder();\n //first line\n sb.append(\"Usage: \");\n if(commandName == null || commandName.length() == 0)\n sb.append(name());\n else\n sb.append(commandName);\n if(opts.size() > 0)\n sb.append(\" [<options>]\");\n\n if(argument != null) {\n if(argument.isTypeAssignableByResourcesOrFile())\n sb.append(\" <file>\");\n else\n sb.append(\" <\").append(argument.getFieldName()).append(\">\");\n }\n\n if(arguments != null) {\n if(arguments.isTypeAssignableByResourcesOrFile())\n sb.append(\" [<files>]\");\n else\n sb.append(\" [<\").append(arguments.getFieldName()).append(\">]\");\n }\n sb.append(Config.getLineSeparator());\n //second line\n sb.append(description()).append(Config.getLineSeparator());\n\n //options and arguments\n if (opts.size() > 0)\n sb.append(Config.getLineSeparator()).append(\"Options:\").append(Config.getLineSeparator());\n for (ProcessedOption o : opts)\n sb.append(o.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n if(arguments != null) {\n sb.append(Config.getLineSeparator()).append(\"Arguments:\").append(Config.getLineSeparator());\n sb.append(arguments.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n }\n if(argument != null) {\n sb.append(Config.getLineSeparator()).append(\"Argument:\").append(Config.getLineSeparator());\n sb.append(argument.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n }\n return sb.toString();\n }" ]
[ "public static boolean isDouble(CharSequence self) {\n try {\n Double.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }", "public static base_response add(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice addresource = new gslbservice();\n\t\taddresource.servicename = resource.servicename;\n\t\taddresource.cnameentry = resource.cnameentry;\n\t\taddresource.ip = resource.ip;\n\t\taddresource.servername = resource.servername;\n\t\taddresource.servicetype = resource.servicetype;\n\t\taddresource.port = resource.port;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.publicport = resource.publicport;\n\t\taddresource.maxclient = resource.maxclient;\n\t\taddresource.healthmonitor = resource.healthmonitor;\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.state = resource.state;\n\t\taddresource.cip = resource.cip;\n\t\taddresource.cipheader = resource.cipheader;\n\t\taddresource.sitepersistence = resource.sitepersistence;\n\t\taddresource.cookietimeout = resource.cookietimeout;\n\t\taddresource.siteprefix = resource.siteprefix;\n\t\taddresource.clttimeout = resource.clttimeout;\n\t\taddresource.svrtimeout = resource.svrtimeout;\n\t\taddresource.maxbandwidth = resource.maxbandwidth;\n\t\taddresource.downstateflush = resource.downstateflush;\n\t\taddresource.maxaaausers = resource.maxaaausers;\n\t\taddresource.monthreshold = resource.monthreshold;\n\t\taddresource.hashid = resource.hashid;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.appflowlog = resource.appflowlog;\n\t\treturn addresource.add_resource(client);\n\t}", "@Pure\n\tpublic static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function0<RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply() {\n\t\t\t\treturn function.apply(argument);\n\t\t\t}\n\t\t};\n\t}", "@SuppressWarnings(\"unchecked\") public static TimeUnit getInstance(String units, Locale locale) throws MPXJException\n {\n Map<String, Integer> map = LocaleData.getMap(locale, LocaleData.TIME_UNITS_MAP);\n Integer result = map.get(units.toLowerCase());\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TIME_UNIT + \" \" + units);\n }\n return (TimeUnit.getInstance(result.intValue()));\n }", "protected String getQueryModifier() {\n\n String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER);\n return (null == queryModifier) && (null != m_baseConfig)\n ? m_baseConfig.getGeneralConfig().getQueryModifier()\n : queryModifier;\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 }", "private void updateDates(Task parentTask)\n {\n if (parentTask.hasChildTasks())\n {\n Date plannedStartDate = null;\n Date plannedFinishDate = null;\n\n for (Task task : parentTask.getChildTasks())\n {\n updateDates(task);\n plannedStartDate = DateHelper.min(plannedStartDate, task.getStart());\n plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish());\n }\n\n parentTask.setStart(plannedStartDate);\n parentTask.setFinish(plannedFinishDate);\n }\n }", "public void executeUpdate(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeUpdate: \" + obj);\r\n }\r\n\r\n // obj with nothing but key fields is not updated\r\n if (cld.getNonPkRwFields().length == 0)\r\n {\r\n return;\r\n }\r\n\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n // BRJ: preserve current locking values\r\n // locking values will be restored in case of exception\r\n ValueContainer[] oldLockingValues;\r\n oldLockingValues = cld.getCurrentLockingValues(obj);\r\n try\r\n {\r\n stmt = sm.getUpdateStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getUpdateStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getUpdateStatement returned a null statement\");\r\n }\r\n\r\n sm.bindUpdate(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeUpdate: \" + stmt);\r\n\r\n if ((stmt.executeUpdate() == 0) && cld.isLocking()) //BRJ\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tString objToString = \"\";\r\n \ttry {\r\n \t\tobjToString = obj.toString();\r\n \t} catch (Exception ex) {}\r\n throw new OptimisticLockException(\"Object has been modified by someone else: \" + objToString, obj);\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getUpdateProcedure(), obj, stmt);\r\n }\r\n catch (OptimisticLockException e)\r\n {\r\n // Don't log as error\r\n if (logger.isDebugEnabled())\r\n logger.debug(\r\n \"OptimisticLockException during the execution of update: \" + e.getMessage(),\r\n e);\r\n throw e;\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // BRJ: restore old locking values\r\n setLockingValues(cld, obj, oldLockingValues);\r\n\r\n logger.error(\r\n \"PersistenceBrokerException during the execution of the update: \" + e.getMessage(),\r\n e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedUpdateStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }" ]
Initializes the components. @param components the components
[ "private void initComponents(List<CmsSetupComponent> components) {\n\n for (CmsSetupComponent component : components) {\n CheckBox checkbox = new CheckBox();\n checkbox.setValue(component.isChecked());\n checkbox.setCaption(component.getName() + \" - \" + component.getDescription());\n checkbox.setDescription(component.getDescription());\n checkbox.setData(component);\n checkbox.setWidth(\"100%\");\n m_components.addComponent(checkbox);\n m_componentCheckboxes.add(checkbox);\n m_componentMap.put(component.getId(), component);\n\n }\n }" ]
[ "private RowKeyAndTuple createAndPutAssociationRowForInsert(Serializable key, PersistentCollection collection,\n\t\t\tAssociationPersister associationPersister, SharedSessionContractImplementor session, int i, Object entry) {\n\t\tRowKeyBuilder rowKeyBuilder = initializeRowKeyBuilder();\n\t\tTuple associationRow = new Tuple();\n\n\t\t// the collection has a surrogate key (see @CollectionId)\n\t\tif ( hasIdentifier ) {\n\t\t\tfinal Object identifier = collection.getIdentifier( entry, i );\n\t\t\tString[] names = { getIdentifierColumnName() };\n\t\t\tidentifierGridType.nullSafeSet( associationRow, identifier, names, session );\n\t\t}\n\n\t\tgetKeyGridType().nullSafeSet( associationRow, key, getKeyColumnNames(), session );\n\t\t// No need to write to where as we don't do where clauses in OGM :)\n\t\tif ( hasIndex ) {\n\t\t\tObject index = collection.getIndex( entry, i, this );\n\t\t\tindexGridType.nullSafeSet( associationRow, incrementIndexByBase( index ), getIndexColumnNames(), session );\n\t\t}\n\n\t\t// columns of referenced key\n\t\tfinal Object element = collection.getElement( entry );\n\t\tgetElementGridType().nullSafeSet( associationRow, element, getElementColumnNames(), session );\n\n\t\tRowKeyAndTuple result = new RowKeyAndTuple();\n\t\tresult.key = rowKeyBuilder.values( associationRow ).build();\n\t\tresult.tuple = associationRow;\n\n\t\tassociationPersister.getAssociation().put( result.key, result.tuple );\n\n\t\treturn result;\n\t}", "protected String getQueryModifier() {\n\n String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER);\n return (null == queryModifier) && (null != m_baseConfig)\n ? m_baseConfig.getGeneralConfig().getQueryModifier()\n : queryModifier;\n }", "public static base_response unset(nitro_service client, nsrpcnode resource, String[] args) throws Exception{\n\t\tnsrpcnode unsetresource = new nsrpcnode();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static void clear() {\n JobContext ctx = current_.get();\n if (null != ctx) {\n ctx.bag_.clear();\n JobContext parent = ctx.parent;\n if (null != parent) {\n current_.set(parent);\n ctx.parent = null;\n } else {\n current_.remove();\n Act.eventBus().trigger(new JobContextDestroyed(ctx));\n }\n }\n }", "public AsciiTable setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public AccessAssertion unmarshal(final JSONObject encodedAssertion) {\n final String className;\n try {\n className = encodedAssertion.getString(JSON_CLASS_NAME);\n final Class<?> assertionClass =\n Thread.currentThread().getContextClassLoader().loadClass(className);\n final AccessAssertion assertion =\n (AccessAssertion) this.applicationContext.getBean(assertionClass);\n assertion.unmarshal(encodedAssertion);\n\n return assertion;\n } catch (JSONException | ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }", "@SuppressWarnings(\"serial\")\n private Component createCloseButton() {\n\n Button closeBtn = CmsToolBar.createButton(\n FontOpenCms.CIRCLE_INV_CANCEL,\n m_messages.key(Messages.GUI_BUTTON_CANCEL_0));\n closeBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n closeAction();\n }\n\n });\n return closeBtn;\n }", "private void init() {\n if (initialized.compareAndSet(false, true)) {\n final RowSorter<? extends TableModel> rowSorter = table.getRowSorter();\n rowSorter.toggleSortOrder(1); // sort by date\n rowSorter.toggleSortOrder(1); // descending\n final TableColumnModel columnModel = table.getColumnModel();\n columnModel.getColumn(1).setCellRenderer(dateRenderer);\n columnModel.getColumn(2).setCellRenderer(sizeRenderer);\n }\n }", "private String parseRssFeed(String feed) {\n String[] result = feed.split(\"<br />\");\n String[] result2 = result[2].split(\"<BR />\");\n\n return result2[0];\n }" ]
Don't use input, it's match values might have been reset in the loop that looks for the first possible match. @param pairIndex TODO @param result TODO @return TODO
[ "protected ExpectState prepareClosure(int pairIndex, MatchResult result) {\n /* TODO: potentially remove this?\n {\n System.out.println( \"Begin: \" + result.beginOffset(0) );\n System.out.println( \"Length: \" + result.length() );\n System.out.println( \"Current: \" + input.getCurrentOffset() );\n System.out.println( \"Begin: \" + input.getMatchBeginOffset() );\n System.out.println( \"End: \" + input.getMatchEndOffset() );\n //System.out.println( \"Match: \" + input.match() );\n //System.out.println( \"Pre: >\" + input.preMatch() + \"<\");\n //System.out.println( \"Post: \" + input.postMatch() );\n }\n */\n\n // Prepare Closure environment\n ExpectState state;\n Map<String, Object> prevMap = null;\n if (g_state != null) {\n prevMap = g_state.getVars();\n }\n\n int matchedWhere = result.beginOffset(0);\n String matchedText = result.toString(); // expect_out(0,string)\n\n // Unmatched upto end of match\n // expect_out(buffer)\n char[] chBuffer = input.getBuffer();\n String copyBuffer = new String(chBuffer, 0, result.endOffset(0) );\n\n List<String> groups = new ArrayList<>();\n for (int j = 1; j <= result.groups(); j++) {\n String group = result.group(j);\n groups.add( group );\n }\n state = new ExpectState(copyBuffer.toString(), matchedWhere, matchedText, pairIndex, groups, prevMap);\n\n return state;\n }" ]
[ "@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public String getRemoteUrl(String defaultRemoteUrl) {\n if (StringUtils.isBlank(defaultRemoteUrl)) {\n RemoteConfig remoteConfig = getJenkinsScm().getRepositories().get(0);\n URIish uri = remoteConfig.getURIs().get(0);\n return uri.toPrivateString();\n }\n\n return defaultRemoteUrl;\n }", "public static <T> T createObject(final Class<T> clazz, final Object... args) throws NoSuchConstructorException,\n AmbiguousConstructorException, ReflectiveOperationException {\n return findConstructor(clazz, args).newInstance(args);\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 }", "@SuppressWarnings(\"unchecked\")\n public LinkedHashMap<String, Field> getValueAsListMap() {\n return (LinkedHashMap<String, Field>) type.convert(getValue(), Type.LIST_MAP);\n }", "private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }", "private CmsFavoriteEntry getEntry(Component row) {\n\n if (row instanceof CmsFavInfo) {\n\n return ((CmsFavInfo)row).getEntry();\n\n }\n return null;\n\n }", "public ItemRequest<Task> removeDependents(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public static Map<String,List<Long>> readHints(File hints) throws IOException {\n Map<String,List<Long>> result = new HashMap<>();\n InputStream is = new FileInputStream(hints);\n mergeHints(is, result);\n return result;\n }" ]
Converts a date to an instance date bean. @return the instance date bean.
[ "public CmsJspInstanceDateBean getToInstanceDate() {\n\n if (m_instanceDate == null) {\n m_instanceDate = new CmsJspInstanceDateBean(getToDate(), m_cms.getRequestContext().getLocale());\n }\n return m_instanceDate;\n }" ]
[ "public int color(Context ctx) {\n if (mColorInt == 0 && mColorRes != -1) {\n mColorInt = ContextCompat.getColor(ctx, mColorRes);\n }\n return mColorInt;\n }", "I_CmsSerialDateServiceAsync getService() {\r\n\r\n if (SERVICE == null) {\r\n SERVICE = GWT.create(I_CmsSerialDateService.class);\r\n String serviceUrl = CmsCoreProvider.get().link(\"org.opencms.ade.contenteditor.CmsSerialDateService.gwt\");\r\n ((ServiceDefTarget)SERVICE).setServiceEntryPoint(serviceUrl);\r\n }\r\n return SERVICE;\r\n }", "public boolean canUpdateServer(ServerIdentity server) {\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n if (!parent.canChildProceed())\n return false;\n\n synchronized (this) {\n return failureCount <= maxFailed;\n }\n }", "public List<MapRow> readTable(Class<? extends TableReader> readerClass) throws IOException\n {\n TableReader reader;\n\n try\n {\n reader = readerClass.getConstructor(StreamReader.class).newInstance(this);\n }\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n return readTable(reader);\n }", "public static base_response flush(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup flushresource = new cachecontentgroup();\n\t\tflushresource.name = resource.name;\n\t\tflushresource.query = resource.query;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.selectorvalue = resource.selectorvalue;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "public static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}", "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "public String addExtent(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n\r\n if (!_model.hasClass(name))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_FIND_TYPE,\r\n new String[]{name}));\r\n }\r\n _curClassDef.addExtentClass(_model.getClass(name));\r\n return \"\";\r\n }", "private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }" ]
To be used with AutoText class constants ALIGMENT_LEFT, ALIGMENT_CENTER and ALIGMENT_RIGHT @param aligment @return
[ "public static HorizontalBandAlignment buildAligment(byte aligment){\n\t\tif (aligment == RIGHT.getAlignment())\n\t\t\treturn RIGHT;\n\t\telse if (aligment == LEFT.getAlignment())\n\t\t\treturn LEFT;\n\t\telse if (aligment == CENTER.getAlignment())\n\t\t\treturn CENTER;\n\n\t\treturn LEFT;\n\t}" ]
[ "public void setDatesWithCheckState(Collection<CmsPair<Date, Boolean>> datesWithCheckInfo) {\n\n SortedSet<Date> dates = new TreeSet<>();\n m_checkBoxes.clear();\n for (CmsPair<Date, Boolean> p : datesWithCheckInfo) {\n addCheckBox(p.getFirst(), p.getSecond().booleanValue());\n dates.add(p.getFirst());\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }", "public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\n }\n }", "private EnabledEndpoint getPartialEnabledEndpointFromResultset(ResultSet result) throws Exception {\n EnabledEndpoint endpoint = new EnabledEndpoint();\n endpoint.setId(result.getInt(Constants.GENERIC_ID));\n endpoint.setPathId(result.getInt(Constants.ENABLED_OVERRIDES_PATH_ID));\n endpoint.setOverrideId(result.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID));\n endpoint.setPriority(result.getInt(Constants.ENABLED_OVERRIDES_PRIORITY));\n endpoint.setRepeatNumber(result.getInt(Constants.ENABLED_OVERRIDES_REPEAT_NUMBER));\n endpoint.setResponseCode(result.getString(Constants.ENABLED_OVERRIDES_RESPONSE_CODE));\n\n ArrayList<Object> args = new ArrayList<Object>();\n try {\n JSONArray arr = new JSONArray(result.getString(Constants.ENABLED_OVERRIDES_ARGUMENTS));\n for (int x = 0; x < arr.length(); x++) {\n args.add(arr.get(x));\n }\n } catch (Exception e) {\n // ignore it.. this means the entry was null/corrupt\n }\n\n endpoint.setArguments(args.toArray(new Object[0]));\n\n return endpoint;\n }", "private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }", "public static void checkVectorAddition() {\n DoubleMatrix x = new DoubleMatrix(3, 1, 1.0, 2.0, 3.0);\n DoubleMatrix y = new DoubleMatrix(3, 1, 4.0, 5.0, 6.0);\n DoubleMatrix z = new DoubleMatrix(3, 1, 5.0, 7.0, 9.0);\n\n check(\"checking vector addition\", x.add(y).equals(z));\n }", "public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }", "public static <T> T getBundle(final Class<T> type) {\n return doPrivileged(new PrivilegedAction<T>() {\n public T run() {\n final Locale locale = Locale.getDefault();\n final String lang = locale.getLanguage();\n final String country = locale.getCountry();\n final String variant = locale.getVariant();\n\n Class<? extends T> bundleClass = null;\n if (variant != null && !variant.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, variant), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && country != null && !country.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && lang != null && !lang.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", null, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n throw new IllegalArgumentException(\"Invalid bundle \" + type + \" (implementation not found)\");\n }\n final Field field;\n try {\n field = bundleClass.getField(\"INSTANCE\");\n } catch (NoSuchFieldException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" has no instance field\");\n }\n try {\n return type.cast(field.get(null));\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" could not be instantiated\", e);\n }\n }\n });\n }", "public 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 processAnonymousReference(Properties attributes) throws XDocletException\r\n {\r\n ReferenceDescriptorDef refDef = _curClassDef.getReference(\"super\");\r\n String attrName;\r\n\r\n if (refDef == null)\r\n {\r\n refDef = new ReferenceDescriptorDef(\"super\");\r\n _curClassDef.addReference(refDef);\r\n }\r\n refDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousReference\", \" Processing anonymous reference\");\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n refDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n }" ]
Implement the persistence handler for storing the group properties.
[ "void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException {\n persist(key, value, enableDisableMode, disable, file, null);\n }" ]
[ "public void setColorRange(int firstIndex, int lastIndex, int color) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = color;\n\t}", "private List<Key> getScatterKeys(\n int numSplits, Query query, PartitionId partition, Datastore datastore)\n throws DatastoreException {\n Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);\n\n List<Key> keySplits = new ArrayList<Key>();\n\n QueryResultBatch batch;\n do {\n RunQueryRequest scatterRequest =\n RunQueryRequest.newBuilder()\n .setPartitionId(partition)\n .setQuery(scatterPointQuery)\n .build();\n batch = datastore.runQuery(scatterRequest).getBatch();\n for (EntityResult result : batch.getEntityResultsList()) {\n keySplits.add(result.getEntity().getKey());\n }\n scatterPointQuery.setStartCursor(batch.getEndCursor());\n scatterPointQuery.getLimitBuilder().setValue(\n scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());\n } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);\n Collections.sort(keySplits, DatastoreHelper.getKeyComparator());\n return keySplits;\n }", "public static int compare(double a, double b, double delta) {\n if (equals(a, b, delta)) {\n return 0;\n }\n return Double.compare(a, b);\n }", "public void seek(final int position) throws IOException {\n if (position < 0) {\n throw new IllegalArgumentException(\"position < 0: \" + position);\n }\n if (position > size) {\n throw new EOFException();\n }\n this.pointer = position;\n }", "private boolean isRecyclable(View convertView, T content) {\n boolean isRecyclable = false;\n if (convertView != null && convertView.getTag() != null) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n isRecyclable = prototypeClass.equals(convertView.getTag().getClass());\n }\n return isRecyclable;\n }", "private static IndexOptions prepareOptions(MongoDBIndexType indexType, Document options, String indexName, boolean unique) {\n\t\tIndexOptions indexOptions = new IndexOptions();\n\t\tindexOptions.name( indexName ).unique( unique ).background( options.getBoolean( \"background\" , false ) );\n\n\t\tif ( unique ) {\n\t\t\t// MongoDB only allows one null value per unique index which is not in line with what we usually consider\n\t\t\t// as the definition of a unique constraint. Thus, we mark the index as sparse to only index values\n\t\t\t// defined and avoid this issue. We do this only if a partialFilterExpression has not been defined\n\t\t\t// as partialFilterExpression and sparse are exclusive.\n\t\t\tindexOptions.sparse( !options.containsKey( \"partialFilterExpression\" ) );\n\t\t}\n\t\telse if ( options.containsKey( \"partialFilterExpression\" ) ) {\n\t\t\tindexOptions.partialFilterExpression( (Bson) options.get( \"partialFilterExpression\" ) );\n\t\t}\n\t\tif ( options.containsKey( \"expireAfterSeconds\" ) ) {\n\t\t\t//@todo is it correct?\n\t\t\tindexOptions.expireAfter( options.getInteger( \"expireAfterSeconds\" ).longValue() , TimeUnit.SECONDS );\n\n\t\t}\n\n\t\tif ( MongoDBIndexType.TEXT.equals( indexType ) ) {\n\t\t\t// text is an option we take into account to mark an index as a full text index as we cannot put \"text\" as\n\t\t\t// the order like MongoDB as ORM explicitly checks that the order is either asc or desc.\n\t\t\t// we remove the option from the Document so that we don't pass it to MongoDB\n\t\t\tif ( options.containsKey( \"default_language\" ) ) {\n\t\t\t\tindexOptions.defaultLanguage( options.getString( \"default_language\" ) );\n\t\t\t}\n\t\t\tif ( options.containsKey( \"weights\" ) ) {\n\t\t\t\tindexOptions.weights( (Bson) options.get( \"weights\" ) );\n\t\t\t}\n\n\t\t\toptions.remove( \"text\" );\n\t\t}\n\t\treturn indexOptions;\n\t}", "private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}", "protected void prepForWrite(SelectionKey selectionKey) {\n if(logger.isTraceEnabled())\n traceInputBufferState(\"About to clear read buffer\");\n\n if(requestHandlerFactory.shareReadWriteBuffer() == false) {\n inputStream.clear();\n }\n\n if(logger.isTraceEnabled())\n traceInputBufferState(\"Cleared read buffer\");\n\n outputStream.getBuffer().flip();\n selectionKey.interestOps(SelectionKey.OP_WRITE);\n }", "public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }" ]