code
stringlengths
10
174k
nl
stringlengths
3
129k
public void initializeWith(IntArrayList list,DictionaryMap map){ for ( int key : list) { add(map.get(key)); } }
Initializes this Column with the given values for performance
public ResultEntry(NondominatedPopulation population,TypedProperties properties){ this(population,properties == null ? null : properties.getProperties()); }
Constructs a result file entry with the specified non-dominated population and auxiliary properties.
public double time(){ return getTime(); }
Returns the current timestep
public void shutDown(){ FrescoPlusCore.shutDownDraweeControllerBuilderSupplier(); FrescoPlusView.shutDown(); ImagePipelineFactory.shutDown(); }
Shuts FrescoPlusInitializer down.
public void write(byte x){ writeByte(x & 0xff); }
Writes the 8-bit byte to the binary output stream.
public void filterUnsafeOrUnnecessaryRequest(Map<String,NodeReqResponse> nodeDataMapValidSource,Map<String,NodeReqResponse> nodeDataMapValidSafe){ for ( Entry<String,NodeReqResponse> entry : nodeDataMapValidSource.entrySet()) { String hostName=entry.getKey(); NodeReqResponse nrr=entry.getValue(); Map<String,String> map=nrr.getRequestParameters(); if (map.containsKey(PcConstants.NODE_REQUEST_WILL_EXECUTE)) { Boolean willExecute=Boolean.parseBoolean(map.get(PcConstants.NODE_REQUEST_WILL_EXECUTE)); if (!willExecute) { logger.info("NOT_EXECUTE_COMMAND " + " on target: " + hostName + " at "+ PcDateUtils.getNowDateTimeStrStandard()); continue; } } nodeDataMapValidSafe.put(hostName,nrr); } }
Filter unsafe or unnecessary request.
public boolean contains(String key){ return sharedPreferences.contains(key); }
Checks whether the preferences contains a preference.
private static String massageURI(String uri){ uri=uri.trim(); int protocolEnd=uri.indexOf(':'); if (protocolEnd < 0) { uri="http://" + uri; } else if (isColonFollowedByPortNumber(uri,protocolEnd)) { uri="http://" + uri; } return uri; }
Transforms a string that represents a URI into something more proper, by adding or canonicalizing the protocol.
public void removeElements(final int from,final int to){ it.unimi.dsi.fastutil.Arrays.ensureFromTo(size,from,to); System.arraycopy(a,to,a,from,size - to); size-=(to - from); int i=to - from; while (i-- != 0) a[size + i]=null; }
Removes elements of this type-specific list using optimized system calls.
public void addAttributeNS(QName name,String type,String value){ int index=fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes; if (fLength < SIZE_LIMIT) { attributes=new Attribute[fAttributes.length + 4]; } else { attributes=new Attribute[fAttributes.length << 1]; } System.arraycopy(fAttributes,0,attributes,0,fAttributes.length); for (int i=fAttributes.length; i < attributes.length; i++) { attributes[i]=new AttributeMMImpl(); } fAttributes=attributes; } Attribute attribute=fAttributes[index]; attribute.name.setValues(name); attribute.type=type; attribute.value=value; attribute.nonNormalizedValue=value; attribute.specified=false; attribute.augs.removeAllItems(); }
Adds an attribute. The attribute's non-normalized value of the attribute will have the same value as the attribute value until set using the <code>setNonNormalizedValue</code> method. Also, the added attribute will be marked as specified in the XML instance document unless set otherwise using the <code>setSpecified</code> method. <p> This method differs from <code>addAttribute</code> in that it does not check if an attribute of the same name already exists in the list before adding it. In order to improve performance of namespace processing, this method allows uniqueness checks to be deferred until all the namespace information is available after the entire attribute specification has been read. <p> <strong>Caution:</strong> If this method is called it should not be mixed with calls to <code>addAttribute</code> unless it has been determined that all the attribute names are unique.
private static void copySwap(Object[] src,int from,Object[] dst,int to,int len){ if (src == dst && from + len > to) { int new_to=to + len - 1; for (; from < to; from++, new_to--, len--) { dst[new_to]=src[from]; } for (; len > 1; from++, new_to--, len-=2) { swap(from,new_to,dst); } } else { to=to + len - 1; for (; len > 0; from++, to--, len--) { dst[to]=src[from]; } } }
Copies object from one array to another array with reverse of objects order. Source and destination arrays may be the same.
public double distance(Vector3 a){ return Vector3.distance(a,this); }
Gets the distance between this Vector3 and a given Vector3.
@Override public void run(){ amIActive=true; String streamsHeader=null; String pointerHeader=null; String outputHeader=null; int row, col, x, y; float progress=0; double z; int i, c; int[] dX=new int[]{1,1,1,0,-1,-1,-1,0}; int[] dY=new int[]{-1,0,1,1,1,0,-1,-1}; double[] inflowingVals=new double[]{16,32,64,128,1,2,4,8}; boolean flag=false; double flowDir=0; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (i=0; i < args.length; i++) { if (i == 0) { streamsHeader=args[i]; } else if (i == 1) { pointerHeader=args[i]; } else if (i == 2) { outputHeader=args[i]; } } if ((streamsHeader == null) || (pointerHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster streams=new WhiteboxRaster(streamsHeader,"r"); int rows=streams.getNumberRows(); int cols=streams.getNumberColumns(); double noData=streams.getNoDataValue(); WhiteboxRaster pntr=new WhiteboxRaster(pointerHeader,"r"); if (pntr.getNumberRows() != rows || pntr.getNumberColumns() != cols) { showFeedback("The input images must be of the same dimensions."); return; } WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",streamsHeader,WhiteboxRaster.DataType.INTEGER,0); output.setPreferredPalette("spectrum.pal"); output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS); WhiteboxRaster numInflowingStreamCells=new WhiteboxRaster(outputHeader.replace(".dep","_temp.dep"),"rw",streamsHeader,WhiteboxRaster.DataType.INTEGER,noData); numInflowingStreamCells.isTemporaryFile=true; byte numNeighbouringStreamCells=0; double currentValue=0; updateProgress("Loop 1 of 2:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { if (streams.getValue(row,col) > 0) { numNeighbouringStreamCells=0; for (c=0; c < 8; c++) { x=col + dX[c]; y=row + dY[c]; if (streams.getValue(y,x) > 0 && pntr.getValue(y,x) == inflowingVals[c]) { numNeighbouringStreamCells++; } } if (numNeighbouringStreamCells == 0) { output.setValue(row,col,1); numInflowingStreamCells.setValue(row,col,-1); } else { output.setValue(row,col,0); numInflowingStreamCells.setValue(row,col,numNeighbouringStreamCells); } } else { output.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress("Loop 1 of 2:",(int)progress); } updateProgress("Loop 2 of 2:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { if (numInflowingStreamCells.getValue(row,col) == -1) { x=col; y=row; flag=true; do { z=output.getValue(y,x); flowDir=pntr.getValue(y,x); if (flowDir > 0) { c=(int)(Math.log(flowDir) / LnOf2); if (c > 7) { showFeedback("An unexpected value has " + "been identified in the pointer " + "image. This tool requires a "+ "pointer grid that has been "+ "created using either the D8 "+ "or Rho8 tools."); return; } x+=dX[c]; y+=dY[c]; if (streams.getValue(y,x) <= 0) { flag=false; } else { currentValue=numInflowingStreamCells.getValue(y,x) - 1; numInflowingStreamCells.setValue(y,x,currentValue); if (currentValue > 0) { flag=false; } currentValue=output.getValue(y,x); output.setValue(y,x,z + currentValue); } } else { flag=false; } } while (flag); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress("Loop 2 of 2:",(int)progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); pntr.close(); streams.close(); output.close(); numInflowingStreamCells.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public ByteVector put8(final long l){ int length=this.length; if (length + 8 > data.length) { enlarge(8); } byte[] data=this.data; int i=(int)(l >>> 32); data[length++]=(byte)(i >>> 24); data[length++]=(byte)(i >>> 16); data[length++]=(byte)(i >>> 8); data[length++]=(byte)i; i=(int)l; data[length++]=(byte)(i >>> 24); data[length++]=(byte)(i >>> 16); data[length++]=(byte)(i >>> 8); data[length++]=(byte)i; this.length=length; return this; }
Puts a long into this byte vector. The byte vector is automatically enlarged if necessary.
public KMLBalloonStyle(String namespaceURI){ super(namespaceURI); }
Construct an instance.
public ShortArrayList bottom(int n){ ShortArrayList bottom=new ShortArrayList(); short[] values=data.toShortArray(); ShortArrays.parallelQuickSort(values); for (int i=0; i < n && i < values.length; i++) { bottom.add(values[i]); } return bottom; }
Returns the smallest ("bottom") n values in the column
public boolean isConstructor(){ return (Objects.equal(this.getName(),"constructor") && (!this.isStatic())); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void closeDialog(){ setVisible(false); ModificationRegistery.unregisterEditor(getEditor()); doDefaultCloseAction(); }
Closes the dialog.
public static char toCharValue(boolean b){ return (char)(b ? 1 : 0); }
cast a boolean value to a char value
public synchronized void clear(){ mCategories.clear(); mValues.clear(); }
Removes all the existing values from the series.
public void addDocument(String name,int parentDivId,String fileExt,int sortOrder,String pathDocumentFile,String pathDocAnnFile) throws Exception { checkExistsParent(parentDivId); checkValidDocumentName(parentDivId,name); m_documents.addNewDocument(name,parentDivId,fileExt,sortOrder,pathDocumentFile,pathDocAnnFile); }
Agrega un nuevo documento a un clasificador
public void onDown(long time){ mDragLock=DragLock.NONE; if (mOverviewAnimationType == OverviewAnimationType.NONE) { stopScrollingMovement(time); } mScrollingTab=null; commitDiscard(time,false); }
Get called on down touch event.
protected InferredType mergeTarget(final TypeVariable target,final InferenceResult subordinate){ final InferredValue inferred=this.get(target); if (inferred instanceof InferredTarget) { InferredType newType=mergeTarget(((InferredTarget)inferred).target,subordinate); if (newType == null) { final InferredValue subValue=subordinate.get(target); if (subValue != null && subValue instanceof InferredType) { this.put(target,subValue); return newType; } } else { if (newType.type.getKind() == TypeKind.NULL) { final InferredValue subValue=subordinate.get(target); if (subValue != null && subValue instanceof InferredType) { AnnotatedTypeMirror copy=((InferredType)subValue).type.deepCopy(); copy.replaceAnnotations(newType.type.getAnnotations()); newType=new InferredType(copy); } } this.put(target,newType); return newType; } return null; } return (InferredType)inferred; }
Performs a merge for a specific target, we keep only results that lead to a concrete type
private void timeout(boolean suspectThem,boolean severeAlert){ if (!this.processTimeout()) return; Set activeMembers=getDistributionManagerIds(); long timeout=getAckWaitThreshold(); final Object[] msgArgs=new Object[]{Long.valueOf(timeout + (severeAlert ? getSevereAlertThreshold() : 0)),this,getDistributionManager().getId(),activeMembers}; final StringId msg=LocalizedStrings.ReplyProcessor21_0_SEC_HAVE_ELAPSED_WHILE_WAITING_FOR_REPLIES_1_ON_2_WHOSE_CURRENT_MEMBERSHIP_LIST_IS_3; if (severeAlert) { logger.fatal(LocalizedMessage.create(msg,msgArgs)); } else { logger.warn(LocalizedMessage.create(msg,msgArgs)); } msgArgs[3]="(omitted)"; Breadcrumbs.setProblem(msg,msgArgs); getDistributionManager().getStats().incReplyTimeouts(); final Set suspectMembers; if (suspectThem || severeAlert) { suspectMembers=new HashSet(); } else { suspectMembers=null; } synchronized (this.members) { for (int i=0; i < this.members.length; i++) { if (this.members[i] != null) { if (!activeMembers.contains(this.members[i])) { logger.warn(LocalizedMessage.create(LocalizedStrings.ReplyProcessor21_VIEW_NO_LONGER_HAS_0_AS_AN_ACTIVE_MEMBER_SO_WE_WILL_NO_LONGER_WAIT_FOR_IT,this.members[i])); memberDeparted(this.members[i],false); } else { if (suspectMembers != null) { suspectMembers.add(this.members[i]); } } } } } if (THROW_EXCEPTION_ON_TIMEOUT) { TimeoutException cause=new TimeoutException(LocalizedStrings.TIMED_OUT_WAITING_FOR_ACKS.toLocalizedString()); throw new InternalGemFireException(LocalizedStrings.ReplyProcessor21_0_SEC_HAVE_ELAPSED_WHILE_WAITING_FOR_REPLIES_1_ON_2_WHOSE_CURRENT_MEMBERSHIP_LIST_IS_3.toLocalizedString(msgArgs),cause); } else if (suspectThem) { if (suspectMembers != null && suspectMembers.size() > 0) { getDistributionManager().getMembershipManager().suspectMembers(suspectMembers,"Failed to respond within ack-wait-threshold"); } } }
process a wait-timeout. Usually suspectThem would be used in the first timeout, followed by a subsequent use of disconnectThem
@Override public void updateAsciiStream(int columnIndex,InputStream x,long length) throws SQLException { try { if (isDebugEnabled()) { debugCode("updateAsciiStream(" + columnIndex + ", x, "+ length+ "L);"); } checkClosed(); Value v=conn.createClob(IOUtils.getAsciiReader(x),length); update(columnIndex,v); } catch ( Exception e) { throw logAndConvert(e); } }
Updates a column in the current or insert row.
public static void alert(Context context,OsmElement e){ Preferences prefs=new Preferences(context); if (!prefs.generateAlerts()) { return; } LocationManager locationManager=(LocationManager)context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE); Location location=null; try { location=locationManager.getLastKnownLocation("gps"); } catch ( SecurityException sex) { } double eLon=0D; double eLat=0D; if ("node".equals(e.getName())) { eLon=((Node)e).getLon() / 1E7D; eLat=((Node)e).getLat() / 1E7D; } else if ("way".equals(e.getName())) { double[] result=Logic.centroidLonLat((Way)e); eLon=result[0]; eLat=result[1]; } else { return; } String title=context.getString(R.string.alert_data_issue); String ticker=title; String message=""; if (location != null) { long distance=0; if ("node".equals(e.getName())) { distance=Math.round(GeoMath.haversineDistance(location.getLongitude(),location.getLatitude(),eLon,eLat)); } else if ("way".equals(e.getName())) { ClosestPoint cp=getClosestDistance(location.getLongitude(),location.getLatitude(),(Way)e); distance=Math.round(cp.distance); eLon=cp.lon; eLat=cp.lat; } if (distance > prefs.getMaxAlertDistance()) { return; } long bearing=GeoMath.bearing(location.getLongitude(),location.getLatitude(),eLon,eLat); String[] bearings={"NE","E","SE","S","SW","W","NW","N"}; int index=(int)(bearing - 22.5); if (index < 0) index+=360; index=index / 45; message=context.getString(R.string.alert_distance_direction,distance,bearings[index]) + "\n"; ticker=ticker + " " + message; } message=message + e.describeProblem(); NotificationCompat.Builder mBuilder; try { mBuilder=new NotificationCompat.Builder(context).setSmallIcon(R.drawable.osm_logo).setContentTitle(title).setContentText(message).setPriority(NotificationCompat.PRIORITY_HIGH).setTicker(ticker).setAutoCancel(true).setGroup(GROUP_DATA); } catch ( RuntimeException re) { ACRA.getErrorReporter().putCustomData("STATUS","NOCRASH"); ACRA.getErrorReporter().handleException(re); return; } Intent resultIntent=new Intent(Intent.ACTION_VIEW); try { BoundingBox box=GeoMath.createBoundingBoxForCoordinates(eLat,eLon,prefs.getDownloadRadius(),true); Uri rc=Uri.parse("http://127.0.0.1:8111/load_and_zoom?left=" + box.getLeft() / 1E7D + "&right=" + box.getRight() / 1E7D + "&top=" + box.getTop() / 1E7D + "&bottom=" + box.getBottom() / 1E7D + "&select=" + e.getName() + e.getOsmId()); Log.d("IssueAlert",rc.toString()); resultIntent.setData(rc); TaskStackBuilder stackBuilder=TaskStackBuilder.create(context); stackBuilder.addParentStack(Main.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(id(e),mBuilder.build()); Application.getOsmDataNotifications(context).save(mNotificationManager,id(e)); } catch ( OsmException e1) { Log.d("IssueAlert","Illegal BB created from lat " + eLat + " lon "+ eLon+ " r "+ prefs.getDownloadRadius()); } }
Generate an alert/notification if something is problematic about the OSM object
private MutableBigInteger divideLongMagnitude(long ldivisor,MutableBigInteger quotient){ MutableBigInteger rem=new MutableBigInteger(new int[intLen + 1]); System.arraycopy(value,offset,rem.value,1,intLen); rem.intLen=intLen; rem.offset=1; int nlen=rem.intLen; int limit=nlen - 2 + 1; if (quotient.value.length < limit) { quotient.value=new int[limit]; quotient.offset=0; } quotient.intLen=limit; int[] q=quotient.value; int shift=Long.numberOfLeadingZeros(ldivisor); if (shift > 0) { ldivisor<<=shift; rem.leftShift(shift); } if (rem.intLen == nlen) { rem.offset=0; rem.value[0]=0; rem.intLen++; } int dh=(int)(ldivisor >>> 32); long dhLong=dh & LONG_MASK; int dl=(int)(ldivisor & LONG_MASK); for (int j=0; j < limit; j++) { int qhat=0; int qrem=0; boolean skipCorrection=false; int nh=rem.value[j + rem.offset]; int nh2=nh + 0x80000000; int nm=rem.value[j + 1 + rem.offset]; if (nh == dh) { qhat=~0; qrem=nh + nm; skipCorrection=qrem + 0x80000000 < nh2; } else { long nChunk=(((long)nh) << 32) | (nm & LONG_MASK); if (nChunk >= 0) { qhat=(int)(nChunk / dhLong); qrem=(int)(nChunk - (qhat * dhLong)); } else { long tmp=divWord(nChunk,dh); qhat=(int)(tmp & LONG_MASK); qrem=(int)(tmp >>> 32); } } if (qhat == 0) continue; if (!skipCorrection) { long nl=rem.value[j + 2 + rem.offset] & LONG_MASK; long rs=((qrem & LONG_MASK) << 32) | nl; long estProduct=(dl & LONG_MASK) * (qhat & LONG_MASK); if (unsignedLongCompare(estProduct,rs)) { qhat--; qrem=(int)((qrem & LONG_MASK) + dhLong); if ((qrem & LONG_MASK) >= dhLong) { estProduct-=(dl & LONG_MASK); rs=((qrem & LONG_MASK) << 32) | nl; if (unsignedLongCompare(estProduct,rs)) qhat--; } } } rem.value[j + rem.offset]=0; int borrow=mulsubLong(rem.value,dh,dl,qhat,j + rem.offset); if (borrow + 0x80000000 > nh2) { divaddLong(dh,dl,rem.value,j + 1 + rem.offset); qhat--; } q[j]=qhat; } if (shift > 0) rem.rightShift(shift); quotient.normalize(); rem.normalize(); return rem; }
Divide this MutableBigInteger by the divisor represented by positive long value. The quotient will be placed into the provided quotient object & the remainder object is returned.
public boolean isFatalEnabled(){ return (getLogger().isLoggable(Level.SEVERE)); }
Is fatal logging currently enabled?
private void addProteinToBatch(Protein protein){ proteinsAwaitingPersistence.add(protein); if (proteinsAwaitingPersistence.size() == proteinInsertBatchSize) { persistBatch(); } }
Adds a protein to the batch of proteins to be persisted. If the maximum batch size is reached, store all these proteins (by calling persistBatch().)
public Account(Account other){ if (other.isSetUserid()) { this.userid=other.userid; } if (other.isSetPasswd()) { this.passwd=other.passwd; } }
Performs a deep copy on <i>other</i>.
public final AC shrink(){ return shrink(100f,curIx); }
Specifies that the current row/column's shrink weight withing the columns/rows with the <code>shrink priority</code> 100f. <p> Same as <code>shrink(100f)</code>. <p> For a more thorough explanation of what this constraint does see the White Paper or Cheat Sheet at www.migcomponents.com.
public Optional<T> filter(Predicate<? super T> predicate){ if (!isPresent()) return this; return predicate.test(value) ? this : Optional.<T>empty(); }
Performs filtering on inner value if present.
private DateUtils(){ }
This class should not be instantiated.
@Override protected EClass eStaticClass(){ return TypesPackage.Literals.TENUM; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void sort(ArrayList<Value[]> rows){ Collections.sort(rows,this); }
Sort a list of rows.
private void generateMatrix(){ final int dwidth=mDrawable.getIntrinsicWidth(); final int dheight=mDrawable.getIntrinsicHeight(); final int vwidth=mAllowCrop ? sCropSize : getWidth(); final int vheight=mAllowCrop ? sCropSize : getHeight(); final boolean fits=(dwidth < 0 || vwidth == dwidth) && (dheight < 0 || vheight == dheight); if (fits && !mAllowCrop) { mMatrix.reset(); } else { mTempSrc.set(0,0,dwidth,dheight); if (mAllowCrop) { mTempDst.set(mCropRect); } else { mTempDst.set(0,0,vwidth,vheight); } RectF scaledDestination=new RectF((vwidth / 2) - (dwidth * mMaxInitialScaleFactor / 2),(vheight / 2) - (dheight * mMaxInitialScaleFactor / 2),(vwidth / 2) + (dwidth * mMaxInitialScaleFactor / 2),(vheight / 2) + (dheight * mMaxInitialScaleFactor / 2)); if (mTempDst.contains(scaledDestination)) { mMatrix.setRectToRect(mTempSrc,scaledDestination,Matrix.ScaleToFit.CENTER); } else { mMatrix.setRectToRect(mTempSrc,mTempDst,Matrix.ScaleToFit.CENTER); } } mOriginalMatrix.set(mMatrix); }
Generates the initial transformation matrix for drawing. Additionally, it sets the minimum and maximum scale values.
public LingRunner(GraphSource graphWrapper,Parameters params,KnowledgeBoxModel knowledgeBoxModel){ super(graphWrapper.getGraph(),params,knowledgeBoxModel); }
Constucts a wrapper for the given EdgeListGraph.
protected void onServiceStarted(){ }
Called when the service has been started. The device name and address are set. It nRF Logger is installed than logger was also initialized.
private int indexOf(K key){ for (int i=0, n=entries.size(); i < n; i++) if (keyEquality.areEqual(entries.get(i).getKey(),key)) return i; return -1; }
Returns the index for the specified key.
public void addNotificationListener(NotificationListener listener,NotificationFilter filter,Object handback) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,handback); }
MBean Notification support You shouldn't update these methods
public double calculateSimilarity(PatternReference pattern){ if (patterns.isEmpty()) { return 0; } else { final double sum=patterns.stream().map(null).reduce(0.0,null); return sum / size(); } }
Calculate similarity (similarity measure is as defined by the pattern).
protected void update(ControlDecoration decoration,IStatus status){ if (status == null || status.isOK()) { decoration.hide(); } else { decoration.setImage(getImage(status)); decoration.setDescriptionText(getDescriptionText(status)); decoration.showHoverText(getDescriptionText(status)); decoration.show(); } }
Updates the visibility, image, and description text of the given ControlDecoration to represent the given status.
public TransferSubscriptionsResponse TransferSubscriptions(RequestHeader RequestHeader,UnsignedInteger[] SubscriptionIds,Boolean SendInitialValues) throws ServiceFaultException, ServiceResultException { TransferSubscriptionsRequest req=new TransferSubscriptionsRequest(RequestHeader,SubscriptionIds,SendInitialValues); return (TransferSubscriptionsResponse)channel.serviceRequest(req); }
Synchronous TransferSubscriptions service request.
protected void loadSteps(){ if (stepsHash != null) { loadStepsSet(); return; } if (toReplace != null) { steps=toReplace; size=steps.length; toReplace=null; } int toBeRemovedSize=toBeRemoved.size(); if (toBeRemovedSize > 0) { boolean ensuresOrder=this.ensuresOrder && canEnsureOrder(); Steppable[] steps=this.steps; Bag toBeRemoved=this.toBeRemoved; int stepsSize=this.size; for (int s=stepsSize - 1; s >= 0; s--) { for (int r=0; r < toBeRemovedSize; r++) { if (steps[s] == toBeRemoved.get(r)) { if (s < stepsSize - 1) { if (ensuresOrder) System.arraycopy(steps,s + 1,steps,s,stepsSize - s - 1); else steps[s]=steps[stepsSize - 1]; } steps[stepsSize - 1]=null; stepsSize--; toBeRemoved.remove(r); toBeRemovedSize--; break; } } if (toBeRemovedSize == 0) { break; } } toBeRemoved.clear(); this.size=stepsSize; } int toBeAddedSize=this.toBeAdded.size(); if (toBeAddedSize > 0) { Bag toBeAdded=this.toBeAdded; int stepsSize=this.size; int newLen=stepsSize + toBeAddedSize; if (newLen >= steps.length) { int newSize=steps.length * 2 + 1; if (newSize <= newLen) newSize=newLen; Steppable[] newSteppables=new Steppable[newSize]; System.arraycopy(steps,0,newSteppables,0,steps.length); this.steps=newSteppables; steps=newSteppables; } if (toBeAddedSize < 20) for (int i=0; i < toBeAddedSize; i++) steps[stepsSize + i]=(Steppable)(toBeAdded.get(i)); else toBeAdded.copyIntoArray(0,steps,stepsSize,toBeAddedSize); toBeAdded.clear(); this.size=newLen; } }
Subclasses should call this method as more or less the first thing in their step(...) method. This method replaces, removes, and adds new Steppables to the internal array as directed by the user. After calling this method, the Sequence is ready to have the Steppables in its internal array stepped.
public static void formatJapaneseNumber(Editable text){ JapanesePhoneNumberFormatter.format(text); }
Formats a phone number in-place using the Japanese formatting rules. Numbers will be formatted as: <p><code> 03-xxxx-xxxx 090-xxxx-xxxx 0120-xxx-xxx +81-3-xxxx-xxxx +81-90-xxxx-xxxx </code></p>
public static int[] matrixToArray(int[][] input,int fromRow,int rows,int fromColumn,int columns){ int[] output=new int[rows * columns]; for (int c=0; c < columns; c++) { for (int r=0; r < rows; r++) { output[c * rows + r]=input[r + fromRow][c + fromColumn]; } } return output; }
Converts a 2 dimensional array into a single dimension. Places each column on top of each other. Provides controllers for selecting a subset of rows or columns.
@Override public void map(LongWritable key,Text value,Context context) throws IOException, InterruptedException { heartBeater.needHeartBeat(); try { runner.map(value.toString(),context.getConfiguration(),context); } finally { heartBeater.cancelHeartBeat(); } }
Extract content from the path specified in the value. Key is useless.
public boolean isPersistent(){ return persistent; }
Check if this database disk-based.
@EventHandler public void onPlayerJoin(PlayerJoinEvent event){ Player player=event.getPlayer(); playerChannels.put(player,new PlayerChannel(player)); }
Adds a new player channel whenever a player joins the server.
public void undoCommand(IUndoableCommand command){ IUndoableCommand temp; do { temp=undoStack.pop(); temp.undo(); redoStack.push(temp); } while (temp != command); fireOperationsHistoryChanged(); }
Undo the command. Restore the state of the target to the previous state before this command has been executed.
private static void checkEqualPartitionMaps(Map<Integer,ClusterNode> map1,Map<Integer,ClusterNode> map2){ assertEquals(map1.size(),map2.size()); for ( Integer i : map1.keySet()) { assertTrue(map2.containsKey(i)); assertEquals(map1.get(i),map2.get(i)); } }
Check equal maps.
public TransactionDeadlockException(String msg){ super(msg); }
Creates new deadlock exception with given error message.
public void put(AuthTimeWithHash t,KerberosTime currentTime) throws KrbApErrException { if (entries.isEmpty()) { entries.addFirst(t); } else { AuthTimeWithHash temp=entries.getFirst(); int cmp=temp.compareTo(t); if (cmp < 0) { entries.addFirst(t); } else if (cmp == 0) { throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT); } else { ListIterator<AuthTimeWithHash> it=entries.listIterator(1); boolean found=false; while (it.hasNext()) { temp=it.next(); cmp=temp.compareTo(t); if (cmp < 0) { entries.add(entries.indexOf(temp),t); found=true; break; } else if (cmp == 0) { throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT); } } if (!found) { entries.addLast(t); } } } long timeLimit=currentTime.getSeconds() - lifespan; ListIterator<AuthTimeWithHash> it=entries.listIterator(0); AuthTimeWithHash temp=null; int index=-1; while (it.hasNext()) { temp=it.next(); if (temp.ctime < timeLimit) { index=entries.indexOf(temp); break; } } if (index > -1) { do { entries.removeLast(); } while (entries.size() > index); } }
Puts the authenticator timestamp into the cache in descending order, and throw an exception if it's already there.
public int selectedWaysCount(){ return selectedWays == null ? 0 : selectedWays.size(); }
Return how many ways are selected
public void init(ServletConfig config) throws ServletException { super.init(config); if (!WebEnv.initWeb(config)) throw new ServletException("BasketServlet.init"); }
Initialize global variables
@SuppressWarnings("unchecked") public static final <K,V>Map<K,V> mergeMapEntry(CodedInputByteBufferNano input,Map<K,V> map,MapFactory mapFactory,int keyType,int valueType,V value,int keyTag,int valueTag) throws IOException { map=mapFactory.forMap(map); final int length=input.readRawVarint32(); final int oldLimit=input.pushLimit(length); K key=null; while (true) { int tag=input.readTag(); if (tag == 0) { break; } if (tag == keyTag) { key=(K)input.readPrimitiveField(keyType); } else if (tag == valueTag) { if (valueType == TYPE_MESSAGE) { input.readMessage((MessageNano)value); } else { value=(V)input.readPrimitiveField(valueType); } } else { if (!input.skipField(tag)) { break; } } } input.checkLastTagWas(0); input.popLimit(oldLimit); if (key == null) { key=(K)primitiveDefaultValue(keyType); } if (value == null) { value=(V)primitiveDefaultValue(valueType); } map.put(key,value); return map; }
Merges the map entry into the map field. Note this is only supposed to be called by generated messages.
public synchronized boolean hasService(Class serviceClass){ if (serviceClass == null) throw new NullPointerException("serviceClass"); synchronized (BeanContext.globalHierarchyLock) { if (services.containsKey(serviceClass)) return true; BeanContextServices bcs=null; try { bcs=(BeanContextServices)getBeanContext(); } catch ( ClassCastException cce) { return false; } return bcs == null ? false : bcs.hasService(serviceClass); } }
has a service, which may be delegated
public static int readSingleByte(InputStream in) throws IOException { byte[] buffer=new byte[1]; int result=in.read(buffer,0,1); return (result != -1) ? buffer[0] & 0xff : -1; }
Implements InputStream.read(int) in terms of InputStream.read(byte[], int, int). InputStream assumes that you implement InputStream.read(int) and provides default implementations of the others, but often the opposite is more efficient.
public static void tred2(int n,double[][] V,double[] d,double[] e){ for (int j=0; j < n; j++) { d[j]=V[n - 1][j]; } for (int i=n - 1; i > 0; i--) { double scale=0.0; double h=0.0; for (int k=0; k < i; k++) { scale=scale + Math.abs(d[k]); } if (scale == 0.0) { e[i]=d[i - 1]; for (int j=0; j < i; j++) { d[j]=V[i - 1][j]; V[i][j]=0.0; V[j][i]=0.0; } } else { for (int k=0; k < i; k++) { d[k]/=scale; h+=d[k] * d[k]; } double f=d[i - 1]; double g=Math.sqrt(h); if (f > 0) { g=-g; } e[i]=scale * g; h=h - f * g; d[i - 1]=f - g; for (int j=0; j < i; j++) { e[j]=0.0; } for (int j=0; j < i; j++) { f=d[j]; V[j][i]=f; g=e[j] + V[j][j] * f; for (int k=j + 1; k <= i - 1; k++) { g+=V[k][j] * d[k]; e[k]+=V[k][j] * f; } e[j]=g; } f=0.0; for (int j=0; j < i; j++) { e[j]/=h; f+=e[j] * d[j]; } double hh=f / (h + h); for (int j=0; j < i; j++) { e[j]-=hh * d[j]; } for (int j=0; j < i; j++) { f=d[j]; g=e[j]; for (int k=j; k <= i - 1; k++) { V[k][j]-=(f * e[k] + g * d[k]); } d[j]=V[i - 1][j]; V[i][j]=0.0; } } d[i]=h; } for (int i=0; i < n - 1; i++) { V[n - 1][i]=V[i][i]; V[i][i]=1.0; double h=d[i + 1]; if (h != 0.0) { for (int k=0; k <= i; k++) { d[k]=V[k][i + 1] / h; } for (int j=0; j <= i; j++) { double g=0.0; for (int k=0; k <= i; k++) { g+=V[k][i + 1] * V[k][j]; } for (int k=0; k <= i; k++) { V[k][j]-=g * d[k]; } } } for (int k=0; k <= i; k++) { V[k][i + 1]=0.0; } } for (int j=0; j < n; j++) { d[j]=V[n - 1][j]; V[n - 1][j]=0.0; } V[n - 1][n - 1]=1.0; e[0]=0.0; }
Symmetric Householder reduction to tridiagonal form, taken from JAMA package. This is derived from the Algol procedures tred2 by Bowdler, Martin, Reinsch, and Wilkinson, Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding Fortran subroutine in EISPACK.
public void addMessageListener(MessageListener listener){ m_notifier.add(listener); }
addMessageListener() -
public static final int[] toIntArray(String s){ s=new String(s.trim()); if (s.length() <= 2) return new int[]{}; return toIntArray((s.substring(1,s.length() - 1)).split(",")); }
ToIntArray - Return an int[] from a String, e.g., "[0,1,2,0]" to [0,1,2,3].
public LambdaBlock(ToplevelPane pane,int arity){ super(pane); this.loadFXML("LambdaBlock"); this.arity=arity; this.signature.setText(""); this.explicitSignature=Optional.empty(); this.definitionName.setText(""); this.definitionName.setVisible(false); this.allDefinitionUsers=new ArrayList<>(); this.body=new LambdaContainer(this,arity); this.bodySpace.getChildren().add(this.body); this.fun=new PolyOutputAnchor(this,new Binder("lam")); this.funSpace.getChildren().add(this.fun); this.dragContext.setGoToForegroundOnContact(false); Polygon triangle=new Polygon(); triangle.getPoints().addAll(new Double[]{20.0,20.0,20.0,0.0,0.0,20.0}); triangle.setFill(Color.BLUE); this.resizer=new Pane(triangle); triangle.setLayoutX(10); triangle.setLayoutY(10); this.resizer.setManaged(false); this.getChildren().add(resizer); this.resizer.relocate(300,300); DragContext sizeDrag=new DragContext(this.resizer); sizeDrag.setDragLimits(new BoundingBox(200,200,Integer.MAX_VALUE,Integer.MAX_VALUE)); ((Pane)this.signature.getParent()).widthProperty().addListener(null); }
Constructs a DefinitionBlock that is an untyped lambda of n arguments.
void unlink(Node<E> p,Node<E> trail){ p.item=null; trail.next=p.next; if (last == p) last=trail; if (count.getAndDecrement() == capacity) notFull.signal(); }
Unlinks interior Node p with predecessor trail.
public static void i(String msg,Throwable thr){ if (DEBUG) Log.i(TAG,buildMessage(msg),thr); }
Send a INFO log message and log the exception.
public SpotPrice toAwsObject(){ SpotPrice spotPrice=new SpotPrice(); spotPrice.setAvailabilityZone(availabilityZone); spotPrice.setInstanceType(type); spotPrice.setSpotPrice(this.spotPrice); return spotPrice; }
Converts this object into an AWS equivalent object.
public static SnmpEngineId createEngineId(int port) throws UnknownHostException { int suniana=42; InetAddress address=null; address=InetAddress.getLocalHost(); return createEngineId(address,port,suniana); }
Generates a unique engine Id. The engine Id unicity is based on the host IP address and port. The IP address used is the localhost one. The creation algorithm uses the SUN Microsystems IANA number (42).
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.
private DoubleDBIDList refineRange(DoubleDBIDList neighc,double adjustedEps){ ModifiableDoubleDBIDList n=DBIDUtil.newDistanceDBIDList(neighc.size()); for (DoubleDBIDListIter neighbor=neighc.iter(); neighbor.valid(); neighbor.advance()) { DoubleDBIDPair p=neighbor.getPair(); double dist=p.doubleValue(); if (dist <= adjustedEps) { n.add(dist,p); } } return n; }
Refine a range query.
@Override protected void tearDown() throws Exception { terminateApplication(); mApplication=null; scrubClass(ApplicationTestCase.class); super.tearDown(); }
Shuts down the Application under test. Also makes sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.
public int skipBytes(int num) throws IOException { return inputStream.skipBytes(num); }
skip ahead in the stream
public final int countActions(){ return mActions.size(); }
Return the number of actions in the filter.
@Override public void run(){ amIActive=true; String NIRHeader=null; String RedHeader=null; String outputHeader=null; int row, col, x, y; double[] NIRVal; double[] redVal; float progress=0; int a; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (int i=0; i < args.length; i++) { if (i == 0) { NIRHeader=args[i]; } else if (i == 1) { RedHeader=args[i]; } else if (i == 2) { outputHeader=args[i]; } } if ((NIRHeader == null) || (RedHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster NIR=new WhiteboxRaster(NIRHeader,"r"); int rows=NIR.getNumberRows(); int cols=NIR.getNumberColumns(); double noData=NIR.getNoDataValue(); WhiteboxRaster red=new WhiteboxRaster(RedHeader,"r"); if (rows != red.getNumberRows() || cols != red.getNumberColumns()) { showFeedback("The two input images must have the same number of rows and columns."); return; } WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",NIRHeader,WhiteboxRaster.DataType.FLOAT,noData); outputFile.setPreferredPalette(NIR.getPreferredPalette()); for (row=0; row < rows; row++) { NIRVal=NIR.getRowValues(row); redVal=red.getRowValues(row); for (col=0; col < cols; col++) { if (NIRVal[col] != noData && redVal[col] != noData) { if ((NIRVal[col] + redVal[col]) != 0) { outputFile.setValue(row,col,(NIRVal[col] - redVal[col]) / (NIRVal[col] + redVal[col] + 0.16)); } else { outputFile.setValue(row,col,noData); } } else { outputFile.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); outputFile.addMetadataEntry("Created on " + new Date()); NIR.close(); red.close(); outputFile.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public Vector3f normalize(){ float length=x * x + y * y + z * z; if (length != 1f && length != 0f) { length=1.0f / FastMath.sqrt(length); return new Vector3f(x * length,y * length,z * length); } return clone(); }
<code>normalize</code> returns the unit vector of this vector.
@Thunk int compareTitles(String titleA,String titleB){ boolean aStartsWithLetter=(titleA.length() > 0) && Character.isLetterOrDigit(titleA.codePointAt(0)); boolean bStartsWithLetter=(titleB.length() > 0) && Character.isLetterOrDigit(titleB.codePointAt(0)); if (aStartsWithLetter && !bStartsWithLetter) { return -1; } else if (!aStartsWithLetter && bStartsWithLetter) { return 1; } return mCollator.compare(titleA,titleB); }
Compares two titles with the same return value semantics as Comparator.
public RE simplifyOps() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); RE res; switch (this.op) { case EMPTY: case EPSILON: case RANGE: case STRING: return this; case STAR: case PLUS: case OPTION: res=new RE(this.op); res.meta=meta; res.unaryArg=unaryArg.simplifyOps(); return res; case UNION: res=new RE(ReOp.UNION); res.meta=meta; res.alts=new HashSet<RE>(); for (RE arg : alts) { res.alts.add(arg.simplifyOps()); } return res; case CONCAT: res=new RE(ReOp.CONCAT); res.meta=meta; res.cats=new LinkedList<RE>(); for (RE arg : cats) { res.cats.add(arg.simplifyOps()); } return res; case BINOP: case UNOP: res=new RE(this); res.cats=new LinkedList<RE>(); for (RE arg : cats) { res.cats.add(arg.simplifyOps()); } return res.interpretOp(); default : return this; } }
For a regular expression that contains string operations, return a regular expression that matches a language of the image of the operations, removing all string operation nodes. This is conservative, and the result may match a superset of the language matched by the original regular expression.
@Override public void run(){ amIActive=true; RandomAccessFile rIn=null; ByteBuffer buf; String inputFilesString=null; String[] XYZFiles; double x, y, north, south, east, west; double z; float minValue, maxValue; float featureValue; int numVertices; byte classValue, numReturns, returnNum; int a, n, loc, featureNum=1; int progress=0; int numPoints=0; String delimiter=" "; ShapeType shapeType=ShapeType.POINT; boolean firstLineHeader=false; String fileExtension=".txt"; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputFilesString=args[0]; firstLineHeader=Boolean.parseBoolean(args[1]); if ((inputFilesString.length() <= 0)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { XYZFiles=inputFilesString.split(";"); int numZYZFiles=XYZFiles.length; shapeType=ShapeType.POINT; for (int j=0; j < numZYZFiles; j++) { String fileName=XYZFiles[j]; File file=new File(fileName); if (!file.exists()) { return; } DBFField fields[]=new DBFField[1]; fields[0]=new DBFField(); fields[0].setName("Z"); fields[0].setDataType(DBFField.DBFDataType.NUMERIC); fields[0].setFieldLength(10); fields[0].setDecimalCount(3); fileExtension=FileUtilities.getFileExtension(fileName); String outputFile=fileName.replace("." + fileExtension,".shp"); File outfile=new File(outputFile); if (outfile.exists()) { outfile.delete(); } ShapeFile output=new ShapeFile(outputFile,shapeType,fields); DataInputStream in=null; BufferedReader br=null; try { FileInputStream fstream=new FileInputStream(file); in=new DataInputStream(fstream); br=new BufferedReader(new InputStreamReader(in)); String line; String[] str; j=1; while ((line=br.readLine()) != null) { str=line.split(delimiter); if (str.length <= 1) { delimiter="\t"; str=line.split(delimiter); if (str.length <= 1) { delimiter=" "; str=line.split(delimiter); if (str.length <= 1) { delimiter=","; str=line.split(delimiter); } } } if ((j > 1 || !firstLineHeader) && (str.length >= 3)) { x=Double.parseDouble(str[0]); y=Double.parseDouble(str[1]); z=Double.parseDouble(str[2]); whitebox.geospatialfiles.shapefile.Point wbGeometry=new whitebox.geospatialfiles.shapefile.Point(x,y); Object[] rowData=new Object[1]; rowData[0]=new Double(z); output.addRecord(wbGeometry,rowData); } j++; } in.close(); br.close(); } catch ( java.io.IOException e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { try { if (in != null || br != null) { in.close(); br.close(); } } catch ( java.io.IOException ex) { } } output.write(); } returnData(XYZFiles[0].replace("." + fileExtension,".shp")); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); if (rIn != null) { try { rIn.close(); } catch ( Exception e) { } } amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
protected void decodeAtom(PushbackInputStream inStream,OutputStream outStream,int l) throws IOException { int i, p1, p2, np1, np2; byte a=-1, b=-1, c=-1; byte high_byte, low_byte; byte tmp[]=new byte[3]; i=inStream.read(tmp); if (i != 3) { throw new CEStreamExhausted(); } for (i=0; (i < 64) && ((a == -1) || (b == -1) || (c == -1)); i++) { if (tmp[0] == map_array[i]) { a=(byte)i; } if (tmp[1] == map_array[i]) { b=(byte)i; } if (tmp[2] == map_array[i]) { c=(byte)i; } } high_byte=(byte)(((a & 0x38) << 2) + (b & 0x1f)); low_byte=(byte)(((a & 0x7) << 5) + (c & 0x1f)); p1=0; p2=0; for (i=1; i < 256; i=i * 2) { if ((high_byte & i) != 0) p1++; if ((low_byte & i) != 0) p2++; } np1=(b & 32) / 32; np2=(c & 32) / 32; if ((p1 & 1) != np1) { throw new CEFormatException("UCDecoder: High byte parity error."); } if ((p2 & 1) != np2) { throw new CEFormatException("UCDecoder: Low byte parity error."); } outStream.write(high_byte); crc.update(high_byte); if (l == 2) { outStream.write(low_byte); crc.update(low_byte); } }
Decode one atom - reads the characters from the input stream, decodes them, and checks for valid parity.
public void tagFrameLabel(String label) throws IOException { if (tags != null) { tags.tagFrameLabel(label); } }
SWFTagTypes interface
public synchronized void stop(){ watch=false; notify(); }
Stop watching.
public void confirmByte(char lastByte){ pktStat=PacketStatus.COMPLEMENT; writeChar((char)~lastByte,true); }
confirm reception of last byte by sending complement of it back
public void paint(Graphics a,JComponent b){ for (int i=0; i < uis.size(); i++) { ((ComponentUI)(uis.elementAt(i))).paint(a,b); } }
Invokes the <code>paint</code> method on each UI handled by this object.
private void encodeDelete(final DiffPart part) throws EncodingException { data.writeBit(0); data.writeBit(1); data.writeBit(1); data.writeValue(codecData.getBlocksizeS(),part.getStart()); data.writeValue(codecData.getBlocksizeE(),part.getLength()); data.writeFillBits(); }
Encodes a Delete operation.
public static Map<String,Object> testRandomAuthorize(DispatchContext dctx,Map<String,? extends Object> context){ Locale locale=(Locale)context.get("locale"); Map<String,Object> result=ServiceUtil.returnSuccess(); String refNum=UtilDateTime.nowAsString(); Random r=new Random(); int i=r.nextInt(9); if (i < 5 || i % 2 == 0) { result.put("authResult",Boolean.TRUE); result.put("authFlag","A"); } else { result.put("authResult",Boolean.FALSE); result.put("authFlag","D"); } result.put("processAmount",context.get("processAmount")); result.put("authRefNum",refNum); result.put("authAltRefNum",refNum); result.put("authCode","100"); result.put("authMessage",UtilProperties.getMessage(resource,"AccountingPaymentTestCapture",locale)); return result; }
Test authorize - does random declines
public void testBug19803348() throws Exception { Connection testConn=null; try { testConn=getConnectionWithProps("useInformationSchema=false,getProceduresReturnsFunctions=false,nullCatalogMeansCurrent=false"); DatabaseMetaData dbmd=testConn.getMetaData(); String testDb1="testBug19803348_db1"; String testDb2="testBug19803348_db2"; if (!dbmd.supportsMixedCaseIdentifiers()) { testDb1=testDb1.toLowerCase(); testDb2=testDb2.toLowerCase(); } createDatabase(testDb1); createDatabase(testDb2); createFunction(testDb1 + ".testBug19803348_f","(d INT) RETURNS INT BEGIN RETURN d; END"); createProcedure(testDb1 + ".testBug19803348_p","(d int) BEGIN SELECT d; END"); this.rs=dbmd.getFunctions(null,null,"testBug19803348_%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_f",this.rs.getString(3)); assertFalse(this.rs.next()); this.rs=dbmd.getFunctionColumns(null,null,"testBug19803348_%","%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_f",this.rs.getString(3)); assertEquals("",this.rs.getString(4)); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_f",this.rs.getString(3)); assertEquals("d",this.rs.getString(4)); assertFalse(this.rs.next()); this.rs=dbmd.getProcedures(null,null,"testBug19803348_%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_p",this.rs.getString(3)); assertFalse(this.rs.next()); this.rs=dbmd.getProcedureColumns(null,null,"testBug19803348_%","%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_p",this.rs.getString(3)); assertEquals("d",this.rs.getString(4)); assertFalse(this.rs.next()); dropFunction(testDb1 + ".testBug19803348_f"); dropProcedure(testDb1 + ".testBug19803348_p"); createFunction(testDb1 + ".testBug19803348_B_f","(d INT) RETURNS INT BEGIN RETURN d; END"); createProcedure(testDb1 + ".testBug19803348_B_p","(d int) BEGIN SELECT d; END"); createFunction(testDb2 + ".testBug19803348_A_f","(d INT) RETURNS INT BEGIN RETURN d; END"); createProcedure(testDb2 + ".testBug19803348_A_p","(d int) BEGIN SELECT d; END"); this.rs=dbmd.getFunctions(null,null,"testBug19803348_%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_B_f",this.rs.getString(3)); assertTrue(this.rs.next()); assertEquals(testDb2,this.rs.getString(1)); assertEquals("testBug19803348_A_f",this.rs.getString(3)); assertFalse(this.rs.next()); this.rs=dbmd.getFunctionColumns(null,null,"testBug19803348_%","%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_B_f",this.rs.getString(3)); assertEquals("",this.rs.getString(4)); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_B_f",this.rs.getString(3)); assertEquals("d",this.rs.getString(4)); assertTrue(this.rs.next()); assertEquals(testDb2,this.rs.getString(1)); assertEquals("testBug19803348_A_f",this.rs.getString(3)); assertEquals("",this.rs.getString(4)); assertTrue(this.rs.next()); assertEquals(testDb2,this.rs.getString(1)); assertEquals("testBug19803348_A_f",this.rs.getString(3)); assertEquals("d",this.rs.getString(4)); assertFalse(this.rs.next()); this.rs=dbmd.getProcedures(null,null,"testBug19803348_%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_B_p",this.rs.getString(3)); assertTrue(this.rs.next()); assertEquals(testDb2,this.rs.getString(1)); assertEquals("testBug19803348_A_p",this.rs.getString(3)); assertFalse(this.rs.next()); this.rs=dbmd.getProcedureColumns(null,null,"testBug19803348_%","%"); assertTrue(this.rs.next()); assertEquals(testDb1,this.rs.getString(1)); assertEquals("testBug19803348_B_p",this.rs.getString(3)); assertEquals("d",this.rs.getString(4)); assertTrue(this.rs.next()); assertEquals(testDb2,this.rs.getString(1)); assertEquals("testBug19803348_A_p",this.rs.getString(3)); assertEquals("d",this.rs.getString(4)); assertFalse(this.rs.next()); } finally { if (testConn != null) { testConn.close(); } } }
Tests fix for BUG#19803348 - GETPROCEDURES() RETURNS INCORRECT O/P WHEN USEINFORMATIONSCHEMA=FALSE. Composed by two parts: 1. Confirm that getProcedures() and getProcedureColumns() aren't returning more results than expected (as per reported bug). 2. Confirm that the results from getProcedures() and getProcedureColumns() are in the right order (secondary bug). Test duplicated in testsuite.regression.MetaDataRegressionTest.
public StringBuffer numberToString(final String strNumberToConvert){ String strNumber="", signBit=""; if (strNumberToConvert.startsWith("-")) { strNumber="" + strNumberToConvert.substring(1,strNumberToConvert.length()); signBit="-"; } else strNumber="" + strNumberToConvert; final DecimalFormat dft=new DecimalFormat("##############0.00"); final String strtemp="" + dft.format(Double.parseDouble(strNumber)); StringBuffer strbNumber=new StringBuffer(strtemp); final int intLen=strbNumber.length(); for (int i=intLen - 6; i > 0; i=i - 2) strbNumber.insert(i,','); if (signBit.equals("-")) strbNumber=strbNumber.insert(0,"-"); return strbNumber; }
function to format amount into to Indaian rupees format
public double nextDouble(double mean,double gamma,double cut){ if (gamma == 0.0) return mean; if (cut == Double.NEGATIVE_INFINITY) { double val=Math.atan(-mean / gamma); double rval=this.uniform.nextDoubleFromTo(val,Math.PI / 2.0); double displ=gamma * Math.tan(rval); return Math.sqrt(mean * mean + mean * displ); } else { double tmp=Math.max(0.0,mean - cut); double lower=Math.atan((tmp * tmp - mean * mean) / (mean * gamma)); double upper=Math.atan(((mean + cut) * (mean + cut) - mean * mean) / (mean * gamma)); double rval=this.uniform.nextDoubleFromTo(lower,upper); double displ=gamma * Math.tan(rval); return Math.sqrt(Math.max(0.0,mean * mean + mean * displ)); } }
Returns a mean-squared random number from the distribution; bypasses the internal state.
public void testRealmJMXAuthenticatorRandomNumberGenerator(){ int randomNumber=SecurityHelper.getRandomInt(0,0,0); assertTrue(randomNumber == 0); randomNumber=SecurityHelper.getRandomInt(-1,-10,1); assertTrue(randomNumber == 0); randomNumber=SecurityHelper.getRandomInt(-10,2,1); assertTrue(MessageFormat.format("randomNumber={0}",randomNumber),randomNumber >= 0 && randomNumber <= 2); randomNumber=SecurityHelper.getRandomInt(5,2,1); assertTrue(MessageFormat.format("randomNumber={0}",randomNumber),randomNumber <= 5 && randomNumber >= 2); randomNumber=SecurityHelper.getRandomInt(500,3000,100); assertTrue(MessageFormat.format("randomNumber={0}",randomNumber),(randomNumber - 500) % 100 == 0); randomNumber=SecurityHelper.getRandomInt(500,3000,15); assertTrue(MessageFormat.format("randomNumber={0}",randomNumber),(randomNumber - 500) % 15 == 0); randomNumber=SecurityHelper.getRandomInt(500,3000,0); assertTrue(MessageFormat.format("randomNumber={0}",randomNumber),randomNumber >= 500 && randomNumber <= 3000); randomNumber=SecurityHelper.getRandomInt(0,10,11); assertTrue(MessageFormat.format("randomNumber={0}",randomNumber),randomNumber >= 0 && randomNumber <= 10); }
Confirm that RealmJMXAuthenticator.getRandomInt(min, max) always returns a coherent value
public boolean hasRecvSequenceNumber(){ return recvSequenceNumber != null; }
Check whether recv sequence number has been set.
public LicensePanel(AssetPackProject project){ this.project=project; initComponents(); setName("License"); jTextArea1.setText(project.getLicense()); }
Creates new form LicensePanel
public ProcessTerminatedAbnormallyException(final int exitValue,final String message,final Throwable cause){ super(message,cause); this.exitValue=exitValue; }
Constructs an instance of the ProcessTerminatedAbnormallyException class with the given exit value of the process as well as a message indicating the reason of the abnormal termination along with a Throwable representing the underlying cause of the process termination. </p>
protected void addTrailerToOutput(byte[] msg,int offset,AbstractMRMessage m){ incomingLength=((SerialMessage)m).getResponseLength(); currentAddr=((SerialMessage)m).getAddr(); return; }
Although this protocol doesn't use a trailer, we implement this method to set the expected reply length and address for this message.
public static void main(String... a){ print("Object",new Object()); print("Timestamp",new java.sql.Timestamp(0)); print("Date",new java.sql.Date(0)); print("Time",new java.sql.Time(0)); print("BigDecimal",new BigDecimal("0")); print("BigInteger",new BigInteger("0")); print("String",new String("Hello")); print("Data",Data.create(null,10)); print("Row",new RowImpl(new Value[0],0)); System.out.println(); for (int i=1; i < 128; i+=i) { System.out.println(getArraySize(1,i) + " bytes per p1[]"); print("boolean[" + i + "]",new boolean[i]); System.out.println(getArraySize(2,i) + " bytes per p2[]"); print("char[" + i + "]",new char[i]); print("short[" + i + "]",new short[i]); System.out.println(getArraySize(4,i) + " bytes per p4[]"); print("int[" + i + "]",new int[i]); print("float[" + i + "]",new float[i]); System.out.println(getArraySize(8,i) + " bytes per p8[]"); print("long[" + i + "]",new long[i]); print("double[" + i + "]",new double[i]); System.out.println(getArraySize(Constants.MEMORY_POINTER,i) + " bytes per obj[]"); print("Object[" + i + "]",new Object[i]); System.out.println(); } }
Run just this test.
public SQLException(String theReason,Throwable theCause){ super(theReason,theCause); }
Creates an SQLException object. The Reason string is set to the given and the cause Throwable object is set to the given cause Throwable object.
@Override public void write(byte[] value) throws IOException { if (isFirstTime) { init(); isFirstTime=false; } checkAndWriteDictionaryChunkToFile(); oneDictionaryChunkList.add(ByteBuffer.wrap(value)); totalRecordCount++; }
This method will write the data in thrift format to disk. This method will be guided by parameter dictionary_one_chunk_size and data will be divided into chunks based on this parameter
public boolean remove(HttpConnection connection){ TimeValues times=connectionToTimes.remove(connection); if (times == null) { log.warn("Removing a connection that never existed!"); return true; } else { return System.currentTimeMillis() <= times.timeExpires; } }
Removes the given connection from the list of connections to be closed when idle. This will return true if the connection is still valid, and false if the connection should be considered expired and not used.
@RequestProcessing(value="/about",method=HTTPRequestMethod.GET) @Before(adviceClass={StopwatchStartAdvice.class,AnonymousViewCheck.class}) @After(adviceClass=StopwatchEndAdvice.class) public void showAbout(final HTTPRequestContext context,final HttpServletRequest request,final HttpServletResponse response) throws Exception { request.setAttribute(Keys.TEMAPLTE_DIR_NAME,Symphonys.get("skinDirName")); final AbstractFreeMarkerRenderer renderer=new SkinRenderer(); context.setRenderer(renderer); renderer.setTemplateName("about.ftl"); final Map<String,Object> dataModel=renderer.getDataModel(); filler.fillHeaderAndFooter(request,response,dataModel); filler.fillRandomArticles(dataModel); filler.fillHotArticles(dataModel); filler.fillSideTags(dataModel); filler.fillLatestCmts(dataModel); }
Shows about.
protected void sendMessage(boolean flush) throws IOException { sendMessage(); if (flush) flush(); }
Send outgoing message and optionally flush stream.
public void storeOriginals(){ mStartingStartTrim=mStartTrim; mStartingEndTrim=mEndTrim; mStartingRotation=mRotation; }
If the start / end trim are offset to begin with, store them so that animation starts from that offset.
private void writeQNameAttribute(java.lang.String namespace,java.lang.String attName,javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace=qname.getNamespaceURI(); java.lang.String attributePrefix=xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix=registerPrefix(xmlWriter,attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue=attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue=qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attributeValue); } else { registerPrefix(xmlWriter,namespace); xmlWriter.writeAttribute(namespace,attName,attributeValue); } }
Util method to write an attribute without the ns prefix
private static Channel configureChannel(ChannelType channel_type) throws IllegalArgumentException { if (channel_type == null) { throw new IllegalArgumentException("Cannot configure a network channel from a null type."); } ChannelQueue channel=new ChannelQueue(channel_type.getName()); channel.setWeight(channel_type.getWeight()); ClassifierType classifier_type=channel_type.getClassifier(); if (classifier_type != null) { ChannelClassifier classifier=new ChannelClassifier(); if (classifier_type.getIncludes() != null) { for ( ClassifierCriteriaType include_type : classifier_type.getIncludes().getInclude()) { ChannelClassifierRules rules=new ChannelClassifierRules(); rules.setEmailPattern(include_type.getUserEmailPattern()); rules.setServiceName(include_type.getService()); classifier.addIncludeRules(rules); } } if (classifier_type.getExcludes() != null) { for ( ClassifierCriteriaType exclude_type : classifier_type.getExcludes().getExclude()) { ChannelClassifierRules rules=new ChannelClassifierRules(); rules.setEmailPattern(exclude_type.getUserEmailPattern()); rules.setServiceName(exclude_type.getService()); classifier.addExcludeRules(rules); } } channel.setClassifier(classifier); } UserQuotasType user_quota_type=channel_type.getDefaultUserQuotas(); if (user_quota_type != null) { UserQuotas.Builder quota_builder=new UserQuotas.Builder(); if (user_quota_type.getMaxConcurrent() != null) { quota_builder.maxConcurrent(user_quota_type.getMaxConcurrent().intValue()); } if (user_quota_type.getMaxCount() != null) { PeriodicalPositiveInt max_count=user_quota_type.getMaxCount(); quota_builder.maxCount(max_count.getValue(),max_count.getPeriod(),TimeUnit.valueOf(max_count.getPeriodUnit().value())); } if (user_quota_type.getMaxSize() != null) { quota_builder.maxSize(user_quota_type.getMaxSize().longValue()); } if (user_quota_type.getMaxCumulativeSize() != null) { PeriodicalPositiveLong max_cumul_size=user_quota_type.getMaxCumulativeSize(); quota_builder.maxCumulativeSize(max_cumul_size.getValue(),max_cumul_size.getPeriod(),TimeUnit.valueOf(max_cumul_size.getPeriodUnit().value())); } if (user_quota_type.getMaxBandwidth() != null) { quota_builder.maxBandwidth(user_quota_type.getMaxBandwidth().intValue()); } channel.setDefaultUserQuotas(quota_builder.build()); } for ( ChannelType sub_channel_type : channel_type.getChannel()) { channel.addChannel(configureChannel(sub_channel_type)); } return channel; }
TODO Documentation