code
stringlengths
10
174k
nl
stringlengths
3
129k
public SVGAltGlyphHandler(BridgeContext ctx,Element textElement){ this.ctx=ctx; this.textElement=textElement; }
Constructs an SVGAltGlyphHandler.
protected byte[] inputStreamToByteArray(InputStream is) throws IOException { ByteArrayOutputStream bos=new ByteArrayOutputStream(); int next=is.read(); while (next > -1) { bos.write(next); next=is.read(); } bos.flush(); is.close(); return bos.toByteArray(); }
Reads an input stream into a byte array
public MecanumDrive(Motor leftFront,Motor leftRear,Motor rightFront,Motor rightRear,AngleSensor gyro){ this(leftFront,leftRear,rightFront,rightRear,gyro,null); }
Creates a new DriveSystem subsystem that uses the supplied drive train and no shifter. The voltage send to the drive train is limited to [-1.0,1.0].
public void addPattern(String pattern){ if (pattern.equals("!")) { clearPatterns(); } else { patterns.add(new SimpleStringPattern(pattern)); } }
Adds a string to the list of ignore file patters using the SimpleStringPattern.
private static void transferStreams(InputStream source,OutputStream destination){ byte[] buffer=new byte[8096]; try { while (true) { int bytesRead=-1; try { bytesRead=source.read(buffer); } catch ( IOException e) { return; } if (bytesRead == -1) break; try { destination.write(buffer,0,bytesRead); } catch ( IOException e) { return; } } } finally { try { source.close(); } catch ( IOException e) { } finally { try { destination.close(); } catch ( IOException e) { } } } }
Transfers all available bytes from the given input stream to the given output stream. Regardless of failure, this method closes both streams.
@Override public void interrupt(){ super.interrupt(); U.closeQuiet(proc.getErrorStream()); U.closeQuiet(proc.getInputStream()); U.closeQuiet(proc.getOutputStream()); }
Interrupts a thread and closes process streams.
public void onDrawerOpened(View drawerView){ super.onDrawerOpened(drawerView); }
Called when a drawer has settled in a completely open state.
public String toString(){ StringBuffer sb=new StringBuffer("MContactInterest[").append("R_InterestArea_ID=").append(getR_InterestArea_ID()).append(",AD_User_ID=").append(getAD_User_ID()).append(",Subscribed=").append(isSubscribed()).append("]"); return sb.toString(); }
String representation
public static void inPlaceSort(Comparable[] x){ inPlaceSort(x,0,x.length - 1); }
In-Place Merge Sort. Building on the algorithm core found in http://www.cs.ubc.ca/~harrison/Java/MergeSortAlgorithm.java.html
public static Cuboid floor(Cuboid cuboid){ Vector min=floor(cuboid.minimum()); Vector max=floor(cuboid.maximum()); return Cuboid.between(min,max); }
Rounds all values of a cuboid down.
public static ClassInfo findOrCreateClass(String dalvikClassName){ return ClassInfo.findOrCreateClass(toCanonicalName(dalvikClassName)); }
Find a ClassInfo by Dalvik class name
public CompiledAutomaton(Automaton automaton){ this(automaton,null,true); }
Create this, passing simplify=true and finite=null, so that we try to simplify the automaton and determine if it is finite.
public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject,String containerName,IPath[] inclusionFilters,IPath[] exclusionFilters) throws CoreException { return addSourceContainer(jproject,containerName,inclusionFilters,exclusionFilters,null); }
Adds a source container to a IJavaProject.
public String minNumInstancesTipText(){ return "Set the minimum number of instances at which a node is considered for splitting. " + "The default value is 15."; }
Returns the tip text for this property
@Override public boolean needsSaving(boolean flag){ return this.isModified; }
Check whether this column needs to be written back to disk for persistence
@Override public void transform(AffineTransform tx){ if (get(TRANSFORM) != null || tx.getType() != (tx.getType() & AffineTransform.TYPE_TRANSLATION)) { if (get(TRANSFORM) == null) { set(TRANSFORM,(AffineTransform)tx.clone()); } else { AffineTransform t=TRANSFORM.getClone(this); t.preConcatenate(tx); set(TRANSFORM,t); } } else { for (int i=0; i < coordinates.length; i++) { tx.transform(coordinates[i],coordinates[i]); } if (get(FILL_GRADIENT) != null && !get(FILL_GRADIENT).isRelativeToFigureBounds()) { Gradient g=FILL_GRADIENT.getClone(this); g.transform(tx); set(FILL_GRADIENT,g); } if (get(STROKE_GRADIENT) != null && !get(STROKE_GRADIENT).isRelativeToFigureBounds()) { Gradient g=STROKE_GRADIENT.getClone(this); g.transform(tx); set(STROKE_GRADIENT,g); } } invalidate(); }
Transforms the figure.
public boolean startsWith(String prefix,int toffset){ return value.startsWith(prefix,toffset); }
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
public static int dayOfYear(int year,int month,int date){ int leapAdjust=month > 2 && isLeapYear(year) ? 1 : 0; return MONTH_START_TO_DOY[month - 1] + leapAdjust + date - 1; }
Gets the day of the year for a given date.
public void reset(){ operations.clear(); }
reset the buffer, empty the operations list
@Override public Iterator<IModule> iterator(){ return subModules.iterator(); }
Returns an iterator for the module's submodules
public BayesPm(Graph graph,int lowerBound,int upperBound){ if (graph == null) { throw new NullPointerException("The graph must not be null."); } this.dag=new EdgeListGraph(graph); this.nodesToVariables=new HashMap<>(); initializeValues(lowerBound,upperBound); }
Constructs a new BayesPm from the given DAG, assigning each variable a random number of values between <code>lowerBound</code> and <code>upperBound</code>. Uses a fixed number of values if lowerBound == upperBound. The values are named "value1" ... "valuen".
public static synchronized void sdkInitialize(Context applicationContext,int callbackRequestCodeOffset){ if (sdkInitialized && callbackRequestCodeOffset != FacebookSdk.callbackRequestCodeOffset) { throw new FacebookException(CALLBACK_OFFSET_CHANGED_AFTER_INIT); } if (callbackRequestCodeOffset < 0) { throw new FacebookException(CALLBACK_OFFSET_NEGATIVE); } FacebookSdk.callbackRequestCodeOffset=callbackRequestCodeOffset; sdkInitialize(applicationContext); }
This function initializes the Facebook SDK, the behavior of Facebook SDK functions are undetermined if this function is not called. It should be called as early as possible.
private void errorLocation(){ if (!getCellPosition()) { sendSMS(M.e("Cell and GPS info not available")); } }
Error location.
public int convertToPixels(int dipCount,boolean horizontal){ return impl.convertToPixels(dipCount,horizontal); }
Converts the dips count to pixels, dips are roughly 1mm in length. This is a very rough estimate and not to be relied upon
public IdentityHashMap(){ this(DEFAULT_MAX_SIZE); }
Creates an IdentityHashMap with default expected maximum size.
public List<NotizenMassnahmeResult> findNotizenForZielobjekt(String name){ List<NotizenMassnahmeResult> result=new ArrayList<NotizenMassnahmeResult>(); NZielobjektDAO dao=new NZielobjektDAO(); Transaction transaction=dao.getSession().beginTransaction(); Query query=dao.getSession().createQuery(QUERY_NOTIZEN_FOR_ZIELOBJEKT_NAME); query.setParameter("name",name,Hibernate.STRING); Iterator iterate=query.iterate(); while (iterate.hasNext()) { Object[] next=(Object[])iterate.next(); result.add(new NotizenMassnahmeResult((MbBaust)next[0],(MbMassn)next[1],(MUmsetzStatTxt)next[2],(ModZobjBst)next[3],(ModZobjBstMass)next[4],(NmbNotiz)next[5])); } query=dao.getSession().createQuery(QUERY_BAUSTEIN_NOTIZEN_FOR_ZIELOBJEKT_NAME); query.setParameter("name",name,Hibernate.STRING); iterate=query.iterate(); while (iterate.hasNext()) { Object[] next=(Object[])iterate.next(); result.add(new NotizenMassnahmeResult((MbBaust)next[0],null,null,(ModZobjBst)next[1],null,(NmbNotiz)next[2])); } transaction.commit(); dao.getSession().close(); return result; }
Finds notes that are attached to "massnahmen" by target object.
public static void waitForState(String service,State state,long timeoutMillis) throws TimeoutException { final long endMillis=SystemClock.elapsedRealtime() + timeoutMillis; while (true) { synchronized (sPropertyLock) { final State currentState=getState(service); if (state.equals(currentState)) { return; } if (SystemClock.elapsedRealtime() >= endMillis) { throw new TimeoutException("Service " + service + " currently "+ currentState+ "; waited "+ timeoutMillis+ "ms for "+ state); } try { sPropertyLock.wait(timeoutMillis); } catch ( InterruptedException e) { } } } }
Wait until given service has entered specific state.
public String format(DateTime commentedAt){ DateTime now=DateTime.now(); Minutes minutesBetween=Minutes.minutesBetween(commentedAt,now); if (minutesBetween.isLessThan(Minutes.ONE)) { return "just now"; } Hours hoursBetween=Hours.hoursBetween(commentedAt,now); if (hoursBetween.isLessThan(Hours.ONE)) { return formatMinutes(minutesBetween.getMinutes()); } Days daysBetween=Days.daysBetween(commentedAt,now); if (daysBetween.isLessThan(Days.ONE)) { return formatHours(hoursBetween.getHours()); } Weeks weeksBetween=Weeks.weeksBetween(commentedAt,now); if (weeksBetween.isLessThan(Weeks.ONE)) { return formatDays(daysBetween.getDays()); } Months monthsBetween=Months.monthsBetween(commentedAt,now); if (monthsBetween.isLessThan(Months.ONE)) { return formatWeeks(weeksBetween.getWeeks()); } Years yearsBetween=Years.yearsBetween(commentedAt,now); if (yearsBetween.isLessThan(Years.ONE)) { return formatMonths(monthsBetween.getMonths()); } return formatYears(yearsBetween.getYears()); }
For use with org.joda.DateTime
@Override protected void doAction(){ DImportKeyPairType dImportKeyPairType=new DImportKeyPairType(frame); dImportKeyPairType.setLocationRelativeTo(frame); dImportKeyPairType.setVisible(true); if (!dImportKeyPairType.importTypeSelected()) { return; } if (dImportKeyPairType.importPkcs12()) { importKeyPairPkcs12(); } else if (dImportKeyPairType.importPkcs8()) { importKeyPairPkcs8(); } else if (dImportKeyPairType.importPvk()) { importKeyPairPvk(); } else { importKeyPairOpenSsl(); } }
Do action.
public Iterator<K1> iterator(){ return new KeyIterator<K1,V1>(_map); }
Returns the iterator.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case N4JSPackage.BREAK_STATEMENT__LABEL: if (resolve) return getLabel(); return basicGetLabel(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public boolean isTypeBox(){ return getPrintFormatType().equals(PRINTFORMATTYPE_Line) || getPrintFormatType().equals(PRINTFORMATTYPE_Rectangle); }
Type Box
public boolean contains(JComponent a,int b,int c){ boolean returnValue=((ComponentUI)(uis.elementAt(0))).contains(a,b,c); for (int i=1; i < uis.size(); i++) { ((ComponentUI)(uis.elementAt(i))).contains(a,b,c); } return returnValue; }
Invokes the <code>contains</code> method on each UI handled by this object.
public void swap(final Type prev,final Type type){ if (type.getSize() == 1) { if (prev.getSize() == 1) { swap(); } else { dupX2(); pop(); } } else { if (prev.getSize() == 1) { dup2X1(); pop2(); } else { dup2X2(); pop2(); } } }
Generates the instructions to swap the top two stack values.
public EventException(){ cause=null; }
Constructs a new EventException
public BufferedInputStream(InputStream in,int size,String name){ this.in=in; if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf=new byte[size]; streamCount++; this.name=name; Util.getImplementation().logStreamCreate(name,true,streamCount); }
Creates a <code>BufferedInputStream</code> with the specified buffer size, and saves its argument, the input stream <code>in</code>, for later use. An internal buffer array of length <code>size</code> is created and stored in <code>buf</code>.
public static boolean isPositiveInteger(String s){ if (isEmpty(s)) return defaultEmptyOK; try { long temp=Long.parseLong(s); if (temp > 0) return true; return false; } catch ( Exception e) { return false; } }
Returns true if string s is an integer > 0. NOTE: using the Java Long object for greatest precision
public int substringWidth(String str,int offset,int len){ return Display.impl.stringWidth(font,str.substring(offset,offset + len)); }
Return the width of the given string subset in this font instance
public DecimalAnswerFormat(float minValue,float maxValue){ this.minValue=minValue; this.maxValue=maxValue; }
Creates an answer format with the specified min and max values
@Override public void onMapSharedElements(List<String> names,Map<String,View> sharedElements){ if (sharedElements.size() != names.size()) { final View sharedShot=sharedElements.get(shotTransitionName); if (sharedShot != null) { sharedElements.put(shotBackgroundTransitionName,sharedShot); } } }
We're performing a slightly unusual shared element transition i.e. from one view (image in the grid) to two views (the image & also the background of the details view, to produce the expand effect). After changing orientation, the transition system seems unable to map both shared elements (only seems to map the shot, not the background) so in this situation we manually map the background to the same view.
public synchronized Object clone(){ try { Vector v=(Vector)super.clone(); v.elementData=new Object[elementCount]; System.arraycopy(elementData,0,v.elementData,0,elementCount); v.modCount=0; return v; } catch ( CloneNotSupportedException e) { throw new InternalError(); } }
Returns a clone of this vector. The copy will contain a reference to a clone of the internal data array, not a reference to the original internal data array of this <tt>Vector</tt> object.
public DefaultPlayerBridge(final IGame aGame){ m_game=aGame; final GameStepListener m_gameStepListener=null; m_game.addGameStepListener(m_gameStepListener); }
Creates new DefaultPlayerBridge
public GetRequestMessage(GetRequestMessage other){ if (other.isSetHeader()) { this.header=new AsyncMessageHeader(other.header); } if (other.isSetStoreName()) { this.storeName=other.storeName; } if (other.isSetKey()) { this.key=org.apache.thrift.TBaseHelper.copyBinary(other.key); ; } }
Performs a deep copy on <i>other</i>.
public List<WebElement> findElements(By by){ return driver.findElements(by); }
Finds all WebElements by the given By locator.
public CSVWriter(String mimeType){ super(mimeType); if ("text/tab-separated-values".equals(mimeType)) { setDefault(SEPARATOR_CHAR,'\t'); } else { setDefault(SEPARATOR_CHAR,','); } }
Creates a new instance with the specified MIME-Type. The delimiter is set depending on the MIME type parameter. By default a comma is used as a delimiter.
public static ComputeState mapInstanceToComputeState(Instance instance,String parentComputeLink,String resourcePoolLink,String computeDescriptionLink,List<String> tenantLinks){ ComputeService.ComputeState computeState=new ComputeService.ComputeState(); computeState.id=instance.getInstanceId(); computeState.name=instance.getInstanceId(); computeState.parentLink=parentComputeLink; computeState.resourcePoolLink=resourcePoolLink; computeState.descriptionLink=UriUtils.buildUriPath(computeDescriptionLink); computeState.address=instance.getPublicIpAddress(); computeState.powerState=AWSUtils.mapToPowerState(instance.getState()); computeState.customProperties=new HashMap<String,String>(); computeState.customProperties.put(CUSTOM_OS_TYPE,getNormalizedOSType(instance)); if (!instance.getTags().isEmpty()) { computeState.tagLinks=instance.getTags().stream().filter(null).map(null).map(null).collect(Collectors.toSet()); String nameTag=getTagValue(instance,AWS_TAG_NAME); if (nameTag != null) { computeState.name=nameTag; } } computeState.customProperties.put(SOURCE_TASK_LINK,ResourceEnumerationTaskService.FACTORY_LINK); if (instance.getLaunchTime() != null) { computeState.creationTimeMicros=TimeUnit.MILLISECONDS.toMicros(instance.getLaunchTime().getTime()); } computeState.tenantLinks=tenantLinks; computeState.customProperties.put(AWS_VPC_ID,instance.getVpcId()); return computeState; }
Maps the instance discovered on AWS to a local compute state that will be persisted.
private void process(final HttpServletRequest req,final HttpServletResponse res) throws IOException { try { final byte[] img; final String imgType; if (req.getParameter(Constants.REQ_PARAM_TYPE) == null) { imgType="image/jpeg"; img=createCaptcha(req); } else { final VOImageResource imageResource=retrieveVOImageResource(req); res.setHeader("Cache-Control","max-age=1800"); final Calendar cal=Calendar.getInstance(); cal.add(Calendar.MINUTE,30); res.setHeader("Expires",new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(cal.getTime())); if (imageResource == null) { imgType="image/gif"; img=TRANSPARENT_PIXEL; } else { imgType=imageResource.getContentType(); img=imageResource.getBuffer(); } } res.setContentType(imgType); res.getOutputStream().write(img); } catch ( Throwable ex) { logger.logError(Log4jLogger.SYSTEM_LOG,ex,LogMessageIdentifier.ERROR_IMAGE_FOR_SUPPLIER_NOT_FOUND); } }
Writes the image with the requested id to the output stream of the response
private static void splitAllLiveRanges(Instruction s,java.util.HashMap<Register,Register> newMap,IR ir,boolean rootOnly){ for (Enumeration<Operand> u=rootOnly ? s.getRootUses() : s.getUses(); u.hasMoreElements(); ) { Operand use=u.nextElement(); if (use.isRegister()) { RegisterOperand rUse=use.asRegister(); RegisterOperand temp=findOrCreateTemp(rUse,newMap,ir); insertMoveBefore(temp,rUse.copyRO(),s); } } for (Enumeration<Operand> d=s.getDefs(); d.hasMoreElements(); ) { Operand def=d.nextElement(); if (def.isRegister()) { RegisterOperand rDef=def.asRegister(); RegisterOperand temp=findOrCreateTemp(rDef,newMap,ir); insertMoveAfter(rDef.copyRO(),temp,s); } } for (Enumeration<Operand> ops=rootOnly ? s.getRootOperands() : s.getOperands(); ops.hasMoreElements(); ) { Operand op=ops.nextElement(); if (op.isRegister()) { RegisterOperand rOp=op.asRegister(); Register r=rOp.getRegister(); Register newR=newMap.get(r); if (newR != null) { rOp.setRegister(newR); } } } }
Split the live ranges of all register operands of an instruction
static Handler remove(Handler h,Label start,Label end){ if (h == null) { return null; } else { h.next=remove(h.next,start,end); } int hstart=h.start.position; int hend=h.end.position; int s=start.position; int e=end == null ? Integer.MAX_VALUE : end.position; if (s < hend && e > hstart) { if (s <= hstart) { if (e >= hend) { h=h.next; } else { h.start=end; } } else if (e >= hend) { h.end=start; } else { Handler g=new Handler(); g.start=end; g.end=h.end; g.handler=h.handler; g.desc=h.desc; g.type=h.type; g.next=h.next; h.end=start; h.next=g; } } return h; }
Removes the range between start and end from the given exception handlers.
private void restoreIcon(Key key,byte[] buffer,int dataSize) throws IOException { if (VERBOSE) Log.v(TAG,"unpacking icon " + key.id); if (DEBUG) Log.d(TAG,"read (" + buffer.length + "): "+ Base64.encodeToString(buffer,0,dataSize,Base64.NO_WRAP)); Resource res=unpackProto(new Resource(),buffer,dataSize); if (DEBUG) { Log.d(TAG,"unpacked " + res.dpi + " dpi icon"); } Bitmap icon=BitmapFactory.decodeByteArray(res.data,0,res.data.length); if (icon == null) { Log.w(TAG,"failed to unpack icon for " + key.name); } else { if (VERBOSE) Log.v(TAG,"saving restored icon as: " + key.name); mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name),icon,res.dpi,"",mUserSerial,mIdp); } }
Read an icon from the stream. <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
@SuppressWarnings("unchecked") public static <T>T assertCast(Object object,Class<T> klass){ assertTrue(object == null || klass.isInstance(object)); return (T)object; }
Asserts that given object is null or an instance of given klass. Returns casted object.
private boolean isPassive(){ return this.DataSocketPassiveMode; }
use passive ftp?
private void verifyMarketingPermissions(VOTechnicalService tp,List<String> orgIds,String userKey) throws Exception { AccountService as=serviceFactory.getAccountService(userKey,DEFAULT_PASSWORD); List<VOOrganization> supps=as.getSuppliersForTechnicalService(tp); for ( VOOrganization supp : supps) { assertTrue(orgIds.contains(supp.getOrganizationId())); } if (orgIds == null || orgIds.isEmpty()) { assertTrue(supps.isEmpty()); } }
Ensures that the given organizations are permitted to use the technical service.
public static String[] readStrings(){ return new In().readAllStrings(); }
Reads all strings from stdin
protected Size2D arrangeRR(BlockContainer container,Graphics2D g2,RectangleConstraint constraint){ Size2D size1=arrange(container,g2,RectangleConstraint.NONE); if (constraint.getWidthRange().contains(size1.getWidth())) { if (constraint.getHeightRange().contains(size1.getHeight())) { return size1; } else { double h=constraint.getHeightRange().constrain(size1.getHeight()); RectangleConstraint cc=new RectangleConstraint(size1.getWidth(),h); return arrangeFF(container,g2,cc); } } else { if (constraint.getHeightRange().contains(size1.getHeight())) { double w=constraint.getWidthRange().constrain(size1.getWidth()); RectangleConstraint cc=new RectangleConstraint(w,size1.getHeight()); return arrangeFF(container,g2,cc); } else { double w=constraint.getWidthRange().constrain(size1.getWidth()); double h=constraint.getHeightRange().constrain(size1.getHeight()); RectangleConstraint cc=new RectangleConstraint(w,h); return arrangeFF(container,g2,cc); } } }
Arrange with ranges for both the width and height constraints.
private void forceConsistency(LinearFunction f1,LinearFunction f2){ boolean warn=false; for (int i=0; i < f1._b.length; i++) { if (f2._b.length < (i + 1)) break; if (!f1._vars[i].equals(f2._vars[i]) && !(f1._vars[i].startsWith(INTERAL_FN_INDEX_ROW) && f2._vars[i].startsWith(INTERAL_FN_INDEX_ROW)) && !(f1._vars[i].startsWith(INTERAL_FN_INDEX_COL) && f2._vars[i].startsWith(INTERAL_FN_INDEX_COL))) { boolean exchange=false; for (int j=i + 1; j < f2._b.length; j++) if (f1._vars[i].equals(f2._vars[j]) || (f1._vars[i].startsWith(INTERAL_FN_INDEX_ROW) && f2._vars[j].startsWith(INTERAL_FN_INDEX_ROW)) || (f1._vars[i].startsWith(INTERAL_FN_INDEX_COL) && f2._vars[j].startsWith(INTERAL_FN_INDEX_COL))) { long btmp=f2._b[i]; String vartmp=f2._vars[i]; f2._b[i]=f2._b[j]; f2._vars[i]=f2._vars[j]; f2._b[j]=btmp; f2._vars[j]=vartmp; exchange=true; } if (!exchange) warn=true; } } if (warn && LOG.isTraceEnabled()) LOG.trace("PARFOR: Warning - index functions f1 and f2 cannot be made consistent."); }
Tries to obtain consistent linear functions by forcing the same variable ordering for efficient comparison: f2 is modified in a way that it matches the sequence of variables in f1.
public synchronized void addWatchSyncPredicate(WatchPredicate<ReplDBMSHeader> predicate) throws InterruptedException { if (logger.isDebugEnabled()) { logger.debug("Adding watch sync predicate: taskId=" + taskId + " predicate="+ predicate.toString()); } watchPredicates.add(predicate); if (lastFrag) { processPredicates(); } }
Add a new predicate to the list of predicates that should generate sync events. If we are at the end of a transaction, see if the event should be posted immediately.
@Field(17) public __VARIANT_NAME_3_union plVal(Pointer<CLong> plVal){ this.io.setPointerField(this,17,plVal); return this; }
VT_BYREF|VT_I4<br> C type : LONG
public boolean removeMiddleOfLastThree(){ if (!hasThree()) return false; IPoint last=points.removeLast(); points.removeLast(); points.insert(last); return true; }
Removes middle of last three.
public SVGPath relativeQuadTo(double c1x,double c1y,double x,double y){ append(PATH_QUAD_TO_RELATIVE,c1x,c1y,x,y); return this; }
Quadratic Bezier line to the given relative coordinates.
private static Collection<InetSocketAddress> address(String ipStr) throws IgniteSpiException { ipStr=ipStr.trim(); String errMsg="Failed to parse provided address: " + ipStr; int colonCnt=ipStr.length() - ipStr.replace(":","").length(); if (colonCnt > 1) { if (ipStr.startsWith("[")) { ipStr=ipStr.substring(1); if (ipStr.contains("]:")) return addresses(ipStr,"\\]\\:",errMsg); else if (ipStr.endsWith("]")) ipStr=ipStr.substring(0,ipStr.length() - 1); else throw new IgniteSpiException(errMsg); } } else { if (ipStr.endsWith(":")) ipStr=ipStr.substring(0,ipStr.length() - 1); else if (ipStr.indexOf(':') >= 0) return addresses(ipStr,"\\:",errMsg); } return Collections.singleton(new InetSocketAddress(ipStr,0)); }
Creates address from string.
public void pauseTransferBySystem(){ if (sLogger.isActivated()) { sLogger.warn("System is pausing transfer"); } mIsPaused=true; getListener().onHttpTransferPausedBySystem(); }
Interrupts file transfer
public static String asHex(byte[] bytes){ return asHex(bytes,null); }
Returns a hexadecimal representation of the given byte array.
public static Ignite start(IgniteConfiguration cfg) throws IgniteCheckedException { return start(cfg,null,true); }
Starts grid with given configuration. Note that this method is no-op if grid with the name provided in given configuration is already started.
public MapCounter(Map<K,Integer> map){ mCount=map; }
Constructs a new CounterMap based on a given Map implementation.
private void initIndicators(){ if (mIndicators.getChildCount() != mHeroes.size() && mHeroes.size() > 1) { mIndicators.removeAllViews(); Resources res=mIndicators.getResources(); int size=res.getDimensionPixelOffset(R.dimen.indicator_size); int margin=res.getDimensionPixelOffset(R.dimen.indicator_margin); for (int i=0; i < getPagerCount(); i++) { ImageView indicator=new ImageView(mIndicators.getContext()); indicator.setAlpha(180); LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(size,size); lp.setMargins(margin,0,0,0); lp.gravity=Gravity.CENTER; indicator.setLayoutParams(lp); Drawable drawable=res.getDrawable(R.drawable.selector_indicator); indicator.setImageDrawable(drawable); mIndicators.addView(indicator); } } }
oh shit! An indicator view is badly needed! this shit have no animation at all.
void removeBuddy(String name){ Buddy buddy=buddyMap.get(name); if (buddy != null) { buddyMap.remove(name); int index=buddyList.indexOf(buddy); buddyList.remove(buddy); fireIntervalRemoved(this,index,index); } }
Remove a buddy from the list.
public void mouseExited(MouseEvent e){ }
Invoked when the mouse exits a component.
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
public static double gainRatio(double[][] matrix){ double preSplit=0, postSplit=0, splitEnt=0, sumForRow, sumForColumn, total=0, infoGain; for (int i=0; i < matrix[0].length; i++) { sumForColumn=0; for (int j=0; j < matrix.length; j++) sumForColumn+=matrix[j][i]; preSplit+=lnFunc(sumForColumn); total+=sumForColumn; } preSplit-=lnFunc(total); for (int i=0; i < matrix.length; i++) { sumForRow=0; for (int j=0; j < matrix[0].length; j++) { postSplit+=lnFunc(matrix[i][j]); sumForRow+=matrix[i][j]; } splitEnt+=lnFunc(sumForRow); } postSplit-=splitEnt; splitEnt-=lnFunc(total); infoGain=preSplit - postSplit; if (Utils.eq(splitEnt,0)) return 0; return infoGain / splitEnt; }
Computes gain ratio for contingency table (split on rows). Returns Double.MAX_VALUE if the split entropy is 0.
public KillRingTransferable(@NotNull String data,@NotNull Document document,int startOffset,int endOffset,boolean cut){ myData=data; myDocument=new WeakReference<Document>(document); myStartOffset=startOffset; myEndOffset=endOffset; myCut=cut; }
Creates new <code>KillRingTransferable</code> object.
public void startPreview(){ if (camera != null && !previewing) { camera.startPreview(); previewing=true; } }
Asks the camera hardware to begin drawing preview frames to the screen.
static DataBundle loadStream(ProgressDelegate progressBarDelegate,final BufferedInputStream is,final String shortName,boolean showProgress) throws IOException { int lines=0; int totalVariants=-1; final ArrayList<RocPoint> points=new ArrayList<>(); final ArrayList<String> scores=new ArrayList<>(); String line=null; String scoreName=null; try (BufferedReader br=new BufferedReader(new InputStreamReader(is))){ String prevScore=null; float prevFp=0.0f; float prevTp=0.0f; float prevRawTp=0.0f; int scoreCol=0; int tpCol=1; int fpCol=2; int tpRawCol=-1; String score=String.format("%.3g",0.0f); while ((line=br.readLine()) != null) { if (line.startsWith("#")) { if (line.startsWith("#total")) { final String[] parts=line.split("\\s"); if (parts.length > 3) { switch (parts[1]) { case "baseline": totalVariants=Integer.parseInt(parts[parts.length - 1]); break; default : break; } } else { totalVariants=Integer.parseInt(parts[parts.length - 1]); } } else if (line.startsWith("#score field:")) { final String[] parts=line.split("\\s"); if (parts.length >= 3) { scoreName=parts[2]; } } else { final List<String> header=Arrays.asList(StringUtils.split(line.substring(1),'\t')); if (header.containsAll(WITH_RAW_HEADINGS)) { scoreCol=header.indexOf(SCORE); tpCol=header.indexOf(TRUE_POSITIVES_BASELINE); fpCol=header.indexOf(FALSE_POSITIVES); tpRawCol=header.indexOf(TRUE_POSITIVES_CALL); } else if (header.containsAll(SIMPLE_HEADINGS)) { scoreCol=header.indexOf(SCORE); tpCol=header.indexOf(TRUE_POSITIVES); fpCol=header.indexOf(FALSE_POSITIVES); } } continue; } final String[] linearr=line.split("\t"); if (linearr.length < 3) { throw new NoTalkbackSlimException("Malformed line: " + line + " in \""+ shortName+ "\""); } final float fp=Float.parseFloat(linearr[fpCol]); final float tp=Float.parseFloat(linearr[tpCol]); final float rawTp; if (tpRawCol > -1 && linearr.length > tpRawCol) { rawTp=Float.parseFloat(linearr[tpRawCol]); } else { rawTp=0.0f; } try { final float numeric=Float.parseFloat(linearr[scoreCol]); score=String.format("%.3g",numeric); } catch (final NumberFormatException e) { score=linearr[0]; } if (prevScore == null || score.compareTo(prevScore) != 0) { points.add(new RocPoint(0.0,prevTp,prevFp,rawTp)); scores.add(score); } prevFp=Math.max(prevFp,fp); prevTp=Math.max(prevTp,tp); prevRawTp=Math.max(prevRawTp,rawTp); prevScore=score; lines++; if (showProgress && lines % 100 == 0) { progressBarDelegate.setProgress(lines); } } points.add(new RocPoint(0.0,prevTp,prevFp,prevRawTp)); scores.add(score); } catch (final NumberFormatException e) { throw new NoTalkbackSlimException("Malformed line: " + line + " in \""+ shortName+ "\""); } progressBarDelegate.addFile(lines); final DataBundle dataBundle=new DataBundle(shortName,points.toArray(new RocPoint[points.size()]),scores.toArray(new String[scores.size()]),totalVariants); dataBundle.setScoreName(scoreName); return dataBundle; }
Loads ROC file into data bundle.
public static final double metersToFeet(double meters){ return meters * METER_TO_FOOT; }
Converts meters to feet.
public void closeAllOpenDatabases(){ while (!dbrmap.isEmpty()) { String dbname=dbrmap.keySet().iterator().next(); this.closeDatabaseNow(dbname); DBRunner r=dbrmap.get(dbname); try { r.q.put(new DBQuery()); } catch ( Exception ex) { Log.e(SQLitePlugin.class.getSimpleName(),"couldn't stop db thread for db: " + dbname,ex); } dbrmap.remove(dbname); } }
Clean up and close all open databases.
public IconicsDrawable iconOffsetXRes(int iconOffsetXRes){ return iconOffsetXPx(mContext.getResources().getDimensionPixelSize(iconOffsetXRes)); }
set the icon offset for X from resource
protected void updateWorkingBuffers(){ if (rootFilter == null) { rootFilter=rootGN.getGraphicsNodeRable(true); rootCR=null; } rootCR=renderGNR(); if (rootCR == null) { workingRaster=null; workingOffScreen=null; workingBaseRaster=null; currentOffScreen=null; currentBaseRaster=null; currentRaster=null; return; } SampleModel sm=rootCR.getSampleModel(); int w=offScreenWidth; int h=offScreenHeight; int tw=sm.getWidth(); int th=sm.getHeight(); w=(((w + tw - 1) / tw) + 1) * tw; h=(((h + th - 1) / th) + 1) * th; if ((workingBaseRaster == null) || (workingBaseRaster.getWidth() < w) || (workingBaseRaster.getHeight() < h)) { sm=sm.createCompatibleSampleModel(w,h); workingBaseRaster=Raster.createWritableRaster(sm,new Point(0,0)); } int tgx=-rootCR.getTileGridXOffset(); int tgy=-rootCR.getTileGridYOffset(); int xt, yt; if (tgx >= 0) xt=tgx / tw; else xt=(tgx - tw + 1) / tw; if (tgy >= 0) yt=tgy / th; else yt=(tgy - th + 1) / th; int xloc=xt * tw - tgx; int yloc=yt * th - tgy; workingRaster=workingBaseRaster.createWritableChild(0,0,w,h,xloc,yloc,null); workingOffScreen=new BufferedImage(rootCR.getColorModel(),workingRaster.createWritableChild(0,0,offScreenWidth,offScreenHeight,0,0,null),rootCR.getColorModel().isAlphaPremultiplied(),null); if (!isDoubleBuffered) { currentOffScreen=workingOffScreen; currentBaseRaster=workingBaseRaster; currentRaster=workingRaster; } }
Internal method used to synchronize local state in response to various set methods.
protected static String LexicalErr(boolean EOFSeen,int lexState,int errorLine,int errorColumn,String errorAfter,int curChar){ char curChar1=(char)curChar; return ("Lexical error at line " + errorLine + ", column "+ errorColumn+ ". Encountered: "+ (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar1)) + "\"") + " (" + (int)curChar+ "), ")+ "after : \""+ addEscapes(errorAfter)+ "\""); }
Returns a detailed message for the Error when it is thrown by the token manager to indicate a lexical error. Parameters : EOFSeen : indicates if EOF caused the lexical error curLexState : lexical state in which this error occurred errorLine : line number when the error occurred errorColumn : column number when the error occurred errorAfter : prefix that was seen before this error occurred curchar : the offending character Note: You can customize the lexical error message by modifying this method.
public boolean handleMobileCellScroll(final Rect r){ final int offset=computeVerticalScrollOffset(); final int height=getHeight(); final int extent=computeVerticalScrollExtent(); final int range=computeVerticalScrollRange(); final int hoverViewTop=r.top; final int hoverHeight=r.height(); if (hoverViewTop <= 0 && offset > 0) { smoothScrollBy(-mSmoothScrollAmountAtEdge,0); return true; } if (hoverViewTop + hoverHeight >= height && offset + extent < range) { smoothScrollBy(mSmoothScrollAmountAtEdge,0); return true; } return false; }
This method is in charge of determining if the hover cell is above or below the bounds of the listview. If so, the listview does an appropriate upward or downward smooth scroll so as to reveal new items.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static void initializeLoggers(){ initializeLog4J(); initializeJavaLogger(); }
This method initializes the loggers, currently just reseting the Mock Appender captured events.
public boolean isConnected(){ try { if (parser.getXBeeConnection().getInputStream() != null && parser.getXBeeConnection().getOutputStream() != null) { return true; } return false; } catch ( Exception e) { return false; } }
Indicates if serial port connection has been established. The open method may be called if this returns true
public static AccessibilityNodeInfo obtain(AccessibilityNodeInfo info){ AccessibilityNodeInfo infoClone=AccessibilityNodeInfo.obtain(); infoClone.init(info); return infoClone; }
Returns a cached instance if such is available or a new one is create. The returned instance is initialized from the given <code>info</code>.
public void bounceOff(Particle that){ double dx=that.rx - this.rx; double dy=that.ry - this.ry; double dvx=that.vx - this.vx; double dvy=that.vy - this.vy; double dvdr=dx * dvx + dy * dvy; double dist=this.radius + that.radius; double magnitude=2 * this.mass * that.mass* dvdr / ((this.mass + that.mass) * dist); double fx=magnitude * dx / dist; double fy=magnitude * dy / dist; this.vx+=fx / this.mass; this.vy+=fy / this.mass; that.vx-=fx / that.mass; that.vy-=fy / that.mass; this.count++; that.count++; }
Updates the velocities of this particle and the specified particle according to the laws of elastic collision. Assumes that the particles are colliding at this instant.
public boolean registerSlave(EvolutionState state,String name,Socket socket,DataOutputStream out,DataInputStream in){ if (isShutdownInProgress()) { try { out.writeByte(Slave.V_SHUTDOWN); } catch ( Exception e) { } try { out.flush(); } catch ( Exception e) { } try { out.close(); } catch ( Exception e) { } try { in.close(); } catch ( Exception e) { } try { socket.close(); } catch ( IOException e) { } return false; } SlaveConnection newSlave=new SlaveConnection(state,name,socket,out,in,this); synchronized (allSlaves) { allSlaves.addLast(newSlave); notifyMonitor(allSlaves); } synchronized (availableSlaves) { availableSlaves.addLast(newSlave); notifyMonitor(availableSlaves); } return true; }
Registers a new slave with the monitor. Upon registration, a slave is marked as available for jobs.
@Nullable @Override protected PlatformFutureUtils.Writer futureWriter(int opId){ if (opId == OP_GET_ALL) return WRITER_GET_ALL; if (opId == OP_INVOKE) return WRITER_INVOKE; if (opId == OP_INVOKE_ALL) return WRITER_INVOKE_ALL; return null; }
<inheritDoc />
public TimeEventSpecItemProvider(AdapterFactory adapterFactory){ super(adapterFactory); }
This constructs an instance from a factory and a notifier. <!-- begin-user-doc --> <!-- end-user-doc -->
public void read(InputStream in,Document doc,int pos) throws IOException, BadLocationException { if (doc instanceof StyledDocument) { RTFReader rdr=new RTFReader((StyledDocument)doc); rdr.readFromStream(in); rdr.close(); } else { super.read(in,doc,pos); } }
Insert content from the given stream which is expected to be in a format appropriate for this kind of content handler.
private String makeSingleInputHashChain() throws Exception { LOG.trace("makeSingleInputHashChain()"); HashChainType hashChain=new HashChainType(); hashChain.setDefaultDigestMethod(digestMethod()); hashChain.getHashStep().add(multipartStep(multiparts.get(0),0)); return elementToString(objectFactory.createHashChain(hashChain)); }
Makes hash chain for special case of inputs.size() == 1.
public void compileIfModified(String fileName,LineMap lineMap) throws IOException, ClassNotFoundException { compile(fileName,lineMap,true); }
Compiles the class. className is a fully qualified Java class, e.g. work.jsp.Test
public Editor edit() throws IOException { return DiskLruCache.this.edit(key,sequenceNumber); }
Returns an editor for this snapshot's entry, or null if either the entry has changed since this snapshot was created or if another edit is in progress.
public static CCMenuItemLabel item(CCLabelProtocol label,CCNode target,String selector){ return new CCMenuItemLabel(label,target,selector); }
creates a CCMenuItemLabel with a Label, target and selector
public static double[][] parseMatlabString(String matrixString) throws OperatorException { if (matrixString == null || matrixString.trim().length() == 0) { return null; } double[][] matrix; Pattern possibleRedundantWhitespace=Pattern.compile("\\s+"); Matcher whitespaceMatcher=possibleRedundantWhitespace.matcher(matrixString); matrixString=whitespaceMatcher.replaceAll(" "); Pattern lineFeed=Pattern.compile("\\n"); Matcher lineFeedMatcher=lineFeed.matcher(matrixString); matrixString=lineFeedMatcher.replaceAll(""); matrixString=matrixString.trim(); Pattern illegalChar=Pattern.compile("[^0-9\\-\\+\\.\\,\\; \\[\\]]"); Matcher findIllegalChar=illegalChar.matcher(matrixString); if (findIllegalChar.find()) { throw new OperatorException("StringToMatrixConverter: Matlab String contains illegal characters, parsing failed."); } Pattern squareBrackets=Pattern.compile("[\\[\\]]"); Matcher removeSquareBrackets=squareBrackets.matcher(matrixString); matrixString=removeSquareBrackets.replaceAll(""); String usedDelimiter=VALUE_DELIMITER; if (matrixString.indexOf(",") < 0) { usedDelimiter=" "; matrixString=matrixString.trim(); } else { Pattern space=Pattern.compile("\\s+"); Matcher spaceMatcher=space.matcher(matrixString); matrixString=spaceMatcher.replaceAll(""); } String[] matrixRows; try { matrixRows=matrixString.split(ROW_DELIMITER); } catch ( Exception e) { throw new OperatorException("StringToMatrixConverter: Matlab String does not provide correct row separation, parsing failed."); } int numberOfRows=matrixRows.length; int numberOfValues=matrixRows[0].split(usedDelimiter).length; String[][] stringMatrix=new String[numberOfRows][]; try { for (int i=0; i < numberOfRows; i++) { matrixRows[i]=matrixRows[i].trim(); String[] currentRow=matrixRows[i].split(usedDelimiter); if (currentRow.length != numberOfValues) { throw new OperatorException("StringToMatrixConverter: Matlab String contains data rows of different length, parsing failed."); } stringMatrix[i]=currentRow; } } catch ( Exception e) { if (e instanceof OperatorException) { throw (OperatorException)e; } else { throw new OperatorException("StringToMatrixConverter: Matlab String does not provide correct value separation, parsing failed."); } } matrix=new double[numberOfRows][numberOfValues]; try { for (int i=0; i < numberOfRows; i++) { for (int j=0; j < numberOfValues; j++) { matrix[i][j]=Double.parseDouble(stringMatrix[i][j]); } } } catch ( RuntimeException e) { throw new OperatorException("StringToMatrixConverter: Matlab String contains irregular values, all values must be integer or double literals. Parsing failed."); } return matrix; }
parses a Matlab string to create a double matrix
private RandomGenerator(){ super(); }
Initializes the random number generator without a seed.
@Override public String toString(){ if (eIsProxy()) return super.toString(); StringBuffer result=new StringBuffer(super.toString()); result.append(" (returnType: "); result.append(returnType); result.append(')'); return result.toString(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void paint(Graphics g,int y,int start,int stop){ stop-=myWidthProvider.compute() / 4; Color oldColor=g.getColor(); g.setColor(myColorHolder.getColor()); final int height=myHeightProvider.compute(); final int halfHeight=height / 2; int mid=y - halfHeight; int top=y - height; UIUtil.drawLine(g,start,mid,stop,mid); UIUtil.drawLine(g,stop,y,stop,top); g.fillPolygon(new int[]{stop - halfHeight,stop - halfHeight,stop},new int[]{y,y - height,y - halfHeight},3); g.setColor(oldColor); }
Paints arrow at the given graphics buffer using given coordinate parameters.
public Bytecode(ConstPool cp,int stacksize,int localvars){ constPool=cp; maxStack=stacksize; maxLocals=localvars; tryblocks=new ExceptionTable(cp); stackDepth=0; }
Constructs a <code>Bytecode</code> object with an empty bytecode sequence. <p>The parameters <code>stacksize</code> and <code>localvars</code> specify initial values of <code>max_stack</code> and <code>max_locals</code>. They can be changed later.
public boolean supportsCatalogsInDataManipulation() throws SQLException { return false; }
Can a catalog name be used in a data manipulation statement?
public IVariableBinding resolveFieldBinding(){ return this.ast.getBindingResolver().resolveField(this); }
Resolves and returns the binding for the field accessed by this expression. <p> Note that bindings are generally unavailable unless requested when the AST is being built. </p>
public Date releaseDate(){ return new Date(revTs); }
Gets release date.