code
stringlengths
10
174k
nl
stringlengths
3
129k
@Override public void declareExtensions(ExtensionProfile extProfile){ super.declareExtensions(extProfile); extProfile.declare(SitemapsMobileEntry.class,ExtensionDescription.getDefaultDescription(MarkupLanguage.class)); }
Initializes an ExtensionProfile based upon the extensions expected by a SitemapsMobileEntry.
public static IByteSequence readAllBytesFromStream(InputStream inputStream,int capacity) throws IOException { try { final int BUFFER_SIZE=1024; byte[] buffer=new byte[BUFFER_SIZE]; ByteArrayOutputStreamExt bytes=new ByteArrayOutputStreamExt(capacity); int read; while ((read=inputStream.read(buffer)) != EOF) { bytes.write(buffer,0,read); } return bytes; } finally { inputStream.close(); } }
Reads and returns all bytes from given inputStream until an EOF is read. Closes inputStream afterwards. ByteArray buffer is initialized to given capacity.
private void showPopupMenu(final MouseEvent event){ final ITagTreeNode selectedNode=(ITagTreeNode)TreeHelpers.getNodeAt(this,event.getX(),event.getY()); if (selectedNode == null) { final JPopupMenu popupMenu=new JPopupMenu(); popupMenu.add(CActionProxy.proxy(new CAddRootTagNodeAction(m_parent,m_tagManager,m_rootNode.getTag()))); popupMenu.show(this,event.getX(),event.getY()); } else { final JPopupMenu menu=selectedNode.getPopupMenu(); if (menu != null) { menu.show(this,event.getX(),event.getY()); } } }
Shows the context menu for a given mouse event.
public static byte[] decode(byte[] data){ ByteArrayOutputStream bOut=new ByteArrayOutputStream(); try { encoder.decode(data,0,data.length,bOut); } catch ( Exception e) { throw new DecoderException("exception decoding URL safe base64 string: " + e.getMessage(),e); } return bOut.toByteArray(); }
Decode the URL safe base 64 encoded input data - white space will be ignored.
public void addXTextLabel(double x,String text){ mXTextLabels.put(x,text); }
Adds a new text label for the specified X axis value.
public static String localString(RegisterSpec spec){ return spec.regString() + ' ' + spec.getLocalItem().toString()+ ": "+ spec.getTypeBearer().toHuman(); }
Returns the local variable listing string for a single register spec.
public void parseConflictString(String conflictString){ setConflict(conflictString); this.conflictStringWithoutConflictMarker=conflictString; this.lastModified=null; this.conflict=false; this.timeStampMatchesFile=false; if (conflictString == null || conflictString.equals(DUMMY_TIMESTAMP) || conflictString.equals(MERGE_TIMESTAMP) || conflictString.equals(DUMMY_TIMESTAMP_NEW_ENTRY)) { return; } int parseStartIndex=0; final int conflictIndex=conflictStringWithoutConflictMarker.indexOf(HAD_CONFLICTS); if (conflictIndex >= 0) { conflict=true; parseStartIndex=conflictIndex + 1; } final int timeMatchIndex=conflictStringWithoutConflictMarker.indexOf(TIMESTAMP_MATCHES_FILE); if (timeMatchIndex >= 0) { timeStampMatchesFile=true; parseStartIndex=Math.max(parseStartIndex,timeMatchIndex + 1); } if (parseStartIndex > 0) { conflictStringWithoutConflictMarker=conflictStringWithoutConflictMarker.substring(parseStartIndex); } if (conflictStringWithoutConflictMarker.length() == 0) { conflictStringWithoutConflictMarker=null; return; } if (conflictStringWithoutConflictMarker.startsWith(INITIAL_PREFIX)) { return; } try { this.lastModified=getLastModifiedDateFormatter().parse(conflictStringWithoutConflictMarker); } catch ( Exception ex) { lastModified=null; System.err.println("[Entry] can't parse conflict '" + conflictStringWithoutConflictMarker + "'"); } }
A typical conflict string looks like "+=".
@Override public void respond(String response){ getChannel().send().message(getUser(),response); }
Respond with a channel message in <code>user: message</code> format to the user that joined
public WrongPredictionCondition(){ }
Creates a new condition.
public Rectangle(Rectangle rect){ x=rect.x; y=rect.y; width=rect.width; height=rect.height; }
Constructs a rectangle based on the given rectangle
public static VOCountryVatRate toVOCountryVatRate(VatRate domObj){ if (domObj == null) { return null; } VOCountryVatRate vo=new VOCountryVatRate(); vo.setRate(domObj.getRate()); vo.setCountry(domObj.getTargetCountry().getCountryISOCode()); updateValueObject(vo,domObj); return vo; }
Creates a new VOCountryVatRate object and fills the fields with the corresponding fields from the given domain object.
public JLTransform(final int k){ this(k,TransformMode.SPARSE); }
Creates a new JL Transform
public MapOptions zoom(int zoom){ this.zoom=zoom; return this; }
Sets the zoom level. Higher means more zoomed in. default = 15
protected void configureImageReaderLoaders(){ imageReaderLoaders=new Vector<ImageReaderLoader>(); ImageReaderLoader idl=(ImageReaderLoader)ComponentFactory.create("com.bbn.openmap.dataAccess.image.geotiff.GeoTIFFImageReaderLoader"); if (idl != null) { imageReaderLoaders.add(idl); } else { logger.warning("ImageTileLayer needs JAI installed in order to use GeoTIFF Image Reader."); } idl=(ImageReaderLoader)ComponentFactory.create("com.bbn.openmap.dataAccess.image.WorldFileImageReaderLoader"); if (idl != null) { imageReaderLoaders.add(idl); } else { logger.warning("ImageTileLayer needs JAI installed in order to use World File Image Reader."); } }
Internal callback method for subclasses to use to be able to configure imageReaderLoader Vector with specific ImageReaderLoaders. By default, loads GeoTIFFImageReader.Loader.
public OrderRestRep submit(OrderCreateParam input){ OrderRestRep order=client.post(OrderRestRep.class,input,PathConstants.ORDER2_URL); return order; }
Submit an order <p> API Call: <tt>POST /catalog/orders</tt>
public void testSamplingChange() throws Exception { startUp(); assert !logEnabled(); fs.close(); igfs.globalSampling(true); fs=fileSystem(); assert logEnabled(); fs.close(); igfs.globalSampling(null); fs=fileSystem(); assert !logEnabled(); igfs.globalSampling(false); fs=fileSystem(); assert !logEnabled(); fs.close(); igfs.globalSampling(null); fs=fileSystem(); assert !logEnabled(); fs.close(); igfs.globalSampling(true); igfs.globalSampling(false); fs=fileSystem(); assert !logEnabled(); fs.close(); igfs.globalSampling(true); fs=fileSystem(); assert logEnabled(); }
Ensure sampling change through API causes changes in logging on subsequent client connections.
private void doClearTurret(){ String title=Messages.getString("FiringDisplay.ClearTurret.title"); String body=Messages.getString("FiringDisplay.ClearTurret.message"); if (!clientgui.doYesNoDialog(title,body)) { return; } if ((((attacks.size() == 0) && (ce() instanceof Tank) && (((Tank)ce()).isTurretJammed(((Tank)ce()).getLocTurret()))) || ((Tank)ce()).isTurretJammed(((Tank)ce()).getLocTurret2()))) { UnjamTurretAction uta=new UnjamTurretAction(ce().getId()); attacks.add(uta); ready(); } }
clear turret
public void removeFromActiveList(DownloadInfoRunnable downloadInfoRunnable){ mActiveList.remove(downloadInfoRunnable); }
Removes a download from the active list.
public void evenMore(int i,int j){ if (true) System.out.println("True"); }
This comment must be preserved too.
public Object clone(){ try { return super.clone(); } catch ( CloneNotSupportedException e) { return null; } }
Default cloning behaviour (bitwise copy) is just fine... Could clear out cached string presentation, but there's probably no point in doing that.
public final boolean isHeartbeatActive(){ return _isHeartbeatActive; }
Returns true if the target server's heartbeat is active.
public Bindings add(String property,JComboBox<String> combo,int defaultValue){ registerPropertyChangeListener(combo); return add(new JComboBoxBinding(property,combo,defaultValue)); }
Handles JComboBox
public void checkinConnectionOnError(DBConnectionWrapper conn){ conn.setCurrentStatement(null); conn.close(); synchronized (this) { for (int i=0; i < this.connections.size(); i++) { if (conn == this.connections.get(i)) { logger.fine("Remove closed connection (" + conn.getAppUser() + ","+ conn.getDb()); this.connections.remove(i); break; } } } }
Well, we need close the connection and remove it
@Override public String globalInfo(){ return "Duplicates each multi-labelled example, and assigns one of the labels (only) to each copy; then trains a regular multi-class base classifier.\n" + "At test time, a threshold separates relevant from irrelevant labels using the posterior for each class value (i.e., label)."; }
Description to display in the GUI.
static <T>T[] newArray(T[] reference,int length){ Class<?> type=reference.getClass().getComponentType(); @SuppressWarnings("unchecked") T[] result=(T[])Array.newInstance(type,length); return result; }
Returns a new array of the given length with the same type as a reference array.
@Override public void abort() throws IOException { super.abort(); }
Close the stream without necessarily flushing immediately. This may be called if the stream is in error such as after a previous write or close threw an exception.
public TouchlessScrollView(Context context,AttributeSet attrs,int defStyleAttr){ super(context,attrs,defStyleAttr); }
Creates a new instance of TouchlessScrollview.
boolean isPotentialDragTarget(){ return isVisibleNow() && !mRemoved && mInputChannel != null && mInputWindowHandle != null; }
Can this window possibly be a drag/drop target? The test here is a combination of the above "visible now" with the check that the Input Manager uses when discarding windows from input consideration.
public final void expectToken(TokenType tokenType,String message) throws IOException { if (mCurrentToken.mType != tokenType) { parseError(message + "(token found " + mCurrentToken.mType+ ")"); } }
Raises an exception with the specified message if the current token is not as specified. Tokens are specified using StreamTokenizer constants.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case N4mfPackage.PROJECT_DEPENDENCY__VERSION_CONSTRAINT: return getVersionConstraint(); case N4mfPackage.PROJECT_DEPENDENCY__DECLARED_SCOPE: return getDeclaredScope(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public IntersectionFinderAdder(LineIntersector li){ this.li=li; interiorIntersections=new ArrayList(); }
Creates an intersection finder which finds all proper intersections
public static void clearScreen(final float r,final float g,final float b){ Gdx.gl.glClearColor(r,g,b,1f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); }
Clears the screen with the selected color.
private static void localListen() throws IgniteException { System.out.println(); System.out.println(">>> Local event listener example."); Ignite ignite=Ignition.ignite(); IgnitePredicate<TaskEvent> lsnr=null; ignite.events().localListen(lsnr,EVTS_TASK_EXECUTION); ignite.compute().withName("example-event-task").run(null); ignite.events().stopLocalListen(lsnr); }
Listen to events that happen only on local node.
public static FastBitmapDrawable createIconDrawable(Bitmap icon){ FastBitmapDrawable d=new FastBitmapDrawable(icon); d.setFilterBitmap(true); resizeIconDrawable(d); return d; }
Returns a FastBitmapDrawable with the icon, accurately sized.
public void testDelete(){ File file=FileTesting.createFile(); FileBuffer buffer=FileBuffer.allocate(file,16); buffer.writeLong(10).writeLong(11).flip(); assertEquals(buffer.readLong(),10); assertEquals(buffer.readLong(),11); assertTrue(Files.exists(file.toPath())); buffer.delete(); assertFalse(Files.exists(file.toPath())); }
Tests deleting a file.
public View addProperty(String name,View view){ properties.put(name,new ViewProperty(name,view)); return this; }
Add a property to this view.
public boolean hideOverflowMenu(){ if (mPostedOpenRunnable != null && mMenuView != null) { ((View)mMenuView).removeCallbacks(mPostedOpenRunnable); mPostedOpenRunnable=null; return true; } MenuPopupHelper popup=mOverflowPopup; if (popup != null) { popup.dismiss(); return true; } return false; }
Hide the overflow menu if it is currently showing.
public String toString(){ return this.mode == 'd' ? this.writer.toString() : null; }
Return the JSON text. This method is used to obtain the product of the JSONStringer instance. It will return <code>null</code> if there was a problem in the construction of the JSON text (such as the calls to <code>array</code> were not properly balanced with calls to <code>endArray</code>).
protected int addHeaderToOutput(byte[] msg,jmri.jmrix.AbstractMRMessage m){ if (log.isDebugEnabled()) { log.debug("Appending '<' to start of outgoing message. msg length = {}",msg.length); } msg[0]=(byte)'<'; return 1; }
Add header to the outgoing byte stream.
public static GraphFromAgentContainerSynchronizer synchronize(final IScope scope,final IContainer popVertices,final IContainer popEdges,final IGraph graph){ final GraphFromAgentContainerSynchronizer res=new GraphFromAgentContainerSynchronizer(scope,popVertices,popEdges,graph); if (res.getEdgesPopulation() != null) { res.getEdgesPopulation().addListener(res); } if (res.getVerticesPopulation() != null) { res.getVerticesPopulation().addListener(res); } return res; }
Creates a synchronizer which listens for a population of vertices and updates the graph accordingly
private void saveBitmap(Bitmap currentBitmap,int frameNum){ if (mRootFolder == null) { File filesDir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); String pictureFolderName=getContext().getString(R.string.app_name); mRootFolder=new File(filesDir,pictureFolderName); if (!mRootFolder.exists()) { mRootFolder.mkdirs(); } MediaScannerConnection.scanFile(getContext(),new String[]{mRootFolder.getAbsolutePath()},null,null); } try { File filePicture=new File(mRootFolder,getName() + frameNum + ".png"); filePicture.setWritable(true); FileOutputStream fos=new FileOutputStream(filePicture); currentBitmap.compress(Bitmap.CompressFormat.PNG,100,fos); fos.flush(); fos.close(); currentBitmap.recycle(); MediaScannerConnection.scanFile(getContext(),new String[]{filePicture.getAbsolutePath()},null,null); Log.d("LinearLayoutScreenRec","The file has been recorded as " + filePicture.getName() + " in "+ mRootFolder); } catch ( FileNotFoundException e) { Log.e("LinearLayoutScreenRec","Fuck occurs FileNotFoundException",e); } catch ( IOException e) { Log.e("LinearLayoutScreenRec","Fuck occurs IOException",e); } }
Saving a bitmap
public void uninstallUI(JComponent a){ for (int i=0; i < uis.size(); i++) { ((ComponentUI)(uis.elementAt(i))).uninstallUI(a); } }
Invokes the <code>uninstallUI</code> method on each UI handled by this object.
@Override public void close() throws IOException { synchronized (lock) { in.close(); } }
Closes this reader. This implementation closes the filtered reader.
public static ConnectionManager createInstance(Context ctx,RcsServiceControl rcsServiceControl,Set<RcsServiceName> managedServices){ if (sInstance != null) { return sInstance; } synchronized (ConnectionManager.class) { if (sInstance == null) { if (ctx == null) { throw new IllegalArgumentException("Context is null"); } sInstance=new ConnectionManager(ctx,managedServices,rcsServiceControl); } } return sInstance; }
Get an instance of ConnectionManager.
private void saveasPropFile(){ File pfile=new File(sb.dataPath,"DATA/SETTINGS/autosearch.conf"); if (querystack.size() == 0) { if (pfile.exists()) { pfile.delete(); } } else { try { Properties prop=new Properties(); for ( String s : querystack) { prop.put("query" + s.hashCode(),s); } OutputStream fileOut=new FileOutputStream(pfile); prop.store(fileOut,"AutoSearch query list"); fileOut.close(); } catch ( FileNotFoundException ex) { ConcurrentLog.warn(AutoSearch.class.getName(),"can not create file " + pfile.getAbsolutePath()); } catch ( IOException ex) { ConcurrentLog.warn(AutoSearch.class.getName(),"IO error writing to file " + pfile.getAbsolutePath()); } } }
Save current queries to a (temporary) property file to allow continue after a restart. Existing file will be overwritten or deleted.
public final static byte[] base64Decode(byte[] data){ if (data == null) { return null; } int tail=data.length; while (data[tail - 1] == '=') { tail--; } byte dest[]=new byte[tail - data.length / 4]; for (int idx=0; idx < data.length; idx++) { data[idx]=Base64DecMap[data[idx]]; } int sidx, didx; for (sidx=0, didx=0; didx < dest.length - 2; sidx+=4, didx+=3) { dest[didx]=(byte)(((data[sidx] << 2) & 255) | ((data[sidx + 1] >>> 4) & 003)); dest[didx + 1]=(byte)(((data[sidx + 1] << 4) & 255) | ((data[sidx + 2] >>> 2) & 017)); dest[didx + 2]=(byte)(((data[sidx + 2] << 6) & 255) | (data[sidx + 3] & 077)); } if (didx < dest.length) { dest[didx]=(byte)(((data[sidx] << 2) & 255) | ((data[sidx + 1] >>> 4) & 003)); } if (++didx < dest.length) { dest[didx]=(byte)(((data[sidx + 1] << 4) & 255) | ((data[sidx + 2] >>> 2) & 017)); } return dest; }
This method decodes the given byte[] using the base64-encoding specified in RFC-2045 (Section 6.8).
public WritableRaster copyData(WritableRaster argbWR){ try { RenderedImage img=getSource(); ColorModel imgCM=img.getColorModel(); ColorSpace imgCS=imgCM.getColorSpace(); int nImageComponents=imgCS.getNumComponents(); int nProfileComponents=colorSpace.getNumComponents(); if (nImageComponents != nProfileComponents) { System.err.println("Input image and associated color profile have" + " mismatching number of color components: conversion is not possible"); return argbWR; } int w=argbWR.getWidth(); int h=argbWR.getHeight(); int minX=argbWR.getMinX(); int minY=argbWR.getMinY(); WritableRaster srcWR=imgCM.createCompatibleWritableRaster(w,h); srcWR=srcWR.createWritableTranslatedChild(minX,minY); img.copyData(srcWR); if (!(imgCM instanceof ComponentColorModel) || !(img.getSampleModel() instanceof BandedSampleModel) || (imgCM.hasAlpha() && imgCM.isAlphaPremultiplied())) { ComponentColorModel imgCompCM=new ComponentColorModel(imgCS,imgCM.getComponentSize(),imgCM.hasAlpha(),false,imgCM.getTransparency(),DataBuffer.TYPE_BYTE); WritableRaster wr=Raster.createBandedRaster(DataBuffer.TYPE_BYTE,argbWR.getWidth(),argbWR.getHeight(),imgCompCM.getNumComponents(),new Point(0,0)); BufferedImage imgComp=new BufferedImage(imgCompCM,wr,imgCompCM.isAlphaPremultiplied(),null); BufferedImage srcImg=new BufferedImage(imgCM,srcWR.createWritableTranslatedChild(0,0),imgCM.isAlphaPremultiplied(),null); Graphics2D g=imgComp.createGraphics(); g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_QUALITY); g.drawImage(srcImg,0,0,null); img=imgComp; imgCM=imgCompCM; srcWR=wr.createWritableTranslatedChild(minX,minY); } ComponentColorModel newCM=new ComponentColorModel(colorSpace,imgCM.getComponentSize(),false,false,Transparency.OPAQUE,DataBuffer.TYPE_BYTE); DataBufferByte data=(DataBufferByte)srcWR.getDataBuffer(); srcWR=Raster.createBandedRaster(data,argbWR.getWidth(),argbWR.getHeight(),argbWR.getWidth(),new int[]{0,1,2},new int[]{0,0,0},new Point(0,0)); BufferedImage newImg=new BufferedImage(newCM,srcWR,newCM.isAlphaPremultiplied(),null); ComponentColorModel sRGBCompCM=new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),new int[]{8,8,8},false,false,Transparency.OPAQUE,DataBuffer.TYPE_BYTE); WritableRaster wr=Raster.createBandedRaster(DataBuffer.TYPE_BYTE,argbWR.getWidth(),argbWR.getHeight(),sRGBCompCM.getNumComponents(),new Point(0,0)); BufferedImage sRGBImage=new BufferedImage(sRGBCompCM,wr,false,null); ColorConvertOp colorConvertOp=new ColorConvertOp(null); colorConvertOp.filter(newImg,sRGBImage); if (imgCM.hasAlpha()) { DataBufferByte rgbData=(DataBufferByte)wr.getDataBuffer(); byte[][] imgBanks=data.getBankData(); byte[][] rgbBanks=rgbData.getBankData(); byte[][] argbBanks={rgbBanks[0],rgbBanks[1],rgbBanks[2],imgBanks[3]}; DataBufferByte argbData=new DataBufferByte(argbBanks,imgBanks[0].length); srcWR=Raster.createBandedRaster(argbData,argbWR.getWidth(),argbWR.getHeight(),argbWR.getWidth(),new int[]{0,1,2,3},new int[]{0,0,0,0},new Point(0,0)); sRGBCompCM=new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),new int[]{8,8,8,8},true,false,Transparency.TRANSLUCENT,DataBuffer.TYPE_BYTE); sRGBImage=new BufferedImage(sRGBCompCM,srcWR,false,null); } BufferedImage result=new BufferedImage(sRGBCM,argbWR.createWritableTranslatedChild(0,0),false,null); Graphics2D g=result.createGraphics(); g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_QUALITY); g.drawImage(sRGBImage,0,0,null); g.dispose(); return argbWR; } catch ( Exception e) { e.printStackTrace(); throw new Error(e.getMessage()); } }
This method will turn the input image in an sRGB image as follows. If there is no colorSpace defined, then the input image is simply converted to singlePixelPacked sRGB if needed. If there is a colorSpace defined, the the image data is 'interpreted' as being in that space, instead of that of the image's colorSpace. Here is how the input image is processed: a. It is converted to using a ComponentColorModel b. Its data is extracted, ignoring it's ColorSpace c. A new ComponentColorModel is built for the replacing colorSpace Note that if the number of components in the input image and the number of components in the replacing ColorSpace do not match, it is not possible to apply the conversion. d. A new BufferedImage is built, using the new ComponentColorModel and the data from the original image converted to the ComponentColorModel built in a. The alpha channel is excluded from that new BufferedImage. e. The BufferedImage created in d. is converted to sRGB using ColorConvertOp f. The alpha channel information is integrated back into the image. IMPORTANT NOTE: The code uses a BandedSampleModel in c.) and d.) and discard the alpha channel during the color conversions (it is restored in f.)), because of bugs in the interleaved model with alpha. The BandedSampleModel did not cause any bug as of JDK 1.3.
public FileAlreadyExistsException(final Throwable thr){ super(thr.getMessage(),thr); }
Creates a new <code>FileAlreadyExistsException</code> that was caused by a given exception
public boolean isHasWeeks(){ return hasWeeks; }
Returns true if a subexpression exists that is a weeks-part.
public ConfuseStatus(){ super("confuse"); }
Create the status
public static ParameterType makeFileParameterType(ParameterHandler parameterHandler,String parameterName,String description,String fileExtension,PortProvider portProvider){ return makeFileParameterType(parameterHandler,parameterName,description,portProvider,fileExtension); }
Uses a single allowed file extension.
protected DataAccessException convertJdbcAccessException(JDBCException ex,SQLExceptionTranslator translator){ return translator.translate("Hibernate operation: " + ex.getMessage(),ex.getSQL(),ex.getSQLException()); }
Convert the given Hibernate JDBCException to an appropriate exception from the <code>org.springframework.dao</code> hierarchy, using the given SQLExceptionTranslator.
public void testClearBitNegativeInside4(){ String as="-4294967295"; String res="-4294967296"; int number=0; BigInteger aNumber=new BigInteger(as); BigInteger result=aNumber.clearBit(number); assertEquals(res,result.toString()); }
clearBit(0) in the negative number of length 1 with all ones in bit representation. the resulting number's length is 2.
MatlabNumericArray(double[] real,double[] imaginary,int[] lengths){ _fromMatlab=true; _realValues=real; _imaginaryValues=imaginary; _isReal=(imaginary == null); _lengths=lengths; _arrayType=DoubleArrayType.getInstance(lengths.length); }
Constructs an array from data retrieved from MATLAB.
public static float mixRestitution(float restitution1,float restitution2){ return restitution1 > restitution2 ? restitution1 : restitution2; }
Restitution mixing law. Feel free to customize this. TODO djm: add customization
public static String createBoundary(){ return "--------------------" + Long.toString(System.currentTimeMillis(),16); }
Creates a multipart boundary string by concatenating 20 hyphens (-) and the hexadecimal (base-16) representation of the current time in milliseconds.
public String valueString(int index) throws Exception { return value(index); }
Gets the value at index from the array as a String. Calls value().
public final void unmarkResourceAbsent(Tile tile){ if (tile == null) { String msg=Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } tile.getLevel().unmarkResourceAbsent(this.getTileNumber(tile)); }
Removes the absent-tile mark associated with a tile, if one is associatied.
public void editPolicy(String policyName) throws IOException, InterruptedException { driver.findElement(By.xpath(uiElementMapper.getElement("emm.policy.add.profile.encryption"))).click(); WebElement enableElement=driver.findElement(By.xpath(uiElementMapper.getElement("emm.policy.add.profile.encryption.enable"))); actions.moveToElement(enableElement).click().perform(); CommonUtil.waitAndClick(driver,By.xpath(uiElementMapper.getElement("emm.policy.add.profile.edit.continue"))); CommonUtil.waitAndClick(driver,By.xpath(uiElementMapper.getElement("emm.policy.add.groups.continue.button.xpath"))); WebElement policyNameField=driver.findElement(By.xpath(uiElementMapper.getElement("emm.policy.add.name.input.xpath"))); policyNameField.sendKeys(policyName); driver.findElement(By.xpath(uiElementMapper.getElement("emm.policy.add.publish.button.xpath"))).click(); String resultText=driver.findElement(By.id(uiElementMapper.getElement("emm.policy.add.publish.created.msg"))).getText(); if (!resultText.contains("POLICY IS SUCCESSFULLY RE-CONFIGURED.")) { throw new IllegalStateException("Policy was not updated"); } }
Imitates edit policy action.
protected boolean shouldSpawnJvm(){ return true; }
Calling the run tool ATM needs a new JVM: https://github.com/ceylon/ceylon-compiler/issues/1366
public static HashMap<String,String> parseMimeAttributes(StringMap stringMap){ if (stringMap == null || stringMap.empty()) { return null; } HashMap<String,String> messageKeyValue=new HashMap<>(); String origin=stringMap.keys().toString().replace("[",""); origin=origin.replace("]",""); String elements[]=origin.split(";"); if (elements.length < 2) { return messageKeyValue; } messageKeyValue.put(VCARD_KEY_MIME_TYPE,elements[0]); String[] pairs=elements[1].split(","); for ( String pair : pairs) { String[] kv=pair.split("="); messageKeyValue.put(kv[0].trim(),kv[1]); } return messageKeyValue; }
Parse the "stringmap" of the mime attributes to build a proper hashtable
public final synchronized boolean sameSearchId(int id){ return (searchRequest != null) && (searchRequest.searchId == id); }
Return true if current search job is equal to id.
@Override public void contextDestroyed(ServletContextEvent event){ log("contextDestroyed()"); this.context=null; }
Record the fact that this web application has been destroyed.
@Override public boolean isCellEditable(int rowIndex,int columnIndex){ return (columnIndex > 0) && !isReadOnly(); }
returns true if the cell at rowindex and columnindexis editable
@Override public JsonObject asGeoJSON(boolean isRoot){ JsonObject json=new JsonObject(); if (isRoot) { json.add("crs",geoJSONNamedCRS("urn:ogc:def:crs:OGC:1.3:CRS84")); } JsonArray features=new JsonArray(); for ( KmlFeature item : mItems) { JsonObject subJson=item.asGeoJSON(false); if (item instanceof KmlFolder) { JsonArray subFeatures=subJson.getAsJsonArray("features"); if (subFeatures != null) { for (int i=0; i < subFeatures.size(); i++) { JsonElement j=subFeatures.get(i); features.add(j); } } } else if (subJson != null) { features.add(subJson); } } json.add("features",features); json.addProperty("type","FeatureCollection"); return json; }
Set isRoot to true if this is the root of the final GeoJSON structure. Set isRoot to false if there is an enclosing FeatureCollection. As GeoJSON doesn't support nested FeatureCollection, sub-items will be inserted directly in the result. This is flattening the resulting GeoJSON hierarchy.
public EventBean adapterForBean(Object theEvent){ EventType eventType=typesPerJavaBean.get(theEvent.getClass()); if (eventType == null) { eventType=beanEventAdapter.createBeanType(theEvent.getClass().getName(),theEvent.getClass(),false,false,false); } return new BeanEventBean(theEvent,eventType); }
Create an event bean given an event of object id.
public static boolean equalsOnSystem(String filename1,String filename2){ return equals(filename1,filename2,false,IOCase.SYSTEM); }
Checks whether two filenames are equal using the case rules of the system. <p> No processing is performed on the filenames other than comparison. The check is case-sensitive on Unix and case-insensitive on Windows.
@Override public void previous(Long maxId,Callback<TimelineResult<Tweet>> cb){ createListTimelineRequest(null,decrementMaxId(maxId)).enqueue(new TweetsCallback(cb)); }
Loads Tweets with id less than (older than) maxId.
public void addAttribute(String uri,String localName,String qName,String type,String value){ ensureCapacity(length + 1); data[length * 5]=uri; data[length * 5 + 1]=localName; data[length * 5 + 2]=qName; data[length * 5 + 3]=type; data[length * 5 + 4]=value; length++; }
Add an attribute to the end of the list. <p> <p> For the sake of speed, this method does no checking to see if the attribute is already in the list: that is the responsibility of the application. </p>
private static String doGetPath(String filename,int separatorAdd){ if (filename == null) { return null; } int prefix=getPrefixLength(filename); if (prefix < 0) { return null; } int index=indexOfLastSeparator(filename); int endIndex=index + separatorAdd; if (prefix >= filename.length() || index < 0 || prefix >= endIndex) { return ""; } return filename.substring(prefix,endIndex); }
Does the work of getting the path.
public void testSyncCancellation_closesActivityWhenUserInitiatedAndDataModelAvailable(){ mController.init(); mFakeEventBus.post(new SyncCancelRequestedEvent()); LocationTree locationTree=FakeAppLocationTreeFactory.build(); mFakeEventBus.post(new AppLocationTreeFetchedEvent(locationTree)); mFakeEventBus.post(new SyncCanceledEvent()); verify(mMockUi).finish(); }
Tests that user-initiated sync cancellation closes the activity even when the data model has become available since cancellation was requested.
public final double mean(){ long count=0; double mean=0; double[][] fieldx=null; double[] fieldxy=null; final int width=this.width; final int height=this.height; final int length=this.length; for (int x=0; x < width; x++) { fieldx=field[x]; for (int y=0; y < height; y++) { fieldxy=fieldx[y]; for (int z=0; z < length; z++) { mean+=fieldxy[z]; count++; } } } return (count == 0 ? 0 : mean / count); }
Returns the mean value stored in the grid
public void testmodInversePos2(){ byte aBytes[]={15,24,123,56,-11,-112,-34,-98,8,10,12,14,25,125,-15,28,-127}; byte mBytes[]={2,122,45,36,100}; int aSign=1; int mSign=1; byte rBytes[]={1,-93,40,127,73}; BigInteger aNumber=new BigInteger(aSign,aBytes); BigInteger modulus=new BigInteger(mSign,mBytes); BigInteger result=aNumber.modInverse(modulus); byte resBytes[]=new byte[rBytes.length]; resBytes=result.toByteArray(); for (int i=0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign",1,result.signum()); }
modInverse: positive number (another case: a < 0)
public Duration toStandardDuration(){ long seconds=getValue(); return new Duration(seconds * DateTimeConstants.MILLIS_PER_SECOND); }
Converts this period in seconds to a duration in milliseconds assuming a 24 hour day, 60 minute hour and 60 second minute. <p> This method allows you to convert from a period to a duration. However to achieve this it makes the assumption that all seconds are 24 hours long, all hours are 60 minutes and all minutes are 60 seconds. This is not true when daylight savings time is considered, and may also not be true for some unusual chronologies. However, it is included as it is a useful operation for many applications and business rules.
public static void resetState() throws SQLException { DbConnectionFactory dbConnectionFactory=getDbConnectionFactory(); ReplicationTestUtils.dropDatabase(dbConnectionFactory,DB_NAME); AuditLogHookUtils.setupAuditLogTables(dbConnectionFactory,DB_NAME,AUDIT_LOG_TABLE_NAME,OUTPUT_OBJECTS_TABLE_NAME,MAP_RED_STATS_TABLE_NAME); }
Resets the testing database.
public byte[] decryptRaw(byte[] baseKey,int usage,byte[] ivec,byte[] ciphertext,int start,int len,byte[] seqNum) throws GeneralSecurityException { if (!KeyUsage.isValid(usage)) { throw new GeneralSecurityException("Invalid key usage number: " + usage); } if (debug) { System.out.println("\nARCFOUR: decryptRaw with usage = " + usage); } byte[] klocal=new byte[baseKey.length]; for (int i=0; i <= 15; i++) { klocal[i]=(byte)(baseKey[i] ^ 0xF0); } byte[] salt=new byte[4]; byte[] kcrypt=getHmac(klocal,salt); byte[] sequenceNum=new byte[4]; System.arraycopy(seqNum,0,sequenceNum,0,sequenceNum.length); kcrypt=getHmac(kcrypt,sequenceNum); Cipher cipher=Cipher.getInstance("ARCFOUR"); SecretKeySpec secretKey=new SecretKeySpec(kcrypt,"ARCFOUR"); cipher.init(Cipher.DECRYPT_MODE,secretKey); byte[] output=cipher.doFinal(ciphertext,start,len); return output; }
Decrypts data using specified key and initial vector.
public static void testVerifyPos() throws AssertFailException { boolean result=false; byte[] data=BaseEncoding.base16().lowerCase().decode("CF80CD8AED482D5D1527D7DC72FCEFF84E6326592848447D2DC0B0E87DFC9A90".toLowerCase()); byte[] sig=BaseEncoding.base16().lowerCase().decode("3044022079BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F817980220294F14E883B3F525B5367756C2A11EF6CF84B730B36C17CB0C56F0AAB2C98589".toLowerCase()); byte[] pub=BaseEncoding.base16().lowerCase().decode("040A629506E1B65CD9D2E0BA9C75DF9C4FED0DB16DC9625ED14397F0AFC836FAE595DC53F8B0EFE61E703075BD9B143BAC75EC0E19F82A2208CAEB32BE53414C40".toLowerCase()); result=NativeSecp256k1.verify(data,sig,pub); assertEquals(result,true,"testVerifyPos"); }
This tests verify() for a valid signature
public boolean visitInstruction(ElemTemplateElement elem){ return true; }
Visit an XSLT instruction. Any element that isn't called by one of the other visit methods, will be called by this method.
@Override public boolean markSupported(){ return true; }
Mark is supported (returns true).
@PublishJmsMessages private void mockMethod(){ }
Do not invoke this method. This method is a test input for reflection related tests.
@Override public void moveUp(int i){ super.moveUp(i); List<Vector3f> controlPoints=jmeMotionPath.getMotionPath().getSpline().getControlPoints(); if (i < 1 || i > controlPoints.size()) { throw new IndexOutOfBoundsException(); } Vector3f element=controlPoints.get(i); Vector3f over_element=controlPoints.get(i - 1); controlPoints.set(i - 1,element); controlPoints.set(i,over_element); jmeMotionPath.getMotionPath().getSpline().setType(jmeMotionPath.getMotionPath().getSpline().getType()); refreshChildren(true); jmeMotionPath.updateSpline(true); }
Move an element up
@SuppressWarnings("unchecked") @Override public void eSet(int featureID,Object newValue){ switch (featureID) { case UmplePackage.ANONYMOUS_MORE_CODE_1__CODE_LANG_1: getCodeLang_1().clear(); getCodeLang_1().addAll((Collection<? extends CodeLang_>)newValue); return; case UmplePackage.ANONYMOUS_MORE_CODE_1__CODE_LANGS_1: getCodeLangs_1().clear(); getCodeLangs_1().addAll((Collection<? extends CodeLangs_>)newValue); return; } super.eSet(featureID,newValue); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void testUnsizedLongsCountSeq(){ LongAdder counter=new LongAdder(); SplittableRandom r=new SplittableRandom(); long size=100; r.longs().limit(size).forEach(null); assertEquals(counter.sum(),size); }
A sequential unsized stream of longs generates at least 100 values
public Executor pool(byte plc) throws IgniteCheckedException { switch (plc) { case P2P_POOL: return p2pPool; case SYSTEM_POOL: return sysPool; case PUBLIC_POOL: return pubPool; case MANAGEMENT_POOL: return mgmtPool; case AFFINITY_POOL: return affPool; case UTILITY_CACHE_POOL: assert utilityCachePool != null : "Utility cache pool is not configured."; return utilityCachePool; case MARSH_CACHE_POOL: assert marshCachePool != null : "Marshaller cache pool is not configured."; return marshCachePool; case IGFS_POOL: assert igfsPool != null : "IGFS pool is not configured."; return igfsPool; case IDX_POOL: assert idxPool != null : "Indexing pool is not configured."; return idxPool; default : { assert plc >= 0 : "Negative policy: " + plc; if (isReservedGridIoPolicy(plc)) throw new IgniteCheckedException("Failed to process message with policy of reserved" + " range (0-31), [policy=" + plc + ']'); IoPool pool=ioPools[plc]; if (pool == null) throw new IgniteCheckedException("Failed to process message because no pool is registered " + "for policy. [policy=" + plc + ']'); assert plc == pool.id(); Executor ex=pool.executor(); if (ex == null) throw new IgniteCheckedException("Failed to process message because corresponding executor " + "is null. [id=" + plc + ']'); return ex; } } }
Gets execution pool for policy.
private void testBug71396StatementCheck(Statement testStmt,String query,int expRowCount) throws SQLException { ResultSet testRS; testRS=testStmt.executeQuery(query); assertTrue(testRS.last()); assertEquals(String.format("Wrong number of rows for query '%s'",query),expRowCount,testRS.getRow()); testRS.close(); testStmt.execute(query); testRS=testStmt.getResultSet(); assertTrue(testRS.last()); assertEquals(String.format("Wrong number of rows for query '%s'",query),expRowCount,testRS.getRow()); testRS.close(); }
Executes one query using a Statement and tests if the results count is the expected.
public Builder<V> valueType(DataType valueType){ this.valueType=valueType; return this; }
Set the key data type.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:49.326 -0500",hash_original_method="DB40CF4190456B2BE2224926B4D8156A",hash_generated_method="7240BE9063BFF72D528C947ED57FEB0C") public boolean hasNameValue(String name){ return hmap.containsKey(name.toLowerCase()); }
Returns a boolean telling if this NameValueList has a record with this name
@Override protected void onPostExecute(Void notUsed){ super.onPostExecute(notUsed); getWorldWindow().getLayers().addLayer(this.airportLayer); getWorldWindow().getLayers().addLayer(this.aircraftLayer); statusText.setText(""); PlacemarksMilStd2525DemoActivity.this.startAnimation(); }
Updates the WorldWindow layer list on the UI Thread and starts the animation.
public void openRealtimeSearcher(){ synchronized (this) { try { RefCounted<SolrIndexSearcher> holder=uhandler.core.openNewSearcher(true,true); holder.decref(); } catch ( Exception e) { SolrException.log(log,"Error opening realtime searcher",e); return; } if (map != null) map.clear(); if (prevMap != null) prevMap.clear(); if (prevMap2 != null) prevMap2.clear(); } }
Opens a new realtime searcher and clears the id caches. This may also be called when we updates are being buffered (from PeerSync/IndexFingerprint)
public synchronized void notifyExceptionFromOutputStream(Throwable e){ pendingExceptionFromOutputStream=e; notifyAll(); }
Notifies the input stream that the output stream failed on the next input streams read
public void writeFile(String dir){ String filePath=dir + File.separator + mSootClass.toString(); PrintWriter writer; try { writer=new PrintWriter(filePath + "_steps.jimple"); } catch ( Exception ex) { logger.warn("Cannot open file {} ",filePath); return; } writer.printf("class %s { \n",mSootClass.toString()); writer.println(""); logger.info("fields "); for ( SootField field : mSootClass.getFields()) { logger.info("field {} ",field); writer.printf("\t%s %s \n",Modifier.toString(field.getModifiers()),field); } logger.info("methods "); writer.println(""); for ( SootMethod method : mSootClass.getMethods()) { Body body=method.getActiveBody(); logger.info("====== method {} ======== ",method); writer.printf("\t%s %s { \n",Modifier.toString(method.getModifiers()),method); for ( Local local : body.getLocals()) { logger.info("{}",local); writer.printf("\t\t%s %s \n",local.getType(),local); } writer.println(""); Chain<Unit> units=body.getUnits(); for ( Unit unit : units) { String unitString; try { unitString=unit.toString(); } catch ( Exception ex) { unitString="***Invalid Statement "; } writer.printf("\t\t%s \n",unitString); logger.info("{} ",unitString); } writer.printf("\t} \n"); logger.info(""); } writer.printf("} \n"); writer.flush(); }
Write to the file
@Optional.Method(modid="CoFHAPI|energy") @Override public int extractEnergy(EnumFacing facing,int maxExtract,boolean simulate){ return MetaphaserRF.INSTANCE.extractEnergy(this,facing,maxExtract,simulate,false); }
------------------------------------------------------------------------- Start of the CoFH Energy implementation, also known as Redstone Flux (RF) -------------------------------------------------------------------------
@Deprecated public synchronized void addPlugin(Plugin plugin){ if (!mPlugins.contains(plugin)) { mPlugins.add(plugin); } }
Adds a plugin to the list.
public LineBreakMeasurer(AttributedCharacterIterator text,BreakIterator breakIter,FontRenderContext frc){ if (text.getEndIndex() - text.getBeginIndex() < 1) { throw new IllegalArgumentException("Text must contain at least one character."); } this.breakIter=breakIter; this.measurer=new TextMeasurer(text,frc); this.limit=text.getEndIndex(); this.pos=this.start=text.getBeginIndex(); charIter=new CharArrayIterator(measurer.getChars(),this.start); this.breakIter.setText(charIter); }
Constructs a <code>LineBreakMeasurer</code> for the specified text.
public void writeRVV(LocalRegion region,Boolean isRVVTrusted){ if (this.getFlags().contains(DiskRegionFlag.IS_WITH_VERSIONING)) { getDiskStore().writeRVV(this,region,isRVVTrusted); } }
Record current RVV to disk and update into disk region RVV.
public static int px2dp(Context context,float pxValue){ final float scale=context.getResources().getDisplayMetrics().density; return (int)(pxValue / scale + 0.5f); }
Transform px value into dip or dp
@Override public boolean isNamed(){ return (flags & NO_NAME) == 0; }
Return true if we have are anonymous and have a name which is not system-generated. Currently only object expressions have no name.
@Override public void onAddPartition(AddPartitionEvent event) throws MetaException { try { Table table=new Table(event.getTable()); Set<ReadEntity> readEntities=new HashSet<>(); Set<WriteEntity> writeEntities=new HashSet<>(); for ( org.apache.hadoop.hive.metastore.api.Partition partition : event.getPartitions()) { writeEntities.add(new WriteEntity(new Partition(table,partition),WriteType.INSERT)); } run(readEntities,writeEntities,HiveOperation.THRIFT_ADD_PARTITION); } catch ( Exception e) { throw new RuntimeException(e); } }
Listener which fires when a partition is added. <p>For auditing purposes the read/write differential is the non-existence and existence of the added partition respectively.</p>
@Override protected void init_actions(){ action_obj=new CUP$Parser$actions(this); }
Action encapsulation object initializer.
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.