code
stringlengths
10
174k
nl
stringlengths
3
129k
private void transmit(Packet packet){ byte[] data=packet.data; if (packet.offset > 0) { System.arraycopy(data,packet.offset,data=new byte[packet.length],0,packet.length); } stats.numBytes+=packet.length; stats.numPackets++; try { datagramConnection.send(remoteAddress,remotePort,data); RtpSource s=rtcpSession.getMySource(); s.activeSender=true; rtcpSession.timeOfLastRTPSent=rtcpSession.currentTime(); rtcpSession.packetCount++; rtcpSession.octetCount+=data.length; } catch ( IOException e) { e.printStackTrace(); } }
Transmit a RTCP compound packet to the remote destination
protected void layoutComponents(){ container.setMinimumSize(new Dimension(300,300)); JScrollPane detailsPane=new JScrollPane(details); detailsPane.setMinimumSize(new Dimension(150,150)); JSplitPane splitPane=new JSplitPane(JSplitPane.VERTICAL_SPLIT,container,detailsPane); splitPane.setResizeWeight(0.5); splitPane.setDividerLocation(0.4); JPanel buttonPane=new JPanel(new FlowLayout(FlowLayout.CENTER)); buttonPane.add(close); getContentPane().setLayout(new BorderLayout()); getContentPane().add(splitPane,BorderLayout.CENTER); getContentPane().add(buttonPane,BorderLayout.SOUTH); }
Layout the components on the GUI.
public Status kill(final TaskID taskId){ Status status=driver.killTask(taskId); LOGGER.info("Task {} kill initiated with Driver status {}",taskId,status); return status; }
Kills the specified task via the underlying Mesos SchedulerDriver. Important note from the Mesos documentation: "attempting to kill a task is currently not reliable. If, for example, a scheduler fails over while it was attempting to kill a task it will need to retry in the future Likewise, if unregistered / disconnected, the request will be dropped (these semantics may be changed in the future)."
public boolean handleMessage(Message m,Object object){ if (m.getType().equals(M_FINISHED)) { output.message(m.getSender().name + " finished."); if (iamroot) islands.remove(m.getSender()); return true; } else if (m.getType().equals(M_IDEAL_FOUND)) { output.message(m.getSender().name + " found an ideal individual."); ideal_found=true; if (iamroot) announceIdealIndividual(m.getSender()); return true; } else return super.handleMessage(m,object); }
Handles incoming messages.
public static Color brighter(Color color,double factor){ if (factor < 0.0) factor=0.7; else if (factor > 1.0) factor=0.7; return new Color(Math.min((int)(color.getRed() / factor),255),Math.min((int)(color.getGreen() / factor),255),Math.min((int)(color.getBlue() / factor),255)); }
Get brighter color
public static boolean isEspDevice(String BSSID){ return BSSID != null && (BSSID.startsWith("18:fe:34")); }
check whether the bssid is belong to ESP device
public boolean minValue(long val,long minVal){ return GenericValidator.minValue(val,minVal); }
Checks if the value is greater than or equal to the min.
public byte[] unCompress(byte[] compInput){ try { return Snappy.uncompress(compInput); } catch ( IOException e) { LOGGER.error(e,e.getMessage()); } return compInput; }
wrapper method for unCompress byte[] compInput.
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case EipPackage.EIP_MODEL__OWNED_ROUTES: return ((InternalEList<?>)getOwnedRoutes()).basicRemove(otherEnd,msgs); case EipPackage.EIP_MODEL__OWNED_SERVICE_REFS: return ((InternalEList<?>)getOwnedServiceRefs()).basicRemove(otherEnd,msgs); } return super.eInverseRemove(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public void startElement(String localName) throws SAXException { startElement("",localName,"",EMPTY_ATTS); }
Start a new element without a qname, attributes or a Namespace URI. <p/> <p>This method will provide an empty string for the Namespace URI, and empty string for the qualified name, and a default empty attribute list. It invokes #startElement(String, String, String, Attributes)} directly.</p>
private void synonymNext(){ int length=m_synonym.length(); char cc=m_synonym.charAt(0); if (cc == 'Z') { cc='A'; length++; } else cc++; m_synonym=String.valueOf(cc); if (length == 1) return; m_synonym+=String.valueOf(cc); if (length == 2) return; m_synonym+=String.valueOf(cc); }
Next Synonym. Creates next synonym A..Z AA..ZZ AAA..ZZZ
public void testTimeoutNotGreedy(){ doTestTimeout(false,false); }
Test that timeout is obtained, and soon enough!
public dfn addElement(String element){ addElementToRegistry(element); return (this); }
Adds an Element to the element.
public void destroy(){ log.fine("destroy"); super.destroy(); }
Clean up resources
public ITurnOrdered nextJumpshipElement(){ return this.getTurnJSEnum().nextElement(); }
Get the next "jumpship" <code>TurnOrdered</code> marker.
public void testSize0IsolatedMode() throws Exception { processSize0Test(DeploymentMode.ISOLATED); }
Test GridDeploymentMode.ISOLATED mode.
public boolean increment(int key){ return adjustValue(key,1); }
Increments the primitive value mapped to key by 1
boolean casNext(Node<K,V> cmp,Node<K,V> val){ return UNSAFE.compareAndSwapObject(this,nextOffset,cmp,val); }
compareAndSet next field
static boolean isSystemWindows(){ return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR; }
Determines if Windows file system is in use.
protected void doValidateIntContents(String path,String filename,int start,int end){ File inFile=new File(path,filename); DataInputStream inStream=null; Log.i(LOG_TAG,"Validating file " + filename + " at "+ path); try { inStream=new DataInputStream(new FileInputStream(inFile)); for (int i=start; i < end; ++i) { if (inStream.readInt() != i) { fail("Unexpected value read in OBB file"); } } if (inStream != null) { inStream.close(); } Log.i(LOG_TAG,"Successfully validated file " + filename); } catch ( FileNotFoundException e) { fail("File " + inFile + " not found: "+ e.toString()); } catch ( IOException e) { fail("IOError with file " + inFile + ":"+ e.toString()); } }
Helper to validate the contents of an "int" file in an OBB. The format of the files are sequential int's, in the range of: [start..end)
private boolean validateDeleteMirrorCopies(FileShare fs,VirtualPool currentVpool,StringBuffer notSuppReasonBuff){ _log.info(String.format("Checking validateDeleteMirrorCopies for Fs [%s] ",fs.getLabel())); if (!doBasicMirrorValidation(fs,currentVpool,notSuppReasonBuff)) { return false; } if (fs.getPersonality() != null && fs.getPersonality().equalsIgnoreCase(PersonalityTypes.SOURCE.name()) && (MirrorStatus.FAILED_OVER.name().equalsIgnoreCase(fs.getMirrorStatus()) || MirrorStatus.SUSPENDED.name().equalsIgnoreCase(fs.getMirrorStatus()))) { notSuppReasonBuff.append(String.format("File system given in request is in active or failover state %s.",fs.getLabel())); _log.info(notSuppReasonBuff.toString()); return false; } if (fs.getMirrorfsTargets() == null || fs.getMirrorfsTargets().isEmpty()) { notSuppReasonBuff.append(String.format("File system given in request has no active target file system %s.",fs.getLabel())); _log.info(notSuppReasonBuff.toString()); return false; } return true; }
Checks to see if the file replication change is supported.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:42.811 -0500",hash_original_method="DD0B324AD7DDAC3BE4C7F5BE9E799132",hash_generated_method="F9846DE7B677AFDC64B654EEA711F5FA") public static boolean waitingForDebugger(){ return mWaiting; }
Returns "true" if one or more threads is waiting for a debugger to attach.
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 YadisUrl(XriIdentifier xriId) throws YadisException { this(urlFromString(xriId.toURINormalForm())); }
Constructs a YadisURL from an XRI identifier.
public void defineDictionary(String name,Map<String,Object> mapping){ dictionaries.put(name,mapping); }
Define a map for this group. <p> Not thread safe...do not keep adding these while you reference them.</p>
@Override public boolean eventGeneratable(String eventName){ if (m_listenee == null) { return false; } if (m_listenee instanceof EventConstraints) { if (((EventConstraints)m_listenee).eventGeneratable("dataSet") || ((EventConstraints)m_listenee).eventGeneratable("trainingSet") || ((EventConstraints)m_listenee).eventGeneratable("testSet")) { return true; } else { return false; } } return true; }
Returns true, if at the current time, the named event could be generated. Assumes that the supplied event name is an event that could be generated by this bean
public void replace(String statement) throws CannotCompileException { thisClass.getClassFile(); ConstPool constPool=getConstPool(); int pos=currentPos; int index=iterator.u16bitAt(pos + 1); Javac jc=new Javac(thisClass); ClassPool cp=thisClass.getClassPool(); CodeAttribute ca=iterator.get(); try { CtClass[] params=new CtClass[]{cp.get(javaLangObject)}; CtClass retType=getType(); int paramVar=ca.getMaxLocals(); jc.recordParams(javaLangObject,params,true,paramVar,withinStatic()); int retVar=jc.recordReturnType(retType,true); jc.recordProceed(new ProceedForCast(index,retType)); checkResultValue(retType,statement); Bytecode bytecode=jc.getBytecode(); storeStack(params,true,paramVar,bytecode); jc.recordLocalVariables(ca,pos); bytecode.addConstZero(retType); bytecode.addStore(retVar,retType); jc.compileStmnt(statement); bytecode.addLoad(retVar,retType); replace0(pos,bytecode,3); } catch ( CompileError e) { throw new CannotCompileException(e); } catch ( NotFoundException e) { throw new CannotCompileException(e); } catch ( BadBytecode e) { throw new CannotCompileException("broken method"); } }
Replaces the explicit cast operator with the bytecode derived from the given source text. <p>$0 is available but the value is <code>null</code>.
public TrustingMonotonicArraySet(Object[] elements){ this(); for ( Object element : elements) add(element); }
Create a set which contains the given elements.
public void open(final RPEntity user){ attending=user; chestSynchronizer=new SyncContent(); SingletonRepository.getTurnNotifier().notifyInTurns(0,chestSynchronizer); final RPSlot content=getSlot("content"); content.clear(); for ( final RPObject item : getBankSlot()) { try { content.addPreservingId(cloneItem(item)); } catch ( final Exception e) { LOGGER.error("Cannot clone item " + item,e); } } super.open(); }
Open the chest for an attending user.
protected void put(String propName,Object propValue){ properties.put(propName,propValue); }
Allow StringTemplate to add values, but prevent the end user from doing so.
protected CCScaleTo(float t,float sx,float sy){ super(t); endScaleX=sx; endScaleY=sy; }
initializes the action with and X factor and a Y factor
@Override public boolean isValidateRoot(){ return true; }
Overridden to return true so that any calls to <code>revalidate</code> on any descendants of this <code>JScrollPane</code> will cause the entire tree beginning with this <code>JScrollPane</code> to be validated.
public static String calcSizeString(float sz){ if (sz < 1024 * 1024 * 10) { if (sz < 1024 * 1024) { if (sz < 1024) { if (sz < 0) sz=0; return String.format(n_bytes,(int)sz); } return String.format(n_kilobytes,(int)(sz * (1f / 1024))); } return String.format(n_megabytes,sz * (1f / 1024 / 1024)); } if (sz < 1024 * 1024 * 200) { return String.format(n_megabytes10,sz * (1f / 1024 / 1024)); } return String.format(n_megabytes100,(int)(sz * (1f / 1024 / 1024))); }
Calculate size string for specified file length in bytes. Currently used by delete activity preview file list loader.
protected boolean beforeDelete(){ DB.executeUpdate("DELETE FROM AD_Browse_Access WHERE AD_Browse_ID=? ",getAD_Browse_ID(),get_TrxName()); DB.executeUpdate("DELETE FROM AD_Browse_Trl WHERE AD_Browse_ID=? ",getAD_Browse_ID(),get_TrxName()); return true; }
Before Delete
static void subdivideCubic(float src[],int srcoff,float left[],int leftoff,float right[],int rightoff){ float x1=src[srcoff + 0]; float y1=src[srcoff + 1]; float ctrlx1=src[srcoff + 2]; float ctrly1=src[srcoff + 3]; float ctrlx2=src[srcoff + 4]; float ctrly2=src[srcoff + 5]; float x2=src[srcoff + 6]; float y2=src[srcoff + 7]; if (left != null) { left[leftoff + 0]=x1; left[leftoff + 1]=y1; } if (right != null) { right[rightoff + 6]=x2; right[rightoff + 7]=y2; } x1=(x1 + ctrlx1) / 2.0f; y1=(y1 + ctrly1) / 2.0f; x2=(x2 + ctrlx2) / 2.0f; y2=(y2 + ctrly2) / 2.0f; float centerx=(ctrlx1 + ctrlx2) / 2.0f; float centery=(ctrly1 + ctrly2) / 2.0f; ctrlx1=(x1 + centerx) / 2.0f; ctrly1=(y1 + centery) / 2.0f; ctrlx2=(x2 + centerx) / 2.0f; ctrly2=(y2 + centery) / 2.0f; centerx=(ctrlx1 + ctrlx2) / 2.0f; centery=(ctrly1 + ctrly2) / 2.0f; if (left != null) { left[leftoff + 2]=x1; left[leftoff + 3]=y1; left[leftoff + 4]=ctrlx1; left[leftoff + 5]=ctrly1; left[leftoff + 6]=centerx; left[leftoff + 7]=centery; } if (right != null) { right[rightoff + 0]=centerx; right[rightoff + 1]=centery; right[rightoff + 2]=ctrlx2; right[rightoff + 3]=ctrly2; right[rightoff + 4]=x2; right[rightoff + 5]=y2; } }
Subdivides the cubic curve specified by the coordinates stored in the <code>src</code> array at indices <code>srcoff</code> through (<code>srcoff</code>&nbsp;+&nbsp;7) and stores the resulting two subdivided curves into the two result arrays at the corresponding indices. Either or both of the <code>left</code> and <code>right</code> arrays may be <code>null</code> or a reference to the same array as the <code>src</code> array. Note that the last point in the first subdivided curve is the same as the first point in the second subdivided curve. Thus, it is possible to pass the same array for <code>left</code> and <code>right</code> and to use offsets, such as <code>rightoff</code> equals (<code>leftoff</code> + 6), in order to avoid allocating extra storage for this common point.
@Override public boolean isAutoIncrement(int columnIndex){ return false; }
Returns false.
public BigInteger calculateAgreement(DHPublicKeyParameters pub,BigInteger message){ if (!pub.getParameters().equals(dhParams)) { throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters."); } BigInteger p=dhParams.getP(); return message.modPow(key.getX(),p).multiply(pub.getY().modPow(privateValue,p)).mod(p); }
given a message from a given party and the corresponding public key, calculate the next message in the agreement sequence. In this case this will represent the shared secret.
final public boolean isAdded(){ return mActivity != null && mAdded; }
Return true if the fragment is currently added to its activity.
void checkState() throws JMSException { session.checkState(); }
Check state
public ProcessInfo workflow(Properties ctx,ProcessInfo pi,int AD_Workflow_ID){ log.info("[" + m_no + "] "+ AD_Workflow_ID); m_workflowCount++; ProcessUtil.startWorkFlow(ctx,pi,AD_Workflow_ID); return pi; }
Run Workflow (and wait) on Server
public ScanResult runWithBackoff(){ ScanResult result=null; boolean interrupted=false; try { do { try { result=client.scan(request); } catch ( Exception e) { try { Thread.sleep(exponentialBackoffTime); } catch ( InterruptedException ie) { interrupted=true; } finally { exponentialBackoffTime*=2; } continue; } } while (result == null); return result; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
begins a scan with an exponential back off if throttled.
public MainView(){ super(new Stage(new ScreenViewport())); }
Creates a new main view with default stage.
private static DelaunayTriangle nextFlipTriangle(DTSweepContext tcx,Orientation o,DelaunayTriangle t,DelaunayTriangle ot,TriangulationPoint p,TriangulationPoint op){ int edgeIndex; if (o == Orientation.CCW) { edgeIndex=ot.edgeIndex(p,op); ot.dEdge[edgeIndex]=true; legalize(tcx,ot); ot.clearDelunayEdges(); return t; } edgeIndex=t.edgeIndex(p,op); t.dEdge[edgeIndex]=true; legalize(tcx,t); t.clearDelunayEdges(); return ot; }
After a flip we have two triangles and know that only one will still be intersecting the edge. So decide which to contiune with and legalize the other
BluetoothHeadset(Context context,ServiceListener l){ mContext=context; mServiceListener=l; mAdapter=BluetoothAdapter.getDefaultAdapter(); IBluetoothManager mgr=mAdapter.getBluetoothManager(); if (mgr != null) { try { mgr.registerStateChangeCallback(mBluetoothStateChangeCallback); } catch ( RemoteException e) { Log.e(TAG,"",e); } } if (!context.bindService(new Intent(IBluetoothHeadset.class.getName()),mConnection,0)) { Log.e(TAG,"Could not bind to Bluetooth Headset Service"); } }
Create a BluetoothHeadset proxy object.
public void tagDefineBitsJPEG3(int id,byte[] imageData,byte[] alphaData) throws IOException { if (tags != null) { tags.tagDefineBitsJPEG3(id,imageData,alphaData); } }
SWFTagTypes interface
protected void forwardCommandChangeToLayout(int newState){ if ((newState & Turnout.CLOSED) != 0) { if ((newState & Turnout.THROWN) != 0) { log.error("Cannot command both CLOSED and THROWN: " + newState); return; } else { sendMessage(true); } } else { sendMessage(false); } }
Handle a request to change state by sending a turnout command
public BufferedImage dataToRGB(final byte[] data,final int w,final int h){ final BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB); final Raster raster=ColorSpaceConvertor.createInterleavedRaster(data,w,h); image.setData(raster); return image; }
convert color content of data to sRGB data
private boolean applyVolumesToMasksUsingRules(StorageSystem storage,ExportGroup exportGroup,Map<URI,Map<URI,Integer>> existingMasksToUpdateWithNewVolumes,Map<URI,Map<URI,Integer>> volumesWithNoMask,Map<ExportMask,ExportMaskPolicy> masksMap,Map<URI,Set<Initiator>> maskToInitiatorsMap,Set<URI> partialMasks,String token){ boolean isVMAX3=storage.checkIfVmax3(); if (exportGroup.checkInternalFlags(Flag.RECOVERPOINT) || (exportGroup.checkInternalFlags(Flag.RECOVERPOINT_JOURNAL))) { masksMap=applyVolumesToMasksUsingRPVMAXRules(storage,exportGroup,masksMap); if (masksMap.isEmpty()) { _log.info("No masks were found for RP that aligned with the masks of the compute resource, proceeding to create new masks"); return true; } } if (!applyVolumesToMasksUsingRule(exportGroup,token,existingMasksToUpdateWithNewVolumes,volumesWithNoMask,masksMap,maskToInitiatorsMap,partialMasks,1,isVMAX3)) { return false; } if (!applyVolumesToMasksUsingRule(exportGroup,token,existingMasksToUpdateWithNewVolumes,volumesWithNoMask,masksMap,maskToInitiatorsMap,partialMasks,2,isVMAX3)) { return false; } if (!applyVolumesToMasksUsingRule(exportGroup,token,existingMasksToUpdateWithNewVolumes,volumesWithNoMask,masksMap,maskToInitiatorsMap,partialMasks,3,isVMAX3)) { return false; } return true; }
This method will call the method to apply a set of business rules to the volumes required to be added to masking views. See the "applyVolumesToMasksUsingRule" method documentation for exact rule logic.
public void actionPerformed(ActionEvent e){ String license=LicenseUtils.license(); JTextArea textArea=new JTextArea(license); textArea.setFont(new Font("Monospaced",Font.PLAIN,12)); JScrollPane scroll=new JScrollPane(textArea); scroll.setPreferredSize(new Dimension(600,400)); Box b=Box.createVerticalBox(); b.add(scroll); JOptionPane.showMessageDialog(JOptionUtils.centeringComp(),b,"License",JOptionPane.PLAIN_MESSAGE); }
Closes the frontmost session of this action's desktop.
protected boolean makeFigure(MouseEvent event){ ControlPanelEditor ed=_parent.getEditor(); Rectangle r=ed.getSelectRect(); if (r != null) { _width=r.width; _height=r.height; Ellipse2D.Double rr=new Ellipse2D.Double(0,0,_width,_height); PositionableEllipse ps=new PositionableEllipse(ed,rr); ps.setLocation(r.x,r.y); ps.setDisplayLevel(ControlPanelEditor.MARKERS); setPositionableParams(ps); ps.updateSize(); ed.putItem(ps); } return true; }
Create a new PositionableShape
public int show(FragmentTransaction transaction,String tag){ mDismissed=false; mShownByMe=true; transaction.add(this,tag); mViewDestroyed=false; mBackStackId=transaction.commit(); return mBackStackId; }
Display the dialog, adding the fragment using an existing transaction and then committing the transaction.
public StoragePortRestRep toStoragePortRestRep(StoragePort storagePort){ return apply(storagePort); }
Translate <code>StoragePort</code> object to <code>StoragePortRestRep</code>
public boolean intersectsSegment(Vec4 pa,Vec4 pb){ if (pa == null || pb == null) { String message=Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (this.contains(pa) || this.contains(pb)) return true; if (pa.equals(pb)) return false; for ( Plane p : this.getAllPlanes()) { if (p.onSameSide(pa,pb) < 0) return false; if (p.clip(pa,pb) != null) return true; } return false; }
Determines whether a line segment intersects this frustum.
protected void prepare(){ p_Record_ID=getRecord_ID(); ProcessInfoParameter[] parameters=getParameter(); for ( ProcessInfoParameter para : parameters) { String name=para.getParameterName(); if (para.getParameter() == null) ; if (MBrowse.COLUMNNAME_AD_Browse_ID.equals(para.getParameterName())) p_AD_Browse_ID=para.getParameterAsInt(); else log.log(Level.SEVERE,"Unknown Parameter: " + name); } }
Get Parameters
@Override public Object create(final ConfigurableFactoryContext ctx){ KeyDestroyingDoor door=new KeyDestroyingDoor(getKey(ctx),getClass(ctx)); door.setRejectedMessage(getRejectedMessage(ctx)); return door; }
Create a locked door.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public EgDemandDetails insertAdvanceCollection(final String demandReason,final BigDecimal advanceCollectionAmount,final Installment installment){ EgDemandDetails demandDetail=null; if (advanceCollectionAmount != null && advanceCollectionAmount.compareTo(BigDecimal.ZERO) > 0) { final EgDemandReasonMaster egDemandReasonMaster=demandGenericDAO.getDemandReasonMasterByCode(demandReason,module()); if (egDemandReasonMaster == null) throw new ApplicationRuntimeException(" Advance Demand reason Master is null in method insertAdvanceCollection"); final EgDemandReason egDemandReason=demandGenericDAO.getDmdReasonByDmdReasonMsterInstallAndMod(egDemandReasonMaster,installment,module()); if (egDemandReason == null) throw new ApplicationRuntimeException(" Advance Demand reason is null in method insertAdvanceCollection "); demandDetail=createDemandDetails(egDemandReason,advanceCollectionAmount,BigDecimal.ZERO); } return demandDetail; }
Method used to insert advance collection in EgDemandDetail table.
public boolean isQuestCompleted(final String name){ final String info=getQuest(name,0); if (info == null) { return false; } return info.equals("done"); }
Checks whether the player has completed the given quest or not.
public static void takeScreenshot(Activity activity,File toFile){ if (activity == null) { throw new IllegalArgumentException("Parameter activity cannot be null."); } if (toFile == null) { throw new IllegalArgumentException("Parameter toFile cannot be null."); } Bitmap bitmap=null; try { if (!toFile.exists()) { toFile.createNewFile(); } bitmap=takeBitmapUnchecked(activity); writeBitmap(bitmap,toFile); } catch ( Exception e) { String message="Unable to take screenshot to file " + toFile.getAbsolutePath() + " of activity "+ activity.getClass().getName(); Log.e(TAG,message,e); throw new UnableToTakeScreenshotException(message,e); } finally { if (bitmap != null) { bitmap.recycle(); } } Log.d(TAG,"Screenshot captured to " + toFile.getAbsolutePath()); }
Takes screenshot of provided activity and saves it to provided file. File content will be overwritten if there is already some content.
public VaultConfig sslPemUTF8(final String sslPemUTF8){ this.sslPemUTF8=sslPemUTF8; return this; }
<p>An X.509 certificate, to use when communicating with Vault over HTTPS. This method accepts a string containing the certificate data. This string should meet the following requirements:</p> <ul> <li>Contain an unencrypted X.509 certificate, in PEM format.</li> <li>Use UTF-8 encoding.</li> <li> Contain a line-break between the certificate header (e.g. "-----BEGIN CERTIFICATE-----") and the rest of the certificate content. It doesn't matter whether or not there are additional line breaks within the certificate content, or whether there is a line break before the certificate footer (e.g. "-----END CERTIFICATE-----"). But the Java standard library will fail to properly process the certificate without a break following the header (see http://www.doublecloud.org/2014/03/reading-x-509-certificate-in-java-how-to-handle-format-issue/). </li> </ul> <p>If no certificate data is provided, either by this method or <code>sslPemFile()</code> or <code>sslPemResource()</code>, then <code>VaultConfig</code> will look to the <code>VAULT_SSL_CERT</code> environment variable.</p>
public final void transpose(){ int i, j; if (nRow != nCol) { double[][] tmp; i=nRow; nRow=nCol; nCol=i; tmp=new double[nRow][nCol]; for (i=0; i < nRow; i++) { for (j=0; j < nCol; j++) { tmp[i][j]=values[j][i]; } } values=tmp; } else { double swap; for (i=0; i < nRow; i++) { for (j=0; j < i; j++) { swap=values[i][j]; values[i][j]=values[j][i]; values[j][i]=swap; } } } }
Transposes this matrix in place.
public String randomAlphaMixed(int length){ return randomString(alphaMixed(),length); }
Get a random string of lower and upper case letters of given length
private void initWidget(){ this.widgetCard=(ImageView)findViewById(R.id.widget_day_week_card); widgetCard.setVisibility(View.GONE); this.widgetIcon=(ImageView)findViewById(R.id.widget_day_week_icon); this.widgetWeather=(TextView)findViewById(R.id.widget_day_week_weather); this.widgetTemp=(TextView)findViewById(R.id.widget_day_week_temp); this.widgetRefreshTime=(TextView)findViewById(R.id.widget_day_week_refreshTime); this.widgetWeeks=new TextView[]{(TextView)findViewById(R.id.widget_day_week_week_1),(TextView)findViewById(R.id.widget_day_week_week_2),(TextView)findViewById(R.id.widget_day_week_week_3),(TextView)findViewById(R.id.widget_day_week_week_4),(TextView)findViewById(R.id.widget_day_week_week_5)}; this.widgetIcons=new ImageView[]{(ImageView)findViewById(R.id.widget_day_week_icon_1),(ImageView)findViewById(R.id.widget_day_week_icon_2),(ImageView)findViewById(R.id.widget_day_week_icon_3),(ImageView)findViewById(R.id.widget_day_week_icon_4),(ImageView)findViewById(R.id.widget_day_week_icon_5)}; this.widgetTemps=new TextView[]{(TextView)findViewById(R.id.widget_day_week_temp_1),(TextView)findViewById(R.id.widget_day_week_temp_2),(TextView)findViewById(R.id.widget_day_week_temp_3),(TextView)findViewById(R.id.widget_day_week_temp_4),(TextView)findViewById(R.id.widget_day_week_temp_5)}; ImageView wallpaper=(ImageView)findViewById(R.id.activity_create_widget_day_week_wall); wallpaper.setImageDrawable(WallpaperManager.getInstance(this).getDrawable()); this.container=(CoordinatorLayout)findViewById(R.id.activity_create_widget_day_week_container); ArrayAdapter<String> adapter=new ArrayAdapter<>(this,R.layout.spinner_text,nameList); adapter.setDropDownViewResource(R.layout.spinner_text); Spinner locationSpinner=(Spinner)findViewById(R.id.activity_create_widget_day_week_spinner); locationSpinner.setAdapter(adapter); locationSpinner.setOnItemSelectedListener(this); this.showCardSwitch=(Switch)findViewById(R.id.activity_create_widget_day_week_showCardSwitch); showCardSwitch.setOnCheckedChangeListener(new ShowCardSwitchCheckListener()); this.hideRefreshTimeSwitch=(Switch)findViewById(R.id.activity_create_widget_day_week_hideRefreshTimeSwitch); hideRefreshTimeSwitch.setOnCheckedChangeListener(new HideRefreshTimeSwitchCheckListener()); this.blackTextSwitch=(Switch)findViewById(R.id.activity_create_widget_day_week_blackTextSwitch); blackTextSwitch.setOnCheckedChangeListener(new BlackTextSwitchCheckListener()); Button doneButton=(Button)findViewById(R.id.activity_create_widget_day_week_doneButton); doneButton.setOnClickListener(this); }
<br> UI.
private void handleSelectorDimmerClick(int idx,String[] levelNames){ listener.onSelectorDimmerClick(idx,levelNames); }
Handles the selector dimmer click
@Override public java.util.List<JToolBar> createToolBars(Application a,@Nullable View pr){ ResourceBundleUtil drawLabels=ResourceBundleUtil.getBundle("org.jhotdraw.draw.Labels"); NetView p=(NetView)pr; DrawingEditor editor; if (p == null) { editor=getSharedEditor(); } else { editor=p.getEditor(); } LinkedList<JToolBar> list=new LinkedList<JToolBar>(); JToolBar tb; tb=new JToolBar(); addCreationButtonsTo(tb,editor); tb.setName(drawLabels.getString("window.drawToolBar.title")); list.add(tb); tb=new JToolBar(); ButtonFactory.addAttributesButtonsTo(tb,editor); tb.setName(drawLabels.getString("window.attributesToolBar.title")); list.add(tb); tb=new JToolBar(); ButtonFactory.addAlignmentButtonsTo(tb,editor); tb.setName(drawLabels.getString("window.alignmentToolBar.title")); list.add(tb); return list; }
Creates toolbars for the application.
public void startEntity(String name) throws org.xml.sax.SAXException { }
Report the beginning of an entity. The start and end of the document entity are not reported. The start and end of the external DTD subset are reported using the pseudo-name "[dtd]". All other events must be properly nested within start/end entity events.
@Override public String toSource(String className) throws Exception { if (m_Tree == null) { throw new Exception("REPTree: No model built yet."); } StringBuffer[] source=m_Tree.toSource(className,m_Tree); return "class " + className + " {\n\n"+ " public static double classify(Object [] i)\n"+ " throws Exception {\n\n"+ " double p = Double.NaN;\n"+ source[0]+ " return p;\n"+ " }\n"+ source[1]+ "}\n"; }
Returns the tree as if-then statements.
@Override public boolean eventGeneratable(String eventName){ if (m_listenee == null) { return false; } if (m_listenee instanceof EventConstraints) { if (!((EventConstraints)m_listenee).eventGeneratable("incrementalClassifier")) { return false; } } return true; }
Returns true, if at the current time, the named event could be generated. Assumes that supplied event names are names of events that could be generated by this bean.
public void clear(){ for (int i=0; i < mSubcategories.size(); i++) { mSubcategories.get(i).clear(); } mBlocks.clear(); mSubcategories.clear(); }
Clear the contents of this category and all subcategories; remove subcategories.
void deleteTask(long id){ datastore.delete(keyFactory.newKey(id)); }
Deletes a task entity.
protected void init(){ if (!isInit) { Terminal[] terminals=Reflection.getTerminals(); NonTerminal[] nonTerminals=Reflection.getNonTerminals(); symbolValueClasses=Reflection.getSymbolValueClasses(terminals,nonTerminals); isInit=true; } }
Initializes this class. The grammar method would be too late, because we need some information earlier.
public static BinaryType type(BinaryContext ctx,BinaryObjectEx obj){ if (ctx == null) throw new BinaryObjectException("BinaryContext is not set for the object."); return ctx.metadata(obj.typeId()); }
Create binary type which is used by users.
synchronized boolean unexport(boolean force){ if ((force == true) || (callCount == 0) || (disp == null)) { disp=null; unpinImpl(); DGCImpl dgc=DGCImpl.getDGCImpl(); Enumeration<VMID> enum_=refSet.elements(); while (enum_.hasMoreElements()) { VMID vmid=enum_.nextElement(); dgc.unregisterTarget(vmid,this); } return true; } else { return false; } }
Mark this target as not accepting new calls if any of the following conditions exist: a) the force parameter is true, b) the target's call count is zero, or c) the object is already not accepting calls. Returns true if target is marked as not accepting new calls; returns false otherwise.
public MonthWeekEventsView(Context context){ super(context); }
Shows up as an error if we don't include this.
public static long toLong(NibbleArray nibbles,int start){ return toLong(nibbles.get(start),nibbles.get(start + 1),nibbles.get(start + 2),nibbles.get(start + 3),nibbles.get(start + 4),nibbles.get(start + 5),nibbles.get(start + 6),nibbles.get(start + 7),nibbles.get(start + 8),nibbles.get(start + 9),nibbles.get(start + 10),nibbles.get(start + 11),nibbles.get(start + 12),nibbles.get(start + 13),nibbles.get(start + 14),nibbles.get(start + 15)); }
Returns long from given array of nibbles. <br> Array must have at least start + 16 elements in it.
public void doNew(final Strategy strategy){ try { String templateName=ConfigProperties.getPropAsString("trade.strategy.template"); String fileName=m_strategyDir + "/" + StrategyRule.PACKAGE.replace('.','/')+ templateName+ ".java"; commentText.setText(null); setContent(readFile(fileName)); setContent((getContent().replaceAll(templateName,strategy.getClassName()))); createRule(strategy); } catch ( Exception ex) { setErrorMessage("Error loading template strategy",ex.getMessage(),ex); } }
Method doNew.
public LogTradeEventCommand(Player player,Item item,int quantity,int price){ this.charname=player.getName(); this.item=item; this.quantity=quantity; this.price=price; }
logs a trade event
public static <T extends Predicate<String>>Validator<String> custom(T predicate,BiFunction<String,StringCustomValidator<T>,? extends IllegalArgumentException> exception){ return new ValidatorEntry<>(StringCustomValidator.create(predicate),exception); }
Create new custom String validator that throws given exception on invalid parameter.
public void markSaved(){ this.entities.markSaved(this.world.getTotalWorldTime()); this.isModified=false; }
Mark this cube as saved to disk
public void destroy(){ context.removeVisualizationListener(this); context.removeResultListener(this); plot.dispose(); }
Destroy this overview plot.
@Override public void endSampling(Sampler<?,?,?> sampler){ }
Does nothing.
@LogMessageDoc(level="ERROR",message="Tried to write OFFlowMod to {switch} but got {error}",explanation="An I/O error occured while trying to write a " + "static flow to a switch",recommendation=LogMessageDoc.CHECK_SWITCH) private void writeFlowModToSwitch(IOFSwitch sw,OFFlowMod flowMod){ sw.write(flowMod); sw.flush(); }
Writes an OFFlowMod to a switch
public static boolean isOptionApplies(DimensionOption option,AppContext ctx){ if (option.getGroupFilter() == null && option.getUserFilter() == null) { return true; } else { if (option.getGroupFilter() != null) { for ( String groupFilter : option.getGroupFilter()) { if (ctx.getUser().getGroups().contains(groupFilter)) { return true; } } } if (option.getUserFilter() != null) { String userNamep=ctx.getUser().getLogin().toUpperCase(); for ( String userFilter : option.getGroupFilter()) { if (userFilter.toUpperCase().equals(userNamep)) return true; } } return false; } }
check if the option applies to the user context
@HLEFunction(nid=0x50A14DFC,version=150,checkInsideInterrupt=true) public int __sceSasCoreWithMix(int sasCore,int sasInOut,int leftVolume,int rightVolume){ checkSasHandleGood(sasCore); long startTime=Emulator.getClock().microTime(); mixer.synthesizeWithMix(sasInOut,grainSamples,leftVolume << 3,rightVolume << 3); delayThreadSasCore(startTime); return 0; }
Process the voices and generate the next samples. Mix the resulting samples in an exiting buffer.
public SQLNonTransientConnectionException(String reason,String sqlState,int vendorCode,Throwable cause){ super(reason,sqlState,vendorCode,cause); }
Creates an SQLNonTransientConnectionException object. The Reason string is set to the given reason string, the SQLState string is set to the given SQLState string , the Error Code is set to the given error code value, and the cause Throwable object is set to the given cause Throwable object.
public boolean isEnd() throws IOException { int code=parseTag(); _peekTag=code; return (code < 0 || code >= 100); }
Returns true if this is the end of a list or a map.
@Override public Map createHeaderParams(final WorkOrder workOrder,final String type){ final Map<String,Object> reportParams=new HashMap<String,Object>(); if (workOrder != null) if ("estimate".equalsIgnoreCase(type)) { for ( final WorkOrderEstimate workOrderEstimate : workOrder.getWorkOrderEstimates()) if (workOrderEstimate != null && workOrderEstimate.getEstimate() != null) { reportParams.put("deptName",workOrderEstimate.getEstimate().getExecutingDepartment().getName()); final Boundary b=getTopLevelBoundary(workOrderEstimate.getEstimate().getWard()); reportParams.put("cityName",b == null ? "" : b.getName()); reportParams.put("deptAddress",""); reportParams.put("aeWorkNameForEstimate",workOrderEstimate.getEstimate().getName()); reportParams.put("negotiatedAmtForEstimate",workOrder.getWorkOrderAmount()); reportParams.put("estimateNo",workOrderEstimate.getEstimate().getEstimateNumber()); reportParams.put("estimateDate",workOrderEstimate.getEstimate().getEstimateDate()); if (workOrderEstimate.getEstimate().getProjectCode() != null) reportParams.put("projectCode",workOrderEstimate.getEstimate().getProjectCode().getCode()); } } else { final List<WorkOrderEstimate> aeList=getAbstractEstimateListForWp(workOrder); final String projectCode=getProjectCodeListForAe(aeList); reportParams.put("projectCodeList",projectCode); final WorksPackage wp=workspackageService.findByNamedQuery("GET_WORKSPACKAGE_PACKAGENUMBER",workOrder.getPackageNumber()); if (wp != null) reportParams.put("workPackageDate",wp.getCreatedDate()); if (wp != null) reportParams.put("tenderFileNumber",wp.getTenderFileNumber()); reportParams.put("workPackageNo",workOrder.getPackageNumber()); if (aeList != null && !aeList.isEmpty()) { reportParams.put("deptName",aeList.get(0).getEstimate().getExecutingDepartment().getName()); final Boundary b=getTopLevelBoundary(aeList.get(0).getEstimate().getWard()); reportParams.put("cityName",b == null ? "" : b.getName()); reportParams.put("deptAddress",""); } } if (workOrder != null && workOrder.getContractor() != null) { String contractorAddress=workOrder.getContractor().getName() + " , " + workOrder.getContractor().getCode(); if (workOrder.getContractor().getPaymentAddress() != null) contractorAddress=contractorAddress + " , " + workOrder.getContractor().getPaymentAddress(); reportParams.put("contractorAddress",contractorAddress); } reportParams.put("WorkOrderObj",workOrder); return reportParams; }
returns headermap for pdf
public boolean engineIsOn(){ return (start_button.isSelected()); }
Return true if the start button is "on"
private boolean isMediaTypeSupported(String media){ for (int i=0; i < SUPPORTED_MEDIA_TYPES.length; i++) { if (media.equalsIgnoreCase(SUPPORTED_MEDIA_TYPES[i])) { return true; } } return false; }
Returns true if the specified CSS media type is unsupported, false otherwise
public StatusNotification(String title,Status status,DisplayMode displayMode){ super(title); this.status=status; this.displayMode=displayMode; }
Creates status notification object with specified title, status and display mode.
@Deprecated public void append(final String name,final String value){ List<String> l=map.get(name); if (l != null) { l.add(value); } else { l=Lists.newArrayList(value); map.put(name,l); } }
Add a new value for name
@InfoName("CL_DEVICE_AVAILABLE") public boolean isAvailable(){ return infos.getBool(getEntity(),CL_DEVICE_AVAILABLE); }
Is CL_TRUE if the device is available and CL_FALSE if the device is not available.
public Class parseClass(GroovyCodeSource codeSource,boolean shouldCacheSource) throws CompilationFailedException { synchronized (sourceCache) { Class answer=sourceCache.get(codeSource.getName()); if (answer != null) return answer; answer=doParseClass(codeSource); if (shouldCacheSource) sourceCache.put(codeSource.getName(),answer); return answer; } }
Parses the given code source into a Java class. If there is a class file for the given code source, then no parsing is done, instead the cached class is returned.
int turnoutState(){ if (namedTurnout != null) { return getTurnout().getKnownState(); } else { return Turnout.UNKNOWN; } }
Get current state of attached turnout
public static QueryParser newQueryParser(String string){ return new QueryParser(version,string,ENGLISH); }
Uses default analyzer
@Override public void writeVertices(final OutputStream outputStream,final Iterator<Vertex> vertexIterator) throws IOException { writeVertices(outputStream,vertexIterator,null); }
Writes a list of vertices without edges.
public synchronized void finer(String msg){ LogRecord record=new LogRecord(Level.FINER,msg); log(record); }
Logs a FINER message
@Override public void write(byte[] buf,int offset,int length,boolean isEnd) throws IOException { if (_os == null) { if (_s == null) { return; } _os=_s.getOutputStream(); } try { _needsFlush=true; _os.write(buf,offset,length); _totalWriteBytes+=length; } catch ( IOException e) { IOException exn=ClientDisconnectException.create(this + ":" + e,e); try { close(); } catch ( IOException e1) { } throw exn; } }
Writes bytes to the socket.
public synchronized void accept(Agent agent) throws RemoteException { Thread t; t=new Thread(agent); System.out.println("Agent Accepted: " + t); t.start(); }
Remote method called by Agent to have server accept it.