code
stringlengths
10
174k
nl
stringlengths
3
129k
public DistributionLocatorId(int port,String bindAddress){ this(port,bindAddress,null); }
Constructs a DistributionLocatorId with the given port. The host will be set to the local host.
@Override public double kurtosis(){ QL.require(sampleNumber_ > 3,UNSUFFICIENT_SAMPLE_NUMBER_3); double m=mean(); double v=variance(); double c=(sampleNumber_ - 1.0) / (sampleNumber_ - 2.0); c*=(sampleNumber_ - 1.0) / (sampleNumber_ - 3.0); c*=3.0; if (v == 0) return c; double result=fourthPowerSum_ / sampleWeight_; result-=4.0 * m * (cubicSum_ / sampleWeight_); result+=6.0 * m * m* (quadraticSum_ / sampleWeight_); result-=3.0 * m * m* m* m; result/=v * v; result*=sampleNumber_ / (sampleNumber_ - 1.0); result*=sampleNumber_ / (sampleNumber_ - 2.0); result*=(sampleNumber_ + 1.0) / (sampleNumber_ - 3.0); return result - c; }
returns the excess kurtosis, defined as \fracN^2(N+1)}{(N-1)(N-2)(N-3)} \frac{\left\langle \left(x-\langle x \rangle \right)^4 \right\rangle}{\sigma^4} - \frac{3(N-1)^2}{(N-2)(N-3)}. } The above evaluates to 0 for a Gaussian distribution.
public void testSneakyFieldTypes() throws Exception { TypeFactory tf=TypeFactory.defaultInstance(); Field field=SneakyBean.class.getDeclaredField("intMap"); JavaType type=tf.constructType(field.getGenericType()); assertTrue(type instanceof MapType); MapType mapType=(MapType)type; assertEquals(tf.constructType(Integer.class),mapType.getKeyType()); assertEquals(tf.constructType(Long.class),mapType.getContentType()); field=SneakyBean.class.getDeclaredField("longList"); type=tf.constructType(field.getGenericType()); assertTrue(type instanceof CollectionType); CollectionType collectionType=(CollectionType)type; assertEquals(tf.constructType(Long.class),collectionType.getContentType()); }
Plus sneaky types may be found via introspection as well.
public LambdaContainer(LambdaBlock wrapper,int arity){ super(); this.loadFXML("LambdaContainer"); this.wrapper=wrapper; attachedBlocks=new HashSet<>(); this.args=new ArrayList<>(); for (int i=0; i < arity; i++) { this.args.add(new BinderAnchor(this,wrapper,new Binder("a_" + i))); } this.res=new ResultAnchor(this,wrapper,Optional.empty()); this.argSpace.getChildren().addAll(this.args); this.resSpace.getChildren().add(this.res); TouchContext context=new TouchContext(this,false); context.setPanningAction(null); }
Constructs a LambdaContainer for an untyped lambda of n arguments.
public void mouseDragged(final MouseEvent e){ if (drawingWalls) { draggingPoint=e.getPoint(); repaint(); } if (selectedEntity != null) { final Point test=new Point(e.getPoint().x + distanceX,e.getPoint().y + distanceY); final Rectangle testRect=new Rectangle((int)test.getX(),(int)test.getY(),selectedEntity.getWidth(),selectedEntity.getHeight()); testRect.grow(-5,-5); if (getBounds().contains((testRect.getBounds()))) { selectedEntity.setX(test.x); selectedEntity.setY(test.y); repaint(); } } }
Task to perform when mouse button is held and mouse moved.
private void fillNewTags(final Map<String,Object> dataModel) throws Exception { dataModel.put(Common.NEW_TAGS,tagQueryService.getNewTags(Symphonys.getInt("newTagsCnt"))); }
Fils new tags.
public void listaTiposDocumentosExecuteLogic(ActionMapping mappings,ActionForm form,HttpServletRequest request,HttpServletResponse response){ saveCurrentInvocation(KeysClientsInvocations.DOCUMENTOS_VITALES_VER_TIPOS_DOCUMENTOS,request); request.setAttribute(DocumentosVitalesConstants.TIPOS_DOCUMENTOS_VITALES_KEY,getGestionDocumentosVitalesBI(request).getTiposDocumentosVitales()); setReturnActionFordward(request,mappings.findForward("ver_tipos")); }
Muestra la lista de tipos de documentos vitales.
public MicroPipelineManager(final String processingNodeId,final ComponentRepository componentRepository,final int maxNumberOfThreads) throws RequiredInputMissingException { if (componentRepository == null) throw new RequiredInputMissingException("Missing required component repository"); if (StringUtils.isBlank(processingNodeId)) throw new RequiredInputMissingException("Missing required processing node identifier"); this.processingNodeId=StringUtils.lowerCase(StringUtils.trim(processingNodeId)); this.microPipelineFactory=new MicroPipelineFactory(this.processingNodeId,componentRepository); if (maxNumberOfThreads == 1) this.executorService=Executors.newSingleThreadExecutor(); else if (maxNumberOfThreads > 1) this.executorService=Executors.newFixedThreadPool(maxNumberOfThreads); else this.executorService=Executors.newCachedThreadPool(); }
Initializes the micro pipeline manager
@Override public void close(){ _client.destroy(); }
Close the client
private void returnData(Object ret){ if (myHost != null) { myHost.returnData(ret); } }
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
public static LoggingFraction createDefaultLoggingFraction(Level level){ return new LoggingFraction().applyDefaults(level); }
Create a default logging fraction for the specified level.
public void init() throws ServletException { }
Initialization of the servlet. <br>
public static synchronized Bitmap decodeSampledBitmapFromFile(String filename,int reqWidth,int reqHeight){ final BitmapFactory.Options options=new BitmapFactory.Options(); options.inJustDecodeBounds=true; BitmapFactory.decodeFile(filename,options); options.inSampleSize=calculateInSampleSize(options,reqWidth,reqHeight); options.inJustDecodeBounds=false; return BitmapFactory.decodeFile(filename,options); }
Decode and sample down a bitmap from a file to the requested width and height.
public Quaterniond rotateLocalX(double angle){ return rotateLocalX(angle,this); }
Apply a rotation to <code>this</code> quaternion rotating the given radians about the local x axis. <p> If <code>Q</code> is <code>this</code> quaternion and <code>R</code> the quaternion representing the specified rotation, then the new quaternion will be <code>R * Q</code>. So when transforming a vector <code>v</code> with the new quaternion by using <code>R * Q * v</code>, the rotation represented by <code>this</code> will be applied first!
DrmConstraintInfo(){ count=-1; startDate=-1; endDate=-1; interval=-1; }
Construct the DrmConstraint.
private InstrumentationNode cloneWithNewTarget(ValueNode newTarget,VirtualizerTool tool){ InstrumentationNode clone=new InstrumentationNode(newTarget,anchored,weakDependencies.size(),stateBefore); clone.instrumentationGraph=instrumentationGraph; for (int i=0; i < weakDependencies.size(); i++) { ValueNode input=weakDependencies.get(i); if (!(input instanceof VirtualObjectNode)) { ValueNode alias=tool.getAlias(input); if (alias instanceof VirtualObjectNode) { clone.weakDependencies.initialize(i,alias); continue; } } clone.weakDependencies.initialize(i,input); } return clone; }
Clone the InstrumentationNode with the given new target. The weakDependencies will be initialized with aliased nodes.
public SaveAsAction(KseFrame kseFrame){ super(kseFrame); putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(res.getString("SaveAsAction.accelerator").charAt(0),Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.ALT_MASK)); putValue(LONG_DESCRIPTION,res.getString("SaveAsAction.statusbar")); putValue(NAME,res.getString("SaveAsAction.text")); putValue(SHORT_DESCRIPTION,res.getString("SaveAsAction.tooltip")); putValue(SMALL_ICON,new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource(res.getString("SaveAsAction.image"))))); }
Construct action.
public synchronized void flush() throws IOException { checkNotClosed(); trimToSize(); trimToFileCount(); journalWriter.flush(); }
Force buffered operations to the filesystem.
@Override void initAnimation(){ if (!mInitialized) { int numValues=mValues.length; for (int i=0; i < numValues; ++i) { mValues[i].setupSetterAndGetter(mTarget); } super.initAnimation(); } }
This function is called immediately before processing the first animation frame of an animation. If there is a nonzero <code>startDelay</code>, the function is called after that delay ends. It takes care of the final initialization steps for the animation. This includes setting mEvaluator, if the user has not yet set it up, and the setter/getter methods, if the user did not supply them. <p>Overriders of this method should call the superclass method to cause internal mechanisms to be set up correctly.</p>
public StatementBuilder(String string){ builder=new StringBuilder(string); }
Create a new builder.
private void relocateFromHeaders(ByteBuffer f,SceModule module,int baseAddress,Elf32 elf,int elfOffset) throws IOException { int i=0; for ( Elf32ProgramHeader phdr : elf.getProgramHeaderList()) { if (phdr.getP_type() == 0x700000A0L) { int RelCount=phdr.getP_filesz() / Elf32Relocate.sizeof(); if (log.isDebugEnabled()) { log.debug(String.format("PH#%d: relocating %d entries",i,RelCount)); } f.position(elfOffset + phdr.getP_offset()); relocateFromBuffer(f,module,baseAddress,elf,RelCount,true); return; } else if (phdr.getP_type() == 0x700000A1L) { if (log.isDebugEnabled()) { log.debug(String.format("Type 0x700000A1 PH#%d: relocating A1 entries, size=0x%X",i,phdr.getP_filesz())); } f.position(elfOffset + phdr.getP_offset()); relocateFromBufferA1(f,elf,baseAddress,i,phdr.getP_filesz()); return; } i++; } for ( Elf32SectionHeader shdr : elf.getSectionHeaderList()) { if (mustRelocate(elf,shdr)) { int RelCount=shdr.getSh_size() / Elf32Relocate.sizeof(); if (log.isDebugEnabled()) { log.debug(shdr.getSh_namez() + ": relocating " + RelCount+ " entries"); } f.position(elfOffset + shdr.getSh_offset()); relocateFromBuffer(f,module,baseAddress,elf,RelCount,shdr.getSh_type() != Elf32SectionHeader.SHT_REL); } } }
Uses info from the elf program headers and elf section headers to relocate a PRX.
public CompiledST defineTemplate(String name,String argsS,String template){ if (name.charAt(0) != '/') name="/" + name; String[] args=argsS.split(","); List<FormalArgument> a=new ArrayList<FormalArgument>(); for ( String arg : args) { a.add(new FormalArgument(arg)); } return defineTemplate(name,new CommonToken(GroupParser.ID,name),a,template,null); }
for testing
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-24 16:07:23.812 -0400",hash_original_method="F5106D0386D3020336DFAB8E81694EB1",hash_generated_method="19EBF7A8C1F496ACA7BB8F658932423D") private void onAgentCancel(){ Intent intent=new Intent(BluetoothDevice.ACTION_PAIRING_CANCEL); mContext.sendBroadcast(intent,BLUETOOTH_ADMIN_PERM); mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_AGENT_CANCEL),1500); return; }
Called by native code on a Cancel method call to org.bluez.Agent.
public String optString(int index){ return this.optString(index,""); }
Get the optional string value associated with an index. It returns an empty string if there is no value at that index. If the value is not a string and is not null, then it is coverted to a string.
public void addOutMessage(final String address){ }
Add a new OSC out message with the specified address.
@Override public void remove(){ throw new UnsupportedOperationException("The remove operation is not supported by this Iterator."); }
The remove operation is not supported by this Iterator.
@PostMapping(consumes="multipart/form-data") public ResponseEntity<FileInfo> uploadFile(@RequestParam("file") MultipartFile file,@RequestParam(required=false) String name,HttpServletRequest request){ try { if (Strings.isNullOrEmpty(name)) { name=file.getOriginalFilename(); } long size=file.getSize(); FileDescriptor fd=createFileDescriptor(name,size); InputStream is=file.getInputStream(); uploadToMiddleware(is,fd); saveFileDescriptor(fd); return createFileInfoResponseEntity(request,fd); } catch ( Exception e) { log.error("File upload failed",e); throw new RestAPIException("File upload failed","File upload failed",HttpStatus.INTERNAL_SERVER_ERROR); } }
Method for multipart file upload. It expects the file contents to be passed in the part called 'file'
static double ensureNonNegative(double value){ checkArgument(!isNaN(value)); if (value > 0.0) { return value; } else { return 0.0; } }
Returns its argument if it is non-negative, zero if it is negative.
public v4ParserException(){ }
Used for remote debugger deserialization
void log(String msg){ System.err.println(msg); }
Write a message to stderr.
@After public void tearDown() throws Exception { Locale.setDefault(this.savedLocale); }
Restore the default locale after the tests complete.
public void multiply(Matrix2f rhs){ Matrix2f tmp=new Matrix2f(); tmp.loadMultiply(this,rhs); load(tmp); }
Post-multiplies the current matrix by a given parameter
public Quaternionf mul(float qx,float qy,float qz,float qw){ set(w * qx + x * qw + y * qz - z * qy,w * qy - x * qz + y * qw + z * qx,w * qz + x * qy - y * qx + z * qw,w * qw - x * qx - y * qy - z * qz); return this; }
Multiply this quaternion by the quaternion represented via <tt>(qx, qy, qz, qw)</tt>. <p> If <tt>T</tt> is <code>this</code> and <tt>Q</tt> is the given quaternion, then the resulting quaternion <tt>R</tt> is: <p> <tt>R = T * Q</tt> <p> So, this method uses post-multiplication like the matrix classes, resulting in a vector to be transformed by <tt>Q</tt> first, and then by <tt>T</tt>.
public JRangeSlider createRangeSlider(int orientation,int direction){ return new JRangeSlider(m_model,orientation,direction); }
Create a new range slider for interacting with the query, using the given orientation and direction.
private JPopupMenu createOperatorPopupMenu(){ JPopupMenu menu=new JPopupMenu(); menu.add(EXPAND_ALL_ACTION); menu.add(COLLAPSE_ALL_ACTION); menu.addSeparator(); String name="Tree"; if (mainFrame.getProcess().getProcessLocation() != null) { name=mainFrame.getProcess().getProcessLocation().getShortName(); } menu.add(PrintingTools.makeExportPrintMenu(this,name)); return menu; }
Creates a new popup menu for the selected operator.
public final LC rightToLeft(){ setLeftToRight(Boolean.FALSE); return this; }
Same functionality as setLeftToRight(false) only this method returns <code>this</code> for chaining multiple calls. <p> For a more thorough explanation of what this constraint does see the white paper or cheat Sheet at www.migcomponents.com.
private boolean removeOrMaterializeIf(SimplifierTool tool){ assert trueSuccessor().hasNoUsages() && falseSuccessor().hasNoUsages(); if (trueSuccessor().next() instanceof AbstractEndNode && falseSuccessor().next() instanceof AbstractEndNode) { AbstractEndNode trueEnd=(AbstractEndNode)trueSuccessor().next(); AbstractEndNode falseEnd=(AbstractEndNode)falseSuccessor().next(); AbstractMergeNode merge=trueEnd.merge(); if (merge == falseEnd.merge() && trueSuccessor().anchored().isEmpty() && falseSuccessor().anchored().isEmpty()) { PhiNode singlePhi=null; int distinct=0; for ( PhiNode phi : merge.phis()) { ValueNode trueValue=phi.valueAt(trueEnd); ValueNode falseValue=phi.valueAt(falseEnd); if (trueValue != falseValue) { distinct++; singlePhi=phi; } } if (distinct == 0) { removeThroughFalseBranch(tool); return true; } else if (distinct == 1) { ValueNode trueValue=singlePhi.valueAt(trueEnd); ValueNode falseValue=singlePhi.valueAt(falseEnd); ConditionalNode conditional=canonicalizeConditionalCascade(trueValue,falseValue); if (conditional != null) { singlePhi.setValueAt(trueEnd,conditional); removeThroughFalseBranch(tool); return true; } } } } if (trueSuccessor().next() instanceof ReturnNode && falseSuccessor().next() instanceof ReturnNode) { ReturnNode trueEnd=(ReturnNode)trueSuccessor().next(); ReturnNode falseEnd=(ReturnNode)falseSuccessor().next(); ValueNode trueValue=trueEnd.result(); ValueNode falseValue=falseEnd.result(); ValueNode value=null; if (trueValue != null) { if (trueValue == falseValue) { value=trueValue; } else { value=canonicalizeConditionalCascade(trueValue,falseValue); if (value == null) { return false; } } } ReturnNode newReturn=graph().add(new ReturnNode(value)); replaceAtPredecessor(newReturn); GraphUtil.killCFG(this); return true; } return false; }
Tries to remove an empty if construct or replace an if construct with a materialization.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
private void resize(int c){ int[] newItems=new int[c]; for (int i=0; i < items.length; i+=1) { newItems[i]=items[i]; } items=newItems; }
Resizes ITEMS to C, copying things over.
public static double calculateRSquared(Instances data,double ssr) throws Exception { double yMean=data.meanOrMode(data.classIndex()); double tss=0.0; for (int i=0; i < data.numInstances(); i++) { tss+=(data.instance(i).value(data.classIndex()) - yMean) * (data.instance(i).value(data.classIndex()) - yMean); } double rsq=1 - (ssr / tss); return rsq; }
Returns the R-squared value for a linear regression model, where sum of squared residuals is already calculated. This works for either a simple or a multiple linear regression model.
public final void testSetCaseSensitivity(){ Case caseSensitivity=Case.UPPERCASE; LetterOrNumberValidator characterOrNumberValidator=new LetterOrNumberValidator("foo",Case.CASE_INSENSITIVE,true); characterOrNumberValidator.setCaseSensitivity(caseSensitivity); assertEquals(caseSensitivity,characterOrNumberValidator.getCaseSensitivity()); }
Tests the functionality of the method, which allows to set the case sensitivity.
@Util public static void resetAdminTenantId(){ session.put(TENANT_ID,Security.getUserInfo().getTenant()); }
Resets the AdminTenant in the session back to the users TenantId
public void closeAllFiles(){ while (m_TabbedPane.getTabCount() > 0) { if (!saveChanges(true)) { return; } m_TabbedPane.removeTabAt(getCurrentIndex()); updateFrameTitle(); System.gc(); } }
closes all open files
@Override public final int size(){ return (int)Math.max((tail.get() - head.get()),0); }
This implemention is known to be broken if preemption were to occur after reading the tail pointer. Code should not depend on size for a correct result.
public RAkELdTest(String name){ super(name); }
Initializes the test.
public static void main(String[] args){ try { int fdNum=Integer.parseInt(args[0],10); int targetSdkVersion=Integer.parseInt(args[1],10); if (fdNum != 0) { try { FileDescriptor fd=ZygoteInit.createFileDescriptor(fdNum); DataOutputStream os=new DataOutputStream(new FileOutputStream(fd)); os.writeInt(Process.myPid()); os.close(); IoUtils.closeQuietly(fd); } catch ( IOException ex) { Slog.d(TAG,"Could not write pid of wrapped process to Zygote pipe.",ex); } } ZygoteInit.preload(); String[] runtimeArgs=new String[args.length - 2]; System.arraycopy(args,2,runtimeArgs,0,runtimeArgs.length); RuntimeInit.wrapperInit(targetSdkVersion,runtimeArgs); } catch ( ZygoteInit.MethodAndArgsCaller caller) { caller.run(); } }
The main function called when starting a runtime application through a wrapper process instead of by forking Zygote. The first argument specifies the file descriptor for a pipe that should receive the pid of this process, or 0 if none. The second argument is the target SDK version for the app. The remaining arguments are passed to the runtime.
private final void completeConstruction(){ if (mDbg) mSm.log("completeConstruction: E"); int maxDepth=0; for ( StateInfo si : mStateInfo.values()) { int depth=0; for (StateInfo i=si; i != null; depth++) { i=i.parentStateInfo; } if (maxDepth < depth) { maxDepth=depth; } } if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth); mStateStack=new StateInfo[maxDepth]; mTempStateStack=new StateInfo[maxDepth]; setupInitialStateStack(); sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD,mSmHandlerObj)); if (mDbg) mSm.log("completeConstruction: X"); }
Complete the construction of the state machine.
private void createTestImage(){ mInitialImage=new byte[3 * mSize / 2]; for (int i=0; i < mSize; i++) { mInitialImage[i]=(byte)(40 + i % 199); } for (int i=mSize; i < 3 * mSize / 2; i+=2) { mInitialImage[i]=(byte)(40 + i % 200); mInitialImage[i + 1]=(byte)(40 + (i + 99) % 200); } }
Creates the test image that will be used to feed the encoder.
public void addCascaded(Component comp,Integer layer){ this.add(comp,layer); if (comp instanceof JInternalFrame) { this.cascade(comp); } this.moveToFront(comp); }
Method addCascaded.
private static void dualPivotQuicksort(long[] a,int left,int right){ int sixth=(right - left + 1) / 6; int e1=left + sixth; int e5=right - sixth; int e3=(left + right) >>> 1; int e4=e3 + sixth; int e2=e3 - sixth; long ae1=a[e1], ae2=a[e2], ae3=a[e3], ae4=a[e4], ae5=a[e5]; if (ae1 > ae2) { long t=ae1; ae1=ae2; ae2=t; } if (ae4 > ae5) { long t=ae4; ae4=ae5; ae5=t; } if (ae1 > ae3) { long t=ae1; ae1=ae3; ae3=t; } if (ae2 > ae3) { long t=ae2; ae2=ae3; ae3=t; } if (ae1 > ae4) { long t=ae1; ae1=ae4; ae4=t; } if (ae3 > ae4) { long t=ae3; ae3=ae4; ae4=t; } if (ae2 > ae5) { long t=ae2; ae2=ae5; ae5=t; } if (ae2 > ae3) { long t=ae2; ae2=ae3; ae3=t; } if (ae4 > ae5) { long t=ae4; ae4=ae5; ae5=t; } a[e1]=ae1; a[e3]=ae3; a[e5]=ae5; long pivot1=ae2; a[e2]=a[left]; long pivot2=ae4; a[e4]=a[right]; int less=left + 1; int great=right - 1; boolean pivotsDiffer=(pivot1 != pivot2); if (pivotsDiffer) { outer: for (int k=less; k <= great; k++) { long ak=a[k]; if (ak < pivot1) { if (k != less) { a[k]=a[less]; a[less]=ak; } less++; } else if (ak > pivot2) { while (a[great] > pivot2) { if (great-- == k) { break outer; } } if (a[great] < pivot1) { a[k]=a[less]; a[less++]=a[great]; a[great--]=ak; } else { a[k]=a[great]; a[great--]=ak; } } } } else { for (int k=less; k <= great; k++) { long ak=a[k]; if (ak == pivot1) { continue; } if (ak < pivot1) { if (k != less) { a[k]=a[less]; a[less]=ak; } less++; } else { while (a[great] > pivot1) { great--; } if (a[great] < pivot1) { a[k]=a[less]; a[less++]=a[great]; a[great--]=ak; } else { a[k]=pivot1; a[great--]=ak; } } } } a[left]=a[less - 1]; a[less - 1]=pivot1; a[right]=a[great + 1]; a[great + 1]=pivot2; doSort(a,left,less - 2); doSort(a,great + 2,right); if (!pivotsDiffer) { return; } if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } outer: for (int k=less; k <= great; k++) { long ak=a[k]; if (ak == pivot2) { while (a[great] == pivot2) { if (great-- == k) { break outer; } } if (a[great] == pivot1) { a[k]=a[less]; a[less++]=pivot1; } else { a[k]=a[great]; } a[great--]=pivot2; } else if (ak == pivot1) { a[k]=a[less]; a[less++]=pivot1; } } } doSort(a,less,great); }
Sorts the specified range of the array into ascending order by the Dual-Pivot Quicksort algorithm.
public final int yystate(){ return zzLexicalState; }
Returns the current lexical state.
@Override public void onSeekComplete(MediaPlayer mp){ Log.d(TAG,"onSeekComplete"); stopLoading(); if (lastState != null) { switch (lastState) { case STARTED: { start(); break; } case PLAYBACKCOMPLETED: { currentState=State.PLAYBACKCOMPLETED; break; } case PREPARED: { currentState=State.PREPARED; break; } } } if (this.seekCompleteListener != null) this.seekCompleteListener.onSeekComplete(mp); }
Restore the last State before seekTo()
public int computeWordValue(Vertex word){ int value=2; int count=0; if (word.instanceOf(Primitive.NOUN)) { value=value + 12; count++; } if (word.instanceOf(Primitive.ADJECTIVE)) { value=value + 6; count++; } if (word.instanceOf(Primitive.INTERJECTION)) { value=value + 6; count++; } if (word.instanceOf(Primitive.VERB)) { value=value + 4; count++; } if (word.instanceOf(Primitive.QUESTION)) { value=value + 3; count++; } if (word.instanceOf(Primitive.ADVERB)) { value=value + 2; count++; } if (count == 0) { Collection<Relationship> meanings=word.getRelationships(Primitive.MEANING); if (meanings != null) { for ( Relationship relation : meanings) { Vertex meaning=relation.getTarget(); if (meaning.instanceOf(Primitive.THING)) { value=value + 12; } else if (meaning.instanceOf(Primitive.DESCRIPTION)) { value=value + 6; } else if (meaning.instanceOf(Primitive.INTERJECTION)) { value=value + 6; } else if (meaning.instanceOf(Primitive.ACTION)) { value=value + 4; } else if (meaning.instanceOf(Primitive.QUESTION)) { value=value + 3; } else { value=value + 2; } } value=value / meanings.size(); } else { value=value + 4; } } else { value=value / count; } if (word.instanceOf(Primitive.PUNCTUATION) || (word.instanceOf(Primitive.ARTICLE))) { value=1; } if (word.instanceOf(Primitive.KEYWORD)) { value=25; } return value; }
Return the matching value for the word, some word types are worth more than others.
public TenantResource tenant(){ return tenant; }
Get the subresource containing all of the commands related to a tenant
public static <E>List<E> of(E e1,E e2,E e3,E e4){ List<E> list=new ArrayList<>(); list.add(e1); list.add(e2); list.add(e3); list.add(e4); return list; }
Returns a list of the given elements, in order.
@Deprecated public BitmapDrawable(){ mBitmapState=new BitmapState((Bitmap)null); }
Create an empty drawable, not dealing with density.
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { String l_szRequestID=null; HttpSession sess=request.getSession(true); sess.setMaxInactiveInterval(WebEnv.TIMEOUT); ctx=getCtx(); if (sess.getAttribute("ctx") != null) ctx=(Properties)sess.getAttribute("ctx"); WebSessionCtx wsc=(WebSessionCtx)sess.getAttribute(WebSessionCtx.NAME); if (wsc != null) { String mode=WebUtil.getParameter(request,"Mode"); if (mode != null && mode.equals("RequestNew")) { l_szRequestID=Request.createRequest(request,ctx); } else if (mode != null && mode.equals("RequestChange")) { l_szRequestID=Request.changeRequest(request,ctx); } } String url=request.getParameter("ForwardTo") + l_szRequestID; if (!url.startsWith("/")) url="/" + url; response.sendRedirect(url); }
Process Get Request
public short convertIndexToLocation(int index){ if (index == 0) return 0; if (index <= currentNumLocals) { return currentCompiledMethod.getGeneralLocalLocation(index - 1); } else { return currentCompiledMethod.getGeneralStackLocation(index - 1 - currentNumLocals); } }
given a index in the local area (biased : local0 has index 1) this routine determines the correspondig offset in the stack
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
public void load(String filename,G g) throws IOException { load(new FileReader(filename),g); }
Populates the specified graph with the data parsed from the specified file.
public MockNioSession(){ }
Creates empty mock session.
public void reduceNetworkCapacity(String outputFilename,double fraction){ log.info("Changing the network capacity. Multiplying by " + fraction); int counter=0; int multiplier=1; for ( Id<Link> id : sc.getNetwork().getLinks().keySet()) { double old=sc.getNetwork().getLinks().get(id).getCapacity(); sc.getNetwork().getLinks().get(id).setCapacity(old * fraction); if (++counter == multiplier) { log.info(" Links adapted: " + counter); multiplier*=2; } } log.info(" Links adapted: " + counter + " (Done)"); NetworkWriter nw=new NetworkWriter(sc.getNetwork()); nw.write(outputFilename); }
Changing the network's capacity. Values smaller than 1.0 implies a reduction, while values greater than 1.0 implies an increase.
public static boolean isDangerous(double d){ return Double.isInfinite(d) || Double.isNaN(d) || d == 0.0; }
Returns true if the argument is a "dangerous" double to have around, namely one that is infinite, NaN or zero.
static public void saveData(Context context,String key,String val){ context.getSharedPreferences(PREF_APP,Context.MODE_PRIVATE).edit().putString(key,val).apply(); }
Save data.
private String createChoiceWithFictionalProgressXML(String choiceId,String choiceDescription,String nextMomentId,boolean depleteWeaponCharge,boolean incrementNumEnemiesDefeated,String progressDescription,String iconResourceName){ String xml=""; xml+="<choice "; xml+="id='" + choiceId + "' >"; xml+="<description>" + choiceDescription + "</description>"; xml+=createNextMomentXml(nextMomentId); xml+="<outcome "; xml+="deplete_weapon='" + Boolean.toString(depleteWeaponCharge) + "' "; xml+="increment_enemies='" + Boolean.toString(incrementNumEnemiesDefeated) + "' />"; xml+=createFictionalProgressXml(progressDescription); if (iconResourceName != null) { xml+=createIconXML(iconResourceName); } xml+="</choice>"; return xml; }
A helper function to create an XML string representing a choice. Choices are found within choice moments. Contains a piece of fictional progress.
public static void sort(char[] a){ sort1(a,0,a.length); }
Sorts the specified array of chars into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.
private void addOrUpdateNode(AStarNode newNode){ boolean found=false; for ( AStarNode toUpdate : closedNodes) { if (newNode.equals(toUpdate)) { toUpdate.updateDistance(newNode.getG(),newNode.parent); found=true; break; } } if (!found) { openQueue.offer(newNode); } }
Adds a new AStarNode to the queue unless it is already among the closed nodes, in which case it only updates the closed Node with the new distance.
public boolean hasUnsupportedCriticalExtension(){ Set extns=getCriticalExtensionOIDs(); if (extns == null) { return false; } extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); return !extns.isEmpty(); }
Will return true if any extensions are present and marked as critical as we currently dont handle any extensions!
public void test_MultipleAccessToSeveralTables() throws SQLException { threadPool.runTask(createTask1(1)); threadPool.runTask(createTask2(2)); threadPool.runTask(createTask3(3)); }
A few threads execute select operation in the same time for different tables in the database. Number of threads is defined by numThreads variable
synchronized void releaseLocalIdOnDisk(String localId){ MapEntry entry=getMapEntry(localId); entry.retainCount--; if (entry.retainCount > 0) { putMapEntry(localId,entry); } else { removeMapEntry(localId); } }
Decrements the retain count of a local id on disk. If the retain count hits zero, the id is forgotten forever.
public CCriteriumWrapper(final ICriteriumCreator creator){ super(creator); }
Creates a new criterium object.
@Get("json") public Map<String,Object> retrieve(){ return retrieveInternal(false); }
Retrieves information about all modules available to Floodlight.
public boolean springBackX(int start,int min,int max){ mScrollerX.mMode=FLING_MODE; return mScrollerX.springback(start,min,max); }
Call this when you want to 'spring back' into a valid coordinate range.
@Override protected int sizeOf(String key,BitmapDrawable value){ final int bitmapSize=getBitmapSize(value) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; }
Measure item size in kilobytes rather than units which is more practical for a bitmap cache
public PersianCharFilterFactory(Map<String,String> args){ super(args); if (!args.isEmpty()) { throw new IllegalArgumentException("Unknown parameters: " + args); } }
Creates a new PersianCharFilterFactory
public boolean hasPercentComplete(){ return hasExtension(PercentComplete.class); }
Returns whether it has the percent complete.
private void prohibitLandrushIfExactlyOneSunrise(Registry registry) throws UncontestedSunriseApplicationBlockedInLandrushException { if (registry.getTldState(now) == TldState.LANDRUSH) { ImmutableSet<DomainApplication> applications=loadActiveApplicationsByDomainName(targetId,now); if (applications.size() == 1 && getOnlyElement(applications).getPhase().equals(LaunchPhase.SUNRISE)) { throw new UncontestedSunriseApplicationBlockedInLandrushException(); } } }
Prohibit creating a landrush application in LANDRUSH (but not in SUNRUSH) if there is exactly one sunrise application for the same name.
private void resetNamePatternSection(){ disposeOptionalControls(NAME_PATTERN_ID); validationManager.validationRemoved(NAME_PATTERN_TEXT); validationManager.validationRemoved(REGULAR_EXPRESSION_TEXT); useRegexForNameRadioButton.setSelection(false); useStringValueAsNameRadioButton.setSelection(true); useDefaultPattern=true; }
Resets the name pattern section.
public static PurityResult checkPurity(Tree statement,AnnotationProvider annoProvider,boolean assumeSideEffectFree){ PurityCheckerHelper helper=new PurityCheckerHelper(annoProvider,assumeSideEffectFree); PurityResult res=helper.scan(statement,new PurityResult()); return res; }
Compute whether the given statement is side-effect-free, deterministic, or both. Returns a result that can be queried.
public Node buildTreeFull(Class<?> type,int depth){ if (depth == 0) { return PRNG.nextItem(listAvailableTerminals(type)).copyNode(); } else { Node node=PRNG.nextItem(listAvailableFunctions(type)).copyNode(); for (int i=0; i < node.getNumberOfArguments(); i++) { node.setArgument(i,buildTreeFull(node.getArgumentType(i),depth - 1)); } return node; } }
Generates an expression tree with the given return type using the <i>full</i> initialization method. This method builds the tree so every leaf node is at the specified depth.
private static void sort(DefaultListModel model){ Object[] elements=model.toArray(); Arrays.sort(elements); model.clear(); for ( Object element : elements) { model.addElement(element); } }
Sorts the elemenets of a default list model
protected boolean handleMarkSeenNotPermanent(MimeMessage aMessage) throws MessagingException { return aMessage.isSet(Flags.Flag.SEEN); }
<p> Handler for when the folder does not support the SEEN flag. The default behaviour implemented here is to answer the value of the SEEN flag anyway. </p> <p> Subclasses may choose to override this method and implement their own solutions. </p>
public PatternsRequestCondition(String[] patterns,HttpRequestPathHelper pathHelper,PathMatcher pathMatcher,boolean useSuffixPatternMatch,boolean useTrailingSlashMatch,Set<String> extensions){ this(asList(patterns),pathHelper,pathMatcher,useSuffixPatternMatch,useTrailingSlashMatch,extensions); }
Creates a new instance with the given URL patterns. Each pattern that is not empty and does not start with "/" is pre-pended with "/".
public DataAsyncHttpResponseHandler(){ super(); }
Creates a new AsyncHttpResponseHandler
public DDFSubfield(DDFSubfieldDefinition ddfsd,Object value){ setDefn(ddfsd); setValue(value); }
Create a subfield with a definition and a value.
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter,java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix=xmlWriter.getPrefix(namespace); if (prefix == null) { prefix=generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix=org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix,namespace); xmlWriter.setPrefix(prefix,namespace); } return prefix; }
Register a namespace prefix
static void testBytes(int numBytes,long expectedCount,long start,long lim) throws UnsupportedEncodingException { Random rnd=new Random(); byte[] bytes=new byte[numBytes]; if (lim == -1) { lim=1L << (numBytes * 8); } long count=0; long countRoundTripped=0; for (long byteChar=start; byteChar < lim; byteChar++) { long tmpByteChar=byteChar; for (int i=0; i < numBytes; i++) { bytes[bytes.length - i - 1]=(byte)tmpByteChar; tmpByteChar=tmpByteChar >> 8; } ByteString bs=ByteString.copyFrom(bytes); boolean isRoundTrippable=bs.isValidUtf8(); String s=new String(bytes,"UTF-8"); byte[] bytesReencoded=s.getBytes("UTF-8"); boolean bytesEqual=Arrays.equals(bytes,bytesReencoded); if (bytesEqual != isRoundTrippable) { outputFailure(byteChar,bytes,bytesReencoded); } assertEquals(isRoundTrippable,Utf8.isValidUtf8(bytes)); assertEquals(isRoundTrippable,Utf8.isValidUtf8(bytes,0,numBytes)); int i=rnd.nextInt(numBytes); int j=rnd.nextInt(numBytes); if (j < i) { int tmp=i; i=j; j=tmp; } int state1=Utf8.partialIsValidUtf8(Utf8.COMPLETE,bytes,0,i); int state2=Utf8.partialIsValidUtf8(state1,bytes,i,j); int state3=Utf8.partialIsValidUtf8(state2,bytes,j,numBytes); if (isRoundTrippable != (state3 == Utf8.COMPLETE)) { System.out.printf("state=%04x %04x %04x i=%d j=%d%n",state1,state2,state3,i,j); outputFailure(byteChar,bytes,bytesReencoded); } assertEquals(isRoundTrippable,(state3 == Utf8.COMPLETE)); ByteString rope=RopeByteString.newInstanceForTest(bs.substring(0,i),RopeByteString.newInstanceForTest(bs.substring(i,j),bs.substring(j,numBytes))); assertSame(RopeByteString.class,rope.getClass()); ByteString[] byteStrings={bs,bs.substring(0,numBytes),rope}; for ( ByteString x : byteStrings) { assertEquals(isRoundTrippable,x.isValidUtf8()); assertEquals(state3,x.partialIsValidUtf8(Utf8.COMPLETE,0,numBytes)); assertEquals(state1,x.partialIsValidUtf8(Utf8.COMPLETE,0,i)); assertEquals(state1,x.substring(0,i).partialIsValidUtf8(Utf8.COMPLETE,0,i)); assertEquals(state2,x.partialIsValidUtf8(state1,i,j - i)); assertEquals(state2,x.substring(i,j).partialIsValidUtf8(state1,0,j - i)); assertEquals(state3,x.partialIsValidUtf8(state2,j,numBytes - j)); assertEquals(state3,x.substring(j,numBytes).partialIsValidUtf8(state2,0,numBytes - j)); } ByteString ropeADope=RopeByteString.newInstanceForTest(bs,bs.substring(0,numBytes)); assertEquals(isRoundTrippable,ropeADope.isValidUtf8()); if (isRoundTrippable) { countRoundTripped++; } count++; if (byteChar != 0 && byteChar % 1000000L == 0) { logger.info("Processed " + (byteChar / 1000000L) + " million characters"); } } logger.info("Round tripped " + countRoundTripped + " of "+ count); assertEquals(expectedCount,countRoundTripped); }
Helper to run the loop to test all the permutations for the number of bytes specified. This overload is useful for debugging to get the loop to start at a certain character.
public void addParameterValues(final String requestParameterName,final Object... requestParameterValues){ if (requestParameterValues != null) { for ( final Object requestParameterValue : requestParameterValues) { getParameters().add(requestParameterName,requestParameterValue); } } }
Adds 1 or more parameter values to the HTTP request. <p/>
public String globalInfo(){ return "An instance filter that assumes instances form time-series data and " + "replaces attribute values in the current instance with the difference " + "between the current value and the equivalent attribute attribute value "+ "of some previous (or future) instance. For instances where the time-shifted "+ "value is unknown either the instance may be dropped, or missing values "+ "used. Skips the class attribute if it is set."; }
Returns a string describing this classifier
protected CCBitmapFontAtlas(CharSequence theString,String fntFile){ super((parsed=FNTConfigLoadFile(fntFile)).atlasName,theString.length()); configuration_=parsed; opacity_=255; color_=new ccColor3B(ccColor3B.ccWHITE); contentSize_=CGSize.zero(); opacityModifyRGB_=textureAtlas_.getTexture().hasPremultipliedAlpha(); anchorPoint_=CGPoint.ccp(0.5f,0.5f); string_=new TextBuilder(); setString(theString); }
init a bitmap font altas with an initial string and the FNT file
public static <T>T checkNotNull(T reference,@Nullable String errorMessageTemplate,@Nullable Object... errorMessageArgs){ if (reference == null) { throw new NullPointerException(format(errorMessageTemplate,errorMessageArgs)); } return reference; }
Ensures that an object reference passed as a parameter to the calling method is not null.
public X509Name(String dirName,X509NameEntryConverter converter){ this(DefaultReverse,DefaultLookUp,dirName,converter); }
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or some such, converting it into an ordered set of name attributes with each string value being converted to its associated ASN.1 type using the passed in converter.
void fireMonitorsUpdatedEvents(){ ArrayList registered=null; VmEvent ev=null; synchronized (listeners) { registered=(ArrayList)listeners.clone(); } for (Iterator i=registered.iterator(); i.hasNext(); ) { VmListener l=(VmListener)i.next(); if (ev == null) { ev=new VmEvent(this); } l.monitorsUpdated(ev); } }
Fire MonitoredVmStructureChanged events.
private void exportGuideLine(Project aProject,File aCopyDir) throws IOException { File guidelineDir=new File(aCopyDir + GUIDELINES_FOLDER); FileUtils.forceMkdir(guidelineDir); File annotationGuidlines=repository.getGuidelinesFile(aProject); if (annotationGuidlines.exists()) { for ( File annotationGuideline : annotationGuidlines.listFiles()) { FileUtils.copyFileToDirectory(annotationGuideline,guidelineDir); } } }
Copy Project guidelines from the file system of this project to the export folder
public boolean hasChild(String name){ return (getChild(name) != null); }
Checks whether the node has a child with the given name.
public static double value(double x){ if ((x >= 0) && (x <= epsilon)) { return 0.0; } if ((x < 0) && (-x <= epsilon)) { return 0.0; } return x; }
See if the value is close enough to actually be considered 0.0 and return 0.0 if need be. <p> Otherwise the value is returned.
public static void updateComponentTreeUI(@Nullable Component c){ if (c == null) return; for ( Component component : uiTraverser().postOrderTraversal(c)) { if (component instanceof JComponent) ((JComponent)component).updateUI(); } c.invalidate(); c.validate(); c.repaint(); }
A copy of javax.swing.SwingUtilities#updateComponentTreeUI that invokes children updateUI() first
void addTopLevel(String key,JFrame frame){ if (frame != this) { toplevels.put(key,frame); } }
Records a new internal frame.
protected void resultSetLogError(String message,Throwable error){ Logger.sqlErrorLog(message,error); }
Description: <br>
private boolean validate(Class type,InputNode node,Session session) throws Exception { return validate(type,node,new Source(strategy,support,session)); }
This <code>validate</code> method will validate the contents of the XML document against the specified XML class schema. This is used to perform a read traversal of the class schema such that the document can be tested against it. This is preferred to reading the document as it does not instantiate the objects or invoke any callback methods, thus making it a safe validation.