code
stringlengths
10
174k
nl
stringlengths
3
129k
public QLFFilesCollection(File directory,String extension,Class<F> featureClass,String pathRegexFind,String pathRegexRep){ this(featureClass,pathRegexFind,pathRegexRep); processDirs(directory,extension); }
Construct the collection from the files in the given directory that have the given file extension. All the files are expected to contain features of the given feature class. The file search is recursive, and will also look in sub-directories of the specified directory. The final two parameters allow a regular-expression find and replace operation for be performed on the found filenames in order to create the document identifier for each QLFDocument. This is useful to ensure only the document name is stored in the index, rather than the absolute path.
public static void main(String[] args) throws IOException { boolean enableOutput=true; boolean outputToFile=false; String inputFolder=LrMc.class.getClassLoader().getResource("workload/planetlab").getPath(); String outputFolder="output"; String workload="20110303"; String vmAllocationPolicy="lr"; String vmSelectionPolicy="mc"; String parameter="1.2"; new PlanetLabRunner(enableOutput,outputToFile,inputFolder,outputFolder,workload,vmAllocationPolicy,vmSelectionPolicy,parameter); }
The main method.
void make(BulkTest bulk){ Class c=bulk.getClass(); Method[] all=c.getMethods(); for (int i=0; i < all.length; i++) { if (isTest(all[i])) addTest(bulk,all[i]); if (isBulk(all[i])) addBulk(bulk,all[i]); } }
Appends all the simple tests and bulk tests defined by the given instance's class to the current TestSuite.
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { String inName=(String)in.readObject(); String inDescription=(String)in.readObject(); Object inValue=in.readObject(); Class inClass=(Class)in.readObject(); boolean inUserModifiable=in.readBoolean(); Assert.assertTrue(inName != null); Assert.assertTrue(inDescription != null); Assert.assertTrue(inValue != null); Assert.assertTrue(inClass != null); this.deserialized=true; this.name=inName; setInternalState(inDescription,inValue,inClass,inUserModifiable); }
Override readObject which is used in serialization. Customize serialization of this exception to avoid escape of InternalRole which is not Serializable.
private void returnData(Object ret){ if (myHost != null) { myHost.returnData(ret); } }
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
public static String escape(String s){ if (s == null) return null; StringBuffer sb=new StringBuffer(); escape(s,sb); return sb.toString(); }
Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
public ArrayDeque<E> clone(){ try { @SuppressWarnings("unchecked") ArrayDeque<E> result=(ArrayDeque<E>)super.clone(); result.elements=Arrays.copyOf(elements,elements.length); return result; } catch ( CloneNotSupportedException e) { throw new AssertionError(); } }
Returns a copy of this deque.
public void generateCode(BlockScope currentScope){ if ((this.bits & IsReachable) == 0) { return; } generateInit: { if (this.initialization == null) break generateInit; if (this.binding.resolvedPosition < 0) { if (this.initialization.constant != Constant.NotAConstant) break generateInit; this.initialization.generateCode(currentScope,false); break generateInit; } this.initialization.generateCode(currentScope,true); } }
Code generation for a local declaration: i.e.&nbsp;normal assignment to a local variable + unused variable handling
public static boolean isPotentialValidLink(File file) throws IOException { boolean isPotentiallyValid; try (InputStream fis=new FileInputStream(file)){ final int minimumLength=0x64; isPotentiallyValid=file.isFile() && file.getName().toLowerCase().endsWith(".lnk") && fis.available() >= minimumLength && isMagicPresent(getBytes(fis,32)); } return isPotentiallyValid; }
Provides a quick test to see if this could be a valid link ! If you try to instantiate a new WindowShortcut and the link is not valid, Exceptions may be thrown and Exceptions are extremely slow to generate, therefore any code needing to loop through several files should first check this.
public IGameMove decideMove(IGameState state){ if (state.isDraw()) return null; if (state.isWin()) return null; Collection<IGameMove> moves=logic.validMoves(this,state); if (moves.size() == 0) { return null; } else { IGameMove[] mvs=moves.toArray(new IGameMove[]{}); int idx=(int)(Math.random() * moves.size()); return mvs[idx]; } }
Randomly make a move based upon the available logic of the game. Make sure you check that the game is not already won, lost or drawn before calling this method, because you
public static int nextPowerOf2(int x){ long i=1; while (i < x && i < (Integer.MAX_VALUE / 2)) { i+=i; } return (int)i; }
Get the value that is equal or higher than this value, and that is a power of two.
public Point2D inverseTransform(Point2D viewPoint){ Point2D viewCenter=getViewCenter(); double viewRadius=getViewRadius(); double ratio=getRatio(); double dx=viewPoint.getX() - viewCenter.getX(); double dy=viewPoint.getY() - viewCenter.getY(); dx*=ratio; Point2D pointFromCenter=new Point2D.Double(dx,dy); PolarPoint polar=PolarPoint.cartesianToPolar(pointFromCenter); double radius=polar.getRadius(); if (radius > viewRadius) return delegate.inverseTransform(viewPoint); radius/=viewRadius; radius=Math.abs(Math.tan(radius)); radius/=Math.PI / 2; radius*=viewRadius; double mag=Math.tan(Math.PI / 2 * magnification); radius/=mag; polar.setRadius(radius); Point2D projectedPoint=PolarPoint.polarToCartesian(polar); projectedPoint.setLocation(projectedPoint.getX() / ratio,projectedPoint.getY()); Point2D translatedBack=new Point2D.Double(projectedPoint.getX() + viewCenter.getX(),projectedPoint.getY() + viewCenter.getY()); return delegate.inverseTransform(translatedBack); }
override base class to un-project the fisheye effect
private boolean iconBoundsIntersectBar(RectF barBounds,Rect icon,double scaleFactor){ int iconL=icon.left + scale(icon.width(),scaleFactor); int iconT=icon.top + scale(icon.height(),scaleFactor); int iconR=icon.right - scale(icon.width(),scaleFactor); int iconB=icon.bottom - scale(icon.height(),scaleFactor); return barBounds.intersects(iconL,iconT,iconR,iconB); }
Helper method for calculating intersections for control icons and bars.
public void closeRegistration(){ flushDeferrables(); for ( Map.Entry<String,ClassPlugins> e : registrations.entrySet()) { e.getValue().initializeMap(); } }
Disallows new registrations of new plugins, and creates the internal tables for method lookup.
public static String toGml(final IDirectedGraph<?,? extends IGraphEdge<?>> graph){ Preconditions.checkNotNull(graph,"Graph argument can not be null"); final StringBuilder sb=new StringBuilder(); sb.append("graph\n" + "[\n"); int currentId=0; final Map<Object,Integer> nodeMap=new HashMap<>(); for ( final Object node : graph.getNodes()) { sb.append("\tnode\n" + "\t[\n" + "\tid "+ "\n"); sb.append(currentId); sb.append("\tlabel \""); sb.append(node); sb.append("\"\n" + "\t]\n"); nodeMap.put(node,currentId); ++currentId; } for ( final IGraphEdge<?> edge : graph.getEdges()) { sb.append("\tedge\n" + "\t[\n" + "\tsource "); sb.append(nodeMap.get(edge.getSource())); sb.append("\n" + "\ttarget "); sb.append(nodeMap.get(edge.getTarget())); sb.append("\n" + "\tgraphics\n" + "\t[\n"+ "\t\tfill \"#000000\"\n"+ "\t\ttargetArrow \"standard\"\n"+ "\t]\n"+ "\t]\n"); } sb.append("]\n"); return sb.toString(); }
Creates GML code that represents a given directed graph.
void cachePage(long pos,Page page,int memory){ if (cache != null) { cache.put(pos,page,memory); } }
Put the page in the cache.
public static Class<?> typeToClass(int type){ Class<?> result; switch (type) { case Types.BIGINT: result=Long.class; break; case Types.BINARY: result=String.class; break; case Types.BIT: result=Boolean.class; break; case Types.CHAR: result=Character.class; break; case Types.DATE: result=java.sql.Date.class; break; case Types.DECIMAL: result=Double.class; break; case Types.DOUBLE: result=Double.class; break; case Types.FLOAT: result=Float.class; break; case Types.INTEGER: result=Integer.class; break; case Types.LONGVARBINARY: result=String.class; break; case Types.LONGVARCHAR: result=String.class; break; case Types.NULL: result=String.class; break; case Types.NUMERIC: result=Double.class; break; case Types.OTHER: result=String.class; break; case Types.REAL: result=Double.class; break; case Types.SMALLINT: result=Short.class; break; case Types.TIME: result=java.sql.Time.class; break; case Types.TIMESTAMP: result=java.sql.Timestamp.class; break; case Types.TINYINT: result=Short.class; break; case Types.VARBINARY: result=String.class; break; case Types.VARCHAR: result=String.class; break; default : result=null; } return result; }
Returns the class associated with a SQL type.
private String noteToString(Repository repo,Note note) throws MissingObjectException, IOException, UnsupportedEncodingException { ObjectLoader loader=repo.open(note.getData()); ByteArrayOutputStream baos=new ByteArrayOutputStream(); loader.copyTo(baos); return new String(baos.toByteArray(),"UTF-8"); }
Utility method that converts a note to a string (assuming it's UTF-8).
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void initTimers() throws ValidationException { initAllTimers(); }
Reads the configuration settings for the timer intervals to be used and creates the timers accordingly.
public static String tbiIndexToUniqueString(InputStream is) throws IOException { final StringBuilder ret=new StringBuilder(); final byte[] buf=new byte[4096]; readIOFully(is,buf,4); final String header=new String(buf,0,4); ret.append("Header correct: ").append(header.equals("TBI\u0001")).append(StringUtils.LS); readIOFully(is,buf,4); final int numRefs=ByteArrayIOUtils.bytesToIntLittleEndian(buf,0); ret.append("numRefs: ").append(numRefs).append(StringUtils.LS); readIOFully(is,buf,28); final int format=ByteArrayIOUtils.bytesToIntLittleEndian(buf,0); final int colSeq=ByteArrayIOUtils.bytesToIntLittleEndian(buf,4); final int colBeg=ByteArrayIOUtils.bytesToIntLittleEndian(buf,8); final int colEnd=ByteArrayIOUtils.bytesToIntLittleEndian(buf,12); final int meta=ByteArrayIOUtils.bytesToIntLittleEndian(buf,16); final int skip=ByteArrayIOUtils.bytesToIntLittleEndian(buf,20); final int refNameLength=ByteArrayIOUtils.bytesToIntLittleEndian(buf,24); final String formatStr; formatStr=TbiFormat.values()[format & 0xffff].name(); ret.append("Format: ").append(formatStr).append(" 0-based: ").append((format & 0x10000) != 0).append(StringUtils.LS); ret.append("Columns: (refName:Start-End) ").append(colSeq).append(":").append(colBeg).append("-").append(colEnd).append(StringUtils.LS); ret.append("Meta: ").append((char)meta).append(StringUtils.LS); ret.append("Skip: ").append(skip).append(StringUtils.LS); final byte[] names=new byte[refNameLength]; readIOFully(is,names,names.length); ret.append("Sequence names: "); boolean first=true; int off=0; for (int i=0; i < numRefs; i++) { int newOff=off; while (newOff < names.length && names[newOff] != 0) { newOff++; } if (!first) { ret.append(", "); } ret.append(new String(names,off,newOff - off)); off=newOff + 1; first=false; } ret.append(StringUtils.LS); ret.append(indicesToUniqueString(is,numRefs)).append(StringUtils.LS); return ret.toString(); }
Creates a string representation of the TABIX index
public void addFeatureChangeListener(final FeatureChangeListener l){ featureListeners.add(l); }
Add a feature change listener.
protected UserPassword(){ super(); }
Dear JPA...
public void firePropertyChange(String propertyName,float oldValue,float newValue){ }
Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for more information.
public void testUpdate5(){ int factor=3; String updateQuery="UPDATE " + DatabaseCreator.TEST_TABLE1 + " SET field2=field2 *"+ factor; try { String selectQuery="SELECT field2 FROM " + DatabaseCreator.TEST_TABLE1; ResultSet result=statement.executeQuery(selectQuery); HashSet<BigDecimal> values=new HashSet<BigDecimal>(); int num=statement.executeUpdate(updateQuery); assertEquals("Not all records in the database were updated",numberOfRecords,num); result=statement.executeQuery(selectQuery); assertTrue("Not all records were updated",values.isEmpty()); result.close(); } catch ( SQLException e) { fail("Unexpected exception" + e.getMessage()); } }
UpdateFunctionalityTest#testUpdate5(). Updates values in one columns in the table using condition
public final boolean isCaretBlinkEnabled(){ return caretBlinks; }
Returns true if the caret is blinking, false otherwise.
public void testBug73663() throws Exception { this.rs=this.stmt.executeQuery("show variables like 'collation_server'"); this.rs.next(); String collation=this.rs.getString(2); if (collation != null && collation.startsWith("utf8mb4") && "utf8mb4".equals(((MySQLConnection)this.conn).getServerVariable("character_set_server"))) { Properties p=new Properties(); p.setProperty("characterEncoding","UTF-8"); p.setProperty("statementInterceptors",Bug73663StatementInterceptor.class.getName()); getConnectionWithProps(p); } else { System.out.println("testBug73663 was skipped: This test is only run when character_set_server=utf8mb4 and collation-server set to one of utf8mb4 collations."); } }
Tests fix for Bug#73663 (19479242), utf8mb4 does not work for connector/j >=5.1.13 This test is only run when character_set_server=utf8mb4 and collation-server set to one of utf8mb4 collations (it's better to test two configurations: with default utf8mb4_general_ci and one of non-default, say utf8mb4_bin)
@Override public void removeEdge(final InstructionGraphEdge edge){ super.removeEdge(edge); }
Removes an instruction edge from the instruction graph.
public void addApps(List<AppInfo> apps){ mApps.addApps(apps); }
Adds new apps to the list.
public void stop(){ final String methodName="stop"; synchronized (lifecycle) { log.fine(CLASS_NAME,methodName,"850"); if (running) { running=false; receiving=false; if (!Thread.currentThread().equals(recThread)) { try { recThread.join(); } catch ( InterruptedException ex) { } } } } recThread=null; log.fine(CLASS_NAME,methodName,"851"); }
Stops the Receiver's thread. This call will block.
First(){ }
CONSTRUCTOR <init>
@Override public String toString(){ String temp=""; for (int i=0; i < variables.length; i++) { temp+=variables[i].toString(); temp+="\n"; } return structName + "\n" + temp; }
Override ToString().
public void addActionListener(ActionListener l){ dispatcher.addListener(l); }
Adds a listener to the switch which will cause an event to dispatch on click
@Override protected SystemMemberCache createSystemMemberCache(GemFireVM vm) throws org.apache.geode.admin.AdminException { if (managedSystemMemberCache == null) { managedSystemMemberCache=new SystemMemberCacheJmxImpl(vm); } return managedSystemMemberCache; }
Override createSystemMemberCache by instantiating SystemMemberCacheJmxImpl if it was not created earlier.
@Override public void run(){ amIActive=true; String inputFile=args[0]; if (inputFile.toLowerCase().contains(".dep")) { calculateRaster(); } else if (inputFile.toLowerCase().contains(".shp")) { calculateVector(); } else { showFeedback("There was a problem reading the input file."); } }
Used to execute this plugin tool.
public void test_compressed_timestamp_01b() throws Exception { new TestHelper("compressed-timestamp-01b","compressed-timestamp-01b.rq","compressed-timestamp.ttl","compressed-timestamp-01.srx").runTest(); }
Simple SELECT query returning data typed with the given timestamp, where we have several FILTERs that should evaluate to true.
private void writeAttribute(java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter,namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } }
Util method to write an attribute without the ns prefix
private void addTag(String newTag){ if (StringUtils.isBlank(newTag)) { return; } synchronized (tagsObservable) { if (tagsObservable.contains(newTag)) { return; } tagsObservable.add(newTag); } firePropertyChange("tag",null,tagsObservable); }
Adds the tag.
public EObject basicGetAstElement(){ return astElement; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void detach(){ if (systemOverlay) { getWindowManager().removeView(this); } else { ((ViewGroup)getActivityContentView()).removeView(this); } }
Detaches it from the container view.
private static void patternCompile(){ try { ptnNumber=Pattern.compile(strNumberPattern); ptnShortDate=Pattern.compile(strShortDatePattern); ptnLongDate=Pattern.compile(strLongDatePattern); ptnPercentage=Pattern.compile(strPercentagePattern); ptnCurrency=Pattern.compile(strCurrencyPattern); ptnViCurrency=Pattern.compile(strViCurrencyPattern); } catch ( PatternSyntaxException ex) { System.err.println(ex.getMessage()); System.exit(1); } }
Pattern compile.
public NotificationChain basicSetParams(ExpressionList newParams,NotificationChain msgs){ ExpressionList oldParams=params; params=newParams; if (eNotificationRequired()) { ENotificationImpl notification=new ENotificationImpl(this,Notification.SET,GamlPackage.PARAMETERS__PARAMS,oldParams,newParams); if (msgs == null) msgs=notification; else msgs.add(notification); } return msgs; }
<!-- begin-user-doc --> <!-- end-user-doc -->
static public int unpackInt(DataInput is) throws IOException { int ret=0; byte v; do { v=is.readByte(); ret=(ret << 7) | (v & 0x7F); } while ((v & 0x80) == 0); return ret; }
Unpack int value from the input stream.
public Object loadWorkflowData(String stepId,String key){ Object data=null; String workflowUri=getMainWorkflowUri(stepId); try { if (workflowUri != null) { String dataPath=String.format(_zkStepDataPath,workflowUri) + String.format(_zkWorkflowData,key); if (_dataManager.checkExists(dataPath) != null) { data=_dataManager.getData(dataPath,false); } } } catch ( Exception ex) { String exMsg="Exception adding global data to workflow from stepId: " + stepId + ": "+ ex.getMessage(); _log.error(exMsg); data=null; } return data; }
Gets the step workflow data stored under /workflow/stepdata/{workflowURI}/data/{key} where workflowURI is the URI of the main workflow regardless of whether the step belongs in the main workflow or one of its nested workflows.
public static void fillByte(byte[] array,byte x){ for (int i=0; i < array.length; i++) { array[i]=x; } }
Fill an array with the given value.
@Override public void addDictionaryChunk(List<byte[]> dictionaryChunk){ dictionaryChunks.add(dictionaryChunk); if (null == dictionaryByteArrayToSurrogateKeyMap) { createDictionaryByteArrayToSurrogateKeyMap(dictionaryChunk.size()); } addDataToDictionaryMap(); }
This method will add a new dictionary chunk to existing list of dictionary chunks
public OMWarpingImage(BufferedImage bi){ setWarp(bi,LatLonGCT.INSTANCE,new DataBounds(-180,-90,180,90)); }
Takes an image, assumed to be a world image in the LLXY projection (equal arc) covering -180, 180 longitude to -90, 90 latitude.
private void acquirePrecachingWakeLock(){ if (mPrecachingWakeLock == null) { PowerManager pm=(PowerManager)getSystemService(Context.POWER_SERVICE); mPrecachingWakeLock=pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,TAG); } mPrecachingWakeLock.acquire(); }
Acquire the precaching WakeLock.
public static List<Long> entropyHybridTest(GeoTimeSerie gts,int buckets_per_period,int periods_per_piece,int k,double alpha) throws WarpScriptException { doubleCheck(gts); List<Long> anomalous_ticks=new ArrayList<Long>(); if (!GTSHelper.isBucketized(gts)) { throw new WarpScriptException("GTS must be bucketized"); } if (k >= periods_per_piece * buckets_per_period / 2) { throw new WarpScriptException("Upper bound of number of outliers must be less than half of the number of observations per piece"); } GeoTimeSerie subgts=null; GeoTimeSerie subsubgts=null; GeoTimeSerie seasonal=null; long pieces=gts.bucketcount / buckets_per_period / periods_per_piece; int bpp=periods_per_piece * buckets_per_period; long lb=gts.lastbucket; long bs=gts.bucketspan; for (int u=0; u < pieces; u++) { long start=lb - bs * ((pieces - u) * bpp - 1); long stop=lb - bs * (pieces - u - 1) * bpp; subgts=GTSHelper.subSerie(gts,start,stop,false,false,subgts); subgts.lastbucket=stop; subgts.bucketcount=bpp; subgts.bucketspan=bs; if (null == seasonal) { seasonal=new GeoTimeSerie(bpp); seasonal.doubleValues=new double[bpp]; seasonal.ticks=new long[bpp]; } else { GTSHelper.reset(seasonal); } seasonal.type=TYPE.DOUBLE; for (int v=0; v < buckets_per_period; v++) { subsubgts=GTSHelper.subCycleSerie(subgts,stop - v * bs,buckets_per_period,true,subsubgts); double[] madsigma=madsigma(subsubgts,true); double median=madsigma[0]; double mad=madsigma[1]; double sum=0.0D; for (int w=0; w < subsubgts.values; w++) { subsubgts.doubleValues[w]=0.0D != mad ? Math.abs((subsubgts.doubleValues[w] - median) / mad) : 1.0D; sum+=subsubgts.doubleValues[w]; } double entropy=0.0D; for (int w=0; w < subsubgts.values; w++) { subsubgts.doubleValues[w]/=sum; double tmp=subsubgts.doubleValues[w]; if (0.0D != tmp) { entropy-=tmp * Math.log(tmp); } } if (0.0D != entropy) { entropy/=Math.log(subsubgts.values); } else { entropy=1.0D; } for (int w=0; w < subsubgts.values; w++) { GTSHelper.setValue(seasonal,subsubgts.ticks[w],entropy * subsubgts.doubleValues[w]); } } GTSHelper.sort(seasonal); double m=median(seasonal); int idx=0; for (int i=0; i < subgts.values; i++) { idx=Arrays.binarySearch(seasonal.ticks,idx,seasonal.values,subgts.ticks[i]); if (idx < 0) { throw new WarpScriptException("Internal bug method entropyHybridTest: can't find tick " + subgts.ticks[i] + " in seasonal.ticks"); } else { subgts.doubleValues[i]-=(seasonal.doubleValues[idx] + m); } } anomalous_ticks.addAll(ESDTest(subgts,k,true,alpha)); } return anomalous_ticks; }
Applying Seasonal Entropy Hybrid test This test is based on piecewise decomposition where trend components are approximated by median and seasonal components by entropy of the cycle sub-series. An ESD test is passed upon the residuals. It differs from hybridTest by approximating seasonal component instead of using STL. But in many cases this approximation is more useful than estimation of STL.
public static void collectAndFireTriggers(final HashSet<PlayerID> players,final Match<TriggerAttachment> triggerMatch,final IDelegateBridge aBridge,final String beforeOrAfter,final String stepName){ final HashSet<TriggerAttachment> toFirePossible=collectForAllTriggersMatching(players,triggerMatch,aBridge); if (toFirePossible.isEmpty()) { return; } final HashMap<ICondition,Boolean> testedConditions=collectTestsForAllTriggers(toFirePossible,aBridge); final List<TriggerAttachment> toFireTestedAndSatisfied=Match.getMatches(toFirePossible,AbstractTriggerAttachment.isSatisfiedMatch(testedConditions)); if (toFireTestedAndSatisfied.isEmpty()) { return; } TriggerAttachment.fireTriggers(new HashSet<>(toFireTestedAndSatisfied),testedConditions,aBridge,beforeOrAfter,stepName,true,true,true,true); }
This will collect all triggers for the desired players, based on a match provided, and then it will gather all the conditions necessary, then test all the conditions, and then it will fire all the conditions which are satisfied.
public static long[] clone(long[] array){ if (array == null) { return null; } return (long[])array.clone(); }
<p>Clones an array returning a typecast result and handling <code>null</code>.</p> <p>This method returns <code>null</code> for a <code>null</code> input array.</p>
public ColorPredicate(String input) throws IllegalArgumentException { String rest=input.trim().toLowerCase(); if (rest.startsWith("leaf")) { this.isLeaf=true; rest=rest.substring(4).trim(); } else { this.isLeaf=false; } int endOfStartToken=0; while (endOfStartToken < rest.length() && Character.isLetter(rest.charAt(endOfStartToken))) { endOfStartToken++; } String startToken=rest.substring(0,endOfStartToken); String macro=getMacro(startToken); if (macro != null) { rest=macro; } if (rest.startsWith("some")) { this.isSome=true; rest=rest.substring(4).trim(); } else if (rest.startsWith("every")) { this.isSome=false; rest=rest.substring(5).trim(); } else { throw new IllegalArgumentException("" + " Color predicate must start with the optional keyword `leaf'\n" + " followed by a legal macro name or `every' or `some'."); } this.set=0; while (!rest.equals("")) { if (rest.startsWith("omitted")) { this.set=this.set | (1 << NUMBER_OF_OMITTED_STATE); rest=rest.substring(7).trim(); } else if (rest.startsWith("missing")) { this.set=this.set | (1 << NUMBER_OF_MISSING_STATE); rest=rest.substring(7).trim(); } else if (rest.startsWith("(")) { rest=rest.substring(1).trim(); int[][] stateSetSpec=new int[NUMBER_OF_PROVERS][]; for (int i=0; i < NUMBER_OF_PROVERS; i++) { boolean invert=false; if (rest.startsWith("-")) { invert=true; rest=rest.substring(1).trim(); } boolean[] appears=new boolean[PROVER_STATUSES[i].length]; for (int j=0; j < appears.length; j++) { appears[j]=invert; } String endChar=(i == NUMBER_OF_PROVERS - 1) ? ")" : ","; while (rest.length() > 0 && !rest.startsWith(endChar)) { int endOfToken=0; while (endOfToken < rest.length() && Character.isLetter(rest.charAt(endOfToken))) { endOfToken++; } String token=rest.substring(0,endOfToken); rest=rest.substring(endOfToken).trim(); int statusNumber; try { statusNumber=numberOfProverStatus(i,token); } catch ( IllegalArgumentException e) { String errorMsg="Was expecting status of prover " + PROVER_NAMES[i] + " but found `"+ token+ "' followed by: \n `"+ rest+ "'"; throw new IllegalArgumentException(errorMsg); } appears[statusNumber]=!invert; } if (rest.length() == 0) { throw new IllegalArgumentException("Color predicate specifier ended before `(...)' expression complete"); } rest=rest.substring(1).trim(); int count=0; for (int j=0; j < appears.length; j++) { if (appears[j]) { count++; } } if (count == 0) { if (invert) { throw new IllegalArgumentException("A `-' must be followed by one or more statuses"); } else { count=appears.length; for (int j=0; j < count; j++) { appears[j]=true; } } } stateSetSpec[i]=new int[count]; int k=0; for (int j=0; j < appears.length; j++) { if (appears[j]) { stateSetSpec[i][k]=j; k++; } } } this.set=this.set | bitVectorOfStates(stateSetSpec); } else { throw new IllegalArgumentException("Unexpected token at: `" + rest + "'"); } } }
Returns a ColorPredicate obtained by parsing its argument. See the beginning of ProofStatus.tla for the grammar of the input.
protected void transferFromFile(File idFile) throws IOException { try (BufferedReader br=new BufferedReader(new FileReader(idFile))){ String line; while ((line=br.readLine()) != null) { line=line.trim(); if (line.length() > 0) { transfer(line); } } } }
Transfer all the sequences listed in the supplied file, interpreting entries appropriately.
public String toNamespacedString(){ return (_namespaceURI != null ? ("{" + _namespaceURI + "}"+ _localName) : _localName); }
Return the string representation of the qualified name using the the '{ns}foo' notation. Performs string concatenation, so beware of performance issues.
@SuppressWarnings("deprecation") public void configureManagers(){ powerManager=new jmri.jmrix.nce.NcePowerManager(this); InstanceManager.store(powerManager,jmri.PowerManager.class); turnoutManager=new jmri.jmrix.nce.NceTurnoutManager(getNceTrafficController(),getSystemPrefix()); InstanceManager.setTurnoutManager(turnoutManager); lightManager=new jmri.jmrix.nce.NceLightManager(getNceTrafficController(),getSystemPrefix()); InstanceManager.setLightManager(lightManager); sensorManager=new jmri.jmrix.nce.NceSensorManager(getNceTrafficController(),getSystemPrefix()); InstanceManager.setSensorManager(sensorManager); throttleManager=new jmri.jmrix.nce.NceThrottleManager(this); InstanceManager.setThrottleManager(throttleManager); if (getNceUsbSystem() != NceTrafficController.USB_SYSTEM_NONE) { if (getNceUsbSystem() != NceTrafficController.USB_SYSTEM_POWERHOUSE) { } } else { InstanceManager.setProgrammerManager(getProgrammerManager()); } clockManager=new jmri.jmrix.nce.NceClockControl(getNceTrafficController(),getSystemPrefix()); InstanceManager.addClockControl(clockManager); consistManager=new jmri.jmrix.nce.NceConsistManager(this); InstanceManager.setConsistManager(consistManager); }
Configure the common managers for NCE connections. This puts the common manager config in one place.
public void newLine() throws IOException { out.append('\n'); for (int n=0; n < currentIndentLevel; n++) out.append(indent); currentLine++; currentCol=currentIndentLevel * indent.length(); }
Emits a <code>'\n'</code> plus required indentation characters for the current indentation level.
@Override protected void checkForDuplicatSnapshotName(String name,Volume vplexVolume){ Volume snapshotSourceVolume=getVPLEXSnapshotSourceVolume(vplexVolume); super.checkForDuplicatSnapshotName(name,snapshotSourceVolume); }
Check if a snapshot with the same name exists for the passed volume.
public boolean isOneAssetPerUOM(){ Object oo=get_Value(COLUMNNAME_IsOneAssetPerUOM); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
Get One Asset Per UOM.
public int value(){ return this.value; }
Retrieve value for node computed so far. <p> Primarily here for testing
public boolean isRemove(){ boolean is; if (m_editFlag == FolderEditFlag.REMOVE) is=true; else is=false; return is; }
Devuelve <tt>true</tt> si el campo est? marcado como eliminado
public static String encodeWebSafe(byte[] source,boolean doPadding){ return encode(source,0,source.length,WEBSAFE_ALPHABET,doPadding); }
Encodes a byte array into web safe Base64 notation.
@Override public void commence(HttpServletRequest request,HttpServletResponse response,AuthenticationException arg2) throws IOException, ServletException { log.debug("Pre-authenticated entry point called. Rejecting access"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Access Denied"); }
Always returns a 401 error code to the client.
public int size(){ return _size; }
Returns the current number of entries in the map.
private List<Volume> createVolumeData(String name,int numVolumes){ List<Volume> volumes=new ArrayList<Volume>(); URI cgUri=createBlockConsistencyGroup(name + "-cg"); for (int i=1; i <= numVolumes; i++) { Volume volume=new Volume(); URI volumeURI=URIUtil.createId(Volume.class); testVolumeURIs.add(volumeURI); volume.setId(volumeURI); volume.setLabel(name + i); volume.setConsistencyGroup(cgUri); _dbClient.createObject(volume); } return volumes; }
Creates the BlockObject Volume data.
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 static void closeStream(Closeable stream){ if (stream != null) { try { stream.close(); } catch ( IOException e) { android.util.Log.e("IO","Could not close stream",e); } } }
Closes the specified stream.
private static BufferedImage loadImage(final IdocScanInterface ui,int finalWidth,int finalHeight){ return loadImage(ui,finalWidth,finalHeight,0); }
Muestra la imagen seleccionada de la lista en el visor del applet a escala real
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 void configure(){ XpaSystemConnectionMemo memo=((XpaSystemConnectionMemo)getSystemConnectionMemo()); XpaTrafficController tc=memo.getXpaTrafficController(); tc.connectPort(this); memo.setPowerManager(new jmri.jmrix.xpa.XpaPowerManager(tc)); jmri.InstanceManager.store(memo.getPowerManager(),jmri.PowerManager.class); memo.setTurnoutManager(new jmri.jmrix.xpa.XpaTurnoutManager(memo)); jmri.InstanceManager.store(memo.getTurnoutManager(),jmri.TurnoutManager.class); memo.setThrottleManager(new jmri.jmrix.xpa.XpaThrottleManager(memo)); jmri.InstanceManager.store(memo.getThrottleManager(),jmri.ThrottleManager.class); tc.startTransmitThread(); sinkThread=new Thread(tc); sinkThread.start(); }
set up all of the other objects to operate with an XPA+Modem Connected to an XPressNet based command station connected to this port
public void executeQuery(IMiniTable miniTable){ log.info(""); String sql=""; if (m_DD_Order_ID == null) return; sql=getOrderSQL(); log.fine(sql); int row=0; miniTable.setRowCount(row); try { PreparedStatement pstmt=DB.prepareStatement(sql.toString(),null); pstmt.setInt(1,Integer.parseInt(m_DD_Order_ID.toString())); ResultSet rs=pstmt.executeQuery(); while (rs.next()) { miniTable.setRowCount(row + 1); miniTable.setValueAt(new IDColumn(rs.getInt(1)),row,0); miniTable.setValueAt(rs.getBigDecimal(2),row,1); miniTable.setValueAt(rs.getString(3),row,2); miniTable.setValueAt(rs.getString(4),row,4); miniTable.setValueAt(rs.getString(5),row,3); miniTable.setValueAt(rs.getString(6),row,5); row++; } rs.close(); pstmt.close(); } catch ( SQLException e) { log.log(Level.SEVERE,sql.toString(),e); } miniTable.autoSize(); }
Query Info
public ParameterDatabase(){ super(); accessed=new Hashtable(); gotten=new Hashtable(); directory=new File(new File("").getAbsolutePath()); label="Basic Database"; parents=new Vector(); checked=false; }
Creates an empty parameter database.
private CTagHelpers(){ }
You are not supposed to instantiate this class.
public EventSourceImpl(){ LOG.entering(CLASS_NAME,"<init>"); }
EventSource provides a text-based stream abstraction for Java
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:25.281 -0500",hash_original_method="8F9A0D25038BAA53AA87BFFA0D47316A",hash_generated_method="D647B858B68B1333AC193E85FEBDEE73") public static void registrationComplete(){ synchronized (mHandlerMap) { mRegistrationComplete=true; mHandlerMap.notifyAll(); } }
The application must call here after it finishes registering handlers.
public long next(){ return next(RecurrenceUtil.now()); }
Returns the next recurrence from now.
@Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); mbr.writeExternal(out); }
Calls the super method and writes the MBR object of this entry to the specified output stream.
protected void validate_return(StorageCapability[] param){ }
validate the array for _return
public static String jQuote(String s){ if (s == null) { return "null"; } int ln=s.length(); StringBuilder b=new StringBuilder(ln + 4); b.append('"'); for (int i=0; i < ln; i++) { char c=s.charAt(i); if (c == '"') { b.append("\\\""); } else if (c == '\\') { b.append("\\\\"); } else if (c < 0x20) { if (c == '\n') { b.append("\\n"); } else if (c == '\r') { b.append("\\r"); } else if (c == '\f') { b.append("\\f"); } else if (c == '\b') { b.append("\\b"); } else if (c == '\t') { b.append("\\t"); } else { b.append("\\u00"); int x=c / 0x10; b.append(toHexDigit(x)); x=c & 0xF; b.append(toHexDigit(x)); } } else { b.append(c); } } b.append('"'); return b.toString(); }
Quotes string as Java Language string literal. Returns string <code>"null"</code> if <code>s</code> is <code>null</code>.
public FluentFunction<T3,R> partiallyApply(final T1 param1,final T2 param2){ return new FluentFunction<>(PartialApplicator.partial3(param1,param2,fn)); }
Partially apply the provided parameters to this BiFunction to generate a Function (single input)
public static boolean deleteFile(String path){ if (Handler_String.isBlank(path)) { return true; } File file=new File(path); if (!file.exists()) { return true; } if (file.isFile()) { return file.delete(); } if (!file.isDirectory()) { return false; } for ( File f : file.listFiles()) { if (f.isFile()) { f.delete(); } else if (f.isDirectory()) { deleteFile(f.getAbsolutePath()); } } return file.delete(); }
delete file or directory <ul> <li>if path is null or empty, return true</li> <li>if path not exist, return true</li> <li>if path exist, delete recursion. return true</li> <ul>
private ImmutableSet<CassandraJmxCompactionClient> createCompactionClients(CassandraJmxCompactionConfig jmxConfig){ Set<CassandraJmxCompactionClient> clients=Sets.newHashSet(); Set<InetSocketAddress> servers=config.servers(); int jmxPort=jmxConfig.port(); for ( InetSocketAddress addr : servers) { CassandraJmxCompactionClient client=createCompactionClient(addr.getHostString(),jmxPort,jmxConfig.username(),jmxConfig.password()); clients.add(client); } return ImmutableSet.copyOf(clients); }
Return an empty set if no client can be created.
public static String hashKeyForDisk(String key){ String cacheKey; try { final MessageDigest mDigest=MessageDigest.getInstance("MD5"); mDigest.update(key.getBytes()); cacheKey=bytesToHexString(mDigest.digest()); } catch ( NoSuchAlgorithmException e) { cacheKey=String.valueOf(key.hashCode()); } return cacheKey; }
A hashing method that changes a string (like a URL) into a hash suitable for using as a disk filename.
@Nullable public String space(){ return space; }
Gets swap space name.
public Object runSafely(Catbert.FastStack stack) throws Exception { SeriesInfo si=getSeriesInfo(stack); return si == null ? "" : si.getDescription(); }
Returns the description for the specified SeriesInfo
public UserEntry restoreUser(String username) throws AppsForYourDomainException, ServiceException, IOException { LOGGER.log(Level.INFO,"Restoring user '" + username + "'."); URL retrieveUrl=new URL(domainUrlBase + "user/" + SERVICE_VERSION+ "/"+ username); UserEntry userEntry=userService.getEntry(retrieveUrl,UserEntry.class); userEntry.getLogin().setSuspended(false); URL updateUrl=new URL(domainUrlBase + "user/" + SERVICE_VERSION+ "/"+ username); return userService.update(updateUrl,userEntry); }
Restores a user. Note that executing this method for a user who is not suspended has no effect.
private Class(RVMType type){ this.type=type; }
Prevents this class from being instantiated, except by the create method in this class.
public double weightedFMeasure(){ double[] classCounts=new double[m_NumClasses]; double classCountSum=0; for (int i=0; i < m_NumClasses; i++) { for (int j=0; j < m_NumClasses; j++) { classCounts[i]+=m_ConfusionMatrix[i][j]; } classCountSum+=classCounts[i]; } double fMeasureTotal=0; for (int i=0; i < m_NumClasses; i++) { double temp=fMeasure(i); fMeasureTotal+=(temp * classCounts[i]); } return fMeasureTotal / classCountSum; }
Calculates the macro weighted (by class size) average F-Measure.
@DSSafe(DSCat.DATA_STRUCTURE) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:08.711 -0500",hash_original_method="05A7D65C6D911E0B1F3261A66888CB52",hash_generated_method="3AFFFBA2DDE5D54646A6F203B3BBAF40") public int lastIndexOf(Object obj){ return this.hlist.lastIndexOf(obj); }
Get the last index of the given object.
public Builder showNextButton(boolean showNextButton){ this.showNextButton=showNextButton; return this; }
Set the visibility of the next button
public static ValueLobDb createSmallLob(int type,byte[] small,long precision){ return new ValueLobDb(type,small,precision); }
Create a LOB object that fits in memory.
public void invDct8x8(double[][] input,int[][] output){ double[][] temp=new double[NJPEG][NJPEG]; double temp1=0.0; int i=0; int j=0; int k=0; for (i=0; i < NJPEG; i++) { for (j=0; j < NJPEG; j++) { temp[i][j]=0.0; for (k=0; k < NJPEG; k++) { temp[i][j]+=input[i][k] * this.C[k][j]; } } } for (i=0; i < NJPEG; i++) { for (j=0; j < NJPEG; j++) { temp1=0.0; for (k=0; k < NJPEG; k++) { temp1+=this.Ct[i][k] * temp[k][j]; } temp1+=128.0; output[i][j]=ImageUtil.pixelRange(round(temp1)); } } }
Perform inverse DCT on the 8x8 matrix
public static InputStream openDataFile(){ InputStream stream=SantaFeExample.class.getResourceAsStream("santafe.trail"); if (stream == null) { System.err.println("Unable to find the file santafe.trail."); System.exit(-1); } return stream; }
Returns an input stream that contains the ant trail data file.
public ProductionRule(final String name,final GameData data,final IntegerMap<NamedAttachable> results,final IntegerMap<Resource> costs){ super(name,data); m_results=results; m_cost=costs; }
Creates new ProductionRule
public RootConfiguration(ApplicationInformation ai){ this(ai,getDefaultContexts(applicationClass(ai,CommonUtils.getCallingClass(2)))); }
Initializes the root configuration with default context relative to the calling (instantiating class).
public void addString(String word,Tuple t){ TrieLeaf leaf=new TrieLeaf(word,t); addLeaf(root,leaf,0); }
Add a new word to the trie, associated with the given Tuple.
public void waitOnInitialization() throws InterruptedException { this.initializationLatch.await(); }
Wait for the tracker to finishe being initialized
@Override public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchPart viewPart=HandlerUtil.getActivePart(event); if (viewPart instanceof DroidsafeInfoOutlineViewPart) { Command command=event.getCommand(); boolean oldValue=HandlerUtil.toggleCommandState(command); ((DroidsafeInfoOutlineViewPart)viewPart).setLongLabel(!oldValue); } return null; }
Command implementation. Retrieves the value of the parameter value, and delegates to the view to set the correct value for the methods labels.
@Override protected EClass eStaticClass(){ return UmplePackage.eINSTANCE.getCodeLang_(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private static byte[] streamToBytes(InputStream in,int length) throws IOException { byte[] bytes=new byte[length]; int count; int pos=0; while (pos < length && ((count=in.read(bytes,pos,length - pos)) != -1)) { pos+=count; } if (pos != length) { throw new IOException("Expected " + length + " bytes, read "+ pos+ " bytes"); } return bytes; }
Reads the contents of an InputStream into a byte[].
public void testUpdatePathDoesNotExist() throws Exception { final Map<String,String> props=properties("owner","group","0555"); assert igfs.update(SUBDIR,props) == null; checkNotExist(igfs,igfsSecondary,SUBDIR); }
Check that exception is thrown in case the path being updated doesn't exist remotely.
public void stopProcess() throws InterruptedException { latch.await(); if (this.process != null) { System.out.println("ProcessThread.stopProcess() will kill process"); this.process.destroy(); } }
Stops the process.