code
stringlengths
10
174k
nl
stringlengths
3
129k
public void drawRect(int x,int y,int width,int height){ DebugGraphicsInfo info=info(); if (debugLog()) { info().log(toShortString() + " Drawing rect: " + new Rectangle(x,y,width,height)); } if (isDrawingBuffer()) { if (debugBuffered()) { Graphics debugGraphics=debugGraphics(); debugGraphics.drawRect(x,y,width,height); debugGraphics.dispose(); } } else if (debugFlash()) { Color oldColor=getColor(); int i, count=(info.flashCount * 2) - 1; for (i=0; i < count; i++) { graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor); graphics.drawRect(x,y,width,height); Toolkit.getDefaultToolkit().sync(); sleep(info.flashTime); } graphics.setColor(oldColor); } graphics.drawRect(x,y,width,height); }
Overrides <code>Graphics.drawRect</code>.
public static void main(String[] args) throws IOException { FileInputStream in=new FileInputStream(args[0]); FileOutputStream out=new FileOutputStream(args[1]); SWFWriter writer=new SWFWriter(out); TagWriter tagwtr=new TagWriter(writer); TagParser parser=new TagParser(tagwtr); SWFReader reader=new SWFReader(parser,in); reader.readFile(); out.flush(); out.close(); in.close(); }
The main program for the TagParser class
public void addItem(final String itemName,final int amount){ final Integer curAmount=get(itemName); if (curAmount != null) { put(itemName,curAmount + amount); } else { put(itemName,amount); } }
Add the specified amount of items to the collection.
private static float fuzzAspectRatio(float aspectRatio){ for ( float desiredAspectRatio : sDesiredAspectRatios) { if ((Math.abs(aspectRatio - desiredAspectRatio)) < ASPECT_RATIO_TOLERANCE) { return desiredAspectRatio; } } return aspectRatio; }
Take an aspect ratio and squish it into a nearby desired aspect ratio, if possible.
protected XMLReader createXMLReader() throws SAXException { return SAXHelper.createXMLReader(isValidating()); }
Factory Method to allow alternate methods of creating and configuring XMLReader objects
public StyledString createStyledLabel(CompletionProposal proposal){ switch (proposal.getKind()) { case CompletionProposal.METHOD_NAME_REFERENCE: case CompletionProposal.METHOD_REF: case CompletionProposal.CONSTRUCTOR_INVOCATION: case CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER: case CompletionProposal.POTENTIAL_METHOD_DECLARATION: if (fContext != null && fContext.isInJavadoc()) return createJavadocMethodProposalLabel(proposal); return createMethodProposalLabel(proposal); case CompletionProposal.METHOD_DECLARATION: return createOverrideMethodProposalLabel(proposal); case CompletionProposal.ANONYMOUS_CLASS_DECLARATION: case CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION: return createAnonymousTypeLabel(proposal); case CompletionProposal.TYPE_REF: return createTypeProposalLabel(proposal); case CompletionProposal.JAVADOC_TYPE_REF: return createJavadocTypeProposalLabel(proposal); case CompletionProposal.JAVADOC_FIELD_REF: case CompletionProposal.JAVADOC_VALUE_REF: case CompletionProposal.JAVADOC_BLOCK_TAG: case CompletionProposal.JAVADOC_INLINE_TAG: case CompletionProposal.JAVADOC_PARAM_REF: return createJavadocSimpleProposalLabel(proposal); case CompletionProposal.JAVADOC_METHOD_REF: return createJavadocMethodProposalLabel(proposal); case CompletionProposal.PACKAGE_REF: return createPackageProposalLabel(proposal); case CompletionProposal.ANNOTATION_ATTRIBUTE_REF: case CompletionProposal.FIELD_REF: case CompletionProposal.FIELD_REF_WITH_CASTED_RECEIVER: return createLabelWithTypeAndDeclaration(proposal); case CompletionProposal.LOCAL_VARIABLE_REF: case CompletionProposal.VARIABLE_DECLARATION: return createSimpleLabelWithType(proposal); case CompletionProposal.KEYWORD: case CompletionProposal.LABEL_REF: return createSimpleLabel(proposal); default : Assert.isTrue(false); return null; } }
Creates a display label with styles for a given <code>CompletionProposal</code>.
@SuppressWarnings("unchecked") private void mergeHi(int base1,int len1,int base2,int len2){ if (DEBUG) assert len1 > 0 && len2 > 0 && base1 + len1 == base2; Object[] a=this.a; Object[] tmp=ensureCapacity(len2); System.arraycopy(a,base2,tmp,0,len2); int cursor1=base1 + len1 - 1; int cursor2=len2 - 1; int dest=base2 + len2 - 1; a[dest--]=a[cursor1--]; if (--len1 == 0) { System.arraycopy(tmp,0,a,dest - (len2 - 1),len2); return; } if (len2 == 1) { dest-=len1; cursor1-=len1; System.arraycopy(a,cursor1 + 1,a,dest + 1,len1); a[dest]=tmp[cursor2]; return; } int minGallop=this.minGallop; outer: while (true) { int count1=0; int count2=0; do { if (DEBUG) assert len1 > 0 && len2 > 1; if (((Comparable)tmp[cursor2]).compareTo(a[cursor1]) < 0) { a[dest--]=a[cursor1--]; count1++; count2=0; if (--len1 == 0) break outer; } else { a[dest--]=tmp[cursor2--]; count2++; count1=0; if (--len2 == 1) break outer; } } while ((count1 | count2) < minGallop); do { if (DEBUG) assert len1 > 0 && len2 > 1; count1=len1 - gallopRight((Comparable)tmp[cursor2],a,base1,len1,len1 - 1); if (count1 != 0) { dest-=count1; cursor1-=count1; len1-=count1; System.arraycopy(a,cursor1 + 1,a,dest + 1,count1); if (len1 == 0) break outer; } a[dest--]=tmp[cursor2--]; if (--len2 == 1) break outer; count2=len2 - gallopLeft((Comparable)a[cursor1],tmp,0,len2,len2 - 1); if (count2 != 0) { dest-=count2; cursor2-=count2; len2-=count2; System.arraycopy(tmp,cursor2 + 1,a,dest + 1,count2); if (len2 <= 1) break outer; } a[dest--]=a[cursor1--]; if (--len1 == 0) break outer; minGallop--; } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP); if (minGallop < 0) minGallop=0; minGallop+=2; } this.minGallop=minGallop < 1 ? 1 : minGallop; if (len2 == 1) { if (DEBUG) assert len1 > 0; dest-=len1; cursor1-=len1; System.arraycopy(a,cursor1 + 1,a,dest + 1,len1); a[dest]=tmp[cursor2]; } else if (len2 == 0) { throw new IllegalArgumentException("Comparison method violates its general contract!"); } else { if (DEBUG) assert len1 == 0; if (DEBUG) assert len2 > 0; System.arraycopy(tmp,0,a,dest - (len2 - 1),len2); } }
Like mergeLo, except that this method should be called only if len1 >= len2; mergeLo should be called if len1 <= len2. (Either method may be called if len1 == len2.)
private static void drawLeftTab(int x,int y,int w,int h,Graphics2D g2,ColorUIResource color){ double rTop=RapidLookAndFeel.CORNER_TAB_RADIUS * 0.67; g2.setColor(color); g2.fill(createLeftTabShape(x + 1,y + 1,w - 1,h,rTop,true)); g2.setColor(Colors.TAB_BORDER); g2.draw(createLeftTabShape(x,y,w - 1,h,rTop,false)); }
Draw a left tab at the given location and size with the given background color.
public boolean forEachEntry(TLongLongProcedure procedure){ byte[] states=_states; long[] keys=_set; long[] values=_values; for (int i=keys.length; i-- > 0; ) { if (states[i] == FULL && !procedure.execute(keys[i],values[i])) { return false; } } return true; }
Executes <tt>procedure</tt> for each key/value entry in the map.
public ReplControlEvent(int eventType,long seqno,ReplDBMSHeader header){ this.eventType=eventType; this.seqno=seqno; this.header=header; }
Creates a new control event instance.
public static void updateAfterLoad(final DigestURL url,final long time){ final String host=url.getHost(); if (host == null) return; String hosthash=url.hosthash(); Host h=map.get(hosthash); if (h == null) { h=new Host(host,time,0); if (map.size() > mapMaxSize || MemoryControl.shortStatus()) map.clear(); map.put(hosthash,h); } else { h.update(time); } }
update the latency entry after a host was accessed to load a file
public CompanyApplicationExample(){ oredCriteria=new ArrayList<Criteria>(); }
This method was generated by MyBatis Generator. This method corresponds to the database table company_application
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public ClusterUpdateSettingsRequest transientSettings(String source){ this.transientSettings=Settings.settingsBuilder().loadFromSource(source).build(); return this; }
Sets the source containing the transient settings to be updated. They will not survive a full cluster restart
public static void main(final String[] args) throws Exception { int i=0; int flags=ClassReader.SKIP_DEBUG; boolean ok=true; if (args.length < 1 || args.length > 2) { ok=false; } if (ok && "-debug".equals(args[0])) { i=1; flags=0; if (args.length != 2) { ok=false; } } if (!ok) { System.err.println("Prints a disassembled view of the given class."); System.err.println("Usage: Textifier [-debug] " + "<fully qualified class name or class file name>"); return; } ClassReader cr; if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1 || args[i].indexOf('/') > -1) { cr=new ClassReader(new FileInputStream(args[i])); } else { cr=new ClassReader(args[i]); } cr.accept(new TraceClassVisitor(new PrintWriter(System.out)),flags); }
Prints a disassembled view of the given class to the standard output. <p> Usage: Textifier [-debug] &lt;binary class name or class file name &gt;
public static <V extends FeatureVector<?>>VectorFieldTypeInformation<V> assumeVectorField(Relation<V> relation){ try { return ((VectorFieldTypeInformation<V>)relation.getDataTypeInformation()); } catch ( Exception e) { throw new UnsupportedOperationException("Expected a vector field, got type information: " + relation.getDataTypeInformation().toString(),e); } }
Get the vector field type information from a relation.
@Override protected void process(DistributionManager dm){ Assert.assertTrue(this.id != null); ReplyMessage reply=new ReplyMessage(); reply.setProcessorId(processorId); reply.setRecipient(getSender()); dm.putOutgoing(reply); }
Adds the distribution manager that is started up to the current DM's list of members. This method is invoked on the receiver side
@Override public RegularTimePeriod previous(){ Minute result; if (this.minute != FIRST_MINUTE_IN_HOUR) { result=new Minute(this.minute - 1,getHour()); } else { Hour h=(Hour)getHour().previous(); if (h != null) { result=new Minute(LAST_MINUTE_IN_HOUR,h); } else { result=null; } } return result; }
Returns the minute preceding this one.
public final double KBMeanInformation() throws Exception { if (!m_ClassIsNominal) { throw new Exception("Can't compute K&B Info score: class numeric!"); } if (m_NoPriors) { return Double.NaN; } return m_SumKBInfo / (m_WithClass - m_Unclassified); }
Return the Kononenko & Bratko Information score in bits per instance.
protected boolean isInState(int state){ return this.state == state; }
Returns if the system is in state <code>state</code>.
public boolean isFinal(){ return false; }
Always returns 'false' since this state machine can never become final.
public static double[][] computeNorms(double[][] mvTimeSeries,int t){ int timeSteps=mvTimeSeries.length; int variables=mvTimeSeries[0].length; double[][] norms=new double[timeSteps][variables]; for (int t2=0; t2 < timeSteps; t2++) { if (t2 == t) { for (int v=0; v < variables; v++) { norms[t2][v]=Double.POSITIVE_INFINITY; } continue; } for (int v=0; v < variables; v++) { norms[t2][v]=Math.abs(mvTimeSeries[t][v] - mvTimeSeries[t2][v]); } } return norms; }
Compute the norms for each marginal variable for all other points from the data points at time step t. Puts norms of t from itself as infinity, which is useful when counting the number of points closer than epsilon say.
public boolean isLedBlinking(){ return null == ledBlinking ? _ledBlinking : ledBlinking.get(); }
Returns true if the LED is blinking (if available)
default DequeX<T> toDequeX(){ return DequeX.fromIterable(toList()); }
Returns a DequeX created with a list which is result of a get() call. If this get() returns null the the list is the empty list.
public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); }
Run just this test.
public Object clone(){ JimpleLocal l=new JimpleLocal(name,type); l.index=this.index; return l; }
Returns a clone of the current JimpleLocal.
public boolean isValidSerializationB(String preorder){ String[] nodes=preorder.split(","); int diff=1; for ( String node : nodes) { diff--; if (diff < 0) { return false; } if (!"#".equals(node)) { diff+=2; } } return diff == 0; }
Degree. A value provide 2 out degrees and 1 in degree, except root. A '#' provide no out degree and 1 in degree. https://discuss.leetcode.com/topic/35976/7-lines-easy-java-solution
private final int fetchTag() throws BerException { int result=0; final int backup=next; try { final byte b0=bytes[next++]; result=(b0 >= 0) ? b0 : b0 + 256; if ((result & 31) == 31) { while ((bytes[next] & 128) != 0) { result=result << 7; result=result | (bytes[next++] & 127); } } } catch ( IndexOutOfBoundsException e) { next=backup; throw new BerException(); } return result; }
Fetch a tag and move the current position forward.
public static Border createDottedBorder(int thickness,int color){ return createCSSBorder(TYPE_DOTTED,thickness,color); }
Creates a dotted border with the specified thickness and color
public XMPPException(String message,XMPPError error,Throwable wrappedThrowable){ super(message); this.error=error; this.wrappedThrowable=wrappedThrowable; }
Creates a new XMPPException with a description of the exception, an XMPPError, and the Throwable that was the root cause of the exception.
@Override public void runPlugin(String pluginName,String[] args){ host.runPlugin(pluginName,args); if (automaticallyClose) { this.dispose(); } }
Used to run a plugin through the Host app.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:28:38.296 -0500",hash_original_method="456400F7FD34BEA9F412D24A9889C2FB",hash_generated_method="F28E65C77F981D5409FFCCEB8ED4757B") public static String concatenateWhere(String a,String b){ if (TextUtils.isEmpty(a)) { return b; } if (TextUtils.isEmpty(b)) { return a; } return "(" + a + ") AND ("+ b+ ")"; }
Concatenates two SQL WHERE clauses, handling empty or null values.
public SampleVcpcRunner(GraphSource graphWrapper,Parameters params){ super(graphWrapper.getGraph(),params); }
Constucts a wrapper for the given EdgeListGraph.
private VPlexMigrationInfo migrateLocalVirtualVolumeDevice(String migrationName,VPlexVirtualVolumeInfo virtualVolumeInfo,Map<VolumeInfo,VPlexStorageVolumeInfo> storageVolumeInfoMap,boolean startNow,String transferSize) throws VPlexApiException { String localDeviceName=virtualVolumeInfo.getSupportingDevice(); VPlexApiDiscoveryManager discoveryMgr=_vplexApiClient.getDiscoveryManager(); VPlexDeviceInfo srcDeviceInfo=discoveryMgr.findLocalDevice(localDeviceName); VPlexApiVirtualVolumeManager virtualVolumeMgr=_vplexApiClient.getVirtualVolumeManager(); virtualVolumeMgr.claimStorageVolumes(storageVolumeInfoMap,false); s_logger.info("Claimed storage volume"); try { List<VPlexStorageVolumeInfo> storageVolumeInfoList=new ArrayList<VPlexStorageVolumeInfo>(storageVolumeInfoMap.values()); virtualVolumeMgr.createExtents(storageVolumeInfoList); s_logger.info("Created extent on storage volume"); List<VPlexExtentInfo> extentInfoList=discoveryMgr.findExtents(storageVolumeInfoList); virtualVolumeMgr.createLocalDevices(extentInfoList); s_logger.info("Created local device on extent"); VPlexDeviceInfo tgtDeviceInfo=discoveryMgr.findLocalDevices(extentInfoList).get(0); VPlexMigrationInfo migrationInfo=migrateResource(migrationName,srcDeviceInfo,tgtDeviceInfo,true,startNow,transferSize); migrationInfo.setVirtualVolumeInfo(virtualVolumeInfo); return migrationInfo; } catch ( Exception e) { s_logger.info("Exception occurred migrating local volume device, attempting to cleanup VPLEX artifacts"); try { List<VolumeInfo> nativeVolumeInfoList=new ArrayList<VolumeInfo>(); nativeVolumeInfoList.addAll(storageVolumeInfoMap.keySet()); virtualVolumeMgr.deleteVirtualVolume(nativeVolumeInfoList); } catch ( Exception ex) { s_logger.error("Failed attempting to cleanup VPLEX after failed attempt " + "to migrate local virtual volume {}",virtualVolumeInfo.getPath(),ex); } throw e; } }
Migrate the local device used by the passed virtual volume.
public void testAskSubquery01(){ final String anonFilterVar1="--exists-1"; final String[] filterVars1=new String[]{"x1"}; final String anonFilterVar2="--not-exists-1"; final String[] filterVars2=new String[]{"y1","y2","y3"}; new Helper(){ { given=select(varNode(x),where(filterExistsWithVars(anonFilterVar1,filterVars1),filterExistsOrNotExistsSubqueryWithVars(anonFilterVar1,filterVars1),filterExistsWithVars(anonFilterVar2,filterVars2),filterExistsOrNotExistsSubqueryWithVars(anonFilterVar2,filterVars2),stmtPatternWithVar("x1"),stmtPatternWithVar("y1"),stmtPatternWithVar("y2"),stmtPatternWithVar("y3"))); expected=select(varNode(x),where(stmtPatternWithVar("x1"),filterExistsOrNotExistsSubqueryWithVars(anonFilterVar1,filterVars1),filterExistsWithVars(anonFilterVar1,filterVars1),stmtPatternWithVar("y1"),stmtPatternWithVar("y2"),stmtPatternWithVar("y3"),filterExistsOrNotExistsSubqueryWithVars(anonFilterVar2,filterVars2),filterExistsWithVars(anonFilterVar2,filterVars2))); } } .test(); }
Test case for ASK subqueries, as they emerge from FILTER (NOT) EXISTS clauses.
public static Query cswcq(Term wild){ WildcardQuery query=new WildcardQuery(wild); query.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE); return query; }
macro for readability
protected void asyncCommandProcess(Command cmd,ActionEvent sourceEvent){ }
Warning: This method is invoked OFF the EDT and is intended for usage with asynchronous command processing. This method is invoked when the UI indicates that an operation should occur in the background. To finish the processing of the operation within the EDT one should override the postAsyncCommand() method.
public TextAttributeSet(){ attributes=new HashMap<TextAttribute,Object>(); }
Create a new TextAttributeSet with no defined attributes.
protected StorageTier checkStorageTierExistsInDB(String tierNativeGuid,DbClient _dbClient) throws IOException { StorageTier tier=null; @SuppressWarnings("deprecation") List<URI> storageTierUris=_dbClient.queryByConstraint(AlternateIdConstraint.Factory.getStorageTierByIdConstraint(tierNativeGuid)); if (!storageTierUris.isEmpty()) { tier=_dbClient.queryObject(StorageTier.class,storageTierUris.get(0)); } return tier; }
Check if Storage Tier exists in DB.
public Blade any(String path,RouteHandler handler){ routers.route(path,handler,HttpMethod.ALL); return this; }
Register for any request routing
public CollectionTypeImpl(Class clazz,ObjectType elementType){ super(clazz); this.elementType=elementType; }
Creates a new instance of ObjectTypeImpl
public void addElement(int value){ if ((m_firstFree + 1) >= m_mapSize) { if (null == m_map) { m_map=new int[m_blocksize]; m_mapSize=m_blocksize; } else { m_mapSize+=m_blocksize; int newMap[]=new int[m_mapSize]; System.arraycopy(m_map,0,newMap,0,m_firstFree + 1); m_map=newMap; } } m_map[m_firstFree]=value; m_firstFree++; }
Append a Node onto the vector.
public UseableEntity(){ setRPClass("useable_entity"); put("type","useable_entity"); put("cursor","ACTIVITY"); super.setSize(1,1); }
creates a new UseableEntity
public boolean isCurrentBetween(char left,char right){ if (!isValidIndex()) return false; return lcText[pos] >= left && lcText[pos] <= right; }
is the character at the current position (internal pointer) in the range of the given input characters?
@Override public void bindView(ViewHolder viewHolder,List payloads){ super.bindView(viewHolder,payloads); StringHolder.applyTo(name,viewHolder.name); StringHolder.applyToOrHide(description,viewHolder.description); viewHolder.swipeResultContent.setVisibility(swipedDirection != 0 ? View.VISIBLE : View.GONE); viewHolder.itemContent.setVisibility(swipedDirection != 0 ? View.GONE : View.VISIBLE); CharSequence swipedAction=null; CharSequence swipedText=null; if (swipedDirection != 0) { swipedAction=viewHolder.itemView.getContext().getString(R.string.action_undo); swipedText=swipedDirection == ItemTouchHelper.LEFT ? "Removed" : "Archived"; viewHolder.swipeResultContent.setBackgroundColor(ContextCompat.getColor(viewHolder.itemView.getContext(),swipedDirection == ItemTouchHelper.LEFT ? R.color.md_red_900 : R.color.md_blue_900)); } viewHolder.swipedAction.setText(swipedAction == null ? "" : swipedAction); viewHolder.swipedText.setText(swipedText == null ? "" : swipedText); viewHolder.swipedActionRunnable=this.swipedAction; }
binds the data of this item onto the viewHolder
public void addMatchedComputeElements(final StringSet matchedComputeElements){ if (null != _matchedComputeElements) { _matchedComputeElements.replace(matchedComputeElements); } else { if (null != matchedComputeElements && !matchedComputeElements.isEmpty()) { setMatchedComputeElements(new StringSet()); _matchedComputeElements.addAll(matchedComputeElements); } } }
Add all passed matched Compute Element URsI to ComputeVirtualPool.
public Element store(Object o){ PanelEditor p=(PanelEditor)o; Element panel=new Element("paneleditor"); JFrame frame=p.getTargetFrame(); Dimension size=frame.getSize(); Point posn=frame.getLocation(); panel.setAttribute("class","jmri.jmrit.display.panelEditor.configurexml.PanelEditorXml"); panel.setAttribute("name","" + frame.getTitle()); panel.setAttribute("x","" + posn.x); panel.setAttribute("y","" + posn.y); panel.setAttribute("height","" + size.height); panel.setAttribute("width","" + size.width); panel.setAttribute("editable","" + (p.isEditable() ? "yes" : "no")); panel.setAttribute("positionable","" + (p.allPositionable() ? "yes" : "no")); panel.setAttribute("showtooltips","" + (p.showTooltip() ? "yes" : "no")); panel.setAttribute("controlling","" + (p.allControlling() ? "yes" : "no")); panel.setAttribute("hide",p.isVisible() ? "no" : "yes"); panel.setAttribute("panelmenu",p.isPanelMenuVisible() ? "yes" : "no"); panel.setAttribute("scrollable",p.getScrollable()); if (p.getBackgroundColor() != null) { panel.setAttribute("redBackground","" + p.getBackgroundColor().getRed()); panel.setAttribute("greenBackground","" + p.getBackgroundColor().getGreen()); panel.setAttribute("blueBackground","" + p.getBackgroundColor().getBlue()); } List<Positionable> contents=p.getContents(); if (log.isDebugEnabled()) { log.debug("N elements: " + contents.size()); } for (int i=0; i < contents.size(); i++) { Positionable sub=contents.get(i); if (sub != null && sub.storeItem()) { try { Element e=jmri.configurexml.ConfigXmlManager.elementFromObject(sub); if (e != null) { panel.addContent(e); } } catch ( Exception e) { log.error("Error storing panel element: " + e); e.printStackTrace(); } } } return panel; }
Default implementation for storing the contents of a PanelEditor
public HashTokenSessionMap(Environment environment){ int sessionTimeoutValue; try { sessionTimeoutValue=environment.getProperty(API_SESSION_TIMEOUT,60); } catch ( GuacamoleException e) { logger.error("Unable to read guacamole.properties: {}",e.getMessage()); logger.debug("Error while reading session timeout value.",e); sessionTimeoutValue=60; } logger.info("Sessions will expire after {} minutes of inactivity.",sessionTimeoutValue); executor.scheduleAtFixedRate(new SessionEvictionTask(sessionTimeoutValue * 60000l),1,1,TimeUnit.MINUTES); }
Create a new HashTokenSessionMap configured using the given environment.
public ArrayDeque(){ this(DEFAULT_SIZE); }
Constructs a new empty instance of ArrayDeque big enough for 16 elements.
private void addWlstArguments(JvmLauncher java){ File serverDir=new File(this.getHome(),"server"); java.addClasspathEntries(new File(serverDir,"lib/weblogic.jar")); java.setMainClass("weblogic.WLST"); }
Adding WLST dependencies and setting main class.
private boolean trackedThreadUncaughtException(Thread t,Throwable e){ getLogger().error("Uncaught exception in thread " + t.getName(),e); return true; }
Handle an exception thrown by a tracked thread.
@Override protected EClass eStaticClass(){ return N4mfPackage.Literals.MODULE_FILTER; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static void PackBucketEntry(KBucketEntry e,byte[] buffer,int off,DHTtype type){ if (off + type.NODES_ENTRY_LENGTH > buffer.length) { throw new IllegalArgumentException("Not enough room in buffer"); } ByteBuffer bb=ByteBuffer.wrap(buffer,off,type.NODES_ENTRY_LENGTH); InetSocketAddress addr=e.getAddress(); if (type == DHTtype.IPV6_DHT && addr.getAddress() instanceof Inet4Address) throw new IllegalArgumentException("Attempting to serialize an IPv4 bucket entry into nodes6 buffer"); bb.put(e.getID().getHash()); bb.put(addr.getAddress().getAddress()); bb.putShort((short)addr.getPort()); }
Packs a BucketEntry into the provided buffer.
public void startDocument() throws SAXException { if (documentHandler != null) documentHandler.startDocument(); }
Start document event.
public double manhattanDistance(final MutableDouble2D p){ final double dx=Math.abs((double)this.x - p.x); final double dy=Math.abs((double)this.y - p.y); return dx + dy; }
Returns the manhtattan distance FROM this Double2D TO the specified point
public static Socket createSocket(InetAddress address,int port) throws IOException { Socket socket=null; setKeystore(); SSLSocketFactory f=(SSLSocketFactory)SSLSocketFactory.getDefault(); SSLSocket secureSocket=(SSLSocket)f.createSocket(); secureSocket.connect(new InetSocketAddress(address,port),SysProperties.SOCKET_CONNECT_TIMEOUT); secureSocket.setEnabledProtocols(disableSSL(secureSocket.getEnabledProtocols())); if (SysProperties.ENABLE_ANONYMOUS_TLS) { String[] list=enableAnonymous(secureSocket.getEnabledCipherSuites(),secureSocket.getSupportedCipherSuites()); secureSocket.setEnabledCipherSuites(list); } socket=secureSocket; return socket; }
Create a secure client socket that is connected to the given address and port.
public static void showBlogDetail(Context context,Map<String,String> blogInfo){ Bundle args=new Bundle(); if (blogInfo != null) { for ( Map.Entry<String,String> entry : blogInfo.entrySet()) { args.putString(entry.getKey(),entry.getValue()); } } showSimpleBack(context,SimpleBackPage.DETAILS,args); }
Show Blog Details
public static int hexDigitMsb0ToInt(final char hexDigit){ switch (hexDigit) { case '0': return 0x0; case '1': return 0x8; case '2': return 0x4; case '3': return 0xC; case '4': return 0x2; case '5': return 0xA; case '6': return 0x6; case '7': return 0xE; case '8': return 0x1; case '9': return 0x9; case 'a': case 'A': return 0x5; case 'b': case 'B': return 0xD; case 'c': case 'C': return 0x3; case 'd': case 'D': return 0xB; case 'e': case 'E': return 0x7; case 'f': case 'F': return 0xF; default : throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); } }
<p> Converts a hexadecimal digit into an int using the Msb0 bit ordering. </p> <p> '1' is converted to 8 </p>
public void handleNotification(Notification notification,Object hb){ AdminDistributedSystemJmxImpl systemJmx=(AdminDistributedSystemJmxImpl)this.system; if (!systemJmx.isRmiClientCountZero()) { Helper.handleNotification(this,notification,hb); } }
Handles notification to refresh. Reacts by refreshing the values of this SystemMember's ConfigurationParamaters. Any other notification is ignored. Given notification is handled only if there is any JMX client connected to the system.
private boolean query() throws SQLException { String query="SELECT PrimaryKey, Revision, RevisionCounter," + " RevisionID, ArticleID, Timestamp, FullRevisionID, ContributorName, ContributorId, Comment, Minor, ContributorIsRegistered " + "FROM revisions"; if (primaryKey > 0) { query+=" WHERE PrimaryKey > " + primaryKey; } if (MAX_NUMBER_RESULTS > 0) { query+=" LIMIT "; if (primaryKey + MAX_NUMBER_RESULTS > endPK) { query+=(endPK - primaryKey + 1); } else { query+=MAX_NUMBER_RESULTS; } } else if (endPK != Integer.MAX_VALUE) { query+=" LIMIT " + (endPK - primaryKey + 1); } try { statement=this.connection.prepareStatement(query); result=statement.executeQuery(query); } catch ( Exception e) { logger.error("Conncection Closed: " + connection.isClosed()); logger.error("Connection Valid: " + connection.isValid(5)); connect(); statement=this.connection.prepareStatement(query); result=statement.executeQuery(query); } if (result.next()) { binaryData=result.getMetaData().getColumnType(2) == Types.LONGVARBINARY; return true; } return false; }
Sends the query to the database and stores the result. The statement and resultset connection will not be closed.
public static String encodeX(byte[] a){ if (a == null || a.length == 0) { return "X''"; } int outLen=a.length * 2 + 3; StringBuffer out=new StringBuffer(outLen); out.append('X'); out.append('\''); for (int i=0; i < a.length; i++) { out.append(xdigits[(a[i] >> 4) & 0x0F]); out.append(xdigits[a[i] & 0x0F]); } out.append('\''); return out.toString(); }
Encodes the given byte array into SQLite3 blob notation, ie X'..'
private String makeTimeText(long time,long fixedTime){ Date date=new Date(time); if (time == fixedTime) { return "|" + sdf.format(date) + "|"; } return sdf.format(date); }
Create the text for the start or end time, taking into consideration whether it's a fixed time.
private void loadAdminUsersId(String entidad) throws Exception { DynamicTable tableInfo=new DynamicTable(); DynamicRows rowsInfo=new DynamicRows(); DynamicRow rowInfo=new DynamicRow(); UsersTable usrTbl=new UsersTable(); int counter; BasicUserImpl user; String qual; DbConnection dbConn=new DbConnection(); try { dbConn.open(DBSessionManager.getSession(entidad)); tableInfo.setTableObject(usrTbl); tableInfo.setClassName(UsersTable.class.getName()); qual=usrTbl.getLoadAminUsersQual(UserDefs.PRODUCT_USER); tableInfo.setTablesMethod("getUserAdminTableNames"); tableInfo.setColumnsMethod("getAdminUserColumnNames"); rowInfo=new DynamicRow(); rowsInfo=new DynamicRows(); rowInfo.setClassName(BasicUserImpl.class.getName()); rowInfo.setValuesMethod("loadValues"); rowsInfo.add(rowInfo); DynamicFns.selectMultiple(dbConn,qual,true,tableInfo,rowsInfo); for (counter=0; counter < rowInfo.getRowCount(); counter++) { user=(BasicUserImpl)rowInfo.getRow(counter); _adminUsers.add(user); } } catch ( Exception e) { _logger.error(e); throw e; } finally { dbConn.close(); } }
Obtiene los identificadores de los usuarios suceptibles de ser administradores del grupo.
private void updateProgress(int progress){ if (myHost != null) { myHost.updateProgress(progress); } else { System.out.println("Progress: " + progress + "%"); } }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public boolean isStatic(){ return this.isDeclaredStatic(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void resume(){ engine.resume(); }
Resumes waiting "load&display" tasks
public DDistinguishedNameChooser(JFrame parent,String title,X500Name distinguishedName,boolean editable){ super(parent,title,Dialog.ModalityType.DOCUMENT_MODAL); this.distinguishedName=distinguishedName; this.editable=editable; initComponents(); }
Creates a new DDistinguishedNameChooser dialog.
public static int max(int[] list){ int max=list[list.length - 1]; int index=list.length - 1; return max(list,index,max); }
Method finds the largest number in an array
public short[] elements(){ return elements; }
Returns the elements currently stored, including invalid elements between size and capacity, if any. <b>WARNING:</b> For efficiency reasons and to keep memory usage low, <b>the array is not copied</b>. So if subsequently you modify the returned array directly via the [] operator, be sure you know what you're doing.
public boolean isCanceled(){ if (pane == null) return false; Object v=pane.getValue(); return ((v != null) && (cancelOption.length == 1) && (v.equals(cancelOption[0]))); }
Returns true if the user hits the Cancel button in the progress dialog.
@Override public void keyTyped(KeyEvent e){ synchronized (keyLock) { keysTyped.addFirst(e.getKeyChar()); } for ( DrawListener listener : listeners) listener.keyTyped(e.getKeyChar()); }
This method cannot be called directly.
public static Node selectSingleNode(Node contextNode,String str,Node namespaceNode) throws TransformerException { NodeIterator nl=selectNodeIterator(contextNode,str,namespaceNode); return nl.nextNode(); }
Use an XPath string to select a single node. XPath namespace prefixes are resolved from the namespaceNode.
private void interruptIdleWorkers(){ interruptIdleWorkers(false); }
Common form of interruptIdleWorkers, to avoid having to remember what the boolean argument means.
private void notifyDownloadCompleted(State state,int finalStatus,String errorMsg,int numFailed){ notifyThroughDatabase(state,finalStatus,errorMsg,numFailed); if (DownloadStatus.isCompleted(finalStatus)) { broadcastIntentDownloadComplete(finalStatus); } else if (DownloadStatus.isInsufficientSpace(finalStatus)) { broadcastIntentDownloadFailedInsufficientSpace(); } }
Stores information about the completed download, and notifies the initiating application.
void mergesort(Vector a,Vector b,int l,int r,XPathContext support) throws TransformerException { if ((r - l) > 0) { int m=(r + l) / 2; mergesort(a,b,l,m,support); mergesort(a,b,m + 1,r,support); int i, j, k; for (i=m; i >= l; i--) { if (i >= b.size()) b.insertElementAt(a.elementAt(i),i); else b.setElementAt(a.elementAt(i),i); } i=l; for (j=(m + 1); j <= r; j++) { if (r + m + 1 - j >= b.size()) b.insertElementAt(a.elementAt(j),r + m + 1 - j); else b.setElementAt(a.elementAt(j),r + m + 1 - j); } j=r; int compVal; for (k=l; k <= r; k++) { if (i == j) compVal=-1; else compVal=compare((NodeCompareElem)b.elementAt(i),(NodeCompareElem)b.elementAt(j),0,support); if (compVal < 0) { a.setElementAt(b.elementAt(i),k); i++; } else if (compVal > 0) { a.setElementAt(b.elementAt(j),k); j--; } } } }
This implements a standard Mergesort, as described in Robert Sedgewick's Algorithms book. This is a better sort for our purpose than the Quicksort because it maintains the original document order of the input if the order isn't changed by the sort.
public void addMenu(String category,ImageIcon icon){ int dot=category.lastIndexOf('.'); JMenu categoryMenu; if (dot == -1) { categoryMenu=makeMenuItem(category,JMenu.class); if (icon != null) { categoryMenu.setIcon(icon); } add(categoryMenu); categories.put(getCaption(category),categoryMenu); } else { String subCategory=category.substring(dot + 1); String supCategory=category.substring(0,dot); JMenu supMenu=categories.get(getCaption(supCategory)); if (supMenu == null) { throw new IllegalArgumentException("menu for category " + supCategory + " must"+ " exist before a subcategory "+ subCategory+ " can be added"); } categoryMenu=makeMenuItem(subCategory,JMenu.class); supMenu.add(categoryMenu); categories.put(getCaption(category),categoryMenu); } if (icon != null) { categoryMenu.setIcon(icon); } }
Adds a new (sub-)menu to this <tt>MenuBar</tt>. Menus can be arbitrarily nested. When a menu for a category on the n n-th (n &gt;= 1) level is added, the category string must contain n substrings, separated by '.', describing all higher categories in descending order and finally the n-th category. All submenus for the categories on the levels 1, ..., n-1 must already be present.
@Override public void updateClob(int columnIndex,Reader x,long length) throws SQLException { try { if (isDebugEnabled()) { debugCode("updateClob(" + columnIndex + ", x, "+ length+ "L);"); } checkClosed(); Value v=conn.createClob(x,length); update(columnIndex,v); } catch ( Exception e) { throw logAndConvert(e); } }
Updates a column in the current or insert row.
public ColorList addAll(Collection<TColor> collection){ colors.addAll(collection); return this; }
Adds all entries of the TColor collection to the list (shallow copy only, manipulating the new list will modify the original colors).
public RegExp anyChar(){ List<Interval> list=new ArrayList<Interval>(); list.add(new Interval(0,CharClasses.maxChar)); return new RegExp1(sym.CCLASS,list); }
Returns a regexp that matches any character: <code>[^]</code>
public void fireSessionEvent(SessionEvent event){ fireSessionEvent(event,true); }
Fires a session event. Calls the correct method on the listener for the type of session event it is. All event fired with this session support are stamped with the source object of this session support.
public DERSequence(ASN1Encodable[] array){ super(array); }
create a sequence containing an array of objects.
public Facet glitterFacet(Universe universe,Domain domain,DashboardSelection sel,Axis axis,String filter,int offset,int size,Integer timeoutMs) throws ComputingException, InterruptedException, TimeoutException { try { DomainFacetCompute compute=new DomainFacetCompute(universe); return compute.computeDimensionFacets(domain,sel,axis,filter,offset,size,timeoutMs); } catch ( ExecutionException e) { if (e.getCause() != null) { throw new ComputingException(e.getCause().getLocalizedMessage(),e.getCause()); } else { throw new ComputingException(e.getLocalizedMessage(),e); } } }
compute the facets for the given dimension
public static double min(double x,double y){ return (x < y) ? x : y; }
Get minimum of two given values
public void addObjectDetail(KMLObjectDetail objectDetail){ elements.add(objectDetail); }
Adds a KMLObjectDetail object to the composite.
public synchronized void fatal(String s,Parameter p1,Parameter p2){ println(a("FATAL ERROR:\n" + s),ALL_MESSAGE_LOGS,true); if (p1 != null) println(a("PARAMETER: " + p1),ALL_MESSAGE_LOGS,true); if (p2 != null && p1 != null) println(a(" ALSO: " + p2),ALL_MESSAGE_LOGS,true); else println(a("PARAMETER: " + p2),ALL_MESSAGE_LOGS,true); exitWithError(this,error.toString(),throwsErrors); }
Posts a fatal error. This causes the system to exit.
protected void add(Iterator shapeIterator){ while (shapeIterator.hasNext()) { try { Shape3D shape=(Shape3D)shapeIterator.next(); if (shape != null) { add(shape); } } catch ( ClassCastException cce) { continue; } } }
Add the Shape3D objects from an iterator.
public Image toImage(){ if (Image.isAlphaMutableImageSupported()) { Image img=Image.createImage(width,height,0); Graphics g=img.getGraphics(); g.drawImage(this,0,0); return img; } return null; }
Converts the icon image to an image if possible
public static void delete(File file){ if (file != null && file.exists()) { if (file.isDirectory()) { File[] children=file.listFiles(); if (children != null) { for ( File child : children) { delete(child); } } file.delete(); } else { file.delete(); } } }
delete a file
public void append(DetectorFactory factory){ if (!memberSet.contains(factory)) { throw new IllegalArgumentException("Detector " + factory.getFullName() + " appended to pass it doesn't belong to"); } this.orderedFactoryList.addLast(factory); }
Append the given DetectorFactory to the end of the ordered detector list. The factory must be a member of the pass.
public VehicleRoutingTable(int size){ super(); this.size=size; demands=new HashMap<Integer,Integer>(); depots=new HashSet<Integer>(); }
Constructs a new, empty vehicle routing table.
public StyleMap(int size){ values=new Value[size]; masks=new short[size]; }
Creates a new StyleMap.
public boolean booleanValue(){ if (value instanceof Boolean) return (Boolean)value; if (isNumber()) return longValue() != 0; if (isEmpty()) throw new ClassCastException("Variant null cannot be cast to boolean"); if (getCompositeClass().equals(String.class)) { String s=((String)getValue()).toLowerCase(); if (s.equals("true") || s.equals("1")) return true; if (s.equals("false") || s.equals("0")) return false; throw new ClassCastException("Variant String cannot be cast to boolean: " + s); } return asClass(Boolean.class,false); }
Returns the value of the specified Variant as a <code>boolean</code>
public PersistentCookieStore(Context context){ cookiePrefs=context.getSharedPreferences(COOKIE_PREFS,0); cookies=new HashMap<String,ConcurrentHashMap<String,HttpCookie>>(); Map<String,?> prefsMap=cookiePrefs.getAll(); for ( Map.Entry<String,?> entry : prefsMap.entrySet()) { if (((String)entry.getValue()) != null && !((String)entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) { String[] cookieNames=TextUtils.split((String)entry.getValue(),","); for ( String name : cookieNames) { String encodedCookie=cookiePrefs.getString(COOKIE_NAME_PREFIX + name,null); if (encodedCookie != null) { HttpCookie decodedCookie=decodeCookie(encodedCookie); if (decodedCookie != null) { if (!cookies.containsKey(entry.getKey())) cookies.put(entry.getKey(),new ConcurrentHashMap<String,HttpCookie>()); cookies.get(entry.getKey()).put(name,decodedCookie); } } } } } }
Construct a persistent cookie store.
public static DataRowReader createDataRowReader(DataRowFactory factory,Attribute[] attributes,String[][] values){ List<DataRow> dataRows=new LinkedList<DataRow>(); for (int i=0; i < values.length; i++) { dataRows.add(factory.create(values[i],attributes)); } return new ListDataRowReader(dataRows.iterator()); }
Returns a DataRowReader returning the given values.
public StrBuilder appendNull(){ if (nullText == null) { return this; } return append(nullText); }
Appends the text representing <code>null</code> to this string builder.
public void onDrawerOpened(View drawerView){ super.onDrawerOpened(drawerView); }
Called when a drawer has settled in a completely open state.
protected void initializeAllLiveAttributes(){ super.initializeAllLiveAttributes(); initializeLiveAttributes(); }
Initializes all live attributes for this element.
@SuppressWarnings("unchecked") public void writeBigDecimal(java.math.BigDecimal x) throws SQLException { attribs.add(x); }
Writes a <code>java.math.BigDecimal</code> object in the Java programming language to this <code>SQLOutputImpl</code> object. The driver converts it to an SQL <code>NUMERIC</code> before returning it to the database.
@POST @Path("/organize-imports") @Produces({MediaType.APPLICATION_JSON}) public List<ConflictImportDTO> organizeImports(@QueryParam("projectpath") String projectPath,@QueryParam("fqn") String fqn) throws NotFoundException, CoreException, BadLocationException { IJavaProject project=model.getJavaProject(projectPath); return codeAssist.organizeImports(project,fqn); }
Organizes the imports of a compilation unit.
protected String expandCollectionId(String collectionId){ assert !collectionValuesExactMatch; for ( String value : collectionValuesSet) { if (collectionId.toLowerCase().contains(value.toLowerCase())) { getLogger().debug(String.format("Changing collection ID from '%s' to '%s'.",collectionId,value)); return value; } } return collectionId; }
This method checks whether any of the specified collection values contains the given String. If it does, returns the matching value; if not, it returns the original value.