code
stringlengths
10
174k
nl
stringlengths
3
129k
public static void ensureParentFolderHierarchyExists(IFolder folder){ IContainer parent=folder.getParent(); if (parent instanceof IFolder) { ensureFolderHierarchyExists((IFolder)parent); } }
Ensures the given folder's parent hierarchy is created if they do not already exist.
private Trees(){ throw new UnsupportedOperationException(); }
Utility classes should not be instantiated.
private Element drawLine(DBIDRef iter){ SVGPath path=new SVGPath(); final SpatialComparable obj=relation.get(iter); final int dims=proj.getVisibleDimensions(); boolean drawn=false; int valid=0; double prevpos=Double.NaN; for (int i=0; i < dims; i++) { final int d=proj.getDimForAxis(i); double minPos=proj.fastProjectDataToRenderSpace(obj.getMin(d),i); if (minPos != minPos) { valid=0; continue; } ++valid; if (valid > 1) { if (valid == 2) { path.moveTo(getVisibleAxisX(d - 1),prevpos); } path.lineTo(getVisibleAxisX(d),minPos); drawn=true; } prevpos=minPos; } valid=0; for (int i=dims - 1; i >= 0; i--) { final int d=proj.getDimForAxis(i); double maxPos=proj.fastProjectDataToRenderSpace(obj.getMax(d),i); if (maxPos != maxPos) { valid=0; continue; } ++valid; if (valid > 1) { if (valid == 2) { path.moveTo(getVisibleAxisX(d + 1),prevpos); } path.lineTo(getVisibleAxisX(d),maxPos); drawn=true; } prevpos=maxPos; } if (!drawn) { return null; } return path.makeElement(svgp); }
Draw a single line.
public void testExceptionWithEmpty() throws Exception { ObjectMapper mapper=new ObjectMapper(); try { Object result=mapper.readValue(" ",Object.class); fail("Expected an exception, but got result value: " + result); } catch ( Exception e) { verifyException(e,EOFException.class,"No content"); } }
Simple test to check behavior when end-of-stream is encountered without content. Should throw EOFException.
@Override public void dropUser(User user,boolean ignore) throws SQLException { String sql=String.format("drop user %s",user.getLogin()); try { execute(sql); } catch ( SQLException e) { if (!ignore) { throw e; } else if (logger.isDebugEnabled()) { logger.debug("Drop user failed: " + sql,e); } } }
Drops user, ignoring errors if desired by caller.
public boolean loadSoundEffects(){ int attempts=3; LoadSoundEffectReply reply=new LoadSoundEffectReply(); synchronized (reply) { sendMsg(mAudioHandler,MSG_LOAD_SOUND_EFFECTS,SENDMSG_QUEUE,0,0,reply,0); while ((reply.mStatus == 1) && (attempts-- > 0)) { try { reply.wait(SOUND_EFECTS_LOAD_TIMEOUT_MS); } catch ( InterruptedException e) { Log.w(TAG,"loadSoundEffects Interrupted while waiting sound pool loaded."); } } } return (reply.mStatus == 0); }
Loads samples into the soundpool. This method must be called at first when sound effects are enabled
public static final int gcd(int p,int q){ if (q == 0) { return p; } return gcd(q,p % q); }
Computes the Greatest Common Devisor of integers p and q.
public static void sort(int[] keys,int[] values,int offset,int length){ hybridsort(keys,values,offset,offset + length - 1); }
Sorts a range from the keys in an increasing order. Elements key[i] and values[i] are always swapped together in the corresponding arrays. <p> A mixture of several sorting algorithms is used: <p> A radix sort performs better on the numeric data we sort, but requires additional storage to perform the sorting. Therefore only the not-very-large parts produced by a quick sort are sorted with radix sort. An insertion sort is used to sort the smallest arrays, where the the overhead of the radix sort is also bigger
public boolean isRegistered(ObjectName name){ return mbsInterceptor.isRegistered(name); }
Checks whether an MBean, identified by its object name, is already registered with the MBean server.
private void startItemListItem(StringBuilder result,String rootId,String itemId){ result.append("<div class=\"subtree\">"); result.append("<div class=\"alone " + itemId + "\" id=\"alone_"+ rootId+ ":"+ itemId+ "\">"); }
Called to start adding an item to an item list.
void write(ImageOutputStream ios) throws IOException { }
Writes the data for this segment to the stream in valid JPEG format.
public PatternEveryExpr(){ }
Ctor - for use to create a pattern expression tree, without pattern child expression.
private boolean tryQueueCurrentBuffer(long elapsedWaiting){ if (currentBuffer.isEmpty()) return true; if (isOpen && neverPubQueue.size() < neverPubCapacity) { neverPubQueue.add(currentBuffer); totalQueuedRecords.addAndGet(currentBuffer.sizeRecords()); totalQueuedBuffers.incrementAndGet(); onQueueBufferSuccess(currentBuffer,elapsedWaiting); currentBuffer=new RecordBuffer<>(flow); return true; } else if (elapsedWaiting > 0) { onQueueBufferTimeout(currentBuffer,elapsedWaiting); return false; } else return false; }
Keep private. Call only when holding lock.
private void writeKeysWithPrefix(String prefix,String exclude){ for ( String key : keys) { if (key.startsWith(prefix) && !key.startsWith(exclude)) { ps.println(key + "=" + prop.getProperty(key)); } } ps.println(); }
writes all keys starting with the specified prefix and not starting with the exclude prefix in alphabetical order.
public ProtocolInfo(String name,Collection<Form> connectionForms,Collection<Form> sharingProfileForms){ this.name=name; this.connectionForms=connectionForms; this.sharingProfileForms=sharingProfileForms; }
Creates a new ProtocolInfo having the given name and forms. The given collections of forms are used to describe the parameters for connections and sharing profiles respectively.
public Prepared prepare(String sql){ Prepared p=parse(sql); p.prepare(); if (currentTokenType != END) { throw getSyntaxError(); } return p; }
Parse the statement and prepare it for execution.
void analyze(boolean verbose){ if (verbose) { if (traces.length > 1) System.out.println("Combining " + traces.length + " traces."); } final Tree tree0=getTree(0); double[][] changed=new double[tree0.getNodeCount()][tree0.getNodeCount()]; double[] rateConditionalOnChange=new double[tree0.getNodeCount()]; boolean changesFound=false; cladeSet=new CladeSet(tree0); treeSet=new FrequencySet<String>(); treeSet.add(Tree.Utils.uniqueNewick(tree0,tree0.getRoot())); final int reportRate=60; for ( TreeTrace trace : traces) { final int treeCount=trace.getTreeCount(burnin * trace.getStepSize()); final double stepSize=treeCount / (double)reportRate; int counter=1; if (verbose) { System.out.println("Analyzing " + treeCount + " trees..."); System.out.println("0 25 50 75 100"); System.out.println("|--------------|--------------|--------------|--------------|"); System.out.print("*"); } for (int i=1; i < treeCount; i++) { Tree tree=trace.getTree(i,burnin * trace.getStepSize()); for (int j=0; j < tree.getNodeCount(); j++) { if (tree.getNode(j) != tree.getRoot() && tree.getNodeAttribute(tree.getNode(j),"changed") != null) { changesFound=true; final Object o=tree.getNodeAttribute(tree.getNode(j),"changed"); if (o != null) { boolean ch=getChanged(tree,j); if (ch) { rateConditionalOnChange[j]+=(Double)tree.getNodeAttribute(tree.getNode(j),"rate"); } for (int k=0; k < tree.getNodeCount(); k++) { if (tree.getNode(k) != tree.getRoot()) { changed[j][k]+=(ch && getChanged(tree,k)) ? 1 : 0; } } } } } cladeSet.add(tree); treeSet.add(Tree.Utils.uniqueNewick(tree,tree.getRoot())); if (verbose && i >= (int)Math.round(counter * stepSize) && counter <= reportRate) { System.out.print("*"); System.out.flush(); counter+=1; } } if (verbose) { System.out.println("*"); } } if (changesFound) { for (int j=0; j < tree0.getNodeCount(); j++) { System.out.println(j + "\t" + rateConditionalOnChange[j]); } System.out.println(); for (int j=0; j < tree0.getNodeCount(); j++) { for (int k=0; k < tree0.getNodeCount(); k++) { System.out.print(changed[j][k] + "\t"); } System.out.println(); } } }
Actually analyzes the trace given the burnin
public void logging(String msg1,String msg2,String msg3){ System.out.print(msg1); System.out.print(" "); System.out.print(msg2); System.out.print(" "); System.out.println(msg3); }
Prints a log message.
public void initQueryStringHandlers(){ this.transport=new SimpleTargetedChain(); this.transport.setOption("qs.list","org.apache.axis.transport.http.QSListHandler"); this.transport.setOption("qs.method","org.apache.axis.transport.http.QSMethodHandler"); this.transport.setOption("qs.wsdl","org.apache.axis.transport.http.QSWSDLHandler"); }
Initialize a Handler for the transport defined in the Axis server config. This includes optionally filling in query string handlers.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:42.071 -0500",hash_original_method="236CE70381CAE691CF8D03F3D0A7E2E8",hash_generated_method="34048EFAD324F63AAF648818713681BB") public static String toUpperCase(String string){ boolean changed=false; char[] chars=string.toCharArray(); for (int i=0; i != chars.length; i++) { char ch=chars[i]; if ('a' <= ch && 'z' >= ch) { changed=true; chars[i]=(char)(ch - 'a' + 'A'); } } if (changed) { return new String(chars); } return string; }
A locale independent version of toUpperCase.
HTMLForm(HTMLComponent htmlC,String action,String method,String encType){ this.htmlC=htmlC; this.action=htmlC.convertURL(action); this.encType=encType; if (htmlC.getHTMLCallback() != null) { int linkProps=htmlC.getHTMLCallback().getLinkProperties(htmlC,this.action); if ((linkProps & HTMLCallback.LINK_FORBIDDEN) != 0) { this.action=null; } } this.isPostMethod=((method != null) && (method.equalsIgnoreCase("post"))); }
Constructs the HTMLForm
public CurlInterceptor(Loggable logger,long limit){ this.logger=logger; this.limit=limit; }
Interceptor responsible for printing curl logs
@Override public String toString(){ return String.valueOf(value); }
Returns the String value of this mutable.
public void unRegisterImpulseConstraint(ImpulseConstraint con){ collisionResponseRows-=((ImpulseConstraint)con).GetCollisionResponseRows(); collisions.remove(con); }
Un-registers an impulse constraint with the constraint engine
Index(Node<K,V> node,Index<K,V> down,Index<K,V> right){ this.node=node; this.down=down; this.right=right; }
Creates index node with given values.
@Override public void run(){ amIActive=true; String rasterHeader=null; String distributionType=null; int numberOfClasses=-1; String statsFileName=null; int numCols, numRows; int col, row; double value; List<Double> values=new ArrayList<>(); String str; float progress=0; int index; int h; FileWriter streamWriter=null; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (int i=0; i < args.length; i++) { if (i == 0) { rasterHeader=args[i]; } else if (i == 1) { distributionType=args[i].toLowerCase(); } else if (i == 2) { if (!args[i].toLowerCase().equals("not specified")) { numberOfClasses=Integer.parseInt(args[i]); } } else if (i == 3) { statsFileName=args[i]; } } if ((rasterHeader == null) || (statsFileName == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } if ((!distributionType.equals("complete")) & (numberOfClasses <= 0)) { showFeedback("Specify the number of classes (should be a value larger then 0)."); return; } try { raster=new WhiteboxRaster(rasterHeader,"r"); numRows=raster.getNumberRows(); numCols=raster.getNumberColumns(); streamWriter=new FileWriter(statsFileName); str="Distribution type: " + distributionType + System.lineSeparator(); streamWriter.write(str); switch (distributionType) { case "complete": values=SortGridValues(raster); updateProgress("Writing output:",0); str="Value" + "\t" + "Cum. Rel. Freq."+ System.lineSeparator(); streamWriter.write(str); for (int i=0; i < values.size(); i++) { str=values.get(i) + "\t" + (((float)i + 1) / values.size())+ System.lineSeparator(); streamWriter.write(str); if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * i / (values.size() - 1)); updateProgress("Writing output:",(int)progress); } break; case "n classes with equal class width": List<Integer> distri=new ArrayList<>(); List<Double> upper=new ArrayList<>(); for (int i=1; i <= numberOfClasses; i++) { distri.add(0); upper.add(raster.getMinimumValue() + i * (raster.getMaximumValue() - raster.getMinimumValue()) / numberOfClasses); } updateProgress("Computing distribution:",0); for (row=0; row < numRows; row++) { for (col=0; col < numCols; col++) { value=raster.getValue(row,col); if (value != raster.getNoDataValue()) { h=0; while (value > upper.get(h)) { h=h + 1; } if (h <= numberOfClasses) { distri.set(h,distri.get(h) + 1); } } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (numRows - 1)); updateProgress("Computing distribution:",(int)progress); } int sum=0; float cumu; for (int i=0; i < numberOfClasses; i++) { sum=sum + distri.get(i); } updateProgress("Writing output:",0); str="Value" + "\t" + "Rel. Freq."+ "\t"+ "Cum. Rel. Freq."+ System.lineSeparator(); streamWriter.write(str); if (sum > 0) { cumu=0; for (int i=0; i < numberOfClasses; i++) { cumu=cumu + (float)distri.get(i) / sum; str=upper.get(i) + "\t" + (float)distri.get(i) / sum + "\t" + cumu + System.lineSeparator(); streamWriter.write(str); if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * i / numberOfClasses); updateProgress("Writing output:",(int)progress); } } break; case "n classes with equal class size": values=SortGridValues(raster); updateProgress("Writing output:",0); str="Cum. Rel. Freq." + "\t" + "Value"+ System.lineSeparator(); streamWriter.write(str); for (int i=1; i <= numberOfClasses; i++) { index=(int)((float)i / numberOfClasses * values.size()) - 1; if (index < 0) { index=0; } str=((float)index + 1) / values.size() + "\t" + values.get(index) + System.lineSeparator(); streamWriter.write(str); progress=(float)(100f * i / numberOfClasses); updateProgress("Writing output:",(int)progress); } break; } raster.close(); streamWriter.close(); } catch (Exception e) { showFeedback(e.getMessage()); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public boolean isInBoundsX(float x){ if (isInBoundsLeft(x) && isInBoundsRight(x)) return true; else return false; }
BELOW METHODS FOR BOUNDS CHECK
public T caseAnonymous_constraint_1_(Anonymous_constraint_1_ object){ return null; }
Returns the result of interpreting the object as an instance of '<em>Anonymous constraint 1</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
public CProjectLoaderReporter(final ListenerProvider<IProjectListener> listeners){ m_listeners=listeners; }
Creates a new reporter object.
public String[] queryUniqueIdentifiersForLuns(String arrayUniqueId) throws InvalidArgument, NotFound, InvalidSession, StorageFault, NotImplemented { final String methodName="queryUniqueIdentifiersForLuns(): "; log.info(methodName + "Entry with arrayUniqueId[" + arrayUniqueId+ "]"); sslUtil.checkHttpRequest(true,true); SOSManager sosManager=contextManager.getSOSManager(); String[] ids=sosManager.queryUniqueIdentifiersForLuns(arrayUniqueId); log.info(methodName + "Exit returning ids of size[" + ids.length+ "]"); return ids; }
Returns unique identifiers for LUNs for the give array Id
@Override public boolean onCreateOptionsMenu(Menu menu){ mOpsOptionsMenu=menu; MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.ops_options_menu,menu); return true; }
Inflates the Operations ("Ops") Option Menu.
protected PackageImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void fillAttributeSet(Set attrSet){ attrSet.add("lang"); }
Fills the given set with the attribute names found in this selector.
public void addColumn(final String columnFamily,final String columnQualifier){ Set<String> columns=this.columnFamilies.get(columnFamily); if (columns == null) { columns=new HashSet<String>(); } columns.add(columnQualifier); this.columnFamilies.put(columnFamily,columns); }
Add column family and column qualifier to be extracted from tuple
public static Field<String> ofString(String name,String description){ return new Field<>(name,String.class,description); }
Break down metrics by string. <p> Each unique string will allocate a new submetric. <b>Do not use user content as a field value</b> as field values are never reclaimed.
public OMPoint(double lat,double lon,int radius){ setRenderType(RENDERTYPE_LATLON); set(lat,lon); this.radius=radius; }
Create an OMPoint at a lat/lon position, with the specified radius.
private void saveMicroAgents(final IScope scope,final IMacroAgent agent) throws GamaRuntimeException { innerPopulations=new THashMap<String,List<SavedAgent>>(); for ( final IPopulation<? extends IAgent> microPop : agent.getMicroPopulations()) { final List<SavedAgent> savedAgents=new ArrayList<SavedAgent>(); final Iterator<? extends IAgent> it=microPop.iterator(); while (it.hasNext()) { savedAgents.add(new SavedAgent(scope,it.next())); } innerPopulations.put(microPop.getSpecies().getName(),savedAgents); } }
Recursively save micro-agents of an agent.
public GenerationResult(Shell parent,int style,IPath location,final IResource target){ super(parent,style); this.location=location; this.targetResource=target; setText("EvoSuite Result"); }
Create the dialog.
public void run(){ ActivationLibrary.deactivate(this,getID()); }
Thread to deactivate object. First attempts to make object inactive (via the inactive method). If that fails (the object may still have pending/executing calls), then unexport the object forcibly.
private static a createImageLink(String AD_Language,String name,String js_command,boolean enabled,boolean pressed){ a img=new a("#",createImage(AD_Language,name)); if (!pressed || !enabled) img.setID("imgButtonLink"); else img.setID("imgButtonPressedLink"); if (js_command == null) js_command="'Submit'"; if (js_command.length() > 0 && enabled) { if (js_command.startsWith("startPopup")) img.setOnClick(js_command); else img.setOnClick("SubmitForm('" + name + "', "+ js_command+ ",'toolbar');return false;"); } img.setClass("ToolbarButton"); img.setOnMouseOver("window.status='" + name + "';return true;"); img.setOnMouseOut("window.status='';return true;"); img.setOnBlur("this.hideFocus=false"); return img; }
Create Image with name, id of button_name and set P_Command onClick
public CassandraStatus(CassandraMode mode,boolean joined,boolean rpcRunning,boolean nativeTransportRunning,boolean gossipInitialized,boolean gossipRunning,String hostId,String endpoint,int tokenCount,String dataCenter,String rack,String version){ this.mode=mode; this.joined=joined; this.rpcRunning=rpcRunning; this.nativeTransportRunning=nativeTransportRunning; this.gossipInitialized=gossipInitialized; this.gossipRunning=gossipRunning; this.hostId=hostId; this.endpoint=endpoint; this.tokenCount=tokenCount; this.dataCenter=dataCenter; this.rack=rack; this.version=version; }
Constructs a CassandraStatus.
public void checkDataSource(Map<String,ModelEntity> modelEntities,List<String> messages,boolean addMissing) throws GenericEntityException { genericDAO.checkDb(modelEntities,messages,addMissing); }
Check the datasource to make sure the entity definitions are correct, optionally adding missing entities or fields on the server
public static HashMap<String,String> string2HashMap(String paramString){ HashMap<String,String> params=new HashMap<>(); for ( String keyValue : paramString.split(" *& *")) { String[] pairs=keyValue.split(" *= *",2); params.put(pairs[0],pairs.length == 1 ? "" : pairs[1]); } return params; }
Convert key=value type String to HashMap<String,String>
@LargeTest public void testMediaVideoItemRenderingModes() throws Exception { final String videoItemFileName=INPUT_FILE_PATH + "H263_profile0_176x144_15fps_256kbps_AACLC_32kHz_128kbps_s_0_26.3gp"; final int videoItemRenderingMode=MediaItem.RENDERING_MODE_BLACK_BORDER; boolean flagForException=false; final MediaVideoItem mediaVideoItem1=mVideoEditorHelper.createMediaItem(mVideoEditor,"mediaVideoItem1",videoItemFileName,videoItemRenderingMode); mVideoEditor.addMediaItem(mediaVideoItem1); mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_CROPPING); assertEquals("MediaVideo Item rendering Mode",MediaItem.RENDERING_MODE_CROPPING,mediaVideoItem1.getRenderingMode()); try { mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_CROPPING + 911); } catch ( IllegalArgumentException e) { flagForException=true; } assertTrue("Media Item Invalid rendering Mode",flagForException); flagForException=false; try { mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_BLACK_BORDER - 11); } catch ( IllegalArgumentException e) { flagForException=true; } assertTrue("Media Item Invalid rendering Mode",flagForException); assertEquals("MediaVideo Item rendering Mode",MediaItem.RENDERING_MODE_CROPPING,mediaVideoItem1.getRenderingMode()); mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_STRETCH); assertEquals("MediaVideo Item rendering Mode",MediaItem.RENDERING_MODE_STRETCH,mediaVideoItem1.getRenderingMode()); }
To test creation of Media Video Item with Set and Get rendering Mode
public void visitTree(JCTree tree){ }
Default member enter visitor method: do nothing
private EventLogControlPanel createControls(){ EventLogControlPanel c=new EventLogControlPanel(); c.addHeading("connections"); conUpCheck=c.addControl("up"); conDownCheck=c.addControl("down"); c.addHeading("messages"); msgCreateCheck=c.addControl("created"); msgTransferStartCheck=c.addControl("started relay"); msgRelayCheck=c.addControl("relayed"); msgDeliveredCheck=c.addControl("delivered"); msgRemoveCheck=c.addControl("removed"); msgDropCheck=c.addControl("dropped"); msgAbortCheck=c.addControl("aborted"); return c; }
Creates a control panel for the log
@Override public String type(){ return type; }
Returns the type of document to get the term vector for.
public void test_getIterator$Ljava_text_AttributedCharacterIterator$AttributeII(){ String test="Test string"; try { Map<AttributedCharacterIterator.Attribute,String> hm=new HashMap<AttributedCharacterIterator.Attribute,String>(); AttributedCharacterIterator.Attribute[] aci=new AttributedCharacterIterator.Attribute[3]; aci[0]=new TestAttributedCharacterIteratorAttribute("att1"); aci[1]=new TestAttributedCharacterIteratorAttribute("att2"); aci[2]=new TestAttributedCharacterIteratorAttribute("att3"); hm.put(aci[0],"value1"); hm.put(aci[1],"value2"); AttributedString attrString=new AttributedString(test); attrString.addAttributes(hm,2,4); AttributedCharacterIterator it=attrString.getIterator(aci,1,5); assertTrue("Incorrect iteration on AttributedString",it.getAttribute(aci[0]) == null); assertTrue("Incorrect iteration on AttributedString",it.getAttribute(aci[1]) == null); assertTrue("Incorrect iteration on AttributedString",it.getAttribute(aci[2]) == null); it.next(); assertTrue("Incorrect iteration on AttributedString",it.getAttribute(aci[0]).equals("value1")); assertTrue("Incorrect iteration on AttributedString",it.getAttribute(aci[1]).equals("value2")); assertTrue("Incorrect iteration on AttributedString",it.getAttribute(aci[2]) == null); try { attrString.getIterator(aci,-1,5); fail("IllegalArgumentException is not thrown."); } catch ( IllegalArgumentException iae) { } try { attrString.getIterator(aci,6,5); fail("IllegalArgumentException is not thrown."); } catch ( IllegalArgumentException iae) { } try { attrString.getIterator(aci,3,2); fail("IllegalArgumentException is not thrown."); } catch ( IllegalArgumentException iae) { } } catch ( Exception e) { fail("Unexpected exceptiption " + e.toString()); } }
java.text.AttributedString#getIterator(AttributedCharacterIterator.Attribute[], int, int) Test of method java.text.AttributedString#getIterator(AttributedCharacterIterator.Attribute[], int, int).
private void newplan(TransformationPlan plan){ if (plan.replaces(this.plan)) { this.plan=plan; } }
Install a new plan iff it's more drastic than the existing plan
private SmallContingencyTables buildSmallContingencyTables(){ Set<String> allLabelSet=new TreeSet<String>(); for ( SingleOutcome outcome : id2Outcome.getOutcomes()) { allLabelSet.addAll(outcome.getLabels()); } List<String> labelList=new ArrayList<String>(allLabelSet); int numberOfLabels=labelList.size(); double counterIncreaseValue=1.0; SmallContingencyTables smallContingencyTables=new SmallContingencyTables(labelList); for (int allLabelsClassId=0; allLabelsClassId < numberOfLabels; allLabelsClassId++) { for ( SingleOutcome outcome : id2Outcome.getOutcomes()) { int localClassId=outcome.getReverseLabelMapping(labelList).get(allLabelsClassId); double threshold=outcome.getBipartitionThreshold(); double goldValue; double predictionValue; if (localClassId == -1) { goldValue=0.; predictionValue=0.; } else { goldValue=outcome.getGoldstandard()[localClassId]; predictionValue=outcome.getPrediction()[localClassId]; } if (goldValue >= threshold) { if (predictionValue >= threshold) { smallContingencyTables.addTruePositives(allLabelsClassId,counterIncreaseValue); } else { smallContingencyTables.addFalseNegatives(allLabelsClassId,counterIncreaseValue); } } else { if (predictionValue >= threshold) { smallContingencyTables.addFalsePositives(allLabelsClassId,counterIncreaseValue); } else { smallContingencyTables.addTrueNegatives(allLabelsClassId,counterIncreaseValue); } } } } return smallContingencyTables; }
build small contingency tables (a small contingency table for each label) from id2Outcome
protected String doIt() throws Exception { MRfQ rfq=new MRfQ(getCtx(),p_C_RfQ_ID,get_TrxName()); if (rfq.get_ID() == 0) throw new IllegalArgumentException("No RfQ found"); log.info(rfq.toString()); MRfQResponse[] responses=rfq.getResponses(true,true); log.config("#Responses=" + responses.length); if (responses.length == 0) throw new IllegalArgumentException("No completed RfQ Responses found"); for (int i=0; i < responses.length; i++) { MRfQResponse response=responses[i]; if (!response.isSelectedWinner()) continue; MBPartner bp=new MBPartner(getCtx(),response.getC_BPartner_ID(),get_TrxName()); log.config("Winner=" + bp); MOrder order=new MOrder(getCtx(),0,get_TrxName()); order.setIsSOTrx(false); if (p_C_DocType_ID != 0) order.setC_DocTypeTarget_ID(p_C_DocType_ID); else order.setC_DocTypeTarget_ID(); order.setBPartner(bp); order.setC_BPartner_Location_ID(response.getC_BPartner_Location_ID()); order.setSalesRep_ID(rfq.getSalesRep_ID()); if (response.getDateWorkComplete() != null) order.setDatePromised(response.getDateWorkComplete()); else if (rfq.getDateWorkComplete() != null) order.setDatePromised(rfq.getDateWorkComplete()); order.saveEx(); MRfQResponseLine[] lines=response.getLines(false); for (int j=0; j < lines.length; j++) { MRfQResponseLine line=lines[j]; if (!line.isActive()) continue; MRfQResponseLineQty[] qtys=line.getQtys(false); for (int k=0; k < qtys.length; k++) { MRfQResponseLineQty qty=qtys[k]; if (qty.getRfQLineQty().isActive() && qty.getRfQLineQty().isPurchaseQty()) { MOrderLine ol=new MOrderLine(order); ol.setM_Product_ID(line.getRfQLine().getM_Product_ID(),qty.getRfQLineQty().getC_UOM_ID()); ol.setDescription(line.getDescription()); ol.setQty(qty.getRfQLineQty().getQty()); BigDecimal price=qty.getNetAmt(); ol.setPrice(); ol.setPrice(price); ol.saveEx(); } } } response.setC_Order_ID(order.getC_Order_ID()); response.saveEx(); return order.getDocumentNo(); } int noOrders=0; for (int i=0; i < responses.length; i++) { MRfQResponse response=responses[i]; MBPartner bp=null; MOrder order=null; MRfQResponseLine[] lines=response.getLines(false); for (int j=0; j < lines.length; j++) { MRfQResponseLine line=lines[j]; if (!line.isActive() || !line.isSelectedWinner()) continue; if (bp == null || bp.getC_BPartner_ID() != response.getC_BPartner_ID()) { bp=new MBPartner(getCtx(),response.getC_BPartner_ID(),get_TrxName()); order=null; } log.config("Line=" + line + ", Winner="+ bp); if (order == null) { order=new MOrder(getCtx(),0,get_TrxName()); order.setIsSOTrx(false); order.setC_DocTypeTarget_ID(); order.setBPartner(bp); order.setC_BPartner_Location_ID(response.getC_BPartner_Location_ID()); order.setSalesRep_ID(rfq.getSalesRep_ID()); order.saveEx(); noOrders++; addLog(0,null,null,order.getDocumentNo()); } MRfQResponseLineQty[] qtys=line.getQtys(false); for (int k=0; k < qtys.length; k++) { MRfQResponseLineQty qty=qtys[k]; if (qty.getRfQLineQty().isActive() && qty.getRfQLineQty().isPurchaseQty()) { MOrderLine ol=new MOrderLine(order); ol.setM_Product_ID(line.getRfQLine().getM_Product_ID(),qty.getRfQLineQty().getC_UOM_ID()); ol.setDescription(line.getDescription()); ol.setQty(qty.getRfQLineQty().getQty()); BigDecimal price=qty.getNetAmt(); ol.setPrice(); ol.setPrice(price); ol.saveEx(); } } } if (order != null) { response.setC_Order_ID(order.getC_Order_ID()); response.saveEx(); } } return "#" + noOrders; }
Process. Create purchase order(s) for the resonse(s) and lines marked as Selected Winner using the selected Purchase Quantity (in RfQ Line Quantity) . If a Response is marked as Selected Winner, all lines are created (and Selected Winner of other responses ignored). If there is no response marked as Selected Winner, the lines are used.
public String commandTopic(String command){ if (command == null) { command="+"; } return cmdTopic.replace("{COMMAND}",command); }
Get the MQTT topic for a command.
public static boolean hasExtension(String extension){ if (TextUtils.isEmpty(extension)) { return false; } return extensionToMimeTypeMap.containsKey(extension); }
Returns true if the given extension has a registered MIME type.
@Before public void onBefore(){ tut=new TransportUnitType("TUT"); loc1=new Location(new LocationPK("AREA","ASL","X","Y","Z")); loc2=new Location(new LocationPK("ARE2","ASL2","X2","Y2","Z2")); product=new Product("tttt"); entityManager.persist(product); entityManager.persist(tut); entityManager.persist(loc1); entityManager.persist(loc2); tu=new TransportUnit("TEST"); tu.setTransportUnitType(tut); tu.setActualLocation(loc1); entityManager.persist(tu); entityManager.flush(); }
Setup some test data.
public void beforeRerunningIndexCreationQuery(){ }
Asif : Called just before IndexManager executes the function rerunIndexCreationQuery. After this function gets invoked, IndexManager will iterate over all the indexes of the region making the data maps null & re running the index creation query on the region. The method of Index Manager gets executed from the clear function of the Region
public float buffered(){ return totalSize > 0 ? Futures.getUnchecked(response).cache.cacheSize() / (float)totalSize : -1; }
Returns the percentage that is buffered, or -1, if unknown
@Override public boolean accept(File dir,String name){ return accept(new File(dir,name)); }
Returns true if the file in the given directory with the given name should be accepted.
public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); }
Run just this test.
public boolean isFieldPresent(String field){ return fields.containsKey(field); }
Checks if the given field is present in this extension because not every field is mandatory (according to scim 2.0 spec).
public static String mapToStr(Map<? extends Object,? extends Object> map){ if (map == null) return null; StringBuilder buf=new StringBuilder(); boolean first=true; for ( Map.Entry<? extends Object,? extends Object> entry : map.entrySet()) { Object key=entry.getKey(); Object value=entry.getValue(); if (!(key instanceof String) || !(value instanceof String)) continue; String encodedName=null; try { encodedName=URLEncoder.encode((String)key,"UTF-8"); } catch ( UnsupportedEncodingException e) { Debug.logError(e,module); } String encodedValue=null; try { encodedValue=URLEncoder.encode((String)value,"UTF-8"); } catch ( UnsupportedEncodingException e) { Debug.logError(e,module); } if (first) first=false; else buf.append("|"); buf.append(encodedName); buf.append("="); buf.append(encodedValue); } return buf.toString(); }
Creates an encoded String from a Map of name/value pairs (MUST BE STRINGS!)
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:42.074 -0500",hash_original_method="002C3CFFC816A38E005543BB54E228FD",hash_generated_method="24D6A751F50FC61EC42FBA4D0FC608F4") public static String toLowerCase(String string){ boolean changed=false; char[] chars=string.toCharArray(); for (int i=0; i != chars.length; i++) { char ch=chars[i]; if ('A' <= ch && 'Z' >= ch) { changed=true; chars[i]=(char)(ch - 'A' + 'a'); } } if (changed) { return new String(chars); } return string; }
A locale independent version of toLowerCase.
public String numberToWords(int num){ if (num == 0) { return LESS_THAN_TWENTY[0]; } int i=0; StringBuilder res=new StringBuilder(); while (num > 0) { if (num % 1000 != 0) { res.insert(0," "); res.insert(0,THOUSANDS[i]); res.insert(0,helper(num % 1000)); } num/=1000; i++; } return res.toString().trim(); }
Math, String. Try to find the pattern first. The numbers less than 1000, e.g. xyz, can be x Hundred y"ty" z. The numbers larger than 1000, we need to add thousand or million or billion. Given a number num, we pronounce the least significant digits first. Then concat the result to the end to next three least significant digits. So the recurrence relation is: Next result of num = the pronunciation of least three digits + current result of num After that, remove those three digits from number. Stop when number is 0.
public boolean hasLat(){ return super.hasAttribute(LAT); }
Returns whether it has the Latitude.
public void test_ConstructorIF(){ HashSet hs2=new HashSet(5,(float)0.5); assertEquals("Created incorrect HashSet",0,hs2.size()); try { new HashSet(0,0); } catch ( IllegalArgumentException e) { return; } fail("Failed to throw IllegalArgumentException for initial load factor <= 0"); }
java.util.HashSet#HashSet(int, float)
private int emitCharMapArray(){ CharClasses cl=parser.getCharClasses(); if (cl.getMaxCharCode() < 256) { emitCharMapArrayUnPacked(); return 0; } intervals=cl.getIntervals(); println(""); println(" /** "); println(" * Translates characters to character classes"); println(" */"); println(" private static final String ZZ_CMAP_PACKED = "); int n=0; print(" \""); int i=0, numPairs=0; int count, value; while (i < intervals.length) { count=intervals[i].end - intervals[i].start + 1; value=colMap[intervals[i].charClass]; while (count > 0xFFFF) { printUC(0xFFFF); printUC(value); count-=0xFFFF; numPairs++; n++; } numPairs++; printUC(count); printUC(value); if (i < intervals.length - 1) { if (++n >= 10) { println("\"+"); print(" \""); n=0; } } i++; } println("\";"); println(); println(" /** "); println(" * Translates characters to character classes"); println(" */"); println(" private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);"); println(); return numPairs; }
Returns the number of elements in the packed char map array, or zero if the char map array will be not be packed. This will be more than intervals.length if the count for any of the values is more than 0xFFFF, since the number of char map array entries per value is ceil(count / 0xFFFF)
public int size(){ return mSize; }
Returns the number of key-value mappings that this SparseDoubleArray currently stores.
public void depends(int parent,int child){ dag.addNode(child); dag.addNode(parent); dag.addEdge(parent,child); }
Adds a dependency relation ship between two variables that will be in the network. The integer value corresponds the the index of the i'th categorical variable, where the class target's value is the number of categorical variables.
public DiscreteTransfer(int[] tableValues){ this.tableValues=tableValues; this.n=tableValues.length; }
The input is an int array which will be used later to construct the lut data
public static final float roundTo(float val,float prec){ return floor(val / prec + 0.5f) * prec; }
Rounds a single precision value to the given precision.
public static <K,V>List<KeyValue<K,V>> readKeyValues(String topic,Properties consumerConfig,int maxMessages){ KafkaConsumer<K,V> consumer=new KafkaConsumer<>(consumerConfig); consumer.subscribe(Collections.singletonList(topic)); int pollIntervalMs=100; int maxTotalPollTimeMs=2000; int totalPollTimeMs=0; List<KeyValue<K,V>> consumedValues=new ArrayList<>(); while (totalPollTimeMs < maxTotalPollTimeMs && continueConsuming(consumedValues.size(),maxMessages)) { totalPollTimeMs+=pollIntervalMs; ConsumerRecords<K,V> records=consumer.poll(pollIntervalMs); for ( ConsumerRecord<K,V> record : records) { consumedValues.add(new KeyValue<>(record.key(),record.value())); } } consumer.close(); return consumedValues; }
Returns up to `maxMessages` by reading via the provided consumer (the topic(s) to read from are already configured in the consumer).
private int segment(Object key){ return Math.abs(key.hashCode() % size); }
This method performs the translation of the key hash code to the segment index within the list. Translation is done by acquiring the modulus of the hash and the list size.
private void handleStateLeaving(InetAddress endpoint){ Collection<Token> tokens=getTokensFor(endpoint); if (logger.isDebugEnabled()) logger.debug("Node {} state leaving, tokens {}",endpoint,tokens); if (!tokenMetadata.isMember(endpoint)) { logger.info("Node {} state jump to leaving",endpoint); tokenMetadata.updateNormalTokens(tokens,endpoint); } else if (!tokenMetadata.getTokens(endpoint).containsAll(tokens)) { logger.warn("Node {} 'leaving' token mismatch. Long network partition?",endpoint); tokenMetadata.updateNormalTokens(tokens,endpoint); } tokenMetadata.addLeavingEndpoint(endpoint); PendingRangeCalculatorService.instance.update(); }
Handle node preparing to leave the ring
public MAttributeInstance(Properties ctx,int M_Attribute_ID,int M_AttributeSetInstance_ID,BigDecimal BDValue,String trxName){ super(ctx,0,trxName); setM_Attribute_ID(M_Attribute_ID); setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); setValueNumber(BDValue); }
Number Value Constructior
@Override public boolean supportsPositionedUpdate(){ debugCodeCall("supportsPositionedUpdate"); return true; }
Returns whether positioned updates are supported.
@SuppressWarnings("unchecked") private boolean prepareMapping(String index,Map<String,Object> defaultMappings){ boolean success=true; for ( Map.Entry<String,Object> stringObjectEntry : defaultMappings.entrySet()) { Map<String,Object> mapping=(Map<String,Object>)stringObjectEntry.getValue(); if (mapping == null) { throw new RuntimeException("type mapping not defined"); } PutMappingRequestBuilder putMappingRequestBuilder=client.admin().indices().preparePutMapping().setIndices(index); putMappingRequestBuilder.setType(stringObjectEntry.getKey()); putMappingRequestBuilder.setSource(mapping); if (log.isLoggable(Level.FINE)) { log.fine("Elasticsearch create mapping for index '" + index + " and type '"+ stringObjectEntry.getKey()+ "': "+ mapping); } PutMappingResponse resp=putMappingRequestBuilder.execute().actionGet(); if (resp.isAcknowledged()) { if (log.isLoggable(Level.FINE)) { log.fine("Elasticsearch mapping for index '" + index + " and type '"+ stringObjectEntry.getKey()+ "' was acknowledged"); } } else { success=false; log.warning("Elasticsearch mapping creation was not acknowledged for index '" + index + " and type '"+ stringObjectEntry.getKey()+ "'"); } } return success; }
This method applies the supplied mapping to the index.
public void disableOcr(){ if (!ocrDisabled) { excludeParser(TesseractOCRParser.class); ocrDisabled=true; pdfConfig.setExtractInlineImages(false); } }
Disable OCR. This method only has an effect if Tesseract is installed.
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case DatatypePackage.DICTIONARY_PROPERTY_TYPE__KEY_TYPE: return basicSetKeyType(null,msgs); case DatatypePackage.DICTIONARY_PROPERTY_TYPE__VALUE_TYPE: return basicSetValueType(null,msgs); } return super.eInverseRemove(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static void main(String[] args){ (new Am()).run(args); }
Command-line entry point.
public void removeAllHighlights(){ TextUI mapper=component.getUI(); if (getDrawsLayeredHighlights()) { int len=highlights.size(); if (len != 0) { int minX=0; int minY=0; int maxX=0; int maxY=0; int p0=-1; int p1=-1; for (int i=0; i < len; i++) { HighlightInfo hi=highlights.elementAt(i); if (hi instanceof LayeredHighlightInfo) { LayeredHighlightInfo info=(LayeredHighlightInfo)hi; minX=Math.min(minX,info.x); minY=Math.min(minY,info.y); maxX=Math.max(maxX,info.x + info.width); maxY=Math.max(maxY,info.y + info.height); } else { if (p0 == -1) { p0=hi.p0.getOffset(); p1=hi.p1.getOffset(); } else { p0=Math.min(p0,hi.p0.getOffset()); p1=Math.max(p1,hi.p1.getOffset()); } } } if (minX != maxX && minY != maxY) { component.repaint(minX,minY,maxX - minX,maxY - minY); } if (p0 != -1) { try { safeDamageRange(p0,p1); } catch ( BadLocationException e) { } } highlights.removeAllElements(); } } else if (mapper != null) { int len=highlights.size(); if (len != 0) { int p0=Integer.MAX_VALUE; int p1=0; for (int i=0; i < len; i++) { HighlightInfo info=highlights.elementAt(i); p0=Math.min(p0,info.p0.getOffset()); p1=Math.max(p1,info.p1.getOffset()); } try { safeDamageRange(p0,p1); } catch ( BadLocationException e) { } highlights.removeAllElements(); } } }
Removes all highlights.
public static void init(){ Properties p; try { p=System.getProperties(); } catch ( java.security.AccessControlException ace) { p=new Properties(); } init(p); }
Initialize debugging from the system properties.
public Builder bySecond(Integer... seconds){ return bySecond(Arrays.asList(seconds)); }
Adds one or more BYSECOND rule parts.
public CakePHP3CustomizerPanel(){ initComponents(); init(); }
Creates new form CakePHP3CustomizerPanel
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.
public char first(){ pos=0; return current(); }
Sets the position to getBeginIndex() and returns the character at that position.
@Benchmark public long test4_UsingKeySetAndForEach() throws IOException { long i=0; for ( Integer key : map.keySet()) { i+=key + map.get(key); } return i; }
4. Using keySet and foreach
@Override public void eUnset(int featureID){ switch (featureID) { case N4JSPackage.N4_FIELD_DECLARATION__DECLARED_TYPE_REF: setDeclaredTypeRef((TypeRef)null); return; case N4JSPackage.N4_FIELD_DECLARATION__BOGUS_TYPE_REF: setBogusTypeRef((TypeRef)null); return; case N4JSPackage.N4_FIELD_DECLARATION__DECLARED_NAME: setDeclaredName((LiteralOrComputedPropertyName)null); return; case N4JSPackage.N4_FIELD_DECLARATION__DEFINED_FIELD: setDefinedField((TField)null); return; case N4JSPackage.N4_FIELD_DECLARATION__EXPRESSION: setExpression((Expression)null); return; } super.eUnset(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private StringTextStore(String text){ super(); fText=text != null ? text : ""; fCopyLimit=fText.length() > SMALL_TEXT_LIMIT ? fText.length() / 2 : 0; }
Create a text store with initial content.
public static double incompleteGammaP(double a,double x){ return incompleteGamma(x,a,lnGamma(a)); }
Incomplete Gamma function P(a,x) = 1-Q(a,x) (a cleanroom implementation of Numerical Recipes gammp(a,x); in Mathematica this function is 1-GammaRegularized)
@Scheduled(fixedDelay=60000) public void controlHerdJmsMessageListener(){ try { Boolean jmsMessageListenerEnabled=Boolean.valueOf(configurationHelper.getProperty(ConfigurationValue.JMS_LISTENER_ENABLED)); JmsListenerEndpointRegistry registry=ApplicationContextHolder.getApplicationContext().getBean("org.springframework.jms.config.internalJmsListenerEndpointRegistry",JmsListenerEndpointRegistry.class); MessageListenerContainer jmsMessageListenerContainer=registry.getListenerContainer(HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING); LOGGER.debug("controlHerdJmsMessageListener(): {}={} jmsMessageListenerContainer.isRunning()={}",ConfigurationValue.JMS_LISTENER_ENABLED.getKey(),jmsMessageListenerEnabled,jmsMessageListenerContainer.isRunning()); if (!jmsMessageListenerEnabled && jmsMessageListenerContainer.isRunning()) { LOGGER.info("controlHerdJmsMessageListener(): Stopping the herd JMS message listener ..."); jmsMessageListenerContainer.stop(); LOGGER.info("controlHerdJmsMessageListener(): Done"); } else if (jmsMessageListenerEnabled && !jmsMessageListenerContainer.isRunning()) { LOGGER.info("controlHerdJmsMessageListener(): Starting the herd JMS message listener ..."); jmsMessageListenerContainer.start(); LOGGER.info("controlHerdJmsMessageListener(): Done"); } } catch ( Exception e) { LOGGER.error("controlHerdJmsMessageListener(): Failed to control the herd Jms message listener service.",e); } }
Periodically check the configuration and apply the action to the herd JMS message listener service, if needed.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-08-13 13:14:13.408 -0400",hash_original_method="FC36FCA077BB9356BFDFCA10D99D0311",hash_generated_method="2430FCC224E47ADC0C94FB89530AAC4A") public AnnotationTypeMismatchException(Method element,String foundType){ super("The annotation element " + element + " doesn't match the type "+ foundType); this.element=element; this.foundType=foundType; }
Constructs an instance for the given type element and the type found.
public void startDrag(DragGestureEvent trigger,Cursor dragCursor,Transferable transferable,DragSourceListener dsl) throws InvalidDnDOperationException { startDrag(trigger,dragCursor,null,null,transferable,dsl,null); }
Start a drag, given the <code>DragGestureEvent</code> that initiated the drag, the initial <code>Cursor</code> to use, the <code>Transferable</code> subject data of the drag, and the <code>DragSourceListener</code>. <P>
@SuppressWarnings("IfMayBeConditional") public IgniteInternalFuture<?> dynamicStartCache(@Nullable CacheConfiguration ccfg,String cacheName,@Nullable NearCacheConfiguration nearCfg,CacheType cacheType,boolean failIfExists,boolean failIfNotStarted,boolean checkThreadTx){ if (checkThreadTx) checkEmptyTransactions(); DynamicCacheDescriptor desc=registeredCaches.get(maskNull(cacheName)); DynamicCacheChangeRequest req=new DynamicCacheChangeRequest(cacheName,ctx.localNodeId()); req.failIfExists(failIfExists); if (ccfg != null) { try { cloneCheckSerializable(ccfg); } catch ( IgniteCheckedException e) { return new GridFinishedFuture<>(e); } if (desc != null) { if (failIfExists) { return new GridFinishedFuture<>(new CacheExistsException("Failed to start cache " + "(a cache with the same name is already started): " + cacheName)); } else { CacheConfiguration descCfg=desc.cacheConfiguration(); if (nearCfg != null) { if (CU.affinityNode(ctx.discovery().localNode(),descCfg.getNodeFilter())) { if (descCfg.getNearConfiguration() != null) return new GridFinishedFuture<>(); else return new GridFinishedFuture<>(new IgniteCheckedException("Failed to start near " + "cache (local node is an affinity node for cache): " + cacheName)); } else req.clientStartOnly(true); } else req.clientStartOnly(true); req.deploymentId(desc.deploymentId()); req.startCacheConfiguration(descCfg); } } else { req.deploymentId(IgniteUuid.randomUuid()); try { CacheConfiguration cfg=new CacheConfiguration(ccfg); CacheObjectContext cacheObjCtx=ctx.cacheObjects().contextForCache(cfg); initialize(false,cfg,cacheObjCtx); req.startCacheConfiguration(cfg); } catch ( IgniteCheckedException e) { return new GridFinishedFuture(e); } } } else { req.clientStartOnly(true); if (desc != null) ccfg=desc.cacheConfiguration(); if (ccfg == null) { if (failIfNotStarted) return new GridFinishedFuture<>(new CacheExistsException("Failed to start client cache " + "(a cache with the given name is not started): " + cacheName)); else return new GridFinishedFuture<>(); } req.deploymentId(desc.deploymentId()); req.startCacheConfiguration(ccfg); } if (ccfg.isSwapEnabled()) for ( ClusterNode n : ctx.discovery().allNodes()) if (!GridCacheUtils.clientNode(n) && !GridCacheUtils.isSwapEnabled(n)) return new GridFinishedFuture<>(new IgniteCheckedException("Failed to start cache " + cacheName + " with swap enabled: Remote Node with ID "+ n.id().toString().toUpperCase()+ " has not swap SPI configured")); if (nearCfg != null) req.nearCacheConfiguration(nearCfg); req.cacheType(cacheType); return F.first(initiateCacheChanges(F.asList(req),failIfExists)); }
Dynamically starts cache.
private HtmlSelectOneMenu createFieldMenu(){ HtmlSelectOneMenu field=new HtmlSelectOneMenu(); List children=field.getChildren(); children.add(createSelectItem("Subject")); children.add(createSelectItem("Sender")); children.add(createSelectItem("Date")); children.add(createSelectItem("Priority")); children.add(createSelectItem("Status")); children.add(createSelectItem("To")); children.add(createSelectItem("Cc")); children.add(createSelectItem("To or Cc")); return field; }
Creates the menu that allows the user to select a field.
public void close(){ synchronized (mDiskCacheLock) { if (mDiskLruCache != null) { try { if (!mDiskLruCache.isClosed()) { mDiskLruCache.close(); } } catch ( Throwable e) { LogUtils.e(e.getMessage(),e); } mDiskLruCache=null; } } }
Closes the disk cache associated with this ImageCache object. Note that this includes disk access so this should not be executed on the main/UI thread.
private void init(){ customElements=new CustomElementCollection(); this.setExtension(customElements); }
Common initialization code for new list entries.
public _ScheduleDays(){ super(); }
Constructs a _ScheduleDays with no flags initially set.
public int allocLow(int size,int addrAlignment){ for (MemoryChunk memoryChunk=low; memoryChunk != null; memoryChunk=memoryChunk.next) { if (memoryChunk.isAvailable(size,addrAlignment)) { return allocLow(memoryChunk,size,addrAlignment); } } return 0; }
Allocate a memory at the lowest address.
public double heapInit(){ return memory.getHeapMemoryUsage().getInit(); }
Returns the heap initial memory of the current JVM.
public final long size(){ int sum=0; for (int i=0; i < this.sets.length; i++) { sum+=this.sets[i].size(); } return sum; }
Returns the number of fingerprints in this set. Warning: The size is only accurate in single-threaded mode.
private static Location initLocation(GlowSession session,PlayerReader reader){ if (reader.hasPlayedBefore()) { Location loc=reader.getLocation(); if (loc != null) { return loc; } } return session.getServer().getWorlds().get(0).getSpawnLocation(); }
Read the location from a PlayerReader for entity initialization. Will fall back to a reasonable default rather than returning null.