code
stringlengths
10
174k
nl
stringlengths
3
129k
public LogSimpleItemEventCommand(final RPObject item,final RPEntity player,final String event,final String param1,final String param2,final String param3,final String param4){ this.item=item; this.player=player; this.event=event; this.param1=param1; this.param2=param2; this.param3=param3; this.param4=param4; }
creates a simple item log command
public static List propertyDescriptors(int apiLevel){ return PROPERTY_DESCRIPTORS; }
Returns a list of structural property descriptors for this node type. Clients must not modify the result.
public static void registerMetadata(MetadataRegistry registry){ if (registry.isRegistered(KEY)) { return; } ElementCreator builder=registry.build(KEY); builder.addAttribute(LABEL); builder.addAttribute(REL); builder.addAttribute(VALUE_STRING); builder.addElement(EntryLink.KEY); }
Registers the metadata for this element.
@Override public Object clone(){ ByteArrayList clone=null; try { clone=(ByteArrayList)super.clone(); clone._data=(byte[])_data.clone(); } catch ( CloneNotSupportedException e) { } return clone; }
Returns a clone of this list. Since this is a primitive collection, this will be a deep clone.
@Post public String handlePost(String fmJson){ IFirewallService firewall=(IFirewallService)getContext().getAttributes().get(IFirewallService.class.getCanonicalName()); String newMask; try { newMask=jsonExtractSubnetMask(fmJson); } catch ( IOException e) { log.error("Error parsing new subnet mask: " + fmJson,e); return "{\"status\" : \"Error! Could not parse new subnet mask, see log for details.\"}"; } firewall.setSubnetMask(newMask); return ("{\"status\" : \"subnet mask set\"}"); }
Allows setting of subnet mask
void invalidConversion(Converter converter,Object value){ String valueType=(value == null ? "null" : value.getClass().getName()); String msg="Converting '" + valueType + "' value '"+ value+ "'"; try { Object result=converter.convert(getExpectedType(),value); fail(msg + ", expected ConversionException, but result = '" + result+ "'"); } catch ( ConversionException ex) { } }
Test Conversion Error
private void checkRanges(){ for (int i=0; i < problem.getNumberOfObjectives(); i++) { if (Math.abs(minimum[i] - maximum[i]) < Settings.EPS) { throw new IllegalArgumentException("objective with empty range"); } } }
Checks if any objective has a range that is smaller than machine precision.
private static void checkCRL(DistributionPoint dp,ExtendedPKIXParameters paramsPKIX,X509Certificate cert,Date validDate,X509Certificate defaultCRLSignCert,PublicKey defaultCRLSignKey,CertStatus certStatus,ReasonsMask reasonMask,List certPathCerts) throws AnnotatedException { Date currentDate=new Date(System.currentTimeMillis()); if (validDate.getTime() > currentDate.getTime()) { throw new AnnotatedException("Validation time is in future."); } Set crls=CertPathValidatorUtilities.getCompleteCRLs(dp,cert,currentDate,paramsPKIX); boolean validCrlFound=false; AnnotatedException lastException=null; Iterator crl_iter=crls.iterator(); while (crl_iter.hasNext() && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonMask.isAllReasons()) { try { X509CRL crl=(X509CRL)crl_iter.next(); ReasonsMask interimReasonsMask=RFC3280CertPathUtilities.processCRLD(crl,dp); if (!interimReasonsMask.hasNewReasons(reasonMask)) { continue; } Set keys=RFC3280CertPathUtilities.processCRLF(crl,cert,defaultCRLSignCert,defaultCRLSignKey,paramsPKIX,certPathCerts); PublicKey key=RFC3280CertPathUtilities.processCRLG(crl,keys); X509CRL deltaCRL=null; if (paramsPKIX.isUseDeltasEnabled()) { Set deltaCRLs=CertPathValidatorUtilities.getDeltaCRLs(currentDate,paramsPKIX,crl); deltaCRL=RFC3280CertPathUtilities.processCRLH(deltaCRLs,key); } if (paramsPKIX.getValidityModel() != ExtendedPKIXParameters.CHAIN_VALIDITY_MODEL) { if (cert.getNotAfter().getTime() < crl.getThisUpdate().getTime()) { throw new AnnotatedException("No valid CRL for current time found."); } } RFC3280CertPathUtilities.processCRLB1(dp,cert,crl); RFC3280CertPathUtilities.processCRLB2(dp,cert,crl); RFC3280CertPathUtilities.processCRLC(deltaCRL,crl,paramsPKIX); RFC3280CertPathUtilities.processCRLI(validDate,deltaCRL,cert,certStatus,paramsPKIX); RFC3280CertPathUtilities.processCRLJ(validDate,crl,cert,certStatus); if (certStatus.getCertStatus() == CRLReason.removeFromCRL) { certStatus.setCertStatus(CertStatus.UNREVOKED); } reasonMask.addReasons(interimReasonsMask); Set criticalExtensions=crl.getCriticalExtensionOIDs(); if (criticalExtensions != null) { criticalExtensions=new HashSet(criticalExtensions); criticalExtensions.remove(X509Extensions.IssuingDistributionPoint.getId()); criticalExtensions.remove(X509Extensions.DeltaCRLIndicator.getId()); if (!criticalExtensions.isEmpty()) { throw new AnnotatedException("CRL contains unsupported critical extensions."); } } if (deltaCRL != null) { criticalExtensions=deltaCRL.getCriticalExtensionOIDs(); if (criticalExtensions != null) { criticalExtensions=new HashSet(criticalExtensions); criticalExtensions.remove(X509Extensions.IssuingDistributionPoint.getId()); criticalExtensions.remove(X509Extensions.DeltaCRLIndicator.getId()); if (!criticalExtensions.isEmpty()) { throw new AnnotatedException("Delta CRL contains unsupported critical extension."); } } } validCrlFound=true; } catch ( AnnotatedException e) { lastException=e; } } if (!validCrlFound) { throw lastException; } }
Checks a distribution point for revocation information for the certificate <code>cert</code>.
@Override public String remove(final Object key){ return null; }
Method remove()
@Override public boolean equals(Object obj){ if (obj == this) { return true; } if (!(obj instanceof KeyToGroupMap)) { return false; } KeyToGroupMap that=(KeyToGroupMap)obj; if (!ObjectUtilities.equal(this.defaultGroup,that.defaultGroup)) { return false; } if (!this.keyToGroupMap.equals(that.keyToGroupMap)) { return false; } return true; }
Tests the map for equality against an arbitrary object.
public static boolean isWildcardFileName(String name){ if (name.contains("*") || name.contains("?")) { final String unescaped; if (isWindows()) { unescaped=name.replace("%%","%_").replace("%*","%_").replace("%?","%_"); } else { unescaped=name.replace("\\\\","\\_").replace("\\*","\\_").replace("\\?","\\_"); } return unescaped.contains("*") || unescaped.contains("?"); } return false; }
Returns true if the given name or path contains unescaped wildcard characters. The characters "*" and "?" are considered wildcard chars if they are not escaped with a preceding backslash character \ (Unix and MAC) or % character (Windows).
public TeXParser(boolean isPartial,String parseString,TeXFormula formula,boolean firstpass){ this.formula=formula; this.isPartial=isPartial; if (parseString != null) { this.parseString=new StringBuffer(parseString); this.len=parseString.length(); this.pos=0; if (firstpass) { firstpass(); } } else { this.parseString=null; this.pos=0; this.len=0; } }
Create a new TeXParser with or without a first pass
private static void doSort(char[] a,int left,int right,char[] work,int workBase,int workLen){ if (right - left < QUICKSORT_THRESHOLD) { sort(a,left,right,true); return; } int[] run=new int[MAX_RUN_COUNT + 1]; int count=0; run[0]=left; for (int k=left; k < right; run[count]=k) { if (a[k] < a[k + 1]) { while (++k <= right && a[k - 1] <= a[k]) ; } else if (a[k] > a[k + 1]) { while (++k <= right && a[k - 1] >= a[k]) ; for (int lo=run[count] - 1, hi=k; ++lo < --hi; ) { char t=a[lo]; a[lo]=a[hi]; a[hi]=t; } } else { for (int m=MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) { if (--m == 0) { sort(a,left,right,true); return; } } } if (++count == MAX_RUN_COUNT) { sort(a,left,right,true); return; } } if (run[count] == right++) { run[++count]=right; } else if (count == 1) { return; } byte odd=0; for (int n=1; (n<<=1) < count; odd^=1) ; char[] b; int ao, bo; int blen=right - left; if (work == null || workLen < blen || workBase + blen > work.length) { work=new char[blen]; workBase=0; } if (odd == 0) { System.arraycopy(a,left,work,workBase,blen); b=a; bo=0; a=work; ao=workBase - left; } else { b=work; ao=0; bo=workBase - left; } for (int last; count > 1; count=last) { for (int k=(last=0) + 2; k <= count; k+=2) { int hi=run[k], mi=run[k - 1]; for (int i=run[k - 2], p=i, q=mi; i < hi; ++i) { if (q >= hi || p < mi && a[p + ao] <= a[q + ao]) { b[i + bo]=a[p++ + ao]; } else { b[i + bo]=a[q++ + ao]; } } run[++last]=hi; } if ((count & 1) != 0) { for (int i=right, lo=run[count - 1]; --i >= lo; b[i + bo]=a[i + ao]) ; run[++last]=right; } char[] t=a; a=b; b=t; int o=ao; ao=bo; bo=o; } }
Sorts the specified range of the array.
public void resumeWork(){ mExitTasksEarly=false; setPause(false); if (DEBUG) { CLog.d(LOG_TAG,"work_status: resumeWork %s",this); } }
Resume the work
protected void sequence_AnnotatedExportableElement_N4EnumDeclaration(ISerializationContext context,N4EnumDeclaration semanticObject){ genericSequencer.createSequence(context,semanticObject); }
Contexts: ExportableElement returns N4EnumDeclaration Constraint: ( ( annotationList=AnnotatedExportableElement_N4EnumDeclaration_1_3_0 declaredModifiers+=N4Modifier* name=BindingIdentifier literals+=N4EnumLiteral literals+=N4EnumLiteral ) | (declaredModifiers+=N4Modifier* name=BindingIdentifier? (literals+=N4EnumLiteral literals+=N4EnumLiteral*)?) )
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static <A>FutureWTSeq<A> of(final AnyMSeq<FutureW<A>> monads){ return new FutureWTSeq<>(monads); }
Construct an FutureWT from an AnyM that wraps a monad containing FutureWs
public static InputStream read(File f) throws IOException { InputStream is=new BufferedInputStream(new FileInputStream(f)); if (f.toString().endsWith(".bz2")) is=new BZip2CompressorInputStream(is); if (f.toString().endsWith(".gz")) is=new GZIPInputStream(is); return is; }
open text files for reading. If the files are compressed, choose the appropriate decompression method automatically
public static void writeXmlDocument(Node node,OutputStream os,String encoding,boolean omitXmlDeclaration,boolean indent,int indentAmount) throws TransformerException { Transformer transformer=createOutputTransformer(encoding,omitXmlDeclaration,indent,indentAmount); transformDomDocument(transformer,node,os); }
Serializes a DOM <code>Node</code> to an <code>OutputStream</code> using JAXP TrAX.
public static String unicodeEscape(String s){ if (allAscii(s)) { return s; } StringBuilder sb=new StringBuilder(s.length()); int len=s.length(); for (int i=0; i < len; ++i) { char ch=s.charAt(i); if (ch <= 127) { sb.append(ch); } else { sb.append("\\u"); String hexString=Integer.toHexString(ch); int numZerosToPad=4 - hexString.length(); for (int j=0; j < numZerosToPad; ++j) { sb.append('0'); } sb.append(hexString); } } return sb.toString(); }
Replaces each non-ascii character in s with its Unicode escape sequence \\uxxxx where xxxx is a hex number. Existing escape sequences won't be affected.
protected void processIdent(DetailAST aAST){ final int parentType=aAST.getParent().getType(); if (((parentType != TokenTypes.DOT) && (parentType != TokenTypes.METHOD_DEF)) || ((parentType == TokenTypes.DOT) && (aAST.getNextSibling() != null))) { referenced.add(aAST.getText()); } }
Collects references made by IDENT.
UnixDirectoryStream(UnixPath dir,long dp,DirectoryStream.Filter<? super Path> filter){ this.dir=dir; this.dp=dp; this.filter=filter; }
Initializes a new instance
@Listener @IsCancelled(Tristate.UNDEFINED) public void onPlayerJoin(ClientConnectionEvent.Login event){ if (!(Sponge.getServer().getOnlinePlayers().size() >= Sponge.getServer().getMaxPlayers())) { return; } if (event.getTargetUser().hasPermission(joinFullServer)) { if (cca.getNodeOrDefault().getReservedSlots() != -1 && Sponge.getServer().getOnlinePlayers().size() - Sponge.getServer().getMaxPlayers() >= cca.getNodeOrDefault().getReservedSlots()) { return; } event.setCancelled(false); } }
At the time the player joins if the server is full, check if they are permitted to join a full server.
public void testIdempotency() throws Exception { File lockFile=new File("testIdempotency.lock"); WriteLock wl=new WriteLock(lockFile); for (int i=0; i < 100; i++) { boolean locked=wl.acquire(); assertTrue("Acquire must succeed",locked); assertTrue("File must be locked",wl.isLocked()); } for (int i=0; i < 100; i++) { wl.release(); assertFalse("File must not be locked",wl.isLocked()); } }
Confirm that acquire and release operations are idempotent.
public SimpleDictionary(String... aWords){ words=new HashSet<String>(); for ( String word : aWords) { words.add(word.toLowerCase()); } }
Create a simple dictionary from a list of string. This can be used for testing
private static void usage(){ for ( String s : USAGE_MESSAGE) { System.out.println(s); } for ( String s : WELCOME_MESSAGE) { System.out.println(s); } }
Prints out the usage.
public void runTest() throws Throwable { Document doc; Element element; String nullNS=null; doc=(Document)load("staffNS",true); element=doc.createElementNS("http://www.w3.org/DOM/Test/L2","dom:elem"); { boolean success=false; try { element.setAttributeNS(nullNS,"dom:root","test"); } catch ( DOMException ex) { success=(ex.code == DOMException.NAMESPACE_ERR); } assertTrue("elementsetattributens05",success); } }
Runs the test case.
private void assignTasksToContainers(int[] taskCountPerContainer,List<String> taskNamesToAssign,List<TaskGroup> containers){ for ( TaskGroup taskGroup : containers) { for (int j=taskGroup.size(); j < taskCountPerContainer[taskGroup.getContainerId()]; j++) { String taskName=taskNamesToAssign.remove(0); taskGroup.addTaskName(taskName); log.info("Assigned task {} to container {}",taskName,taskGroup.getContainerId()); } } }
Assigns tasks from the specified list to containers that have fewer containers than indicated in taskCountPerContainer.
public Problem(String problem,String[] causes,Throwable error){ this.problem=problem; this.causes=causes; this.error=error; }
Construct ProblemAndCauses.
public static String convertToBitcoinURI(NetworkParameters params,String address,@Nullable Coin amount,@Nullable String label,@Nullable String message){ checkNotNull(params); checkNotNull(address); if (amount != null && amount.signum() < 0) { throw new IllegalArgumentException("Coin must be positive"); } StringBuilder builder=new StringBuilder(); String scheme=params.getUriScheme(); builder.append(scheme).append(":").append(address); boolean questionMarkHasBeenOutput=false; if (amount != null) { builder.append(QUESTION_MARK_SEPARATOR).append(FIELD_AMOUNT).append("="); builder.append(amount.toPlainString()); questionMarkHasBeenOutput=true; } if (label != null && !"".equals(label)) { if (questionMarkHasBeenOutput) { builder.append(AMPERSAND_SEPARATOR); } else { builder.append(QUESTION_MARK_SEPARATOR); questionMarkHasBeenOutput=true; } builder.append(FIELD_LABEL).append("=").append(encodeURLString(label)); } if (message != null && !"".equals(message)) { if (questionMarkHasBeenOutput) { builder.append(AMPERSAND_SEPARATOR); } else { builder.append(QUESTION_MARK_SEPARATOR); } builder.append(FIELD_MESSAGE).append("=").append(encodeURLString(message)); } return builder.toString(); }
Simple Bitcoin URI builder using known good fields.
private static OFActionSetNwSrc decode_set_src_ip(String actionToDecode,OFVersion version,Logger log){ Matcher n=Pattern.compile("(?:(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+))").matcher(actionToDecode); if (n.matches()) { IPv4Address ipaddr=IPv4Address.of(get_ip_addr(n,actionToDecode,log)); OFActionSetNwSrc.Builder ab=OFFactories.getFactory(version).actions().buildSetNwSrc(); ab.setNwAddr(ipaddr); log.debug("action {}",ab.build()); return ab.build(); } else { log.debug("Invalid action: '{}'",actionToDecode); return null; } }
Parse set_nw_src actions. The key and delimiter for the action should be omitted, and only the data should be presented to this decoder. TODO should consider using IPv4AddressWithMask's built-in parser....
public TimingLogger(String tag,String label){ reset(tag,label); }
Create and initialize a TimingLogger object that will log using the specific tag. If the Log.isLoggable is not enabled to at least the Log.VERBOSE level for that tag at creation time then the addSplit and dumpToLog call will do nothing.
public boolean visitFunction(ExpressionOwner owner,Function func){ if ((func instanceof FuncCurrent) || (func instanceof FuncExtFunction)) m_isAbs=false; return true; }
Visit a function.
public SeekableByteChannel open(GcsPath path) throws IOException { return new GoogleCloudStorageReadChannel(storageClient,path.getBucket(),path.getObject(),errorExtractor,new ClientRequestHelper<StorageObject>()); }
Opens an object in GCS. <p>Returns a SeekableByteChannel that provides access to data in the bucket.
protected void calculatePartialsPartialsPruning(double[] partials1,double[] matrices1,double[] partials2,double[] matrices2,double[] partials3,int[] matrixMap){ throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); }
Calculates partial likelihoods at a node when both children have partials.
@Override public String initialize(){ m_Current=0; for ( File dataset : m_Datasets) { if (!dataset.exists()) return "Dataset does not exist: " + dataset; if (dataset.isDirectory()) return "Dataset points to a directory: " + dataset; } return null; }
Initializes the provider to start providing datasets from scratch.
public FacesException(String message){ super(message); }
<p>Construct a new exception with the specified detail message and no root cause.</p>
public static String convertResourcePathToClassName(String resourcePath){ Assert.notNull(resourcePath,"Resource path must not be null"); return resourcePath.replace('/','.'); }
Convert a "/"-based resource path to a "."-based fully qualified class name.
private void gen_poly(){ int i, j; gg[0]=2; gg[1]=1; for (i=2; i <= NN - KK; i++) { gg[i]=1; for (j=i - 1; j > 0; j--) { if (gg[j] != 0) { gg[j]=gg[j - 1] ^ alpha_to[(index_of[gg[j]] + i) % NN]; } else { gg[j]=gg[j - 1]; } } gg[0]=alpha_to[(index_of[gg[0]] + i) % NN]; } for (i=0; i <= NN - KK; i++) { gg[i]=index_of[gg[i]]; } }
Generates the polynomial for a TT-error correction code. Length NN = ( 2 ** MM -1 ) Reed Solomon code from the product of (X+alpha**i), i=1..2*tt
@DSSafe(DSCat.IPC_CALLBACK) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:59:17.497 -0500",hash_original_method="4ADFD820FBAEE3B9207F7288ABB2B3FA",hash_generated_method="DBD9934380248D13C69A49A59A76507F") @Override public void handleMessage(Message msg){ AsyncResult ar; switch (msg.what) { case EVENT_ICC_FULL: handleIccFull(); break; case EVENT_REPORT_MEMORY_STATUS_DONE: ar=(AsyncResult)msg.obj; if (ar.exception != null) { mReportMemoryStatusPending=true; Log.v(TAG,"Memory status report to modem pending : mStorageAvailable = " + mStorageAvailable); } else { mReportMemoryStatusPending=false; } break; case EVENT_RADIO_ON: if (mReportMemoryStatusPending) { Log.v(TAG,"Sending pending memory status report : mStorageAvailable = " + mStorageAvailable); mCm.reportSmsMemoryStatus(mStorageAvailable,obtainMessage(EVENT_REPORT_MEMORY_STATUS_DONE)); } break; } }
Handles events coming from the phone stack. Overridden from handler.
public static QueryTask.QuerySpecification buildChildServiceTaskStatusQuerySpec(final String selfLink,final Class childClass,final TaskState.TaskStage... stages){ checkArgument(stages != null && stages.length >= 1,"stages.length must be >= 1"); QueryTask.Query parentLinkClause=new QueryTask.Query().setTermPropertyName(PARENT_LINK_FIELD_NAME).setTermMatchValue(selfLink); QueryTask.QuerySpecification spec=buildTaskStatusQuerySpec(childClass,stages); spec.query.addBooleanClause(parentLinkClause); return spec; }
Builds a query specification which will query for service instances of type childClass which have the parentLink field set to the param value and the stage execution field one of the values passed using stages param.
public IgfsLocalMetrics metrics(){ return metrics; }
Get local metrics.
Shape adjustPaintRegion(Shape a){ return adjustAllocation(a); }
Adjusts <code>a</code> based on the visible region and returns it.
public boolean isRemoved(){ return this.removed; }
Always checked when the monitor is held on this object
public void run(){ while (true) { try { handleIncomingData(); } catch ( java.io.IOException e) { log.warn("run: Exception: " + e.toString()); } } }
Handle incoming characters. This is a permanent loop, looking for input messages in character form on the stream connected to the PortController via <code>connectPort</code>. Terminates with the input stream breaking out of the try block.
private Object toDate(final Class type,final long value){ if (type.equals(Date.class)) { return new Date(value); } if (type.equals(java.sql.Date.class)) { return new java.sql.Date(value); } if (type.equals(java.sql.Time.class)) { return new java.sql.Time(value); } if (type.equals(java.sql.Timestamp.class)) { return new java.sql.Timestamp(value); } if (type.equals(Calendar.class)) { Calendar calendar=null; if (this.locale == null && this.timeZone == null) { calendar=Calendar.getInstance(); } else if (this.locale == null) { calendar=Calendar.getInstance(this.timeZone); } else if (this.timeZone == null) { calendar=Calendar.getInstance(this.locale); } else { calendar=Calendar.getInstance(this.timeZone,this.locale); } calendar.setTime(new Date(value)); calendar.setLenient(false); return calendar; } String msg=this.toString(this.getClass()) + " cannot handle conversion to '" + this.toString(type)+ "'"; throw new ConversionException(msg); }
Convert a long value to the specified Date type for this <i>Converter</i>. <p> This method handles conversion to the following types: <ul> <li><code>java.util.Date</code></li> <li><code>java.util.Calendar</code></li> <li><code>java.sql.Date</code></li> <li><code>java.sql.Time</code></li> <li><code>java.sql.Timestamp</code></li> </ul>
@Override public void displayCursor(Cursor cursor){ mAdapter.changeCursor(cursor); }
Display the contents of the cursor as a ListView.
public boolean isSet(_Fields field){ if (field == null) { throw new IllegalArgumentException(); } switch (field) { case BONK: return isSetBonk(); } throw new IllegalStateException(); }
Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise
public static String[] detectCleanMovienameAndYear(String filename){ String[] ret={"",""}; LOGGER.trace("Parse filename for movie title: \"" + filename + "\""); if (filename == null || filename.isEmpty()) { LOGGER.warn("Filename empty?!"); return ret; } String fname=filename.replaceFirst("\\.\\w{2,4}$",""); fname=fname.replaceFirst("(?i)\\W\\d{3,4}x\\d{3,4}"," "); for ( String cw : cleanwords) { fname=fname.replaceFirst("(?i)\\W" + cw," "); } LOGGER.trace("--------------------"); LOGGER.trace("IN: " + fname); List<String> opt=new ArrayList<String>(); Pattern p=Pattern.compile("\\[(.*?)\\]"); Matcher m=p.matcher(fname); while (m.find()) { LOGGER.trace("OPT: " + m.group(1)); String[] o=StringUtils.split(m.group(1),DELIMITER); opt.addAll(Arrays.asList(o)); fname=fname.replace(m.group(),""); } LOGGER.trace("ARR: " + opt); String[] s=StringUtils.split(fname,DELIMITER); if (s.length == 0) { s=opt.toArray(new String[opt.size()]); } int firstFoundStopwordPosition=s.length; for (int i=0; i < s.length; i++) { for ( String stop : stopwords) { if (s[i].equalsIgnoreCase(stop)) { s[i]=""; if (i < firstFoundStopwordPosition && i >= 2) { firstFoundStopwordPosition=i; } } } if (Utils.isValidImdbId(s[i])) { s[i]=""; } } int currentYear=Calendar.getInstance().get(Calendar.YEAR); String year=""; for (int i=s.length - 1; i > 0; i--) { if (s[i].matches("\\d{4}")) { int parsedYear=Integer.parseInt(s[i]); if (parsedYear > 1800 && parsedYear < currentYear + 5) { LOGGER.trace("removed token '" + s[i] + "'- seems to be year"); year=s[i]; s[i]=""; break; } } } if (year.isEmpty()) { for ( String o : opt) { if (o.matches("\\d{4}")) { int parsedYear=Integer.parseInt(o); if (parsedYear > 1800 && parsedYear < currentYear + 5) { year=String.valueOf(parsedYear); LOGGER.trace("found possible year " + o); } } } } String name=""; for (int i=0; i < firstFoundStopwordPosition; i++) { if (!s[i].isEmpty()) { if (!MovieModuleManager.MOVIE_SETTINGS.getBadWords().contains(s[i].toLowerCase())) { String word=s[i]; switch (word.toUpperCase()) { case "I": case "II": case "III": case "IV": case "V": case "VI": case "VII": case "VIII": case "IX": case "X": name=name + word.toUpperCase() + " "; break; default : name=name + WordUtils.capitalizeFully(word) + " "; break; } } } } if (name.isEmpty()) { ret[0]=fname; } else { ret[0]=name.trim(); } ret[1]=year.trim(); LOGGER.trace("Movie title should be: \"" + ret[0] + "\", from "+ ret[1]); return ret; }
Tries to get movie name and year from filename<br> 1. splits string using common delimiters ".- ()"<br> 2. searches for first occurrence of common stopwords<br> 3. if last token is 4 digits, assume year and set [1]<br> 4. everything before the first stopword must be the movie name :p
public static boolean isWildcard(String format){ String routerUrl=cleanUrl(format); String[] routerParts=routerUrl.split("/"); for ( String routerPart : routerParts) { if (routerPart.length() > 2 && routerPart.charAt(0) == ':' && routerPart.charAt(routerPart.length() - 1) == ':') { return true; } } return false; }
Check if given router url format is a :wildcard: format
public String transformFieldDescriptor(String owner,String name,String desc){ return DescriptorMapping.getInstance().getFieldDesc(owner,name,desc); }
Determine if the signature of the given field needs to be transformed, and transform if necessary
@Transient public boolean isDirty(){ for ( IndicatorSeries item : this.getIndicatorSeries()) { if (item.isDirty()) return true; } return super.isDirty(); }
Method isDirty.
public AWTTerminalFrame(String title,TerminalSize terminalSize,TerminalEmulatorDeviceConfiguration deviceConfiguration,AWTTerminalFontConfiguration fontConfiguration,TerminalEmulatorColorConfiguration colorConfiguration,TerminalEmulatorAutoCloseTrigger... autoCloseTriggers){ this(title,new AWTTerminal(terminalSize,deviceConfiguration,fontConfiguration,colorConfiguration),autoCloseTriggers); }
Creates a new AWTTerminalFrame using a specified title and a series of AWT terminal configuration objects
@Override public void onUpgrade(SQLiteDatabase db,ConnectionSource connectionSource,int oldVersion,int newVersion){ try { Log.i(DatabaseHelper.class.getName(),"onUpgrade"); TableUtils.dropTable(connectionSource,AddressBook.class,true); TableUtils.dropTable(connectionSource,AddressItem.class,true); TableUtils.dropTable(connectionSource,Contact.class,true); TableUtils.dropTable(connectionSource,SimpleAddressItem.class,true); onCreate(db,connectionSource); } catch ( SQLException e) { Log.e(DatabaseHelper.class.getName(),"Can't drop databases",e); throw new RuntimeException(e); } }
This is called when your application is upgraded and it has a higher version number. This allows you to adjust the various data to match the new version number.
public CorrelationMatrix(ICovarianceMatrix matrix){ this(matrix.getVariables(),matrix.getMatrix().copy(),matrix.getSampleSize()); }
Constructs a new correlation matrix using the covariances in the given covariance matrix.
private static boolean isNodeAfterSibling(Node parent,Node child1,Node child2){ boolean isNodeAfterSibling=false; short child1type=child1.getNodeType(); short child2type=child2.getNodeType(); if ((Node.ATTRIBUTE_NODE != child1type) && (Node.ATTRIBUTE_NODE == child2type)) { isNodeAfterSibling=false; } else if ((Node.ATTRIBUTE_NODE == child1type) && (Node.ATTRIBUTE_NODE != child2type)) { isNodeAfterSibling=true; } else if (Node.ATTRIBUTE_NODE == child1type) { NamedNodeMap children=parent.getAttributes(); int nNodes=children.getLength(); boolean found1=false, found2=false; for (int i=0; i < nNodes; i++) { Node child=children.item(i); if (child1 == child || isNodeTheSame(child1,child)) { if (found2) { isNodeAfterSibling=false; break; } found1=true; } else if (child2 == child || isNodeTheSame(child2,child)) { if (found1) { isNodeAfterSibling=true; break; } found2=true; } } } else { Node child=parent.getFirstChild(); boolean found1=false, found2=false; while (null != child) { if (child1 == child || isNodeTheSame(child1,child)) { if (found2) { isNodeAfterSibling=false; break; } found1=true; } else if (child2 == child || isNodeTheSame(child2,child)) { if (found1) { isNodeAfterSibling=true; break; } found2=true; } child=child.getNextSibling(); } } return isNodeAfterSibling; }
Figure out if child2 is after child1 in document order. <p> Warning: Some aspects of "document order" are not well defined. For example, the order of attributes is considered meaningless in XML, and the order reported by our model will be consistant for a given invocation but may not match that of either the source file or the serialized output.
public RegistryKey fetchSystemRegistry() throws WineException { return parseRegistryFile(SYSTEM_REGISTRY_FILENAME,SYSTEM_REGISTRY_NODENAME); }
Return the system registry
@Override public void onPause(){ if (Camera != null) Camera.shutdown(); Camera=null; if (SnapHandler != null) SnapHandler.shutdown(); SnapHandler=null; super.onPause(); }
Callback handler when fragment has been removed from view.
private static void shiftLocalSlots(InsnList instructions,int offset){ for ( AbstractInsnNode insn : selectAll(instructions)) { if (insn instanceof VarInsnNode) { VarInsnNode varInsn=(VarInsnNode)insn; varInsn.var+=offset; } else if (insn instanceof IincInsnNode) { IincInsnNode iincInsn=(IincInsnNode)insn; iincInsn.var+=offset; } } }
Shifts all local variable slot references by a specified amount.
public String toString(){ StringBuffer sb=new StringBuffer("MLandedCost["); sb.append(get_ID()).append(",CostDistribution=").append(getLandedCostDistribution()).append(",M_CostElement_ID=").append(getM_CostElement_ID()); if (getM_InOut_ID() != 0) sb.append(",M_InOut_ID=").append(getM_InOut_ID()); if (getM_InOutLine_ID() != 0) sb.append(",M_InOutLine_ID=").append(getM_InOutLine_ID()); if (getM_Product_ID() != 0) sb.append(",M_Product_ID=").append(getM_Product_ID()); sb.append("]"); return sb.toString(); }
String Representation
public boolean isPreDestroyCalled(){ return this.preDestroyCalled; }
Getter for property preDestroyCalled.
public Map<String,Object> addToCart(String catalogId,String shoppingListId,String shoppingListItemSeqId,String productId,String productCategoryId,String itemType,String itemDescription,BigDecimal price,BigDecimal amount,BigDecimal quantity,java.sql.Timestamp reservStart,BigDecimal reservLength,BigDecimal reservPersons,java.sql.Timestamp shipBeforeDate,java.sql.Timestamp shipAfterDate,ProductConfigWrapper configWrapper,String itemGroupNumber,Map<String,? extends Object> context,String parentProductId){ return addToCart(catalogId,shoppingListId,shoppingListItemSeqId,productId,productCategoryId,itemType,itemDescription,price,amount,quantity,reservStart,reservLength,reservPersons,null,null,shipBeforeDate,shipAfterDate,configWrapper,itemGroupNumber,context,parentProductId); }
Event to add an item to the shopping cart.
private void hideFootView(){ if (loadmoreView != null) { loadmoreView.setVisibility(View.GONE); } }
hide footView
public Variable decode(Variable variable,String string){ if (variable instanceof RealVariable) { RealVariable rv=(RealVariable)variable; rv.setValue(Double.parseDouble(string)); return rv; } else if (variable instanceof BinaryVariable) { BinaryVariable bv=(BinaryVariable)variable; if (bv.getNumberOfBits() != string.length()) { throw new FrameworkException("invalid bit string"); } for (int i=0; i < bv.getNumberOfBits(); i++) { char c=string.charAt(i); if (c == '0') { bv.set(i,false); } else if (c == '1') { bv.set(i,true); } else { throw new FrameworkException("invalid bit string"); } } return bv; } else if (variable instanceof Permutation) { Permutation p=(Permutation)variable; String[] tokens=string.split(","); int[] array=new int[tokens.length]; for (int i=0; i < tokens.length; i++) { array[i]=Integer.parseInt(tokens[i]); } try { p.fromArray(array); } catch ( IllegalArgumentException e) { throw new FrameworkException("invalid permutation",e); } return p; } else { if (string.equals("-")) { if (!printedWarning) { System.err.println(ENCODING_WARNING); printedWarning=true; } return variable; } else { try { return deserialize(string); } catch ( Exception e) { throw new FrameworkException("deserialization failed",e); } } } }
Decodes string representations of decision variables, returning the variable with the decoded value. Depending on the implementation and variable type, the same variable as provided in the arguments or a new variable will be returned.
public boolean checkDuration(@Nonnull final Notification notification){ if (!rule.getMaxDuration().isPresent()) { return true; } if (maxDuration > 0 && firstMillis > 0) { final long delta=firstMillis - notification.getCreatedAt().getMillis(); if (delta >= 0 && delta <= maxDuration) { return true; } } return false; }
Check whether the given notification is within the "max-duration" for this matcher or not.
private int indexOfNextDelimiter(int start){ char c; int next; for (next=start; (c=text.charAt(next)) > maxDelimChar || ((nontokenDelims == null || nontokenDelims.indexOf(c) == -1) && (tokenDelims == null || tokenDelims.indexOf(c) == -1)); next++) { if (next == strLength - 1) { return (-1); } } return next; }
Similar to String.indexOf(int, String) but will look for any character from string rather than the entire string.
@Override protected void removeAt(int index){ _values[index]=0; super.removeAt(index); }
removes the mapping at <tt>index</tt> from the map.
private void saveTableVersion(int t_version){ Context ctx=mDb.getContext(); SharedPreferences tableVersions=ctx.getSharedPreferences(PREFS_TABLE_VERSION,Context.MODE_PRIVATE); SharedPreferences.Editor editor=tableVersions.edit(); editor.putInt(mTableName,t_version); editor.commit(); }
save table version
private String processIntegerToken(String token){ String result=token.replaceAll("" + groupSeparator,""); boolean isNegative=false; int preLen=negativePrefix.length(); if ((preLen > 0) && result.startsWith(negativePrefix)) { isNegative=true; result=result.substring(preLen); } int sufLen=negativeSuffix.length(); if ((sufLen > 0) && result.endsWith(negativeSuffix)) { isNegative=true; result=result.substring(result.length() - sufLen,result.length()); } if (isNegative) result="-" + result; return result; }
The integer token must be stripped of prefixes, group separators, and suffixes, non ascii digits must be converted into ascii digits before parse will accept it.
@Override public void init(){ if (!_initialized) { if (!jmri.util.ThreadingUtil.isGUIThread()) log.error("Not on GUI thread",new Exception("traceback")); Thread.yield(); _update=false; _supressDragging=false; makeBottomPanel(null); super.init(); } }
Init for creation
public boolean isPolarized(){ return polarity != null && polarity != Polarity.BOTH; }
If the neuron is polarized, it will be excitatory or inhibitory.
public double eval(double params[]){ return (Math.min(Math.min(params[0],params[1]),Math.min(params[2],params[3]))); }
Evaluate the minimum of 4 parameters.
public String toString(){ StringBuffer buffer=new StringBuffer(); buffer.append("UasDaoUserRecUa["); buffer.append("m_stat = ").append(m_stat); buffer.append(", m_numBadCnts = ").append(m_numBadCnts); buffer.append("]"); return buffer.toString(); }
toString methode: creates a String representation of the object
public String encode(String value){ return doubleMetaphone(value); }
Encode the value using DoubleMetaphone.
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields=s.readFields(); object=fields.get("object",null); baseTypeName=(String)fields.get("baseTypeName",null); reference=(Ref)fields.get("reference",null); }
readObject is called to restore the state of the SerialRef from a stream.
public boolean isUsePercentValuesEnabled(){ return mUsePercentValues; }
Returns true if using percentage values is enabled for the chart.
private final boolean handleBlockedWrite(ByteBuffer buffer,DistributionMessage msg) throws ConnectionException { if (!addToQueue(buffer,msg,true)) { return false; } else { startNioPusher(); return true; } }
Return true if it was able to handle a block write of the given buffer. Return false if it is still the caller is still responsible for writing it.
public static Test suite(){ return new TestSuite(InterquartileRangeTest.class); }
Returns a test suite.
public static Map<String,String> convertListToMap(List<LabelValue> list){ Map<String,String> map=new LinkedHashMap<String,String>(); for ( LabelValue option : list) { map.put(option.getLabel(),option.getValue()); } return map; }
Convert a java.util.List of LabelValue objects to a LinkedHashMap.
@Override public ManagedConnection createManagedConnection(final Subject subject,final ConnectionRequestInfo cxRequestInfo) throws ResourceException { if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("createManagedConnection(" + subject + ", "+ cxRequestInfo+ ")"); } ActiveMQRAConnectionRequestInfo cri=getCRI((ActiveMQRAConnectionRequestInfo)cxRequestInfo); ActiveMQRACredential credential=ActiveMQRACredential.getCredential(this,subject,cri); if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("jms credential: " + credential); } ActiveMQRAManagedConnection mc=new ActiveMQRAManagedConnection(this,cri,ra,credential.getUserName(),credential.getPassword()); if (ActiveMQRAManagedConnectionFactory.trace) { ActiveMQRALogger.LOGGER.trace("created new managed connection: " + mc); } registerRecovery(); return mc; }
Creates a new physical connection to the underlying EIS resource manager.
RandomAccessFile openInputFile(String fileName) throws IOException { RandomAccessFile raf; raf=openInputFileAsZip(fileName); if (raf == null) { File inputFile=new File(fileName); raf=new RandomAccessFile(inputFile,"r"); } return raf; }
Opens an input file, which could be a .dex or a .jar/.apk with a classes.dex inside. If the latter, we extract the contents to a temporary file.
public VmPipeAddress(int port){ this.port=port; }
Creates a new instance with the specifid port number.
public void addFilter(PacketFilter filter){ if (filter == null) { throw new IllegalArgumentException("Parameter cannot be null."); } filters.add(filter); }
Adds a filter to the filter list for the AND operation. A packet will pass the filter if all of the filters in the list accept it.
public ByteQueue(int chunkSize){ this.chunkSize=chunkSize; }
Construct new byte queue.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:24.402 -0500",hash_original_method="CD47D8147DAAE254C6F8BD59780442CD",hash_generated_method="94EC0761D9B928E7003FF2BDA1042097") @Override protected void onCleanUpAllConnections(String cause){ cleanUpAllConnections(true,cause); }
Cleanup all connections. TODO: Cleanup only a specified connection passed as a parameter. Also, make sure when you clean up a conn, if it is last apply logic as though it is cleanupAllConnections
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:50.858 -0500",hash_original_method="FF10597CCF521EBE62B89D95947AA842",hash_generated_method="C08A570AB37737F096BEEA638CE020CD") public void readOctetString() throws IOException { if (tag == ASN1Constants.TAG_OCTETSTRING) { readContent(); } else if (tag == ASN1Constants.TAG_C_OCTETSTRING) { throw new ASN1Exception("Decoding constructed ASN.1 octet string type is not supported"); } else { throw expected("octetstring"); } }
Decodes ASN.1 Octetstring type
public Vector4i div(Vector4i v,Vector4i dest){ dest.x=x / v.x; dest.y=y / v.y; dest.z=z / v.z; dest.w=w / v.w; return dest; }
Divide this Vector4i component-wise by another Vector4i and store the result in <code>dest</code>.
public void testExportDelete() throws Exception { String parentDirectory="/ifs/"; int dirCount=_client.listDir(parentDirectory,null).size(); System.out.println("Directories count in " + parentDirectory + " is: "+ dirCount); }
Small function to clean exports form cluster. Do not run as a test.
private void put112(final int b1,final int b2,final int s){ pool.put11(b1,b2).putShort(s); }
Puts two bytes and one short into the constant pool.
@GET @Path("/postConversation") @Produces(MediaType.APPLICATION_JSON) public Response postConversation(@QueryParam("conversationId") String conversationId,@QueryParam("clientId") String clientId,@QueryParam("input") String input){ long lStartTime=System.nanoTime(); long lEndTime, difference; String errorMessage=null, issue=null; String wdsMessage=null; JsonObject processedText=null; if (input == null || input.trim().isEmpty()) { errorMessage=Messages.getString("WDSBlueMixProxyResource.SPECIFY_INPUT"); issue=Messages.getString("WDSBlueMixProxyResource.EMPTY_QUESTION"); UtilityFunctions.logger.error(issue); return Response.serverError().entity(new ServerErrorPayload(errorMessage,issue)).build(); } try { List<ClassifiedClass> classInfo=null; if (nlcService != null) { if (UtilityFunctions.logger.isTraceEnabled()) { UtilityFunctions.logger.trace(Messages.getString("WDSBlueMixProxyResource.NLC_SERVICE")); } Classification classification=nlcService.classify(classifier_id,input); classInfo=classification.getClasses(); Map<String,String> profile=new HashMap<>(); profile.put("Class1",classInfo.get(0).getName()); profile.put("Class1_Confidence",Double.toString(classInfo.get(0).getConfidence())); profile.put("Class2",classInfo.get(1).getName()); profile.put("Class2_Confidence",Double.toString(classInfo.get(1).getConfidence())); dialogService.updateProfile(dialog_id,new Integer(clientId),profile); } Map<String,Object> converseParams=new HashMap<String,Object>(); converseParams.put("dialog_id",dialog_id); converseParams.put("client_id",Integer.parseInt(clientId)); converseParams.put("conversation_id",Integer.parseInt(conversationId)); converseParams.put("input",input); Conversation conversation=dialogService.converse(converseParams); wdsMessage=StringUtils.join(conversation.getResponse()," "); processedText=matchSearchNowPattern(wdsMessage); WDSConversationPayload conversationPayload=new WDSConversationPayload(); if (!processedText.has("Params")) { conversationPayload.setClientId(clientId); conversationPayload.setConversationId(clientId); conversationPayload.setInput(input); conversationPayload.setWdsResponse(processedText.get("WDSMessage").getAsString()); if (UtilityFunctions.logger.isTraceEnabled()) { lEndTime=System.nanoTime(); difference=lEndTime - lStartTime; UtilityFunctions.logger.trace("Throughput: " + difference / 1000000 + "ms."); } return Response.ok(conversationPayload,MediaType.APPLICATION_JSON_TYPE).build(); } else { JsonObject paramsObj=processedText.getAsJsonObject("Params"); boolean newSearch=false, prevSearch=false, nextSearch=false, repeatSearch=false; String page=paramsObj.get("Page").getAsString(); switch (page) { case "new": newSearch=true; break; case "next": nextSearch=true; break; case "previous": prevSearch=true; break; case "repeat": repeatSearch=true; break; default : errorMessage=Messages.getString("WDSBlueMixProxyResource.DIALOG_UNDERSTAND_FAIL"); issue=Messages.getString("WDSBlueMixProxyResource.PAGE_TYPE_NOT_UNDERSTOOD"); UtilityFunctions.logger.error(issue); } if (UtilityFunctions.logger.isTraceEnabled()) { UtilityFunctions.logger.trace(Messages.getString("WDSBlueMixProxyResource.WDS_RESPONSE") + paramsObj); } String prompt; Integer currentIndex=Integer.parseInt(paramsObj.get("Index").getAsString()); Integer numMovies=0; Integer totalPages=0; boolean tmdbCallNeeded=true; Map<String,String> profile; if (paramsObj.has("Total_Movies")) { numMovies=Integer.parseInt(paramsObj.get("Total_Movies").getAsString()); totalPages=Integer.parseInt(paramsObj.get("Total_Pages").getAsString()); tmdbCallNeeded=!((currentIndex <= 10 && prevSearch) || (currentIndex == numMovies && nextSearch)); } if (tmdbCallNeeded) { int pageNum=(int)Math.ceil((float)currentIndex / 20); if ((nextSearch || newSearch) && (currentIndex % 20) == 0) { pageNum++; } if (prevSearch && (currentIndex % 20 <= 10 && (currentIndex % 20 != 0))) { pageNum--; } int currentDisplayCount=(currentIndex % 10 == 0) ? 10 : currentIndex % 10; SearchTheMovieDbProxyResource tmdb=new SearchTheMovieDbProxyResource(); conversationPayload=tmdb.discoverMovies(UtilityFunctions.getPropValue(paramsObj,"Genre"),UtilityFunctions.getPropValue(paramsObj,"Rating"),UtilityFunctions.getPropValue(paramsObj,"Recency"),currentIndex,pageNum,nextSearch || newSearch); int size=conversationPayload.getMovies().size(); if (prevSearch) { currentIndex-=currentDisplayCount; } else if (nextSearch || newSearch) { currentIndex+=size; } profile=new HashMap<>(); profile.put("Current_Index",currentIndex.toString()); profile.put("Total_Pages",conversationPayload.getTotalPages().toString()); profile.put("Num_Movies",conversationPayload.getNumMovies().toString()); dialogService.updateProfile(dialog_id,new Integer(clientId),profile); } if (!tmdbCallNeeded) { profile=new HashMap<>(); profile.put("Index_Updated","No"); dialogService.updateProfile(dialog_id,new Integer(clientId),profile); List<MoviePayload> movies=new ArrayList<MoviePayload>(); conversationPayload.setMovies(movies); conversationPayload.setNumMovies(numMovies); conversationPayload.setTotalPages(totalPages); } prompt=personalized_prompt_current_index; if (newSearch || repeatSearch) { prompt=personalized_prompt_movies_returned; } converseParams=new HashMap<String,Object>(); converseParams.put("dialog_id",dialog_id); converseParams.put("client_id",Integer.parseInt(clientId)); converseParams.put("conversation_id",Integer.parseInt(conversationId)); converseParams.put("input",prompt); conversation=dialogService.converse(converseParams); wdsMessage=StringUtils.join(conversation.getResponse()," "); conversationPayload.setWdsResponse(wdsMessage); conversationPayload.setClientId(clientId); conversationPayload.setConversationId(clientId); conversationPayload.setInput(input); if (UtilityFunctions.logger.isTraceEnabled()) { lEndTime=System.nanoTime(); difference=lEndTime - lStartTime; UtilityFunctions.logger.trace("Throughput: " + difference / 1000000 + "ms."); } return Response.ok(conversationPayload,MediaType.APPLICATION_JSON_TYPE).build(); } } catch (ClientProtocolException e) { errorMessage=Messages.getString("WDSBlueMixProxyResource.API_CALL_NOT_EXECUTED"); issue=Messages.getString("WDSBlueMixProxyResource.CLIENT_EXCEPTION_IN_GET_RESPONSE"); UtilityFunctions.logger.error(issue,e); } catch (IllegalStateException e) { errorMessage=Messages.getString("WDSBlueMixProxyResource.API_CALL_NOT_EXECUTED"); issue=Messages.getString("WDSBlueMixProxyResource.ILLEGAL_STATE_GET_RESPONSE"); UtilityFunctions.logger.error(issue,e); } catch (IOException e) { errorMessage=Messages.getString("WDSBlueMixProxyResource.API_CALL_NOT_EXECUTED"); issue=Messages.getString("WDSBlueMixProxyResource.IO_EXCEPTION_GET_RESPONSE"); UtilityFunctions.logger.error(issue,e); } catch (HttpException e) { errorMessage=Messages.getString("WDSBlueMixProxyResource.TMDB_API_CALL_NOT_EXECUTED"); issue=Messages.getString("WDSBlueMixProxyResource.HTTP_EXCEPTION_GET_RESPONSE"); UtilityFunctions.logger.error(issue,e); } catch (WatsonTheatersException e) { errorMessage=e.getErrorMessage(); issue=e.getIssue(); UtilityFunctions.logger.error(issue,e); } catch (URISyntaxException e) { errorMessage=Messages.getString("WDSBlueMixProxyResource.TMDB_URL_INCORRECT"); issue=Messages.getString("WDSBlueMixProxyResource.URI_EXCEPTION_IN_DISOVERMOVIE"); UtilityFunctions.logger.error(issue,e); } catch (ParseException e) { errorMessage=Messages.getString("WDSBlueMixProxyResource.TMDB_RESPONSE_PARSE_FAIL"); issue=Messages.getString("WDSBlueMixProxyResource.PARSE_EXCEPTION_TMDB_GET"); UtilityFunctions.logger.error(issue,e); } return Response.serverError().entity(new ServerErrorPayload(errorMessage,issue)).build(); }
Makes chat conversation with WDS <p> This makes chat conversation with WDS for the provided client id and conversation id, against the user input provided. </p> <p> When WDS has collected all the required movie preferences, it sends a bunch of movie parameters embedded in the text response and signals to discover movies from themoviedb.org. There may be the following kinds of discover movie calls: <ul> <li>New search: First time searching for the given set of parameters <li>Repeat search: Repeat the search with the same parameters (just re-display the results) <li>Previous search: Display the results on the previous page <li>Next search: Display the results on the next page </ul> Depending on the kind of call, profile variables are set in WDS and personalized prompts are retrieved to be sent back to the UI in the payload. </p>
public void addSource(Fact predecessor){ sources.add(predecessor); if (predecessor.isInference()) { sourceNodes.addAll(predecessor.getDerivation().sourceNodes); } }
Record that a particular fact was used to derive this.
private void handleIncrementalEvent(){ if (m_executorPool != null && (m_executorPool.getQueue().size() > 0 || m_executorPool.getActiveCount() > 0)) { String messg="[Classifier] " + statusMessagePrefix() + " is currently batch training!"; if (m_log != null) { m_log.logMessage(messg); m_log.statusMessage(statusMessagePrefix() + "WARNING: " + "Can't accept instance - batch training in progress."); } else { System.err.println(messg); } return; } if (m_incrementalEvent.getStatus() == InstanceEvent.FORMAT_AVAILABLE) { m_throughput=new StreamThroughput(statusMessagePrefix()); if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "remove"); } Instances dataset=m_incrementalEvent.getStructure(); if (dataset.classIndex() < 0) { stop(); String errorMessage=statusMessagePrefix() + "ERROR: no class attribute set in incoming stream!"; if (m_log != null) { m_log.statusMessage(errorMessage); m_log.logMessage("[" + getCustomName() + "] "+ errorMessage); } else { System.err.println("[" + getCustomName() + "] "+ errorMessage); } return; } if (m_loadModelFileName != null && m_loadModelFileName.length() > 0 && m_state == IDLE && !m_listenees.containsKey("trainingSet")) { String resolvedFileName=m_loadModelFileName; if (m_env != null) { try { resolvedFileName=m_env.substitute(resolvedFileName); } catch ( Exception ex) { } } File loadFrom=new File(resolvedFileName); try { loadFromFile(loadFrom); } catch ( Exception ex) { m_log.statusMessage(statusMessagePrefix() + "WARNING: unable to load " + "model (see log)."); m_log.logMessage("[Classifier] " + statusMessagePrefix() + "Problem loading classifier - training from scratch... "+ ex.getMessage()); } } try { if (m_trainingSet == null || !m_trainingSet.equalHeaders(dataset) || m_resetIncrementalClassifier) { if (!(m_ClassifierTemplate instanceof weka.classifiers.UpdateableClassifier) && !(m_ClassifierTemplate instanceof weka.classifiers.misc.InputMappedClassifier)) { stop(); if (m_log != null) { String msg=(m_trainingSet == null) ? statusMessagePrefix() + "ERROR: classifier has not been batch " + "trained; can't process instance events." : statusMessagePrefix() + "ERROR: instance event's structure is different from " + "the data that "+ "was used to batch train this classifier; can't continue."; m_log.logMessage("[Classifier] " + msg); m_log.statusMessage(msg); } return; } if (m_ClassifierTemplate instanceof weka.classifiers.misc.InputMappedClassifier) { m_trainingSet=((weka.classifiers.misc.InputMappedClassifier)m_Classifier).getModelHeader(m_trainingSet); } if (m_trainingSet != null && (!dataset.equalHeaders(m_trainingSet))) { if (m_log != null) { String msg=statusMessagePrefix() + " WARNING : structure of instance events differ " + "from data used in batch training this "+ "classifier. Resetting classifier..."; m_log.logMessage("[Classifier] " + msg); m_log.statusMessage(msg); } m_trainingSet=null; } if (m_resetIncrementalClassifier) { if (m_log != null) { String msg=statusMessagePrefix() + " Reseting incremental classifier"; m_log.logMessage("[Classifier] " + msg); m_log.statusMessage(msg); } m_trainingSet=null; } if (m_trainingSet == null) { m_trainingSet=new Instances(dataset,0); m_Classifier=weka.classifiers.AbstractClassifier.makeCopy(m_ClassifierTemplate); if (m_Classifier instanceof EnvironmentHandler && m_env != null) { ((EnvironmentHandler)m_Classifier).setEnvironment(m_env); } m_Classifier.buildClassifier(m_trainingSet); } } } catch ( Exception ex) { stop(); if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); m_log.logMessage("[Classifier] " + statusMessagePrefix() + " problem during incremental processing. "+ ex.getMessage()); } ex.printStackTrace(); return; } if (!m_incrementalEvent.m_formatNotificationOnly) { String msg=m_updateIncrementalClassifier ? statusMessagePrefix() + "Training incrementally..." : statusMessagePrefix() + "Predicting incrementally..."; if (m_log != null) { m_log.statusMessage(msg); } } System.err.println("NOTIFYING NEW BATCH"); m_ie.setStructure(dataset); m_ie.setClassifier(m_Classifier); notifyIncrementalClassifierListeners(m_ie); return; } else { if (m_trainingSet == null) { return; } } try { if (m_incrementalEvent.getInstance() != null) { if (m_incrementalEvent.getInstance().dataset().classIndex() < 0) { m_incrementalEvent.getInstance().dataset().setClassIndex(m_incrementalEvent.getInstance().dataset().numAttributes() - 1); } } int status=IncrementalClassifierEvent.WITHIN_BATCH; if (m_incrementalEvent.getStatus() == InstanceEvent.BATCH_FINISHED || m_incrementalEvent.getInstance() == null) { status=IncrementalClassifierEvent.BATCH_FINISHED; } if (m_incrementalEvent.getInstance() != null) { m_throughput.updateStart(); } m_ie.setStatus(status); m_ie.setClassifier(m_Classifier); m_ie.setCurrentInstance(m_incrementalEvent.getInstance()); if (status == InstanceEvent.BATCH_FINISHED && m_Classifier instanceof UpdateableBatchProcessor) { ((UpdateableBatchProcessor)m_Classifier).batchFinished(); } notifyIncrementalClassifierListeners(m_ie); if (m_ClassifierTemplate instanceof weka.classifiers.UpdateableClassifier && m_updateIncrementalClassifier == true && m_incrementalEvent.getInstance() != null && !(m_incrementalEvent.getInstance().isMissing(m_incrementalEvent.getInstance().dataset().classIndex()))) { ((weka.classifiers.UpdateableClassifier)m_Classifier).updateClassifier(m_incrementalEvent.getInstance()); } if (m_incrementalEvent.getInstance() != null) { m_throughput.updateEnd(m_log); } if (m_incrementalEvent.getStatus() == InstanceEvent.BATCH_FINISHED || m_incrementalEvent.getInstance() == null) { if (m_textListeners.size() > 0) { String modelString=m_Classifier.toString(); String titleString=m_Classifier.getClass().getName(); titleString=titleString.substring(titleString.lastIndexOf('.') + 1,titleString.length()); modelString="=== Classifier model ===\n\n" + "Scheme: " + titleString + "\n"+ "Relation: "+ m_trainingSet.relationName()+ "\n\n"+ modelString; titleString="Model: " + titleString; TextEvent nt=new TextEvent(this,modelString,titleString); notifyTextListeners(nt); } m_throughput.finished(m_log); } } catch ( Exception ex) { stop(); if (m_log != null) { m_log.logMessage("[Classifier] " + statusMessagePrefix() + ex.getMessage()); m_log.statusMessage(statusMessagePrefix() + "ERROR (see log for details)"); ex.printStackTrace(); } else { ex.printStackTrace(); } } }
Handles initializing and updating an incremental classifier
public void addPanListener(PanListener listener){ if (mPan != null) { mPan.addPanListener(listener); } }
Adds a new pan listener.
protected void buildShape(BridgeContext ctx,Element e,ShapeNode shapeNode){ try { SVGOMEllipseElement ee=(SVGOMEllipseElement)e; AbstractSVGAnimatedLength _cx=(AbstractSVGAnimatedLength)ee.getCx(); float cx=_cx.getCheckedValue(); AbstractSVGAnimatedLength _cy=(AbstractSVGAnimatedLength)ee.getCy(); float cy=_cy.getCheckedValue(); AbstractSVGAnimatedLength _rx=(AbstractSVGAnimatedLength)ee.getRx(); float rx=_rx.getCheckedValue(); AbstractSVGAnimatedLength _ry=(AbstractSVGAnimatedLength)ee.getRy(); float ry=_ry.getCheckedValue(); shapeNode.setShape(new Ellipse2D.Float(cx - rx,cy - ry,rx * 2,ry * 2)); } catch ( LiveAttributeException ex) { throw new BridgeException(ctx,ex); } }
Constructs an ellipse according to the specified parameters.
protected boolean isLog4JAvailable(){ return isLogLibraryAvailable("Log4J",LOGGING_IMPL_LOG4J_LOGGER); }
Is a <em>Log4J</em> implementation available?
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public void runTest() throws Throwable { Document doc; NodeList elementList; Node nameNode; Text textNode; Text splitNode; Node secondPart; String value; doc=(Document)load("staff",true); elementList=doc.getElementsByTagName("name"); nameNode=elementList.item(2); textNode=(Text)nameNode.getFirstChild(); splitNode=textNode.splitText(7); secondPart=textNode.getNextSibling(); value=secondPart.getNodeValue(); assertEquals("textSplitTextOneAssert","Jones",value); }
Runs the test case.
@POST @Produces(MediaType.APPLICATION_JSON) @Path("/{alertId}/notifications/{notificationId}/triggers/{triggerId}") @Description("Associates the trigger having the given ID to the given notification ID. Both the trigger and notification must be owned by the alert.") public TriggerDto addTriggerToNotification(@Context HttpServletRequest req,@PathParam("alertId") BigInteger alertId,@PathParam("notificationId") BigInteger notificationId,@PathParam("triggerId") BigInteger triggerId){ if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.",Status.BAD_REQUEST); } if (notificationId == null || notificationId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Notification Id cannot be null and must be a positive non-zero number.",Status.BAD_REQUEST); } if (triggerId == null || triggerId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Trigger Id cannot be null and must be a positive non-zero number.",Status.BAD_REQUEST); } Notification notification=null; Trigger alertTrigger=null; Alert alert=alertService.findAlertByPrimaryKey(alertId); if (alert == null) { throw new WebApplicationException(Status.NOT_FOUND.getReasonPhrase(),Status.NOT_FOUND); } validateResourceAuthorization(req,alert.getOwner(),getRemoteUser(req)); for ( Notification tempNotification : alert.getNotifications()) { if (tempNotification.getId().equals(notificationId)) { notification=tempNotification; break; } } if (notification == null) { throw new WebApplicationException("Notification Id does not exist for this alert.",Status.BAD_REQUEST); } for ( Trigger tempTrigger : alert.getTriggers()) { if (tempTrigger.getId().equals(triggerId)) { alertTrigger=tempTrigger; break; } } if (alertTrigger == null) { throw new WebApplicationException("Trigger Id does not exist for this alert. Create a trigger first then add it to the notification",Status.BAD_REQUEST); } for ( Trigger tempTrigger : notification.getTriggers()) { if (tempTrigger.getId().equals(triggerId)) { throw new WebApplicationException("This trigger already exists for the notification.",Status.BAD_REQUEST); } } List<Trigger> list=new ArrayList<Trigger>(notification.getTriggers()); list.add(alertTrigger); notification.setTriggers(list); alert.setModifiedBy(getRemoteUser(req)); alert=alertService.updateAlert(alert); for ( Notification tempNotification : alert.getNotifications()) { if (tempNotification.getId().equals(notificationId)) { for ( Trigger tempTrigger : notification.getTriggers()) { if (tempTrigger.getId().equals(triggerId)) { return TriggerDto.transformToDto(tempTrigger); } } } } throw new WebApplicationException("Trigger update failed.",Status.INTERNAL_SERVER_ERROR); }
Adds trigger to the notification.
public float[][] calc(float[] xpoints,float[] ypoints){ float[][] res=new float[2][0]; if (xpoints.length > 2) { Cubic[] X=calcNaturalCubic(xpoints.length - 1,xpoints); Cubic[] Y=calcNaturalCubic(ypoints.length - 1,ypoints); Polygon p=new Polygon(); p.addPoint((int)Math.round(X[0].eval(0)),(int)Math.round(Y[0].eval(0))); for (int i=0; i < X.length; i++) { for (int j=1; j <= steps; j++) { float u=j / (float)steps; p.addPoint(Math.round(X[i].eval(u)),Math.round(Y[i].eval(u))); } } res[0]=new float[p.npoints]; res[1]=new float[p.npoints]; for (int i=0; i < p.npoints; i++) { res[0][i]=p.xpoints[i]; res[1][i]=p.ypoints[i]; } p=null; } else { res[0]=xpoints; res[1]=ypoints; } return res; }
Calculates a cubic spline polyline
public static <T>Iterator<T> each(Iterator<T> self,@ClosureParams(FirstParam.FirstGenericType.class) Closure closure){ while (self.hasNext()) { Object arg=self.next(); closure.call(arg); } return self; }
Iterates through an Iterator, passing each item to the given closure.