code
stringlengths
10
174k
nl
stringlengths
3
129k
public synchronized void addListener(final IGlobalProgressManagerListener listener){ m_listeners.addListener(listener); }
Adds a new listener that is notified about changes in the manager.
protected void sendRedirect(HttpServletRequest httpRequest,HttpServletResponse response,String relativePath) throws IOException { sendRedirectStatic(httpRequest,response,relativePath); }
Redirect to the given page overtaking errors if exist.
private void showPickAction(boolean show){ mCards.getCard(CARD_PICKER).setActionVisibility(ACTION_PICK_PLACE,show); }
Sets the visibility of the 'Pick Action' option on the 'Pick a place' card. The action should be hidden when the PlacePicker Intent has been fired to prevent it from being launched multiple times simultaneously.
public void updateRendering(AffineTransform u2d,boolean dbr,boolean cpt,Shape aoi,int width,int height){ repaintManager.setupRenderer(u2d,dbr,aoi,width,height); List l=new ArrayList(1); l.add(aoi); updateRendering(l,cpt); }
Updates the rendering buffer. Only to be called from the update thread.
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:48.363 -0500",hash_original_method="742EA2900A6EB88CE28517352A724CD7",hash_generated_method="34500EE607CF681AAABF6AB99F1567DF") private void resolveProperties(){ if (arePropertiesResolved) { return; } Class<?> cl=forClass(); isProxy=Proxy.isProxyClass(cl); isEnum=Enum.class.isAssignableFrom(cl); isSerializable=isSerializable(cl); isExternalizable=isExternalizable(cl); arePropertiesResolved=true; }
Resolves the class properties, if they weren't already
public static void transformedBooleanComparison(){ transformedBooleanComparison++; }
IFEQ -> IFLE / IFNE -> IFGT
public void attrAdded(Attr node,String newv){ if (!changing && baseVal != null) { baseVal.invalidate(); } fireBaseAttributeListeners(); if (!hasAnimVal) { fireAnimatedAttributeListeners(); } }
Called when an Attr node has been added.
public synchronized long size(){ return size; }
Returns the number of bytes currently being used to store the values in this cache. This may be greater than the max size if a background deletion is pending.
public void clearWho(){ super.removeElement(Who.KEY); }
Removes all existing person description instances.
public SeqNoRange(long minSeqNo,long maxSeqNo){ this.minSeqNo=minSeqNo; this.maxSeqNo=maxSeqNo; }
Creates a new <code>SeqNoRange</code> object
private void fireProcessViewChanged(){ for ( ExtendedProcessEditor editor : processEditors.getListeners(ExtendedProcessEditor.class)) { editor.processViewChanged(process); } }
Fire this when the process view has changed, e.g. when the user enters/leaves a subprocess in the process design panel.
private String prepareURL(){ String str="http://download.finance.yahoo.com/d/quotes.csv?"; str+="s="; for (int i=0; i < symbolList.size(); i++) { if (i != 0) { str+=","; } str+=symbolList.get(i); } str+="&f="; for ( String format : parameterList) { str+=format; } str+="&e=.csv"; return str; }
Prepare URL from symbols and parameters. URL will be something like: http://download.finance.yahoo.com/d/quotes.csv?s=GOOG,FB,YHOO&f=sl1vt1&e=.csv
private void updateConnection(){ if ((debuggerConnection == null) || !isConnected()) { debuggerConnection=new DebugConnection(template.getHost(),template.getPort()); } }
Updates the debugger connection if possible after new template data was received.
public InputStream newInputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { return null; } try { return new FileInputStream(entry.getCleanFile(index)); } catch ( FileNotFoundException e) { return null; } } }
Returns an unbuffered input stream to read the last committed value, or null if no value has been committed.
public void updateZoningMapAndvalidateExportMask(URI varrayURI,Map<URI,List<StoragePort>> initiatorPortMap,URI exportMaskURI,Map<String,Set<String>> directorToInitiatorIds,Map<String,Initiator> idToInitiatorMap,Map<String,String> portWwnToClusterMap,StorageSystem vplex,StorageSystem array,String clusterId,String stepId){ try { WorkflowStepCompleter.stepExecuting(stepId); ExportMask exportMask=_dbClient.queryObject(ExportMask.class,exportMaskURI); updateZoningMap(initiatorPortMap,directorToInitiatorIds,exportMask); boolean passed=VPlexBackEndOrchestratorUtil.validateExportMask(varrayURI,initiatorPortMap,exportMask,null,directorToInitiatorIds,idToInitiatorMap,_dbClient,_coordinator,portWwnToClusterMap); if (!passed) { exportMask.setInactive(Boolean.TRUE); _dbClient.persistObject(exportMask); _log.error("Export Mask is not suitable for VPLEX to backend storage system"); WorkflowStepCompleter.stepFailed(stepId,VPlexApiException.exceptions.couldNotFindValidArrayExportMask(vplex.getNativeGuid(),array.getNativeGuid(),clusterId)); throw VPlexApiException.exceptions.couldNotFindValidArrayExportMask(vplex.getNativeGuid(),array.getNativeGuid(),clusterId); } WorkflowStepCompleter.stepSucceded(stepId); } catch ( Exception ex) { _log.error("Failed to validate export mask for cinder: ",ex); VPlexApiException vplexex=DeviceControllerExceptions.vplex.failedToValidateExportMask(exportMaskURI.toString(),ex); WorkflowStepCompleter.stepFailed(stepId,vplexex); } }
Re-validate the ExportMask This is required to be done as the ExportMask gets updated by reading the cinder export volume response.
public boolean isKeepTags(){ return keepTags; }
Gets the value of the keepTags property.
protected void forceSetComponentCount(int count){ mComponentCountActual=count; }
Sets the component count of this tag. Call this function before setValue() if the length of value does not match the component count.
protected void serializeEntityReference(EntityReference node,boolean bStart) throws SAXException { if (bStart) { EntityReference eref=node; if ((fFeatures & ENTITIES) != 0) { if ((fFeatures & WELLFORMED) != 0) { isEntityReferneceWellFormed(node); } if ((fFeatures & NAMESPACES) != 0) { checkUnboundPrefixInEntRef(node); } } if (fLexicalHandler != null) { fLexicalHandler.startEntity(eref.getNodeName()); } } else { EntityReference eref=node; if (fLexicalHandler != null) { fLexicalHandler.endEntity(eref.getNodeName()); } } }
Serializes an EntityReference Node.
public Address(String zipCode,String city){ this.zipCode=zipCode; this.city=city; }
Creates a new instance of Address
public boolean decodeValueLength(int startIndex){ if ((wspData[startIndex] & 0xff) > WAP_PDU_LENGTH_QUOTE) { return false; } if (wspData[startIndex] < WAP_PDU_LENGTH_QUOTE) { unsigned32bit=wspData[startIndex]; dataLength=1; } else { decodeUintvarInteger(startIndex + 1); dataLength++; } return true; }
Decode the "Value-length" type for WSP pdu
private String printSelectionResults(){ StringBuffer text=new StringBuffer(); text.append("\n\n=== Attribute Selection on all input data ===\n\n" + "Search Method:\n"); text.append(m_searchMethod.toString()); text.append("\nAttribute "); if (m_ASEvaluator instanceof SubsetEvaluator) { text.append("Subset Evaluator ("); } else { text.append("Evaluator ("); } if (!(m_ASEvaluator instanceof UnsupervisedSubsetEvaluator) && !(m_ASEvaluator instanceof UnsupervisedAttributeEvaluator)) { text.append("supervised, "); text.append("Class ("); if (m_trainInstances.attribute(m_trainInstances.classIndex()).isNumeric()) { text.append("numeric): "); } else { text.append("nominal): "); } text.append((m_trainInstances.classIndex() + 1) + " " + m_trainInstances.attribute(m_trainInstances.classIndex()).name()+ "):\n"); } else { text.append("unsupervised):\n"); } text.append(m_ASEvaluator.toString() + "\n"); return text.toString(); }
Assembles a text description of the attribute selection results.
protected void updatePeProvisioning(){ getPeMap().clear(); for ( Pe pe : getPeList()) { pe.getPeProvisioner().deallocateMipsForAllVms(); } Iterator<Pe> peIterator=getPeList().iterator(); Pe pe=peIterator.next(); PeProvisioner peProvisioner=pe.getPeProvisioner(); double availableMips=peProvisioner.getAvailableMips(); for ( Map.Entry<String,List<Double>> entry : getMipsMap().entrySet()) { String vmUid=entry.getKey(); getPeMap().put(vmUid,new LinkedList<Pe>()); for ( double mips : entry.getValue()) { while (mips >= 0.1) { if (availableMips >= mips) { peProvisioner.allocateMipsForVm(vmUid,mips); getPeMap().get(vmUid).add(pe); availableMips-=mips; break; } else { peProvisioner.allocateMipsForVm(vmUid,availableMips); getPeMap().get(vmUid).add(pe); mips-=availableMips; if (mips <= 0.1) { break; } if (!peIterator.hasNext()) { Log.printConcatLine("There is no enough MIPS (",mips,") to accommodate VM ",vmUid); } pe=peIterator.next(); peProvisioner=pe.getPeProvisioner(); availableMips=peProvisioner.getAvailableMips(); } } } } }
Update allocation of VMs on PEs.
@Override protected void withBindHolder(itemGridCellBinder holder,JRitem data,int position){ }
binding normal view holder
public synchronized boolean isClosed(){ return journalWriter == null; }
Returns true if this cache has been closed.
public static ComponentUI createUI(JComponent c){ return new SeaGlassButtonUI(); }
Create a new UI delegate.
private boolean translateReadyOps(int ops,int initialOps,SelectionKeyImpl sk){ int intOps=sk.nioInterestOps(); int oldOps=sk.nioReadyOps(); int newOps=initialOps; if ((ops & Net.POLLNVAL) != 0) { return false; } if ((ops & (Net.POLLERR | Net.POLLHUP)) != 0) { newOps=intOps; sk.nioReadyOps(newOps); return (newOps & ~oldOps) != 0; } if (((ops & Net.POLLIN) != 0) && ((intOps & SelectionKey.OP_READ) != 0)) newOps|=SelectionKey.OP_READ; if (((ops & Net.POLLOUT) != 0) && ((intOps & SelectionKey.OP_WRITE) != 0)) newOps|=SelectionKey.OP_WRITE; sk.nioReadyOps(newOps); return (newOps & ~oldOps) != 0; }
Translates native poll revent ops into a ready operation ops
static public void openTx(long startTime){ if (log.isInfoEnabled()) log.info(TimestampUtility.toString(startTime)); }
Report the start of a new transaction.
@Override public void show(){ final Stage stage=getStage(); stage.getRoot().clearChildren(); LmlUtilities.appendActorsToStage(stage,actors); }
Invoked after previous view is hidden and this view is about to show. Might be called when the view is being reloaded. Clears previous stage actors and adds managed actor to stage. If overridden, call super.
public void testIntsCount(){ LongAdder counter=new LongAdder(); ThreadLocalRandom r=ThreadLocalRandom.current(); long size=0; for (int reps=0; reps < REPS; ++reps) { counter.reset(); r.ints(size).parallel().forEach(null); assertEquals(counter.sum(),size); size+=524959; } }
A parallel sized stream of ints generates the given number of values
public DeleteReferencesRequest clone(){ DeleteReferencesRequest result=new DeleteReferencesRequest(); result.RequestHeader=RequestHeader == null ? null : RequestHeader.clone(); if (ReferencesToDelete != null) { result.ReferencesToDelete=new DeleteReferencesItem[ReferencesToDelete.length]; for (int i=0; i < ReferencesToDelete.length; i++) result.ReferencesToDelete[i]=ReferencesToDelete[i].clone(); } return result; }
Deep clone
public void reverse(){ int[] newBits=new int[bits.length]; int size=this.size; for (int i=0; i < size; i++) { if (get(size - i - 1)) { newBits[i >> 5]|=1 << (i & 0x1F); } } bits=newBits; }
Reverses all bits in the array.
public DoubleMatrix1D like(int size){ return content.like(size); }
Construct and returns a new empty matrix <i>of the same dynamic type</i> as the receiver, having the specified size. For example, if the receiver is an instance of type <tt>DenseDoubleMatrix1D</tt> the new matrix must also be of type <tt>DenseDoubleMatrix1D</tt>, if the receiver is an instance of type <tt>SparseDoubleMatrix1D</tt> the new matrix must also be of type <tt>SparseDoubleMatrix1D</tt>, etc. In general, the new matrix should have internal parametrization as similar as possible.
public static UploadFragment newInstance(){ return new UploadFragment(); }
Use this factory method to create a new instance of this fragment using the provided parameters.
protected void validateState(State current){ ValidationUtils.validateState(current); checkNotNull(current.executionState,"ExecutionState cannot be null."); checkIsPositiveNumber(current.triggersSuccess,"triggersSuccess"); checkIsPositiveNumber(current.triggersError,"triggersError"); }
Validate the service state for coherence.
private Transform lookup(Class type) throws Exception { if (!error.contains(type)) { Transform transform=cache.fetch(type); if (transform != null) { return transform; } return match(type); } return null; }
This method is used to acquire a <code>Transform</code> for the the specified type. If there is no transform for the type then this will return null. Once acquired once the transform is cached so that subsequent lookups will be performed faster.
public NISTCTSBlockCipher(int type,BlockCipher cipher){ this.type=type; this.cipher=new CBCBlockCipher(cipher); blockSize=cipher.getBlockSize(); buf=new byte[blockSize * 2]; bufOff=0; }
Create a buffered block cipher that uses NIST Cipher Text Stealing
@Ignore("This test is flakey and causes tests to fail pretty often.") @Test public void maxUnderReplicationTest() throws EventDeliveryException, IOException { Configuration conf=new Configuration(); conf.set("dfs.replication",String.valueOf(3)); cluster=new MiniDFSCluster(conf,3,true,null); cluster.waitActive(); String outputDir="/flume/underReplicationTest"; Path outputDirPath=new Path(outputDir); logger.info("Running test with output dir: {}",outputDir); FileSystem fs=cluster.getFileSystem(); if (fs.exists(outputDirPath)) { fs.delete(outputDirPath,true); } String nnURL=getNameNodeURL(cluster); logger.info("Namenode address: {}",nnURL); Context chanCtx=new Context(); MemoryChannel channel=new MemoryChannel(); channel.setName("simpleHDFSTest-mem-chan"); channel.configure(chanCtx); channel.start(); Context sinkCtx=new Context(); sinkCtx.put("hdfs.path",nnURL + outputDir); sinkCtx.put("hdfs.fileType",HDFSWriterFactory.DATA_STREAM_TYPE); sinkCtx.put("hdfs.batchSize",Integer.toString(1)); BDREHDFSEventSink sink=new BDREHDFSEventSink(); sink.setName("simpleHDFSTest-hdfs-sink"); sink.configure(sinkCtx); sink.setChannel(channel); sink.start(); channel.getTransaction().begin(); try { for (int i=0; i < 50; i++) { channel.put(EventBuilder.withBody("yarg " + i,Charsets.UTF_8)); } channel.getTransaction().commit(); } finally { channel.getTransaction().close(); } logger.info("Running process(). Create new file."); sink.process(); logger.info("Running process(). Same file."); sink.process(); logger.info("Killing datanode #1..."); cluster.stopDataNode(0); logger.info("Running process(). Create new file? (racy)"); sink.process(); for (int i=3; i < 50; i++) { logger.info("Running process()."); sink.process(); } sink.stop(); channel.stop(); FileStatus[] statuses=fs.listStatus(outputDirPath); Assert.assertNotNull("No files found written to HDFS",statuses); for ( FileStatus status : statuses) { Path filePath=status.getPath(); logger.info("Found file on DFS: {}",filePath); FSDataInputStream stream=fs.open(filePath); BufferedReader reader=new BufferedReader(new InputStreamReader(stream)); String line=reader.readLine(); logger.info("First line in file {}: {}",filePath,line); Assert.assertTrue(line.startsWith("yarg")); } System.out.println("There are " + statuses.length + " files."); Assert.assertEquals("31 files expected, found " + statuses.length,31,statuses.length); if (!KEEP_DATA) { fs.delete(outputDirPath,true); } cluster.shutdown(); cluster=null; }
This is a very basic test that writes one event to HDFS and reads it back.
public ViPRCatalogClient2 withAuthToken(String token){ setAuthToken(token); return this; }
Sets the authentication token and returns the updated client.
public void execute() throws BuildException { bundleDir=new File(mRootDir,bundleProperties.getApplicationName() + ".app"); if (bundleDir.exists()) { Delete deleteTask=new Delete(); deleteTask.setProject(getProject()); deleteTask.setDir(bundleDir); deleteTask.execute(); } if (mRootDir == null) throw new BuildException("Required attribute \"dir\" is not set."); if (mJarAttrs.isEmpty() && mJarFileSets.isEmpty() && mJarFileLists.isEmpty()) throw new BuildException("Either the attribute \"jar\" must " + "be set, or one or more jarfilelists or " + "jarfilesets must be added."); if (!mJarAttrs.isEmpty() && (!mJarFileSets.isEmpty() || !mJarFileLists.isEmpty())) throw new BuildException("Cannot set both the attribute " + "\"jars\" and use jar filesets/filelists. Use only one or the other."); if (bundleProperties.getApplicationName() == null) throw new BuildException("Required attribute \"name\" is not set."); if (bundleProperties.getMainClass() == null) throw new BuildException("Required attribute \"mainclass\" is not set."); if (useOldPropertyNames()) bundleProperties.addJavaProperty(ABOUTMENU_KEY,bundleProperties.getCFBundleName()); String antiAliasedProperty=useOldPropertyNames() ? "com.apple.macosx.AntiAliasedGraphicsOn" : "apple.awt.antialiasing"; if (mAntiAliasedGraphics != null) bundleProperties.addJavaProperty(antiAliasedProperty,mAntiAliasedGraphics.toString()); String antiAliasedTextProperty=useOldPropertyNames() ? "com.apple.macosx.AntiAliasedTextOn" : "apple.awt.textantialiasing"; if (mAntiAliasedText != null) bundleProperties.addJavaProperty(antiAliasedTextProperty,mAntiAliasedText.toString()); if (useOldPropertyNames() && (mLiveResize != null)) bundleProperties.addJavaProperty("com.apple.mrj.application.live-resize",mLiveResize.toString()); String screenMenuBarProperty=useOldPropertyNames() ? "com.apple.macos.useScreenMenuBar" : "apple.laf.useScreenMenuBar"; if (mScreenMenuBar != null) bundleProperties.addJavaProperty(screenMenuBarProperty,mScreenMenuBar.toString()); if ((useOldPropertyNames() == false) && (mGrowbox != null)) bundleProperties.addJavaProperty("apple.awt.showGrowBox",mGrowbox.toString()); if (useOldPropertyNames() && (mGrowboxIntrudes != null)) bundleProperties.addJavaProperty("com.apple.mrj.application.growbox.intrudes",mGrowboxIntrudes.toString()); if (!mRootDir.exists() || (mRootDir.exists() && !mRootDir.isDirectory())) throw new BuildException("Destination directory specified by \"dir\" " + "attribute must already exist."); if (bundleDir.exists()) throw new BuildException("The directory/bundle \"" + bundleDir.getName() + "\" already exists, cannot continue."); log("Creating application bundle: " + bundleDir); if (!bundleDir.mkdir()) throw new BuildException("Unable to create bundle: " + bundleDir); mContentsDir=new File(bundleDir,"Contents"); if (!mContentsDir.mkdir()) throw new BuildException("Unable to create directory " + mContentsDir); mMacOsDir=new File(mContentsDir,"MacOS"); if (!mMacOsDir.mkdir()) throw new BuildException("Unable to create directory " + mMacOsDir); mResourcesDir=new File(mContentsDir,"Resources"); if (!mResourcesDir.mkdir()) throw new BuildException("Unable to create directory " + mResourcesDir); mJavaDir=new File(bundleProperties.getJavaVersion() < 1.7 ? mResourcesDir : mContentsDir,"Java"); if (!mJavaDir.mkdir()) throw new BuildException("Unable to create directory " + mJavaDir); if (mAppIcon != null) { try { File dest=new File(mResourcesDir,mAppIcon.getName()); if (mVerbose) log("Copying application icon file to \"" + bundlePath(dest) + "\""); mFileUtils.copyFile(mAppIcon,dest); } catch ( IOException ex) { throw new BuildException("Cannot copy icon file: " + ex); } } try { Iterator itor=bundleProperties.getDocumentTypes().iterator(); while (itor.hasNext()) { DocumentType documentType=(DocumentType)itor.next(); File iconFile=documentType.getIconFile(); if (iconFile != null) { File dest=new File(mResourcesDir,iconFile.getName()); if (mVerbose) log("Copying document icon file to \"" + bundlePath(dest) + "\""); mFileUtils.copyFile(iconFile,dest); } } } catch ( IOException ex) { throw new BuildException("Cannot copy document icon file: " + ex); } processJarAttrs(); processJarFileSets(); processJarFileLists(); processExecAttrs(); processExecFileSets(); processExecFileLists(); processResourceFileSets(); processJavaFileSets(); processResourceFileLists(); processJavaFileLists(); processExtraClassPathAttrs(); processExtraClassPathFileSets(); processExtraClassPathFileLists(); copyHelpBooks(); copyApplicationStub(); writeInfoPlist(); writePkgInfo(); }
The method executing the task
public boolean destroyVolume(String volumeName,boolean force){ if (log.isDebugEnabled()) { log.debug("Deleting volume with params[name,force]: " + volumeName + ","+ force); } FlexVolume vol=new FlexVolume(server.getNaServer(),volumeName); boolean result=vol.destroyVolume(force); return result; }
Destroys a volume.
@Override public void insert(Item x,int position){ Item[] newItems=(Item[])new Object[items.length + 1]; System.arraycopy(items,0,newItems,0,position); newItems[position]=x; System.arraycopy(items,position,newItems,position + 1,items.length - position); items=newItems; }
Inserts item into given position. Code from discussion #3
public final boolean checkLimits(ConsensusMessage msg){ outOfContextLock.lock(); int lastConsId=tomLayer.getLastExec(); int inExec=tomLayer.getInExec(); Logger.println("(ExecutionManager.checkLimits) Received message " + msg); Logger.println("(ExecutionManager.checkLimits) I'm at consensus " + inExec + " and my last consensus is "+ lastConsId); boolean isRetrievingState=tomLayer.isRetrievingState(); if (isRetrievingState) { Logger.println("(ExecutionManager.checkLimits) I'm waiting for a state"); } boolean canProcessTheMessage=false; if (isRetrievingState || (!(lastConsId == -1 && msg.getNumber() >= (lastConsId + revivalHighMark)) && (msg.getNumber() > lastConsId && (msg.getNumber() < (lastConsId + paxosHighMark))) && !(stopped && msg.getNumber() >= (lastConsId + timeoutHighMark)))) { if (stopped) { stoppedMsgsLock.lock(); if (stopped) { Logger.println("(ExecutionManager.checkLimits) adding message for consensus " + msg.getNumber() + " to stoopped"); stoppedMsgs.add(msg); } stoppedMsgsLock.unlock(); } else { if (isRetrievingState || msg.getNumber() > (lastConsId + 1) || (inExec != -1 && inExec < msg.getNumber()) || (inExec == -1 && msg.getType() != MessageFactory.PROPOSE)) { Logger.println("(ExecutionManager.checkLimits) Message for consensus " + msg.getNumber() + " is out of context, adding it to out of context set"); addOutOfContextMessage(msg); } else { Logger.println("(ExecutionManager.checkLimits) message for consensus " + msg.getNumber() + " can be processed"); canProcessTheMessage=true; } } } else if ((lastConsId == -1 && msg.getNumber() >= (lastConsId + revivalHighMark)) || (msg.getNumber() >= (lastConsId + paxosHighMark)) || (stopped && msg.getNumber() >= (lastConsId + timeoutHighMark))) { Logger.println("(ExecutionManager.checkLimits) Message for consensus " + msg.getNumber() + " is beyond the paxos highmark, adding it to out of context set"); addOutOfContextMessage(msg); if (controller.getStaticConf().isStateTransferEnabled()) { tomLayer.getStateManager().analyzeState(msg.getNumber()); } else { System.out.println("##################################################################################"); System.out.println("- Ahead-of-time message discarded"); System.out.println("- If many messages of the same consensus are discarded, the replica can halt!"); System.out.println("- Try to increase the 'system.paxos.highMarc' configuration parameter."); System.out.println("- Last consensus executed: " + lastConsId); System.out.println("##################################################################################"); } } outOfContextLock.unlock(); return canProcessTheMessage; }
Checks if this message can execute now. If it is not possible, it is stored in outOfContextMessages
public void dispose() throws GSSException { try { destroy(); } catch ( DestroyFailedException e) { GSSException gssException=new GSSException(GSSException.FAILURE,-1,"Could not destroy credentials - " + e.getMessage()); gssException.initCause(e); } }
Called to invalidate this credential element.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:31:09.094 -0500",hash_original_method="512A5161660D68AB5470903C03DA343E",hash_generated_method="9A8C94856F8B55E80E440B65AAF5FD74") public void copyFrom(Bitmap b){ mRS.validate(); validateBitmapSize(b); validateBitmapFormat(b); mRS.nAllocationCopyFromBitmap(getID(),b); }
Copy an allocation from a bitmap. The height, width, and format of the bitmap must match the existing allocation.
public NameCharacterValidator(final String parameterValue){ this.parameterValue=parameterValue; }
creates a NameCharacterValidator.
public Builder gravity(int gravity){ return this; }
Set the gravity for the drawer. START, LEFT | RIGHT, END
@Override public DirichletDensityFunction copy(){ return new DirichletDensityFunction(alphas); }
Copies the density function (keeping the same alpha-values).
public void deleteKeystoneEndpoint(KeystoneApiClient keystoneApi,String serviceId){ _log.debug("START - deleteKeystoneEndpoint"); if (serviceId != null) { EndpointResponse endpoints=keystoneApi.getKeystoneEndpoints(); EndpointV2 endpointToDelete=findEndpoint(endpoints,serviceId); if (endpointToDelete != null) { keystoneApi.deleteKeystoneEndpoint(endpointToDelete.getId()); _log.debug("Keystone endpoint deleted"); } } _log.debug("END - deleteKeystoneEndpoint"); }
Delete endpoint for the service with given ID.
public LinearGradientPaint(Point2D start,Point2D end,float[] fractions,Color[] colors,CycleMethodEnum cycleMethod,ColorSpaceEnum colorSpace){ this(start,end,fractions,colors,cycleMethod,colorSpace,new AffineTransform()); }
<p> Constructs a <code>LinearGradientPaint</code>.
public static void printUserSitemaps(WebmasterToolsService myService,String siteUrl) throws ServiceException, IOException { System.out.println("Printing user's Sitemaps:"); try { String siteId=URLEncoder.encode(siteUrl,"UTF-8"); URL feedUrl=getSitemapsFeedUrl(siteUrl); SitemapsFeed resultFeed=myService.getFeed(feedUrl,SitemapsFeed.class); for ( SitemapsEntry entry : resultFeed.getEntries()) { System.out.println("\t" + entry.getTitle().getPlainText()); } } catch ( MalformedURLException e) { throw new IOException("URL for site URL is malformed."); } }
Prints all Sitemap URLs for a given site.
void handleSenderOpen(final ProtonConnection con,final ProtonSender sender){ final Source remoteSource=sender.getRemoteSource(); LOG.debug("client [{}] wants to open a link for receiving messages [address: {}]",con.getRemoteContainer(),remoteSource); try { final ResourceIdentifier targetResource=getResourceIdentifier(remoteSource.getAddress()); final Endpoint endpoint=getEndpoint(targetResource); if (endpoint == null) { handleUnknownEndpoint(con,sender,targetResource); } else { final String user=getUserFromConnection(con); checkAuthorizationToAttach(user,targetResource,Permission.READ,null); } } catch ( final IllegalArgumentException e) { LOG.debug("client has provided invalid resource identifier as target address",e); sender.close(); } }
Handles a request from a client to establish a link for receiving messages from this server.
public double nextDouble(double k){ double u, v, w, c, z; if (k <= 0.0) throw new IllegalArgumentException(); if (k_set != k) { tau=1.0 + Math.sqrt(1.0 + 4.0 * k * k); rho=(tau - Math.sqrt(2.0 * tau)) / (2.0 * k); r=(1.0 + rho * rho) / (2.0 * rho); k_set=k; } do { u=randomGenerator.raw(); v=randomGenerator.raw(); z=Math.cos(Math.PI * u); w=(1.0 + r * z) / (r + z); c=k * (r - w); } while ((c * (2.0 - c) < v) && (Math.log(c / v) + 1.0 < c)); return (randomGenerator.raw() > 0.5) ? Math.acos(w) : -Math.acos(w); }
Returns a random number from the distribution; bypasses the internal state.
@Override public SAXBuilder createDocumentBuilder(){ return createDocumentBuilder(null); }
Create a document builder.
public static boolean shouldUseLightForegroundOnBackground(int backgroundColor){ return getContrastForColor(backgroundColor) >= CONTRAST_LIGHT_ITEM_THRESHOLD; }
Check whether lighter or darker foreground elements (i.e. text, drawables etc.) should be used depending on the given background color.
public static <K,V,K2,V2>MutableMap<K2,V2> collect(Map<K,V> map,Function2<? super K,? super V,Pair<K2,V2>> function){ return MapIterate.collect(map,function,UnifiedMap.newMap(map.size())); }
For each value of the map, the function is evaluated with the key and value as the parameter. The results of these evaluations are collected into a new UnifiedMap.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:38.207 -0500",hash_original_method="B760B570F2C2CE8C78B1C4B9AE67037F",hash_generated_method="F657FCFE78415ACE6587EA6D62EB320C") private static int[] parsePortAttribute(final String portValue) throws MalformedCookieException { StringTokenizer st=new StringTokenizer(portValue,","); int[] ports=new int[st.countTokens()]; try { int i=0; while (st.hasMoreTokens()) { ports[i]=Integer.parseInt(st.nextToken().trim()); if (ports[i] < 0) { throw new MalformedCookieException("Invalid Port attribute."); } ++i; } } catch ( NumberFormatException e) { throw new MalformedCookieException("Invalid Port " + "attribute: " + e.getMessage()); } return ports; }
Parses the given Port attribute value (e.g. "8000,8001,8002") into an array of ports.
public Set<Map.Entry<String,JsonElement>> entrySet(){ return members.entrySet(); }
Returns a set of members of this object. The set is ordered, and the order is in which the elements were added.
public void connect(int timeout,String host,int tcpPort,int udpPort) throws IOException { connect(timeout,InetAddress.getByName(host),tcpPort,udpPort); }
Opens a TCP and UDP client.
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:19.274 -0500",hash_original_method="BBF3C380B9774B27B4245C54F7894533",hash_generated_method="29490970C6EB4A3079390A7C66417EFB") private boolean matchesMobile(NetworkIdentity ident){ if (ident.mType == TYPE_WIMAX) { return true; } else { return (contains(DATA_USAGE_NETWORK_TYPES,ident.mType) && Objects.equal(mSubscriberId,ident.mSubscriberId)); } }
Check if mobile network with matching IMSI.
static private void loadPropertiesFile(File file){ if (file.isDirectory()) { File[] files=file.listFiles(); for ( File f : files) { if (f.isFile() && f.getName().endsWith(PROPERTIES_SUFFIX) && f.getName().startsWith(PROPERTIES_PREFIX)) { FileReader reader=null; try { Properties props=new Properties(); reader=new FileReader(f); props.load(reader); definitions.add(loadDefinition(props)); } catch ( IOException e) { log.log(Level.SEVERE,"loadPropertiesFile(): Error loading definition {0}",file.getAbsoluteFile()); log.log(Level.SEVERE,"loadPropertiesFile(): Error loading definition...",e); } finally { if (reader != null) { try { reader.close(); } catch ( IOException ex) { } } } } } } }
Private method that loads the definitions using normal directory container.
public static Token newToken(int ofKind,String image){ switch (ofKind) { default : return new Token(ofKind,image); } }
Returns a new Token object, by default. However, if you want, you can create and return subclass objects based on the value of ofKind. Simply add the cases to the switch for all those special cases. For example, if you have a subclass of Token called IDToken that you want to create if ofKind is ID, simply add something like : case MyParserConstants.ID : return new IDToken(ofKind, image); to the following switch statement. Then you can cast matchedToken variable to the appropriate type and use sit in your lexical actions.
public Comment createComment(Note note,String action,String comment){ Comment newComment=new Comment(); newComment.setText(comment); switch (action) { case NoteActivity.CLOSE: newComment.setAction(Comment.ACTION_CLOSE); break; case NoteActivity.COMMENT: newComment.setAction(Comment.ACTION_COMMENT); break; case NoteActivity.REOPEN: newComment.setAction(Comment.ACTION_REOPEN); break; default : newComment.setAction(Comment.ACTION_OPEN); break; } newComment.setNote(note); return newComment; }
Create a Comment with the given parameters without modifying the Note.
public PropertyField(String label,String initialValue,boolean isReadWrite){ this(label,initialValue,isReadWrite,null,SHOW_TEXTFIELD); }
Constructs a labelled PropertyField as a text field with the provided initial value, either writeable or not.
public TransformVariablesShift(BBOBFunction function,double[] offset){ super(function); this.offset=offset; }
Constructs a transformation that shifts all decision variables by a given offset.
public boolean isModified(){ return isModified; }
Return whether or not this Project has unsaved modifications.
public static boolean canCoerce(Class numberClassToBeCoerced,Class numberClassToCoerceTo){ Class boxedFrom=getBoxedType(numberClassToBeCoerced); Class boxedTo=getBoxedType(numberClassToCoerceTo); if (!isNumeric(numberClassToBeCoerced)) { throw new IllegalArgumentException("Class '" + numberClassToBeCoerced + "' is not a numeric type'"); } if (boxedTo == Float.class) { return ((boxedFrom == Byte.class) || (boxedFrom == Short.class) || (boxedFrom == Integer.class)|| (boxedFrom == Long.class)|| (boxedFrom == Float.class)); } else if (boxedTo == Double.class) { return ((boxedFrom == Byte.class) || (boxedFrom == Short.class) || (boxedFrom == Integer.class)|| (boxedFrom == Long.class)|| (boxedFrom == Float.class)|| (boxedFrom == Double.class)); } else if (boxedTo == BigDecimal.class) { return ((boxedFrom == Byte.class) || (boxedFrom == Short.class) || (boxedFrom == Integer.class)|| (boxedFrom == Long.class)|| (boxedFrom == Float.class)|| (boxedFrom == Double.class)|| (boxedFrom == BigInteger.class)|| (boxedFrom == BigDecimal.class)); } else if (boxedTo == BigInteger.class) { return ((boxedFrom == Byte.class) || (boxedFrom == Short.class) || (boxedFrom == Integer.class)|| (boxedFrom == Long.class)|| (boxedFrom == BigInteger.class)); } else if (boxedTo == Long.class) { return ((boxedFrom == Byte.class) || (boxedFrom == Short.class) || (boxedFrom == Integer.class)|| (boxedFrom == Long.class)); } else if ((boxedTo == Integer.class) || (boxedTo == Short.class) || (boxedTo == Byte.class)) { return ((boxedFrom == Byte.class) || (boxedFrom == Short.class) || (boxedFrom == Integer.class)); } else { throw new IllegalArgumentException("Class '" + numberClassToCoerceTo + "' is not a numeric type'"); } }
Determines if a number can be coerced upwards to another number class without loss. <p> Clients must pass in two classes that are numeric types. <p> Any number class can be coerced to double, while only double cannot be coerced to float. Any non-floating point number can be coerced to long. Integer can be coerced to Byte and Short even though loss is possible, for convenience.
public void clean(){ clean(stringClassMap.values()); clean(stringClassMap2.values()); clean(classStringMap.keySet()); }
remove classes which are not in the default class loaders.
private void dropTables(SQLiteDatabase paramSQLiteDatabase){ for ( String table : sTables) { try { paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + table); } catch ( Exception localException) { localException.printStackTrace(); } } }
Goes through all of the tables in sTables and drops each table if it exists. Altered to no longer make use of reflection.
public boolean naive(){ return soot.PhaseOptions.getBoolean(options,"naive"); }
Build naive dependence graph -- . When set to true, the dependence graph is built with a node for each statement, without merging the nodes for equivalent statements. This makes it possible to measure the effect of merging nodes for equivalent statements on the size of the dependence graph.
public static com.vmware.vim.sso.PrincipalId fromIdmPrincipalId(PrincipalId subject){ assert subject != null; return new com.vmware.vim.sso.PrincipalId(subject.getName(),subject.getDomain()); }
Convert principal Id from IDM representation.
@After public void tearDown(){ webClient.closeAllWindows(); }
Tear down after testing.
public List<SoftwareVersion> findInstallableVersions(final boolean forceInstall,final SoftwareVersion localCurrent,final List<SoftwareVersion> localVersions){ List<SoftwareVersion> newVersionList=findNewVersions(localCurrent,localVersions,forceInstall); if (newVersionList.isEmpty()) { return newVersionList; } RepositoryContent repositoryContent=readRepository(_repo); try { if (repositoryContent.getContentType().toLowerCase().contains("text/xml")) { return finInstallableVersionsFromCatalogRepo(readCatalog(readInputStream(repositoryContent.getContentStream())),newVersionList,localVersions); } else { return findInstallableVersionsFromDirectoryRepo(newVersionList,localVersions); } } catch ( RemoteRepositoryException e) { throw e; } catch ( Exception e) { throw SyssvcException.syssvcExceptions.remoteRepoError(MessageFormat.format("Failed to parse the remote repository {0} input={1} ({2})",_repo,Strings.repr(repositoryContent),e)); } finally { try { if (null != repositoryContent.getContentStream()) { repositoryContent.getContentStream().close(); } } catch ( IOException e) { _log.error("Failed to close input stream: " + e); } } }
Get a list of new versions that can be installed from the remote repository
public String attributeIndicesTipText(){ return "Specify range of attributes to act on; " + "this is a comma separated list of attribute indices, with " + "\"first\" and \"last\" valid values; specify an inclusive "+ "range with \"-\"; eg: \"first-3,5,6-10,last\"."; }
Returns the tip text for this property.
public static int murmurhash3_x86_32(byte[] data,int offset,int len,int seed){ final int c1=0xcc9e2d51; final int c2=0x1b873593; int h1=seed; int roundedEnd=offset + (len & 0xfffffffc); for (int i=offset; i < roundedEnd; i+=4) { int k1=(data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | ((data[i + 2] & 0xff) << 16)| (data[i + 3] << 24); k1*=c1; k1=(k1 << 15) | (k1 >>> 17); k1*=c2; h1^=k1; h1=(h1 << 13) | (h1 >>> 19); h1=h1 * 5 + 0xe6546b64; } int k1=0; switch (len & 0x03) { case 3: k1=(data[roundedEnd + 2] & 0xff) << 16; case 2: k1|=(data[roundedEnd + 1] & 0xff) << 8; case 1: k1|=(data[roundedEnd] & 0xff); k1*=c1; k1=(k1 << 15) | (k1 >>> 17); k1*=c2; h1^=k1; } h1^=len; h1^=h1 >>> 16; h1*=0x85ebca6b; h1^=h1 >>> 13; h1*=0xc2b2ae35; h1^=h1 >>> 16; return h1; }
Returns the MurmurHash3_x86_32 hash. Original source/tests at https://github.com/yonik/java_util/
public static boolean isWellFormedSmsAddress(String address){ String networkPortion=PhoneNumberUtils.extractNetworkPortion(address); return (!(networkPortion.equals("+") || TextUtils.isEmpty(networkPortion))) && isDialable(networkPortion); }
Return true iff the network portion of <code>address</code> is, as far as we can tell on the device, suitable for use as an SMS destination address.
public CustomProperty(String value){ this(); setValue(value); }
Constructs a new instance with the given value.
public void runtimeInit(TransformerImpl transformer) throws TransformerException { }
This function will be called on top-level elements only, just before the transform begins.
public boolean contains(int s){ if (null == m_map) return false; for (int i=0; i < m_firstFree; i++) { int node=m_map[i]; if (node == s) return true; } return false; }
Tell if the table contains the given node.
public void add(Permission permission){ perms.put(permission,permission); }
Adds the argument to the collection.
public byte byteAt(int offset){ return ref.bytes[offset]; }
Return the byte at the given offset.
public IThumbnailRequest buildRequest(final List<Option> options){ return new ThumbnailRequest(getRequestUrl(),getClient(),options); }
Creates the request with specific options instead of the existing options
public static <T,U extends T,V extends T>T inject(Object self,U initialValue,Closure<V> closure){ Iterator iter=InvokerHelper.asIterator(self); return (T)inject(iter,initialValue,closure); }
Iterates through the given Object, passing in the initial value to the closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until further iteration of the object is not possible. Also known as foldLeft in functional parlance.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
static void handleReopen(){ if (_allowVisible) { if (!_visibleOnce) restoreView(); setAppVisible(true); } }
Handles a 'reopen' event appropriately. Used primarily for allowing LimeWire to be made visible after it was started from system startup on OSX.
@Override public void run(){ amIActive=true; String inputFile=args[0]; if (inputFile.toLowerCase().contains(".dep")) { calculateRaster(); } else if (inputFile.toLowerCase().contains(".shp")) { calculateVector(); } else { showFeedback("There was a problem reading the input file."); } }
Used to execute this plugin tool.
public boolean isSetB1000(){ return this.b1000 != null; }
Returns true if field b1000 is set (has been assigned a value) and false otherwise
public int tabForCoordinate(JTabbedPane pane,int x,int y){ return tabForCoordinate(pane,x,y,true); }
Returns the tab index which intersects the specified point in the JTabbedPane's coordinate space.
public Period withYears(int years){ int[] values=getValues(); getPeriodType().setIndexedField(this,PeriodType.YEAR_INDEX,values,years); return new Period(values,getPeriodType()); }
Returns a new period with the specified number of years. <p> This period instance is immutable and unaffected by this method call.
@Override public void visit(NodeVisitor v){ if (v.visit(this)) { target.visit(v); for ( AstNode arg : getArguments()) { arg.visit(v); } } }
Visits this node, the target object, and the arguments.
public boolean fitWithinDimenions(){ return fitWithinDimensions; }
Returns whether or not to fit the thumbnail within the specified dimensions.
public void writeInt(int v) throws IOException { _os.write(v >> 24); _os.write(v >> 16); _os.write(v >> 8); _os.write(v); }
Writes an int
static MediaType createApplicationType(String subtype){ return create(APPLICATION_TYPE,subtype); }
Creates a media type with the "application" type and the given subtype.
public static void main(String[] argv){ runFilter(new RemoveWithValues(),argv); }
Main method for testing this class.
public Primitive castToType(Class toType,int operation) throws UtilEvalError { return castPrimitive(toType,getType(),this,false,operation); }
Cast this bsh.Primitive value to a new bsh.Primitive value This is usually a numeric type cast. Other cases include: A boolean can be cast to boolen null can be cast to any object type and remains null Attempting to cast a void causes an exception
public PrinterResolution(int crossFeedResolution,int feedResolution,int units){ super(crossFeedResolution,feedResolution,units); }
Construct a new printer resolution attribute from the given items.
protected void appendShortInteger(int value){ append((value | 0x80) & 0xff); }
Append short integer value to mMessage. This implementation doesn't check the validity of parameter, since it assumes that the values are validated in the GenericPdu setter methods.
@Override public void run(){ amIActive=true; String inputFile; String outputFile; double x, y; int progress; int i, n; double[][] vertices=null; int numFeatures; int oneHundredthTotal; ShapeType shapeType, outputShapeType; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputFile=args[0]; outputFile=args[1]; if ((inputFile == null) || (outputFile == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { ShapeFile input=new ShapeFile(inputFile); shapeType=input.getShapeType(); if (shapeType.getBaseType() != ShapeType.POLYGON && shapeType.getBaseType() != ShapeType.POLYLINE) { showFeedback("This tool only works with shapefiles of a polygon or line base shape type."); return; } outputShapeType=ShapeType.POINT; int numOutputFields=input.getAttributeTable().getFieldCount() + 1; int numInputFields=input.getAttributeTable().getFieldCount(); DBFField[] inputFields=input.getAttributeTable().getAllFields(); DBFField fields[]=new DBFField[numOutputFields]; fields[0]=new DBFField(); fields[0].setName("PARENT_ID"); fields[0].setDataType(DBFField.DBFDataType.NUMERIC); fields[0].setFieldLength(10); fields[0].setDecimalCount(0); System.arraycopy(inputFields,0,fields,1,numInputFields); ShapeFile output=new ShapeFile(outputFile,outputShapeType,fields); output.setProjectionStringFromOtherShapefile(input); numFeatures=input.getNumberOfRecords(); oneHundredthTotal=numFeatures / 100; n=0; progress=0; int recordNum; for ( ShapeFileRecord record : input.records) { recordNum=record.getRecordNumber(); Object[] attData=input.getAttributeTable().getRecord(recordNum - 1); vertices=new double[0][0]; switch (shapeType) { case POLYGON: whitebox.geospatialfiles.shapefile.Polygon recPolygon=(whitebox.geospatialfiles.shapefile.Polygon)(record.getGeometry()); vertices=recPolygon.getPoints(); break; case POLYGONZ: PolygonZ recPolygonZ=(PolygonZ)(record.getGeometry()); vertices=recPolygonZ.getPoints(); break; case POLYGONM: PolygonM recPolygonM=(PolygonM)(record.getGeometry()); vertices=recPolygonM.getPoints(); break; case POLYLINE: PolyLine recPolyline=(PolyLine)(record.getGeometry()); vertices=recPolyline.getPoints(); break; case POLYLINEZ: PolyLineZ recPolylineZ=(PolyLineZ)(record.getGeometry()); vertices=recPolylineZ.getPoints(); break; case POLYLINEM: PolyLineM recPolylineM=(PolyLineM)(record.getGeometry()); vertices=recPolylineM.getPoints(); break; } for (i=0; i < vertices.length; i++) { x=vertices[i][0]; y=vertices[i][1]; Object[] rowData=new Object[numOutputFields]; rowData[0]=(double)recordNum - 1; System.arraycopy(attData,0,rowData,1,numInputFields); output.addRecord(new whitebox.geospatialfiles.shapefile.Point(x,y),rowData); } n++; if (n >= oneHundredthTotal) { n=0; if (cancelOp) { cancelOperation(); return; } progress++; updateProgress(progress); } } output.write(); updateProgress("Displaying vector: ",0); returnData(outputFile); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public boolean closeIfStale() throws IOException { if (isOpen && isStale()) { LOG.debug("Connection is stale, closing..."); close(); return true; } return false; }
Closes the connection if stale.
public String previousToken(){ if (hasPrevious()) { return tokens[--tokenPos]; } return null; }
Gets the previous token from the String.
void flushDeferredWrites() throws IgniteCheckedException { assert isHeldByCurrentThread(); assert handshakeFinished; while (!deferredWriteQueue.isEmpty()) { WriteRequest req=deferredWriteQueue.poll(); req.future().onDone((GridNioFuture<Object>)parent.proceedSessionWrite(ses,req.buffer())); } }
Flushes all deferred write events.