code
stringlengths
10
174k
nl
stringlengths
3
129k
private static char CallStaticCharMethodV(JNIEnvironment env,int classJREF,int methodID,Address argAddress) throws Exception { if (traceJNI) VM.sysWrite("JNI called: CallStaticCharMethodV \n"); RuntimeEntrypoints.checkJNICountDownToGC(); try { Object returnObj=JNIHelpers.invokeWithVarArg(methodID,argAddress,TypeReference.Char); return Reflection.unwrapChar(returnObj); } catch ( Throwable unexpected) { if (traceJNI) unexpected.printStackTrace(System.err); env.recordException(unexpected); return 0; } }
CallStaticCharMethodV: invoke a static method that returns a char value
public void clip(Shape s){ mGraphics.clip(s); }
Intersects the current clip with the interior of the specified Shape and sets the current clip to the resulting intersection. The indicated shape is transformed with the current transform in the Graphics2D state before being intersected with the current clip. This method is used to make the current clip smaller. To make the clip larger, use any setClip method.
public void mark(int value){ buffer.mark(value); }
Mark the current position in the buffer, so that a later call to <code>reset</code> will return here.
public void afterLoadPreferences(Properties ctx){ int AD_Client_ID=Env.getAD_Client_ID(ctx); for (int i=0; i < m_validators.size(); i++) { ModelValidator validator=(ModelValidator)m_validators.get(i); if (AD_Client_ID == validator.getAD_Client_ID() || m_globalValidators.contains(validator)) { java.lang.reflect.Method m=null; try { m=validator.getClass().getMethod("afterLoadPreferences",new Class[]{Properties.class}); } catch ( NoSuchMethodException e) { } try { if (m != null) m.invoke(validator,ctx); } catch ( Exception e) { log.warning("" + validator + ": "+ e.getLocalizedMessage()); } } } }
After Load Preferences into Context for selected client.
private void cmd_EFT(){ ValueNamePair pp=(ValueNamePair)fPaymentRule.getSelectedItem(); if (pp == null) return; String PaymentRule=pp.getValue(); log.info(PaymentRule); if (!getChecks(PaymentRule)) return; dispose(); }
Create EFT payment
@Override public void addValue(double value,double weight){ m_WeightedSum+=value * weight; m_WeightedSumSquared+=value * value * weight; m_SumOfWeights+=weight; if (m_TM.get(value) == null) { m_TM.put(value,weight); } else { m_TM.put(value,m_TM.get(value) + weight); } if (!getUpdateWeightsOnly()) { m_Boundaries=null; } m_Weights=null; }
Adds a value to the density estimator.
public static DefaultNonListCollectionAdapter adapt(Collection collection,ObjectWrapperWithAPISupport wrapper){ return new DefaultNonListCollectionAdapter(collection,wrapper); }
Factory method for creating new adapter instances.
@Override public void agg(Object newVal){ valueSet.add(newVal instanceof Long ? (Long)newVal : Long.valueOf(newVal.toString())); firstTime=false; }
Distinct Aggregate function which update the Distinct set
public void executeFirst(Runnable task){ synchronized (internalLock) { queue.addFirst(task); } startQueueWorker(); }
Prepends a task to the front of the queue and makes sure a worker thread is running, unless the queue has been suspended.
public static String generateXpaytoken(String resourcePath,String queryString,String requestBody) throws SignatureException { String timestamp=timeStamp(); String beforeHash=timestamp + resourcePath + queryString+ requestBody; String hash=hmacSha256Digest(beforeHash); String token="xv2:" + timestamp + ":"+ hash; return token; }
Generate X-Pay-Token as x:+ TimestampUTC + : + SHA256Hash
public StartRecordingKillsAction(final String questSlot,@Dev(defaultValue="1") final int index,final Map<String,Pair<Integer,Integer>> toKill){ this.toKill=checkNotNull(toKill); this.questname=checkNotNull(questSlot); this.index=index; }
Creates a new StartRecordingKillsAction.
public List<InstrumentHeader> createInstrument(final List<Map<String,Object>> paramList){ final List<InstrumentHeader> instrumentHeaderList=instrumentService.addToInstrument(paramList); return instrumentHeaderList; }
Create Instrument Header for list of HashMap of instrument header properties
public boolean removeIndex(String field){ ColumnEntry e=(ColumnEntry)m_entries.get(field); if (e == null) { throw new IllegalArgumentException("Unknown column name: " + field); } if (e.index == null) { return false; } else { e.index.dispose(); e.index=null; return true; } }
Remove the Index associated with the given data field / column name.
public void rollIn(Operator operator){ map.put(operator,new InterpolatedValue(false,getValue(operator))); if (!timer.isRunning()) { timer.start(); } }
Starts interpolating the extension value for the given operator in the opposite direction, starting with the current value.
private RexNode convertUsing(SqlValidatorNamespace leftNamespace,SqlValidatorNamespace rightNamespace,List<String> nameList){ final List<RexNode> list=Lists.newArrayList(); for ( String name : nameList) { List<RexNode> operands=new ArrayList<>(); int offset=0; for ( SqlValidatorNamespace n : ImmutableList.of(leftNamespace,rightNamespace)) { final RelDataType rowType=n.getRowType(); final RelDataTypeField field=catalogReader.field(rowType,name); operands.add(rexBuilder.makeInputRef(field.getType(),offset + field.getIndex())); offset+=rowType.getFieldList().size(); } list.add(rexBuilder.makeCall(SqlStdOperatorTable.EQUALS,operands)); } return RexUtil.composeConjunction(rexBuilder,list,false); }
Returns an expression for matching columns of a USING clause or inferred from NATURAL JOIN. "a JOIN b USING (x, y)" becomes "a.x = b.x AND a.y = b.y". Returns null if the column list is empty.
public Boolean interimResults(){ return interimResults; }
Gets the interim results.
public MimeType(String s){ parse(s); }
Construct a new MIME type object from the given string. The given string is converted into canonical form and stored internally.
private DeclarationListener(Declaration decl){ this.declarationType=decl; declarations=new ArrayList<>(); }
Creates a DeclarationListener object.
public void hierarchyChanged(HierarchyEvent e){ ((HierarchyListener)a).hierarchyChanged(e); ((HierarchyListener)b).hierarchyChanged(e); }
Handles the hierarchyChanged event by invoking the hierarchyChanged methods on listener-a and listener-b.
protected BasicAttributeModifier(UUID uuid,String name,double value,ModifierOperation operation,ModifierSlot slot,AttributeType type){ Validate.notNull(operation,"Operation can't be null."); this.uuid=(uuid == null) ? UUID.randomUUID() : uuid; this.name=name; this.value=value; this.operation=operation; this.slot=slot; this.type=type; }
Construct new BasicAttributeModifier.
public static void main(final String[] args){ DOMTestCase.doMain(processinginstructionsetdatanomodificationallowederr.class,args); }
Runs this test from the command line.
@Override public String toString(){ return super.toString() + ", ids: " + ids.size()+ ", d_min: "+ d_min+ ", d_max "+ d_max; }
Returns a String representation of the HyperBoundingBox.
protected boolean isValidQName(String prefix,String local,boolean xml11Version){ if (local == null) return false; boolean validNCName=false; if (!xml11Version) { validNCName=(prefix == null || XMLChar.isValidNCName(prefix)) && XMLChar.isValidNCName(local); } else { validNCName=(prefix == null || XML11Char.isXML11ValidNCName(prefix)) && XML11Char.isXML11ValidNCName(local); } return validNCName; }
Taken from org.apache.xerces.dom.CoreDocumentImpl Checks if the given qualified name is legal with respect to the version of XML to which this document must conform.
public void addSplashScreenLoadingCompletion(double percentage){ if (splashScreen != null) { splashScreen.addLoadingCompletion(percentage); } }
Add the curent loading completion
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:41.557 -0500",hash_original_method="E2FC40814B9169B5CD5C50C2FA8F907C",hash_generated_method="5DD0BD6D57B1D4C166366483EC7A0A8A") public static int encode(byte[] data,int off,int length,OutputStream out) throws IOException { return encoder.encode(data,off,length,out); }
Encode the byte data to base 64 writing it to the given output stream.
private boolean routeUsingOneTrain(Train testTrain,Car car,Car clone){ addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterTrainCanTransport"),new Object[]{testTrain.getName(),car.toString(),car.getTrack().getTrackTypeName(),car.getLocationName(),car.getTrackName(),clone.getDestinationName(),clone.getDestinationTrackName()})); if (_addtoReport) { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterRoute1TrainsForCar"),new Object[]{car.toString(),car.getLocationName(),car.getTrackName(),testTrain.getName(),clone.getDestinationName(),clone.getDestinationTrackName()})); } if (_train != null && _train != testTrain) { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("TrainDoesNotServiceCar"),new Object[]{_train.getName(),car.toString(),clone.getDestinationName(),clone.getDestinationTrackName()})); if (!_train.getServiceStatus().equals(Train.NONE)) { addLine(_buildReport,SEVEN,_train.getServiceStatus()); } _status=STATUS_NOT_THIS_TRAIN; return true; } _status=car.setDestination(clone.getDestination(),clone.getDestinationTrack()); if (_status.equals(Track.OKAY)) { return true; } addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterCanNotDeliverCar"),new Object[]{car.toString(),clone.getDestinationName(),clone.getDestinationTrackName(),_status,(clone.getDestinationTrack() == null ? Bundle.getMessage("RouterDestination") : clone.getDestinationTrack().getTrackTypeName())})); if ((_status.startsWith(Track.LENGTH) || _status.startsWith(Track.SCHEDULE)) && clone.getDestinationTrack() != null && clone.getDestinationTrack().getAlternateTrack() != null && clone.getDestinationTrack().getAlternateTrack() != car.getTrack()) { String status=car.setDestination(clone.getDestination(),clone.getDestinationTrack().getAlternateTrack()); if (status.equals(Track.OKAY)) { if (_train == null || _train.services(car)) { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterSendCarToAlternative"),new Object[]{car.toString(),clone.getDestinationTrack().getAlternateTrack().getName(),clone.getDestination().getName()})); return true; } addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterNotSendCarToAlternative"),new Object[]{_train.getName(),car.toString(),clone.getDestinationTrack().getAlternateTrack().getName(),clone.getDestination().getName()})); } else { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterAlternateFailed"),new Object[]{clone.getDestinationTrack().getAlternateTrack().getName(),status})); } } else if (clone.getDestinationTrack() != null && clone.getDestinationTrack().getAlternateTrack() != null && clone.getDestinationTrack().getAlternateTrack() == car.getTrack()) { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterAtAlternate"),new Object[]{car.toString(),clone.getDestinationTrack().getAlternateTrack().getName(),clone.getLocationName(),clone.getDestinationTrackName()})); } else if (car.getLocation() == clone.getDestination()) { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterIgnoreAlternate"),new Object[]{car.toString(),car.getLocationName()})); } if (Setup.isForwardToYardEnabled() && _status.startsWith(Track.LENGTH) && car.getLocation() != clone.getDestination()) { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterSpurFull"),new Object[]{clone.getDestinationTrackName(),clone.getDestinationName()})); Location dest=clone.getDestination(); List<Track> yards=dest.getTrackByMovesList(Track.YARD); log.debug("Found {} yard(s) at destination ({})",yards.size(),clone.getDestinationName()); for ( Track track : yards) { String status=car.setDestination(dest,track); if (status.equals(Track.OKAY)) { if (_train != null && !_train.services(car)) { log.debug("Train ({}) can not deliver car ({}) to yard ({})",_train.getName(),car.toString(),track.getName()); continue; } addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterSendCarToYard"),new Object[]{car.toString(),track.getName(),dest.getName()})); return true; } else { addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterCanNotUseYard"),new Object[]{track.getName(),status})); } } addLine(_buildReport,SEVEN,MessageFormat.format(Bundle.getMessage("RouterNoYardTracks"),new Object[]{dest.getName(),car.toString()})); } car.setDestination(null,null); if (car.getTrack().getTrackType().equals(Track.STAGING)) { log.debug("Car ({}) departing staging, single train can't deliver car to ({}, {})",car.toString(),clone.getDestinationName(),clone.getDestinationTrackName()); return false; } return true; }
A single train can service the car. Provide various messages to build report detailing which train can service the car. Also checks to see if the needs to go the alternate track or yard track if the car's final destination track is full. Returns false if car is stuck in staging.
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
protected void uninstallListeners(){ progressBar.removeChangeListener(changeListener); progressBar.removePropertyChangeListener(getHandler()); handler=null; }
Removes all listeners installed by this object.
public void logStatistics(){ for ( QueryStatistic statistic : queryStatistics) { LOGGER.statistic(statistic.getStatistics(queryIWthTask)); } }
Below method will be used to log the statistic
public ImageFetcher(Context context,int imageSize){ super(context,imageSize); init(context); }
Initialize providing a single target image size (used for both width and height);
public static void main(String[] args) throws FloodlightModuleException { System.setProperty("org.restlet.engine.loggerFacadeClass","org.restlet.ext.slf4j.Slf4jLoggerFacade"); CmdLineSettings settings=new CmdLineSettings(); CmdLineParser parser=new CmdLineParser(settings); try { parser.parseArgument(args); } catch ( CmdLineException e) { parser.printUsage(System.out); System.exit(1); } FloodlightModuleLoader fml=new FloodlightModuleLoader(); IFloodlightModuleContext moduleContext=fml.loadModulesFromConfig(settings.getModuleFile()); IRestApiService restApi=moduleContext.getServiceImpl(IRestApiService.class); restApi.run(); IFloodlightProviderService controller=moduleContext.getServiceImpl(IFloodlightProviderService.class); controller.run(); }
Main method to load configuration and modules
@Subscribe(threadMode=ThreadMode.ASYNC) public void onInitDbEvent(InitDbEvent event){ if (FlavorUtils.isPoiStorage()) { Timber.d("Initializing database ..."); syncDownloadPoiTypes(); bus.postSticky(new DbInitializedEvent()); } }
Initialize the database if the Flavor is PoiStorage.
private boolean isRequiredFields(){ String fieldRequired=getString(R.string.Required_field); boolean nameCheck=Utils.checkTextInputLayoutValueRequirement(nameInputWrapper,fieldRequired); boolean streetCheck=Utils.checkTextInputLayoutValueRequirement(streetInputWrapper,fieldRequired); boolean houseNumberCheck=Utils.checkTextInputLayoutValueRequirement(houseNumberInputWrapper,fieldRequired); boolean cityCheck=Utils.checkTextInputLayoutValueRequirement(cityInputWrapper,fieldRequired); boolean zipCheck=Utils.checkTextInputLayoutValueRequirement(zipInputWrapper,fieldRequired); boolean phoneCheck=Utils.checkTextInputLayoutValueRequirement(phoneInputWrapper,fieldRequired); boolean emailCheck=Utils.checkTextInputLayoutValueRequirement(emailInputWrapper,fieldRequired); return nameCheck && streetCheck && houseNumberCheck&& cityCheck&& zipCheck&& phoneCheck&& emailCheck; }
Check if all input fields are filled. Method highlights all unfilled input fields.
public String toString(){ String result=""; if (tag != 5) { result+="[" + tag + "] "; } result+="NULL"; switch (tag) { case errNoSuchObjectTag: result+=" (noSuchObject)"; break; case errNoSuchInstanceTag: result+=" (noSuchInstance)"; break; case errEndOfMibViewTag: result+=" (endOfMibView)"; break; } return result; }
Converts the <CODE>NULL</CODE> value to its ASN.1 <CODE>String</CODE> form. When the tag is not the universal one, it is preprended to the <CODE>String</CODE> form.
protected int checkGridCellSizes(int size,long numcell){ int tcount=0; int hasmin=0; double sqcount=0; for (TLongObjectIterator<ModifiableDBIDs> it=grid.iterator(); it.hasNext(); ) { it.advance(); final int s=it.value().size(); if (s >= size >> 1) { LOG.warning("A single cell contains half of the database (" + s + " objects). This will not scale very well."); } tcount+=s; sqcount+=s * (long)s; if (s >= minpts) { hasmin++; } } double savings=sqcount / size / size; if (savings >= 1) { LOG.warning("Pairwise distances within each cells are more expensive than a full DBSCAN run due to overlap!"); } if (overflown) { LOG.statistics(new StringStatistic(GriDBSCAN.class.getName() + ".all-cells","overflow")); } else { LOG.statistics(new LongStatistic(GriDBSCAN.class.getName() + ".all-cells",numcell)); } LOG.statistics(new LongStatistic(GriDBSCAN.class.getName() + ".used-cells",grid.size())); LOG.statistics(new LongStatistic(GriDBSCAN.class.getName() + ".minpts-cells",hasmin)); LOG.statistics(new DoubleStatistic(GriDBSCAN.class.getName() + ".redundancy",tcount / (double)size)); LOG.statistics(new DoubleStatistic(GriDBSCAN.class.getName() + ".relative-cost",savings)); return hasmin; }
Perform some sanity checks on the grid cells.
public XmlSlurper() throws ParserConfigurationException, SAXException { this(false,true); }
Creates a non-validating and namespace-aware <code>XmlSlurper</code> which does not allow DOCTYPE declarations in documents.
@Deprecated @Override public void putAll(Map<? extends TypeToken<? extends B>,? extends B> map){ throw new UnsupportedOperationException(); }
Guaranteed to throw an exception and leave the map unmodified.
void transfer(Entry<K,V>[] newTable){ int newCapacity=newTable.length; for ( Entry<K,V> e : table) { while (null != e) { Entry<K,V> next=e.next; int i=indexFor(e.hash,newCapacity); e.next=newTable[i]; newTable[i]=e; e=next; } } }
Transfers all entries from current table to newTable.
int frequency(int key){ for (int slot=key & mask; ; slot=(slot + 1) & mask) { if (keys[slot] == key) { return freqs[slot]; } else if (freqs[slot] == 0) { return 0; } } }
Return the frequency of the give key in the bag.
public static <ST>boolean contains(LinkedNode<ST> node,ST value){ while (node != null) { if (node.value() == value) { return true; } node=node.next(); } return false; }
Convenience method that can be used to check if a linked list with given head node (which may be null to indicate empty list) contains given value
public void createDefaultState(final String fileContentDescription,final int numberOfLines,final int tabSize){ setFileType(fileContentDescription); }
Creates an initial state, before actual data is available.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:38:00.087 -0500",hash_original_method="408B8A2F6473D1390F4BD92FAF80FE83",hash_generated_method="16646E13182984A5B04207C46B29C805") public static final boolean isValidCommand(int code){ return (code <= __FIRST_COMMAND && code >= __LAST_COMMAND); }
Determines if a given command code is valid. Returns true if valid, false if not. <p>
public BasicBlock labelToBlock(int label){ int idx=indexOfLabel(label); if (idx < 0) { throw new IllegalArgumentException("no such label: " + Hex.u2(label)); } return get(idx); }
Gets the first block in the list with the given label, if any.
public void addHost(String port,MACAddress host){ this.portToMac.put(port,host); return; }
Adds a host to this network record
public boolean isFree(){ return type == PriceModelType.FREE_OF_CHARGE; }
Checks whether customers are not charged for the service.
public int translateDBColumnType(String type){ try { String value=PROPERTIES.getProperty(type); String typeUnderscore=type.replaceAll(" ","_"); if (value == null) { value=PROPERTIES.getProperty(typeUnderscore); } return Integer.parseInt(value); } catch ( NumberFormatException e) { throw new IllegalArgumentException("Unknown data type: " + type + ". "+ "Add entry in "+ PROPERTY_FILE+ ".\n"+ "If the type contains blanks, either escape them with a backslash "+ "or use underscores instead of blanks."); } }
translates the column data type string to an integer value that indicates which data type / get()-Method to use in order to retrieve values from the database (see DatabaseUtils.Properties, InstanceQuery()). Blanks in the type are replaced with underscores "_", since Java property names can't contain blanks.
public boolean equals(Object obj){ if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } Map map=(Map)obj; if (map.size() != size()) { return false; } MapIterator it=mapIterator(); try { while (it.hasNext()) { Object key=it.next(); Object value=it.getValue(); if (value == null) { if (map.get(key) != null || map.containsKey(key) == false) { return false; } } else { if (value.equals(map.get(key)) == false) { return false; } } } } catch ( ClassCastException ignored) { return false; } catch ( NullPointerException ignored) { return false; } return true; }
Compares this map with another.
public boolean isSetTriggerId(){ return EncodingUtils.testBit(issetBitfield,TRIGGERID_ISSET_ID); }
Returns true if field triggerId is set (has been assigned a value) and false otherwise
private void attachPlot(SVGPlot newplot){ this.plot=newplot; if (newplot == null) { super.setSVGDocument(null); return; } newplot.synchronizeWith(synchronizer); super.setSVGDocument(newplot.getDocument()); super.setDisableInteractions(newplot.getDisableInteractions()); }
Attach to a new plot, and display.
@Override public boolean hasPermission(Authentication auth,Object targetDomainObject,Object permission){ log.debug("Checking whether " + auth + "\n has "+ permission+ " permission for "+ targetDomainObject); if (targetDomainObject == null) return true; VersionedEntity<U,ID> entity=(VersionedEntity<U,ID>)targetDomainObject; return entity.hasPermission(LemonUtil.getUser(auth),(String)permission); }
Called by Spring Security to evaluate the permission
public static URL resolveClassPathOrURLResource(String resourceName,String urlOrClasspathResource){ URL url; try { url=new URL(urlOrClasspathResource); } catch ( MalformedURLException ex) { url=getClasspathResourceAsURL(resourceName,urlOrClasspathResource); } return url; }
Resolve a resource into a URL using the URL string or classpath-relative filename and using a name for any exceptions thrown.
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 final String asciiBoard(Position pos){ StringBuilder ret=new StringBuilder(400); String nl=String.format(Locale.US,"%n"); ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl); for (int y=7; y >= 0; y--) { ret.append(" |"); for (int x=0; x < 8; x++) { ret.append(' '); int p=pos.getPiece(Position.getSquare(x,y)); if (p == Piece.EMPTY) { boolean dark=Position.darkSquare(x,y); ret.append(dark ? ".. |" : " |"); } else { ret.append(Piece.isWhite(p) ? ' ' : '*'); String pieceName=pieceToChar(p); if (pieceName.length() == 0) pieceName="P"; ret.append(pieceName); ret.append(" |"); } } ret.append(nl); ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl); } return ret.toString(); }
Create an ascii representation of a position.
@Override public synchronized void remove(String key){ boolean deleted=getFileForKey(key).delete(); removeEntry(key); if (!deleted) { VolleyLog.d("Could not delete cache entry for key=%s, filename=%s",key,getFilenameForKey(key)); } }
Removes the specified key from the cache if it exists.
public TransitionData(S source,S target,Long period,Integer count,Collection<Action<S,E>> actions,Guard<S,E> guard,TransitionKind kind){ this(source,target,null,null,period,count,actions,guard,kind,null); }
Instantiates a new transition data.
public ProgressStatusEvent(List<String> progressTypes){ super(Events.PROGRESS_STATUS_CHANGE); put("data",progressTypes); }
creates a new ProgressStatusEvent
@Override public String toString(){ return toString(MAX_NUMBER_OF_ITEMSETS); }
This method generates the a string representation of this object.
void copyParentSets(BayesNet dest,BayesNet source){ int nNodes=source.getNrOfNodes(); for (int iNode=0; iNode < nNodes; iNode++) { dest.getParentSet(iNode).copy(source.getParentSet(iNode)); } }
copyParentSets copies parent sets of source to dest BayesNet
public long optLong(int index,long defaultValue){ try { return this.getLong(index); } catch ( Exception e) { return defaultValue; } }
Get the optional long value associated with an index. The defaultValue is returned if there is no value for the index, or if the value is not a number and cannot be converted to a number.
SelectAllAction(){ super(selectAllAction); }
Create this action with the appropriate identifier.
@Override public void removeNotify(){ super.removeNotify(); if (focusedComponent == this) { focusedComponent=null; } }
Called by the AWT when this component is removed from it's parent. This stops clears the currently focused component.
final public static float[] earthCircle(float phi1,float lambda0,float c,float s,float e,int n,float[] ret_val){ double Az, cosAz, sinAz; double cosphi1=Math.cos(phi1); double sinphi1=Math.sin(phi1); double sinc=Math.sin(c); double cosc=Math.cos(c); if (n < 2) n=2; int end=n << 1; if (ret_val == null || end > ret_val.length) { ret_val=new float[end]; } double inc=e / (n - 1); Az=s; for (int i=0; i < end; i+=2, Az+=inc) { cosAz=Math.cos(Az); sinAz=Math.sin(Az); ret_val[i]=(float)Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz); ret_val[i + 1]=(float)Math.atan2(sinc * sinAz,cosphi1 * cosc - sinphi1 * sinc * cosAz) + lambda0; } return ret_val; }
Calculate earth circle in the sphere. <p> Returns n float lat,lon pairs at arc distance c from point at phi1,lambda0. <p>
protected void sendEvidences(final String basePath) throws TransportException, ProtocolException { if (Cfg.DEBUG) { Check.log(TAG + " Info: sendEvidences from: " + basePath); } final EvidenceCollector logCollector=EvidenceCollector.self(); final Vector dirs=logCollector.scanForDirLogs(basePath); final int dsize=dirs.size(); if (Cfg.DEBUG) { Check.log(TAG + " sendEvidences #directories: " + dsize); } for (int i=0; i < dsize; ++i) { final String dir=(String)dirs.elementAt(i); final String[] logs=logCollector.scanForEvidences(basePath,dir); final int lsize=logs.length; if (Cfg.DEBUG) { Check.log(TAG + " dir: " + dir+ " #evidences: "+ lsize); } final byte[] evidenceSize=new byte[12]; System.arraycopy(ByteArray.intToByteArray(lsize),0,evidenceSize,0,4); byte[] response=command(Proto.EVIDENCE_SIZE,evidenceSize); checkOk(response); response=null; for ( final String logName : logs) { final String fullLogName=basePath + dir + logName; final AutoFile file=new AutoFile(fullLogName); if (!file.exists()) { if (Cfg.DEBUG) { Check.log(TAG + " Error: File doesn't exist: " + fullLogName); } continue; } if (file.getSize() > Cfg.PROTOCOL_CHUNK) { sendResumeEvidence(file); } else { sendEvidence(file); } } if (!Path.removeDirectory(basePath + dir)) { if (Cfg.DEBUG) { Check.log(TAG + " Warn: " + "Not empty directory"); } } } }
Send evidences.
private void handleShowOnFirstLaunch(){ if (mActivity != null && mDrawerLayout != null && mShowDrawerOnFirstLaunch) { SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(mActivity); if (!preferences.getBoolean(Drawer.PREF_USER_LEARNED_DRAWER,false)) { mDrawerLayout.openDrawer(mSliderLayout); SharedPreferences.Editor editor=preferences.edit(); editor.putBoolean(Drawer.PREF_USER_LEARNED_DRAWER,true); editor.apply(); } } }
helper method to handle when the drawer should be shown on the first launch
public void testDoubleMissingLast() throws IOException { Directory dir=newDirectory(); RandomIndexWriter writer=new RandomIndexWriter(random(),dir); Document doc=new Document(); writer.addDocument(doc); doc=new Document(); doc.add(new DoublePoint("value",-1.3)); doc.add(new StoredField("value",-1.3)); writer.addDocument(doc); doc=new Document(); doc.add(new DoublePoint("value",4.2333333333333)); doc.add(new StoredField("value",4.2333333333333)); writer.addDocument(doc); doc=new Document(); doc.add(new DoublePoint("value",4.2333333333332)); doc.add(new StoredField("value",4.2333333333332)); writer.addDocument(doc); IndexReader ir=UninvertingReader.wrap(writer.getReader(),Collections.singletonMap("value",Type.DOUBLE_POINT)); writer.close(); IndexSearcher searcher=newSearcher(ir,false); SortField sortField=new SortField("value",SortField.Type.DOUBLE); sortField.setMissingValue(Double.MAX_VALUE); Sort sort=new Sort(sortField); TopDocs td=searcher.search(new MatchAllDocsQuery(),10,sort); assertEquals(4,td.totalHits); assertEquals("-1.3",searcher.doc(td.scoreDocs[0].doc).get("value")); assertEquals("4.2333333333332",searcher.doc(td.scoreDocs[1].doc).get("value")); assertEquals("4.2333333333333",searcher.doc(td.scoreDocs[2].doc).get("value")); assertNull(searcher.doc(td.scoreDocs[3].doc).get("value")); TestUtil.checkReader(ir); ir.close(); dir.close(); }
Tests sorting on type double, specifying the missing value should be treated as Double.MAX_VALUE
public JobExecutionException(String msg,Throwable cause,boolean refireImmediately){ super(msg,cause); refire=refireImmediately; }
<p> Create a JobExcecutionException with the given message, and underlying exception, and the 're-fire immediately' flag set to the given value. </p>
public static int[][] makeDelayEmbeddingVector(int[] data,int k){ try { return makeDelayEmbeddingVector(data,k,k - 1,data.length - k + 1); } catch ( Exception e) { throw new RuntimeException(e); } }
Constructs all embedding vectors of size k for the data. There will be (data.length - k + 1) of these vectors returned.
public static boolean isValidName(String name){ if (name.length() == 0) return false; char ch=name.charAt(0); if (isNameStart(ch) == false) return false; for (int i=1; i < name.length(); i++) { ch=name.charAt(i); if (isName(ch) == false) { return false; } } return true; }
Check to see if a string is a valid Name according to [5] in the XML 1.0 Recommendation
public AstRoot parse(String sourceString,String sourceURI,int lineno){ if (parseFinished) throw new IllegalStateException("parser reused"); this.sourceURI=sourceURI; if (compilerEnv.isIdeMode()) { this.sourceChars=sourceString.toCharArray(); } this.ts=new TokenStream(this,null,sourceString,lineno); try { return parse(); } catch ( IOException iox) { throw new IllegalStateException(); } finally { parseFinished=true; } }
Builds a parse tree from the given source string.
public boolean hasKind(){ return getKind() != null; }
Returns whether it has the kind.
public void deleteComment(final IComment comment) throws com.google.security.zynamics.binnavi.API.disassembly.CouldntDeleteException { try { m_function.deleteGlobalComment(comment); } catch ( final CouldntDeleteException exception) { throw new com.google.security.zynamics.binnavi.API.disassembly.CouldntDeleteException(exception); } }
Delete a function comment.
public void testOrder(){ SubmissionPublisher<Integer> p=basicPublisher(); TestSubscriber s1=new TestSubscriber(); TestSubscriber s2=new TestSubscriber(); p.subscribe(s1); p.subscribe(s2); for (int i=1; i <= 20; ++i) p.submit(i); p.close(); s2.awaitComplete(); s1.awaitComplete(); assertEquals(20,s2.nexts); assertEquals(1,s2.completes); assertEquals(20,s1.nexts); assertEquals(1,s1.completes); }
onNext items are issued in the same order to each subscriber
protected List<StorageUnitEntity> excludeDuplicateBusinessObjectData(List<StorageUnitEntity> storageUnitEntities,List<String> storageNames,List<StorageEntity> storageEntities) throws IllegalArgumentException { Map<BusinessObjectDataEntity,StorageUnitEntity> businessObjectDataToStorageUnitMap=new LinkedHashMap<>(); for ( StorageUnitEntity storageUnitEntity : storageUnitEntities) { BusinessObjectDataEntity businessObjectDataEntity=storageUnitEntity.getBusinessObjectData(); if (businessObjectDataToStorageUnitMap.containsKey(businessObjectDataEntity)) { if (CollectionUtils.isEmpty(storageNames)) { throw new IllegalArgumentException(String.format("Found business object data registered in more than one storage. " + "Please specify storage(s) in the request to resolve this. Business object data {%s}",businessObjectDataHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity))); } else { StorageEntity currentStorageEntity=businessObjectDataToStorageUnitMap.get(businessObjectDataEntity).getStorage(); int currentStorageIndex=storageEntities.indexOf(currentStorageEntity); int newStorageIndex=storageEntities.indexOf(storageUnitEntity.getStorage()); if (newStorageIndex < currentStorageIndex) { businessObjectDataToStorageUnitMap.put(storageUnitEntity.getBusinessObjectData(),storageUnitEntity); } } } else { businessObjectDataToStorageUnitMap.put(storageUnitEntity.getBusinessObjectData(),storageUnitEntity); } } return new ArrayList<>(businessObjectDataToStorageUnitMap.values()); }
Eliminate storage units that belong to the same business object data by picking storage unit registered in a storage listed earlier in the list of storage names specified in the request. If storage names are not specified, simply fail on business object data instances registered with multiple storages.
public OrPredicate(Predicate<T> first,Predicate<T> second){ this.first=first; this.second=second; }
Constructs a predicate that will test the first predicate and then the second.
private void createChildren(){ for ( final ITreeNode<CTag> child : m_rootTag.getChildren()) { add(new CTagTreeNode(m_parent,getGraph(),m_tagManager,m_tagsTree.getModel(),child)); } }
Creates the children of the node.
private void fillDimensionsAndMeasuresForTables(TableSchema tableSchema){ List<CarbonDimension> dimensions=new ArrayList<CarbonDimension>(); List<CarbonMeasure> measures=new ArrayList<CarbonMeasure>(); this.tableDimensionsMap.put(tableSchema.getTableName(),dimensions); this.tableMeasuresMap.put(tableSchema.getTableName(),measures); int dimensionOrdinal=0; int measureOrdinal=0; int keyOrdinal=0; int columnGroupOrdinal=-1; int previousColumnGroupId=-1; List<ColumnSchema> listOfColumns=tableSchema.getListOfColumns(); int complexTypeOrdinal=-1; for (int i=0; i < listOfColumns.size(); i++) { ColumnSchema columnSchema=listOfColumns.get(i); if (columnSchema.isDimensionColumn()) { if (columnSchema.getNumberOfChild() > 0) { CarbonDimension complexDimension=new CarbonDimension(columnSchema,dimensionOrdinal++,-1,-1,++complexTypeOrdinal); complexDimension.initializeChildDimensionsList(columnSchema.getNumberOfChild()); dimensions.add(complexDimension); dimensionOrdinal=readAllComplexTypeChildrens(dimensionOrdinal,columnSchema.getNumberOfChild(),listOfColumns,complexDimension); i=dimensionOrdinal - 1; complexTypeOrdinal=assignComplexOrdinal(complexDimension,complexTypeOrdinal); } else { if (!columnSchema.getEncodingList().contains(Encoding.DICTIONARY)) { dimensions.add(new CarbonDimension(columnSchema,dimensionOrdinal++,-1,-1,-1)); } else if (columnSchema.getEncodingList().contains(Encoding.DICTIONARY) && columnSchema.getColumnGroupId() == -1) { dimensions.add(new CarbonDimension(columnSchema,dimensionOrdinal++,keyOrdinal++,-1,-1)); } else { columnGroupOrdinal=previousColumnGroupId == columnSchema.getColumnGroupId() ? ++columnGroupOrdinal : 0; previousColumnGroupId=columnSchema.getColumnGroupId(); dimensions.add(new CarbonDimension(columnSchema,dimensionOrdinal++,keyOrdinal++,columnGroupOrdinal,-1)); } } } else { measures.add(new CarbonMeasure(columnSchema,measureOrdinal++)); } } }
Fill dimensions and measures for carbon table
public boolean matches(Class<? extends Object> clazz){ return value.equals(Tag.PREFIX + clazz.getName()); }
Check whether this tag matches the global tag for the Class
public static CharSequence cleanUp(Context context,CharSequence text){ if ((text == null) || (text.length() != 1)) { return text; } return getCleanValueFor(context,text.charAt(0)); }
Cleans up text for speech. Converts symbols to their spoken equivalents.
private boolean isTemplateNamePart(char ch){ return !Character.isWhitespace(ch) && ch != '(' && ch != ')' && ch != '{' && ch != '}' && ch != ';' && ch != '>'; }
Tells whether the given character can be part of a template name.
@Override public boolean isActive(){ return true; }
Is the scope active.
public static Map<String,Integer> sizes(){ HashMap<String,Integer> m=new HashMap<>(); m.put(State.INVENTORY.name(),inventory.size()); m.put(State.ARCHIVE.name(),archive.size()); return m; }
get the number of entries for each of the transaction states
public void decUniqueCqQuery(){ this._stats.incInt(_numUniqueCqQuery,-1); }
Decrements number of unique Queries.
private void initializeLiveAttributes(){ filterUnits=createLiveAnimatedEnumeration(null,SVG_FILTER_UNITS_ATTRIBUTE,UNITS_VALUES,(short)2); primitiveUnits=createLiveAnimatedEnumeration(null,SVG_PRIMITIVE_UNITS_ATTRIBUTE,UNITS_VALUES,(short)1); x=createLiveAnimatedLength(null,SVG_X_ATTRIBUTE,SVG_FILTER_X_DEFAULT_VALUE,SVGOMAnimatedLength.HORIZONTAL_LENGTH,false); y=createLiveAnimatedLength(null,SVG_Y_ATTRIBUTE,SVG_FILTER_Y_DEFAULT_VALUE,SVGOMAnimatedLength.VERTICAL_LENGTH,false); width=createLiveAnimatedLength(null,SVG_WIDTH_ATTRIBUTE,SVG_FILTER_WIDTH_DEFAULT_VALUE,SVGOMAnimatedLength.HORIZONTAL_LENGTH,true); height=createLiveAnimatedLength(null,SVG_HEIGHT_ATTRIBUTE,SVG_FILTER_HEIGHT_DEFAULT_VALUE,SVGOMAnimatedLength.VERTICAL_LENGTH,true); href=createLiveAnimatedString(XLINK_NAMESPACE_URI,XLINK_HREF_ATTRIBUTE); externalResourcesRequired=createLiveAnimatedBoolean(null,SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE,false); }
Initializes the live attribute values of this element.
public String[] discoverDatabases(String selected){ if (p_discovered != null) return p_discovered; p_discovered=new String[]{}; return p_discovered; }
Discover Databases. To be overwritten by database configs
public SignatureVisitor visitArrayType(){ return this; }
Visits a signature corresponding to an array type.
private Object readAttribute(InputNode node,String key) throws Exception { String name=style.getAttribute(key); InputNode child=node.getAttribute(name); if (child == null) { return null; } return root.read(child); }
This method is used to read the key value from the node. The value read from the node is resolved using the template filter. If the key value can not be found according to the annotation attributes then an null is assumed and returned.
public void testTwoStepReduceSqlQuery(){ IgniteCache<Integer,Value> cache=grid(0).cache(null); QueryCursor<List<?>> qry=cache.query(new SqlFieldsQuery("select _val from Value order by _key")); List<List<?>> all=qry.getAll(); assertEquals(KEYS,all.size()); for ( List<?> entry : all) ((Value)entry.get(0)).str="after"; check(cache); }
Test two step query value copy.
public WrapLayout(){ super(); }
Constructs a new <code>WrapLayout</code> with a left alignment and a default 5-unit horizontal and vertical gap.
public static boolean verifyPassword(long salt,byte[] hash,String password){ return Arrays.equals(calculateHash(salt,password),hash); }
Verifies that the given password corresponds to the given salt and hash.
static void autoConfigureArchitecture(JNAeratorConfig config){ String arch=System.getProperty("os.arch").toLowerCase(); if (config.verbose) { System.out.println("os.arch = " + arch); } if (arch.equals("x86_64") || arch.equals("amd64")) { config.preprocessorConfig.implicitMacros.put("TARGET_CPU_X86_64",null); config.preprocessorConfig.implicitMacros.put("__i386__",null); config.preprocessorConfig.implicitMacros.put("__x86_64__",null); config.preprocessorConfig.implicitMacros.put("__amd64__",null); config.preprocessorConfig.implicitMacros.put("__LITTLE_ENDIAN__",null); config.preprocessorConfig.implicitMacros.put("M_I86","1"); config.preprocessorConfig.implicitMacros.put("_M_I86","1"); config.preprocessorConfig.implicitMacros.put("_WIN32","1"); } else if (arch.equals("i386") || arch.equals("x86")) { config.preprocessorConfig.implicitMacros.put("TARGET_CPU_X86",null); config.preprocessorConfig.implicitMacros.put("__i386__",null); config.preprocessorConfig.implicitMacros.put("__LITTLE_ENDIAN__",null); config.preprocessorConfig.implicitMacros.put("M_I86","1"); config.preprocessorConfig.implicitMacros.put("_M_I86","1"); config.preprocessorConfig.implicitMacros.put("_WIN32","1"); } else if (arch.equals("ppc")) { config.preprocessorConfig.implicitMacros.put("TARGET_CPU_PPC",null); config.preprocessorConfig.implicitMacros.put("__PPC__",null); config.preprocessorConfig.implicitMacros.put("__powerpc__",null); config.preprocessorConfig.implicitMacros.put("__BIG_ENDIAN__",null); } else if (arch.equals("ppc64")) { config.preprocessorConfig.implicitMacros.put("TARGET_CPU_PPC64",null); config.preprocessorConfig.implicitMacros.put("__PPC_64__",null); config.preprocessorConfig.implicitMacros.put("__BIG_ENDIAN__",null); } }
TODO move this to a .h resource file <ul> <li> endianness <li> TARGET_CPU_* : see /System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/CarbonCore.framework/Headers/fp.h </ul>
@Override public void encode(WbXmlEncoder encoder,WbXmlElement ewlement,WbXmlContent content) throws IOException { if (!content.isString()) { throw new IOException("The content is not a String!"); } String value=content.getString(); if (value != null) { encoder.writeOpaque(value.getBytes(encoder.getIanaCharset().getCharset())); } }
The encoding is just passing the string bytes as an opaque.
private void ib4(int a,int b,int c,int d){ int t1=c | d; int t2=a & t1; int t3=b ^ t2; int t4=a & t3; int t5=c ^ t4; X1=d ^ t5; int t7=~a; int t8=t5 & X1; X3=t3 ^ t8; int t10=X1 | t7; int t11=d ^ t10; X0=X3 ^ t11; X2=(t3 & t11) ^ (X1 ^ t7); }
InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms.
private static Field findField(Object instance,String name) throws NoSuchFieldException { for (Class<?> clazz=instance.getClass(); clazz != null; clazz=clazz.getSuperclass()) { try { Field field=clazz.getDeclaredField(name); if (!field.isAccessible()) { field.setAccessible(true); } return field; } catch ( NoSuchFieldException e) { } } throw new NoSuchFieldException("Field " + name + " not found in "+ instance.getClass()); }
Locates a given field anywhere in the class inheritance hierarchy.
public boolean isProcessed(){ Object oo=get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
Get Processed.
public final void trimToSize(){ Object[] newObjects=new Object[m_Size]; System.arraycopy(m_Objects,0,newObjects,0,m_Size); m_Objects=newObjects; }
Sets the vector's capacity to its size.
public void keyPress(int keyCode){ TestUtils.keyPress(keyCode); }
This method just invokes the test utils method, it is here for convenience
public int compareTo(double value){ if (value >= start) { if (value < end) { return 0; } else { return -1; } } else { return +1; } }
Returns the position of the double value in comparison with the start and end values of the interval
public static String toUpperCase(String s){ return toUpperCase(s,null); }
Converts all of the characters in the string to upper case, based on the portal instance's default locale.
private boolean isConnected(){ return fTextViewer != null && fDocumentUndoManager != null; }
Returns whether this undo manager is connected to a text viewer.
public static ReilInstruction createNop(final long offset){ final ReilOperand firstOperand=createOperand(OperandSize.EMPTY,""); final ReilOperand secondOperand=createOperand(OperandSize.EMPTY,""); final ReilOperand thirdOperand=createOperand(OperandSize.EMPTY,""); return new ReilInstruction(new CAddress(offset),ReilHelpers.OPCODE_NOP,firstOperand,secondOperand,thirdOperand); }
Creates a NOP instruction.