code
stringlengths
10
174k
nl
stringlengths
3
129k
public static <T>T[] newSameSize(List<?> list,Class<T> cpType){ if (list == null) return create(cpType,0); else return create(cpType,list.size()); }
Creates an array with the same size as the given list. If the list is null, a zero-length array is created.
public void addPaintListener(PaintListener pl){ if (m_painters == null) { m_painters=new CopyOnWriteArrayList(); } m_painters.add(pl); }
Add a PaintListener to this Display to receive notifications about paint events.
@Override public boolean isNamed(){ return (flags & NO_NAME) == 0; }
Returns true if this method is anonymous.
public CopyOnWriteMap(){ internalMap=new HashMap<K,V>(); }
Creates a new instance of CopyOnWriteMap.
public static void runTrialParallel(int size,TrialSuite set,IPoint[] pts,IPivotIndex selector,int numThreads,int ratio){ Integer[] ar=new Integer[size]; for (int i=0, idx=0; i < pts.length; i++) { ar[idx++]=(int)(pts[i].getX() * BASE); ar[idx++]=(int)(pts[i].getY() * BASE); } MultiThreadQuickSort<Integer> qs=new MultiThreadQuickSort<Integer>(ar); qs.setPivotMethod(selector); qs.setNumberHelperThreads(numThreads); qs.setThresholdRatio(ratio); System.gc(); long start=System.currentTimeMillis(); qs.qsort(0,size - 1); long end=System.currentTimeMillis(); set.addTrial(size,start,end); for (int i=0; i < ar.length - 1; i++) { assert (ar[i] <= ar[i + 1]); } }
Change the number of helper threads inside to try different configurations. <p> Set to NUM_THREADS by default.
private void initResumableMediaRequest(GDataRequest request,MediaFileSource file,String title){ initMediaRequest(request,title); request.setHeader(GDataProtocol.Header.X_UPLOAD_CONTENT_TYPE,file.getContentType()); request.setHeader(GDataProtocol.Header.X_UPLOAD_CONTENT_LENGTH,new Long(file.getContentLength()).toString()); }
Initialize a resumable media upload request.
public static short[] toShortArray(Short[] array){ short[] result=new short[array.length]; for (int i=0; i < array.length; i++) { result[i]=array[i]; } return result; }
Coverts given shorts array to array of shorts.
public static void createTable(SQLiteDatabase db,boolean ifNotExists){ String constraint=ifNotExists ? "IF NOT EXISTS " : ""; db.execSQL("CREATE TABLE " + constraint + "'SIMPLE_ADDRESS_ITEM' ("+ "'_id' INTEGER PRIMARY KEY ,"+ "'NAME' TEXT,"+ "'ADDRESS' TEXT,"+ "'CITY' TEXT,"+ "'STATE' TEXT,"+ "'PHONE' INTEGER);"); }
Creates the underlying database table.
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case UmplePackage.ABSTRACT_METHOD_DECLARATION___METHOD_DECLARATOR_1: return ((InternalEList<?>)getMethodDeclarator_1()).basicRemove(otherEnd,msgs); } return super.eInverseRemove(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
protected void emit_N4SetterDeclaration_SemicolonKeyword_5_q(EObject semanticObject,ISynNavigable transition,List<INode> nodes){ acceptNodes(transition,nodes); }
Ambiguous syntax: ';'? This ambiguous syntax occurs at: body=Block (ambiguity) (rule end) fpar=FormalParameter ')' (ambiguity) (rule end)
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 FitsDate(String dStr) throws FitsException { if (dStr == null || dStr.isEmpty()) { return; } Matcher match=FitsDate.NORMAL_REGEX.matcher(dStr); if (match.matches()) { this.year=getInt(match,FitsDate.NEW_FORMAT_YEAR_GROUP); this.month=getInt(match,FitsDate.NEW_FORMAT_MONTH_GROUP); this.mday=getInt(match,FitsDate.NEW_FORMAT_DAY_OF_MONTH_GROUP); this.hour=getInt(match,FitsDate.NEW_FORMAT_HOUR_GROUP); this.minute=getInt(match,FitsDate.NEW_FORMAT_MINUTE_GROUP); this.second=getInt(match,FitsDate.NEW_FORMAT_SECOND_GROUP); this.millisecond=getMilliseconds(match,FitsDate.NEW_FORMAT_MILLISECOND_GROUP); } else { match=FitsDate.OLD_REGEX.matcher(dStr); if (match.matches()) { this.year=getInt(match,FitsDate.OLD_FORMAT_YEAR_GROUP) + FitsDate.YEAR_OFFSET; this.month=getInt(match,FitsDate.OLD_FORMAT_MONTH_GROUP); this.mday=getInt(match,FitsDate.OLD_FORMAT_DAY_OF_MONTH_GROUP); } else { if (dStr.trim().isEmpty()) { return; } throw new FitsException("Bad FITS date string \"" + dStr + '"'); } } }
Convert a FITS date string to a Java <CODE>Date</CODE> object.
public static <T>T fromBytes(byte[] value,Class<T> clazz){ try { Input input=new Input(new ByteArrayInputStream(value)); return clazz.cast(kryo.get().readClassAndObject(input)); } catch ( Throwable t) { LOG.error("Unable to deserialize because " + t.getMessage(),t); throw t; } }
Deserialize a profile measurement's value. The value produced by a Profile definition can be any numeric data type. The data type depends on how the profile is defined by the user. The user should be able to choose the data type that is most suitable for their use case.
public SequencesWriter(SequenceDataSource source,File outputDir,long sizeLimit,PrereadType type,boolean compressed){ this(source,outputDir,sizeLimit,null,type,compressed,null); }
Creates a writer for processing sequences from provided data source.
public HtmlPolicyBuilder allowStyling(){ allowStyling(CssSchema.DEFAULT); return this; }
Convert <code>style="&lt;CSS&gt;"</code> to sanitized CSS which allows color, font-size, type-face, and other styling using the default schema; but which does not allow content to escape its clipping context.
private PhoneUtil(){ throw new Error("Do not need instantiate!"); }
Don't let anyone instantiate this class.
@Override public void unregisterTap(Tap tap){ mTaps.remove(tap); }
Remove instrumentation tap
public boolean isNavBarTintEnabled(){ return mNavBarTintEnabled; }
Is tinting enabled for the system navigation bar?
@Override public boolean equals(Object other){ if (_map.equals(other)) { return true; } else if (other instanceof Map) { Map that=(Map)other; if (that.size() != _map.size()) { return false; } else { Iterator it=that.entrySet().iterator(); for (int i=that.size(); i-- > 0; ) { Map.Entry e=(Map.Entry)it.next(); Object key=e.getKey(); Object val=e.getValue(); if (key instanceof Float) { float k=unwrapKey(key); Object v=unwrapValue((V)val); if (_map.containsKey(k) && v == _map.get(k)) { } else { return false; } } else { return false; } } return true; } } else { return false; } }
Compares this map with another map for equality of their stored entries.
public boolean becomePrimary(boolean isRebalance){ initializationGate(); long startTime=getPartitionedRegionStats().startPrimaryTransfer(isRebalance); try { long waitTime=2000; while (!isPrimary()) { this.getAdvisee().getCancelCriterion().checkCancelInProgress(null); boolean attemptToBecomePrimary=false; boolean attemptToDeposePrimary=false; if (Thread.currentThread().isInterrupted()) { if (logger.isDebugEnabled()) { logger.debug("Breaking from becomePrimary loop due to thread interrupt flag being set"); } break; } if (isClosed() || !isHosting()) { if (logger.isDebugEnabled()) { logger.debug("Breaking from becomePrimary loop because {} is closed or not hosting",this); } break; } VolunteeringDelegate vDelegate=null; synchronized (this) { if (isVolunteering()) { if (logger.isDebugEnabled()) { logger.debug("Waiting for volunteering thread {}. Time left: {} ms",this,waitTime); } this.wait(waitTime); continue; } else if (isBecomingPrimary()) { attemptToDeposePrimary=true; } else { vDelegate=this.volunteeringDelegate; if (vDelegate == null) { vDelegate=new VolunteeringDelegate(); this.volunteeringDelegate=vDelegate; } } } if (vDelegate != null) { attemptToBecomePrimary=vDelegate.reserveForBecomePrimary(); } if (attemptToBecomePrimary) { synchronized (this) { if (this.volunteeringDelegate == null) { this.volunteeringDelegate=new VolunteeringDelegate(); } this.volunteeringDelegate.volunteerForPrimary(); attemptToDeposePrimary=true; } Thread.sleep(10); } if (attemptToDeposePrimary) { InternalDistributedMember otherPrimary=getPrimary(); if (otherPrimary != null && !getDistributionManager().getId().equals(otherPrimary)) { if (logger.isDebugEnabled()) { logger.debug("Attempting to depose primary on {} for {}",otherPrimary,this); } DeposePrimaryBucketResponse response=DeposePrimaryBucketMessage.send(otherPrimary,this.pRegion,getBucket().getId()); if (response != null) { response.waitForRepliesUninterruptibly(); if (logger.isDebugEnabled()) { logger.debug("Deposed primary on {}",otherPrimary); } } } Thread.sleep(10); } } } catch ( InterruptedException e) { Thread.currentThread().interrupt(); } finally { getPartitionedRegionStats().endPrimaryTransfer(startTime,isPrimary(),isRebalance); } return isPrimary(); }
Makes this <code>BucketAdvisor</code> become the primary if it is already a secondary.
private void declareExtensions(){ new BlogCommentFeed().declareExtensions(extProfile); new BlogFeed().declareExtensions(extProfile); new BlogPostFeed().declareExtensions(extProfile); new PostCommentFeed().declareExtensions(extProfile); }
Declare the extensions of the feeds for the Blogger service.
@Override public boolean eIsSet(int featureID){ switch (featureID) { case UmplePackage.ANONYMOUS_GEN_EXPR_2__INDEX_1: return INDEX_1_EDEFAULT == null ? index_1 != null : !INDEX_1_EDEFAULT.equals(index_1); } return super.eIsSet(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public ReferenceSequence sequence(final String name){ return mReferences.get(name); }
Get the <code>ReferenceSequence</code> selected by name.
private ChainBuilder(JFrame frame){ super(new BorderLayout()); this.frame=frame; THIS=this; JPanel customPanel=createCustomizationPanel(); JPanel presetPanel=createPresetPanel(); label=new JLabel("Click the \"Begin Generating\" button" + " to begin generating phrases",JLabel.CENTER); Border padding=BorderFactory.createEmptyBorder(20,20,5,20); customPanel.setBorder(padding); presetPanel.setBorder(padding); JTabbedPane tabbedPane=new JTabbedPane(); tabbedPane.addTab("Build your own",null,customPanel,customizationPanelDescription); tabbedPane.addTab("Presets",null,presetPanel,presetPanelDescription); add(tabbedPane,BorderLayout.CENTER); add(label,BorderLayout.PAGE_END); label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); }
Creates the GUI shown inside the frame's content pane.
public String toString(){ return this.materialPackageBO.toString(); }
A method that returns a string representation of a parsed MaterialPackage object
protected VirtualBaseTypeImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private void removeParserNotices(Parser parser){ if (noticesToHighlights != null) { RSyntaxTextAreaHighlighter h=(RSyntaxTextAreaHighlighter)textArea.getHighlighter(); for (Iterator i=noticesToHighlights.entrySet().iterator(); i.hasNext(); ) { Map.Entry entry=(Map.Entry)i.next(); ParserNotice notice=(ParserNotice)entry.getKey(); if (notice.getParser() == parser && entry.getValue() != null) { h.removeParserHighlight(entry.getValue()); i.remove(); } } } }
Removes all parser notices (and clears highlights in the editor) from a particular parser.
public TextLineDecoder(Charset charset,String delimiter){ this(charset,new LineDelimiter(delimiter)); }
Creates a new instance with the spcified <tt>charset</tt> and the specified <tt>delimiter</tt>.
@Override public void resetViewableArea(){ throw new RuntimeException("resetViewableArea called in PdfDecoderFx"); }
NOT PART OF API turns off the viewable area, scaling the page back to original scaling
private void postResults(){ this.reportTestCase.host.updateSystemInfo(false); this.trState.systemInfo=this.reportTestCase.host.getSystemInfo(); Operation factoryPost=Operation.createPost(this.remoteTestResultService).setReferer(this.reportTestCase.host.getReferer()).setBody(this.trState).setCompletion(null); this.reportTestCase.host.testStart(1); this.reportTestCase.host.sendRequest(factoryPost); try { this.reportTestCase.host.testWait(); } catch ( Throwable throwable) { throwable.printStackTrace(); } }
Send current test state to a remote server, by creating an instance for this particular run.
static void clear(Iterator<?> iterator){ checkNotNull(iterator); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } }
Clears the iterator using its remove method.
@Override public boolean isTop(BitSet fact){ return fact.get(topBit); }
Return whether or not given fact is the special TOP value.
public void eraseMap(){ if (MAP_STORE.getMap(MAP_STORE.getSelectedMapName()) == null) { return; } for ( Route r : MAP_STORE.getMap(MAP_STORE.getSelectedMapName()).getRoutes()) { eraseRoute(r); } }
Non-destructively erases all displayed content from the map display
public void doTestTransfer(int size){ Thread.setDefaultUncaughtExceptionHandler(this); long start, elapsed; int received; sendData=createDummyData(size); sendStreamSize=size; recvStream=new ByteArrayOutputStream(size); start=PseudoTCPBase.now(); startClocks(); try { connect(); } catch ( IOException ex) { fail(ex.getMessage()); } assert_Connected_wait(kConnectTimeoutMs); long transferTout=maxTransferTime(sendData.length,kMinTransferRate); boolean transfferInTime=assert_Disconnected_wait(transferTout); elapsed=PseudoTCPBase.now() - start; stopClocks(); received=recvStream.size(); assertEquals("Transfer timeout, transferred: " + received + " required: "+ sendData.length+ " elapsed: "+ elapsed+ " limit: "+ transferTout,true,transfferInTime); assertEquals(size,received); byte[] recvdArray=recvStream.toByteArray(); assertArrayEquals(sendData,recvdArray); logger.log(Level.INFO,"Transferred " + received + " bytes in "+ elapsed+ " ms ("+ (size * 8 / elapsed)+ " Kbps"); }
Transfers the data of <tt>size</tt> bytes
protected void sequence_SkillFakeDefinition(ISerializationContext context,SkillFakeDefinition semanticObject){ if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject,GamlPackage.Literals.GAML_DEFINITION__NAME) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject,GamlPackage.Literals.GAML_DEFINITION__NAME)); } SequenceFeeder feeder=createSequencerFeeder(context,semanticObject); feeder.accept(grammarAccess.getSkillFakeDefinitionAccess().getNameIDTerminalRuleCall_1_0(),semanticObject.getName()); feeder.finish(); }
Contexts: GamlDefinition returns SkillFakeDefinition SkillFakeDefinition returns SkillFakeDefinition Constraint: name=ID
public void closeDriver(){ if (camera != null) { FlashlightManager.disableFlashlight(); camera.release(); camera=null; } }
Closes the camera driver if still in use.
public void removeSecurityManager(Password password,String id) throws PageException { checkWriteAccess(); ((ConfigServerImpl)ConfigImpl.getConfigServer(config,password)).removeSecurityManager(id); Element security=_getRootElement("security"); Element[] children=XMLConfigWebFactory.getChildren(security,"accessor"); for (int i=0; i < children.length; i++) { if (id.equals(children[i].getAttribute("id"))) { security.removeChild(children[i]); } } }
remove security manager matching given id
public static void circle(double x,double y,double r){ if (r < 0) throw new IllegalArgumentException("circle radius must be nonnegative"); double xs=scaleX(x); double ys=scaleY(y); double ws=factorX(2 * r); double hs=factorY(2 * r); if (ws <= 1 && hs <= 1) pixel(x,y); else offscreen.draw(new Ellipse2D.Double(xs - ws / 2,ys - hs / 2,ws,hs)); draw(); }
Draw a circle of radius r, centered on (x, y).
@Override public void run(){ amIActive=true; String inputFile=args[0]; if (inputFile.toLowerCase().contains(".dep")) { calculateRaster(); } else if (inputFile.toLowerCase().contains(".shp")) { calculateVector(); } else { showFeedback("There was a problem reading the input file."); } }
Used to execute this plugin tool.
@SuppressWarnings({"unchecked","rawtypes"}) private static <T>T create(Class<T> cls,QName qname){ return (T)Configuration.getBuilderFactory().getBuilder(qname).buildObject(qname); }
Create object using OpenSAML's builder system.
public HttpConnection createHttpConnection(){ return new AndroidHttpConnection(); }
Create an HTTP connection
@SuppressWarnings("unchecked") private Map<Integer,float[]> parseWaveformsFromJsonFile(File waveformsFile){ Map<Integer,float[]> waveformsMap; try { waveformsMap=(Map<Integer,float[]>)parseJsonFile(waveformsFile); LOG.info("Loaded waveform images from {}",waveformsFile); } catch ( IOException exception) { waveformsMap=new HashMap<>(); LOG.error("Error loading waveform thumbnails: {}",exception.getMessage(),exception); } return waveformsMap; }
Loads the waveforms from a saved file formatted in JSON
public static final void drawShape(GL2 gl,Shape s,boolean points){ if (s instanceof Circle) { RenderUtilities.drawCircle(gl,(Circle)s,points,true); } else if (s instanceof Rectangle) { RenderUtilities.drawRectangle(gl,(Rectangle)s,points); } else if (s instanceof Polygon) { RenderUtilities.drawPolygon(gl,(Polygon)s,points); } else if (s instanceof Segment) { RenderUtilities.drawLineSegment(gl,(Segment)s,points); } else { } }
Draws the given shape.
public void write(Writer writer) throws IOException { Map<String,Object> map=new HashMap<String,Object>(); map.put("vcards",vcards); map.put("utils",new TemplateUtils()); map.put("translucentBg",readImage("translucent-bg.png",ImageType.PNG)); map.put("noProfile",readImage("no-profile.png",ImageType.PNG)); map.put("ezVCardVersion",Ezvcard.VERSION); map.put("ezVCardUrl",Ezvcard.URL); map.put("scribeIndex",new ScribeIndex()); try { template.process(map,writer); } catch ( TemplateException e) { throw new RuntimeException(e); } writer.flush(); }
Writes the HTML document to a writer.
@Override public String toString(String field){ StringBuilder buffer=new StringBuilder(); if (!getField().equals(field)) { buffer.append(getField()); buffer.append(":"); } buffer.append(includeLower ? '[' : '{'); buffer.append(lowerTerm != null ? ("*".equals(Term.toString(lowerTerm)) ? "\\*" : Term.toString(lowerTerm)) : "*"); buffer.append(" TO "); buffer.append(upperTerm != null ? ("*".equals(Term.toString(upperTerm)) ? "\\*" : Term.toString(upperTerm)) : "*"); buffer.append(includeUpper ? ']' : '}'); return buffer.toString(); }
Prints a user-readable version of this query.
public void prepare(PluginContext context) throws ReplicatorException, InterruptedException { logger.info("Import tables from " + this.uri.getPath() + " to the "+ this.getDefaultSchema()+ " schema"); tableNames=new ArrayList<String>(); columnDefinitions=new HashMap<String,ArrayList<ColumnSpec>>(); parser=new CSVParser(',','"'); File importDirectory=new File(this.uri.getPath()); if (!importDirectory.exists()) { throw new ReplicatorException("The " + this.uri.getPath() + " directory does not exist"); } for ( File f : importDirectory.listFiles()) { if (f.getName().endsWith(".def")) { this.prepareTableDefinition(f); } } if (this.tableNames.size() == 0) { throw new ReplicatorException("There are no tables to load"); } }
Prepare plug-in for use. This method is assumed to allocate all required resources. It is called before the plug-in performs any operations.
public void plot(AbstractDrawer draw){ if (!visible) return; draw.setColor(color); draw.setFont(font); draw.setBaseOffset(base_offset); draw.setTextOffset(cornerE,cornerN); draw.setTextAngle(angle); draw.drawText(label,coord); draw.setBaseOffset(null); }
see Text for formatted text output
public void testShiftRight4(){ byte aBytes[]={1,-128,56,100,-2,-76,89,45,91,3,-15,35,26}; int aSign=1; int number=45; byte rBytes[]={12,1,-61,39,-11,-94,-55}; BigInteger aNumber=new BigInteger(aSign,aBytes); BigInteger result=aNumber.shiftRight(number); byte resBytes[]=new byte[rBytes.length]; resBytes=result.toByteArray(); for (int i=0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign",1,result.signum()); }
shiftRight(int n), n > 32
public void fixStatsError(int sendCommand){ for (; this.affectedRows.length < sendCommand; ) { this.affectedRows[currentStat++]=Statement.EXECUTE_FAILED; } }
Add missing information when Exception is thrown.
public byte[] readRawBytes(final int size) throws IOException { if (size < 0) { throw InvalidProtocolBufferNanoException.negativeSize(); } if (bufferPos + size > currentLimit) { skipRawBytes(currentLimit - bufferPos); throw InvalidProtocolBufferNanoException.truncatedMessage(); } if (size <= bufferSize - bufferPos) { final byte[] bytes=new byte[size]; System.arraycopy(buffer,bufferPos,bytes,0,size); bufferPos+=size; return bytes; } else { throw InvalidProtocolBufferNanoException.truncatedMessage(); } }
Read a fixed size of bytes from the input.
private void resetToXMLSAXHandler(){ this.m_escapeSetting=true; }
Reset all of the fields owned by ToXMLSAXHandler class
public static cuComplex cuCmplx(float r,float i){ cuComplex res=new cuComplex(); res.x=r; res.y=i; return res; }
Creates a new complex number consisting of the given real and imaginary part.
public static MethodRepository make(String rawSig,GenericsFactory f){ return new MethodRepository(rawSig,f); }
Static factory method.
public void add(final T object){ mObjects.add(object); notifyItemInserted(getItemCount() - 1); }
Adds the specified object at the end of the array.
public static String compareHardware(Map<String,String> hwMap,boolean checkDisk){ String localMemSizeStr=ServerProbe.getInstance().getMemorySize(); String localCpuCoreStr=ServerProbe.getInstance().getCpuCoreNum(); hwMap.get(PropertyConstants.PROPERTY_KEY_DISK_CAPACITY); if (!localMemSizeStr.equals(hwMap.get(PropertyConstants.PROPERTY_KEY_MEMORY_SIZE))) { log.warn("Local memory {} is not the same as selected cluster {}",localMemSizeStr,hwMap.get(PropertyConstants.PROPERTY_KEY_MEMORY_SIZE)); return String.format("Local memory {%s} is not the same as selected cluster {%s}",localMemSizeStr,hwMap.get(PropertyConstants.PROPERTY_KEY_MEMORY_SIZE)); } if (!localCpuCoreStr.equals(hwMap.get(PropertyConstants.PROPERTY_KEY_CPU_CORE))) { log.warn("Local CPU core number {} is not the same as selected cluster {}",localCpuCoreStr,hwMap.get(PropertyConstants.PROPERTY_KEY_CPU_CORE)); return String.format("Local CPU core number {%s} is not the same as selected cluster {%s}",localCpuCoreStr,hwMap.get(PropertyConstants.PROPERTY_KEY_CPU_CORE)); } if (checkDisk && !hasSameDiskInfo(hwMap.get(PropertyConstants.PROPERTY_KEY_DISK),hwMap.get(PropertyConstants.PROPERTY_KEY_DISK_CAPACITY))) { log.warn("Local disk(s) are not the same as selected cluster capacity {}",hwMap.get(PropertyConstants.PROPERTY_KEY_DISK_CAPACITY)); return String.format("Local disk(s) are not the same as selected cluster capacity {%s}",hwMap.get(PropertyConstants.PROPERTY_KEY_DISK_CAPACITY)); } return null; }
Check local node hardware (i.e. Memory size, CPU core, Disk Capacity) are the same as in the input map.
public static void tearDown(SWTWorkbenchBot bot){ SwtBotUtils.print("Tear Down"); bot.resetWorkbench(); SwtBotUtils.print("Tear Down Done"); }
Performs the necessary tear down work for most SWTBot tests.
private void handleMessage(byte[] data){ Buffer buffer=new Buffer(); buffer.write(data); int type=(buffer.readShort() & 0xffff) & ~(APP_MSG_RESPONSE_BIT); if (type == BeanMessageID.SERIAL_DATA.getRawValue()) { beanListener.onSerialMessageReceived(buffer.readByteArray()); } else if (type == BeanMessageID.BT_GET_CONFIG.getRawValue()) { returnConfig(buffer); } else if (type == BeanMessageID.CC_TEMP_READ.getRawValue()) { returnTemperature(buffer); } else if (type == BeanMessageID.BL_GET_META.getRawValue()) { returnMetadata(buffer); } else if (type == BeanMessageID.BT_GET_SCRATCH.getRawValue()) { returnScratchData(buffer); } else if (type == BeanMessageID.CC_LED_READ_ALL.getRawValue()) { returnLed(buffer); } else if (type == BeanMessageID.CC_ACCEL_READ.getRawValue()) { returnAcceleration(buffer); } else if (type == BeanMessageID.CC_ACCEL_GET_RANGE.getRawValue()) { returnAccelerometerRange(buffer); } else if (type == BeanMessageID.CC_GET_AR_POWER.getRawValue()) { returnArduinoPowerState(buffer); } else if (type == BeanMessageID.BL_STATUS.getRawValue()) { try { Status status=Status.fromPayload(buffer); handleStatus(status); } catch ( NoEnumFoundException e) { Log.e(TAG,"Unable to parse status from buffer: " + buffer.toString()); e.printStackTrace(); } } else { String fourDigitHex=Integer.toHexString(type); while (fourDigitHex.length() < 4) { fourDigitHex="0" + fourDigitHex; } Log.e(TAG,"Received message of unknown type 0x" + fourDigitHex); returnError(BeanError.UNKNOWN_MESSAGE_ID); } }
Handles incoming messages from the Bean and dispatches them to the proper handlers.
public static <K,V>HashMap<K,V> newEmptyHashMap(Iterable<?> iterable){ if (iterable instanceof Collection<?>) return Maps.newHashMapWithExpectedSize(((Collection<?>)iterable).size()); return Maps.newHashMap(); }
Returns an empty map with expected size matching the iterable size if it's of type Collection. Otherwise, an empty map with the default size is returned.
public int calculateScrollY(int firstVisiblePosition,int visibleItemCount){ mFirstVisiblePosition=firstVisiblePosition; if (mReferencePosition < 0) { mReferencePosition=mFirstVisiblePosition; } if (visibleItemCount > 0) { View c=mListView.getListChildAt(0); int scrollY=-c.getTop(); mListViewItemHeights.put(firstVisiblePosition,c.getMeasuredHeight()); if (mFirstVisiblePosition >= mReferencePosition) { for (int i=mReferencePosition; i < firstVisiblePosition; ++i) { if (mListViewItemHeights.get(i) == null) { mListViewItemHeights.put(i,c.getMeasuredHeight()); } scrollY+=mListViewItemHeights.get(i); } return scrollY; } else { for (int i=mReferencePosition - 1; i >= firstVisiblePosition; --i) { if (mListViewItemHeights.get(i) == null) { mListViewItemHeights.put(i,c.getMeasuredHeight()); } scrollY-=mListViewItemHeights.get(i); } return scrollY; } } return 0; }
Call from an AbsListView.OnScrollListener to calculate the scrollY (Here we definite as the distance in pixels compared to the position representing the current date).
public DynamicRegionFactoryImpl(){ }
create an instance of the factory. This is normally only done by DynamicRegionFactory's static initialization
public DViewAsymmetricKeyFields(JDialog parent,String title,DSAPublicKey dsaPublicKey){ super(parent,title,Dialog.ModalityType.DOCUMENT_MODAL); key=dsaPublicKey; initFields(); }
Creates new DViewAsymmetricKeyFields dialog.
public void removeAllActions(CCNode target){ if (target == null) return; HashElement element=targets.get(target); if (element != null) { deleteHashElement(element); } else { } }
Removes all actions from a certain target. All the actions that belongs to the target will be removed.
private static String normalizeName(String name){ name=(name == null) ? "" : name.trim(); return name.isEmpty() ? MISSING_NAME : name; }
Normalizes a name to something OpenMRS will accept.
@Override public Object build(QueryNode queryNode) throws QueryNodeException { process(queryNode); return queryNode.getTag(QUERY_TREE_BUILDER_TAGID); }
Builds some kind of object from a query tree. Each node in the query tree is built using an specific builder associated to it.
public boolean isEnableLighting(){ return false; }
Returns false.
protected void prepare(){ ProcessInfoParameter[] para=getParameter(); for (int i=0; i < para.length; i++) { String name=para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.log(Level.SEVERE,"prepare - Unknown Parameter: " + name); } }
Prepare - e.g., get Parameters.
public void fling(int velocityX,int velocityY){ if (getChildCount() > 0) { int height=getHeight() - getPaddingBottom() - getPaddingTop(); int bottom=getChildAt(0).getHeight(); int width=getWidth() - getPaddingRight() - getPaddingLeft(); int right=getChildAt(0).getWidth(); mScroller.fling(getScrollX(),getScrollY(),velocityX,velocityY,0,right - width,0,bottom - height); final boolean movingDown=velocityY > 0; final boolean movingRight=velocityX > 0; View newFocused=findFocusableViewInMyBounds(movingRight,mScroller.getFinalX(),movingDown,mScroller.getFinalY(),findFocus()); if (newFocused == null) { newFocused=this; } if (newFocused != findFocus() && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) { mTwoDScrollViewMovedFocus=true; mTwoDScrollViewMovedFocus=false; } awakenScrollBars(mScroller.getDuration()); invalidate(); } }
Fling the scroll view
protected Socket createSocket(){ return new Socket(); }
Creates a new unconnected Socket instance. Subclasses may use this method to override the default socket implementation.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:21.616 -0500",hash_original_method="F5BF0DDF083843E14FDE0C117BAE250E",hash_generated_method="E1C3BB6772CE07721D8608A1E4D81EE1") public static int netmaskIntToPrefixLength(int netmask){ return Integer.bitCount(netmask); }
Convert a IPv4 netmask integer to a prefix length
public WritableRaster createWritableChild(int x,int y,int width,int height,int x0,int y0,int[] bandList){ if (x < this.minX) { throw new RasterFormatException("x lies outside the raster"); } if (y < this.minY) { throw new RasterFormatException("y lies outside the raster"); } if ((x + width < x) || (x + width > this.minX + this.width)) { throw new RasterFormatException("(x + width) is outside of Raster"); } if ((y + height < y) || (y + height > this.minY + this.height)) { throw new RasterFormatException("(y + height) is outside of Raster"); } SampleModel sm; if (bandList != null) sm=sampleModel.createSubsetSampleModel(bandList); else sm=sampleModel; int deltaX=x0 - x; int deltaY=y0 - y; return new ShortInterleavedRaster(sm,dataBuffer,new Rectangle(x0,y0,width,height),new Point(sampleModelTranslateX + deltaX,sampleModelTranslateY + deltaY),this); }
Creates a Writable subRaster given a region of the Raster. The x and y coordinates specify the horizontal and vertical offsets from the upper-left corner of this Raster to the upper-left corner of the subRaster. A subset of the bands of the parent Raster may be specified. If this is null, then all the bands are present in the subRaster. A translation to the subRaster may also be specified. Note that the subRaster will reference the same DataBuffers as the parent Raster, but using different offsets.
private boolean isBlockCommented(int startLine,int endLine,String[] prefixes,IDocument document){ try { for (int i=startLine; i <= endLine; i++) { IRegion line=document.getLineInformation(i); String text=document.get(line.getOffset(),line.getLength()); int[] found=TextUtilities.indexOf(prefixes,text,0); if (found[0] == -1) return false; String s=document.get(line.getOffset(),found[0]); s=s.trim(); if (s.length() != 0) return false; } return true; } catch ( BadLocationException x) { } return false; }
Determines whether each line is prefixed by one of the prefixes.
@Override public void eUnset(int featureID){ switch (featureID) { case GamlPackage.PARAMETERS__PARAMS: setParams((ExpressionList)null); return; } super.eUnset(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static void main(String[] args){ String matrixFilename=null; String coordinateFilename=null; String externalZonesFilename=null; String networkFilename=null; String plansFilename=null; Double populationFraction=null; if (args.length != 6) { throw new IllegalArgumentException("Wrong number of arguments"); } else { matrixFilename=args[0]; coordinateFilename=args[1]; externalZonesFilename=args[2]; networkFilename=args[3]; plansFilename=args[4]; populationFraction=Double.parseDouble(args[5]); } List<String> list=new ArrayList<>(); try { BufferedReader br=IOUtils.getBufferedReader(externalZonesFilename); try { String line=null; while ((line=br.readLine()) != null) { list.add(line); } } finally { br.close(); } } catch ( FileNotFoundException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } MyDemandMatrix mdm=new MyDemandMatrix(); mdm.readLocationCoordinates(coordinateFilename,2,0,1); mdm.parseMatrix(matrixFilename,"Saturn","Saturn model received for Sanral project"); Scenario sc=mdm.generateDemand(list,new Random(5463),populationFraction,"car"); NetworkReaderMatsimV1 nr=new NetworkReaderMatsimV1(sc.getNetwork()); nr.readFile(networkFilename); XY2Links xy=new XY2Links(sc.getNetwork(),null); xy.run(sc.getPopulation()); PopulationWriter pw=new PopulationWriter(sc.getPopulation(),sc.getNetwork()); pw.write(plansFilename); }
Class to generate plans files from the Saturn OD-matrices provided by Sanral's modelling consultant, Alan Robinson.
private int partition(int[] a,int left,int right){ int pivot=a[left + (right - left) / 2]; while (left <= right) { while (a[left] > pivot) left++; while (a[right] < pivot) right--; if (left <= right) { int temp=a[left]; a[left]=a[right]; a[right]=temp; left++; right--; } } return left; }
Choose mid value as pivot Move two pointers Swap and move on Return left pointer
public boolean isDone(){ return one.getHand().empty() || two.getHand().empty(); }
Returns true if either hand is empty.
public ClassNotFoundException(@Nullable String s,@Nullable Throwable ex){ super(s,null); this.ex=ex; }
Constructs a <code>ClassNotFoundException</code> with the specified detail message and optional exception that was raised while loading the class.
@Override public boolean eIsSet(int featureID){ switch (featureID) { case BasePackage.DOCUMENTED_ELEMENT__DOCUMENTATION: return DOCUMENTATION_EDEFAULT == null ? documentation != null : !DOCUMENTATION_EDEFAULT.equals(documentation); } return super.eIsSet(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
@Override public void drawRangeLine(Graphics2D g2,CategoryPlot plot,ValueAxis axis,Rectangle2D dataArea,double value,Paint paint,Stroke stroke){ Range range=axis.getRange(); if (!range.contains(value)) { return; } Rectangle2D adjusted=new Rectangle2D.Double(dataArea.getX(),dataArea.getY() + getYOffset(),dataArea.getWidth() - getXOffset(),dataArea.getHeight() - getYOffset()); Line2D line1=null; Line2D line2=null; PlotOrientation orientation=plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { double x0=axis.valueToJava2D(value,adjusted,plot.getRangeAxisEdge()); double x1=x0 + getXOffset(); double y0=dataArea.getMaxY(); double y1=y0 - getYOffset(); double y2=dataArea.getMinY(); line1=new Line2D.Double(x0,y0,x1,y1); line2=new Line2D.Double(x1,y1,x1,y2); } else if (orientation == PlotOrientation.VERTICAL) { double y0=axis.valueToJava2D(value,adjusted,plot.getRangeAxisEdge()); double y1=y0 - getYOffset(); double x0=dataArea.getMinX(); double x1=x0 + getXOffset(); double x2=dataArea.getMaxX(); line1=new Line2D.Double(x0,y0,x1,y1); line2=new Line2D.Double(x1,y1,x2,y1); } g2.setPaint(paint); g2.setStroke(stroke); g2.draw(line1); g2.draw(line2); }
Draws a line perpendicular to the range axis.
void startFading(){ mHandler.removeMessages(MSG_FADE); scheduleFade(); }
Start up the pulse to fade the screen, clearing any existing pulse to ensure that we don't have multiple pulses running at a time.
protected Connection createConnection() throws Exception { ActiveMQConnectionFactory factory=new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); return factory.createConnection(); }
Creates a connection.
protected void drawView(Graphics2D g,Rectangle r,View view,int fontHeight,int y){ float x=r.x; LayeredHighlighter h=(LayeredHighlighter)host.getHighlighter(); RSyntaxDocument document=(RSyntaxDocument)getDocument(); Element map=getElement(); int p0=view.getStartOffset(); int lineNumber=map.getElementIndex(p0); int p1=view.getEndOffset(); setSegment(p0,p1 - 1,document,drawSeg); int start=p0 - drawSeg.offset; Token token=document.getTokenListForLine(lineNumber); if (token != null && token.type == Token.NULL) { h.paintLayeredHighlights(g,p0,p1,r,host,this); return; } while (token != null && token.isPaintable()) { int p=calculateBreakPosition(p0,token,x); x=r.x; h.paintLayeredHighlights(g,p0,p,r,host,this); while (token != null && token.isPaintable() && token.offset + token.textCount - 1 < p) { x=token.paint(g,x,y,host,this); token=token.getNextToken(); } if (token != null && token.isPaintable() && token.offset < p) { int tokenOffset=token.offset; Token temp=new DefaultToken(drawSeg,tokenOffset - start,p - 1 - start,tokenOffset,token.type); temp.paint(g,x,y,host,this); temp=null; token.makeStartAt(p); } p0=(p == p0) ? p1 : p; y+=fontHeight; } if (host.getEOLMarkersVisible()) { g.setColor(host.getForegroundForTokenType(Token.WHITESPACE)); g.setFont(host.getFontForTokenType(Token.WHITESPACE)); g.drawString("\u00B6",x,y - fontHeight); } }
Draws a single view (i.e., a line of text for a wrapped view), wrapping the text onto multiple lines if necessary.
@Override public boolean containsKey(Object key){ if (key == null) { key=NULL_OBJECT; } int index=findIndex(key,elementData); return elementData[index] == key; }
Returns whether this map contains the specified key.
public boolean autoCorrectText(){ return preferences.getBoolean(resources.getString(R.string.key_autocorrect_text),Boolean.parseBoolean(resources.getString(R.string.default_autocorrect_text))); }
Whether message text should be autocorrected.
protected void removeNode(int id) throws Exception { int idx; FolderTokenDocTreeNode node=null; idx=findIndexById(id); if (idx == -1) { throw new IeciTdException(FolderBaseError.EC_NOT_FOUND,FolderBaseError.EM_NOT_FOUND); } node=(FolderTokenDocTreeNode)m_nodes.get(idx); if (node.isNew()) m_nodes.remove(idx); else node.setEditFlag(FolderEditFlag.REMOVE); }
Elimina de la lista de nodos el nodo con el id especificado
public void deleteAttributes(int[] columnIndices){ ((ArffTableModel)getModel()).deleteAttributes(columnIndices); }
deletes the attributes at the given indices
public void onSuccess(int statusCode,Header[] headers,JSONObject response){ Log.w(LOG_TAG,"onSuccess(int, Header[], JSONObject) was not overriden, but callback was received"); }
Returns when request succeeds
public int lastIndexOfFromTo(byte element,int from,int to){ if (size == 0) return -1; checkRangeFromTo(from,to,size); byte[] theElements=elements; for (int i=to; i >= from; i--) { if (element == theElements[i]) { return i; } } return -1; }
Returns the index of the last occurrence of the specified element. Returns <code>-1</code> if the receiver does not contain this element. Searches beginning at <code>to</code>, inclusive until <code>from</code>, inclusive. Tests for identity.
public void put(final long key){ if (key == FREE_KEY) { m_hasFreeKey=true; return; } int ptr=(int)((Tools.phiMix(key) & m_mask)); long e=m_data[ptr]; if (e == FREE_KEY) { m_data[ptr]=key; if (m_size >= m_threshold) { rehash(m_data.length * 2); } else { ++m_size; } return; } else if (e == key) { return; } while (true) { ptr=(int)((ptr + 1) & m_mask); e=m_data[ptr]; if (e == FREE_KEY) { m_data[ptr]=key; if (m_size >= m_threshold) { rehash(m_data.length * 2); } else { ++m_size; } return; } else if (e == key) { return; } } }
Add a single element to the map
public PredictiveInfoCalculatorKraskov(String calculatorName) throws InstantiationException, IllegalAccessException, ClassNotFoundException { super(calculatorName); if (!calculatorName.equalsIgnoreCase(MI_CALCULATOR_KRASKOV1) && !calculatorName.equalsIgnoreCase(MI_CALCULATOR_KRASKOV2)) { throw new ClassNotFoundException("Must be an underlying Kraskov-Grassberger calculator"); } }
Creates a new instance of the Kraskov-Stoegbauer-Grassberger estimator for PI, with the supplied MI calculator name.
public DefaultDirectAdjacentSelector(short type,Selector parent,SimpleSelector simple){ super(type,parent,simple); }
Creates a new DefaultDirectAdjacentSelector object.
@Inline public void postCopy(ObjectReference object,boolean majorGC){ initializeHeader(object,false); if (!HEADER_MARK_BITS) { testAndSetLiveBit(object); } }
Perform any required post copy (i.e. in-GC allocation) initialization. This is relevant (for example) when MS is used as the mature space in a copying GC.
public static LinkedHashMap<Pattern,String> parseRulesFile(InputStream is){ LinkedHashMap<Pattern,String> rules=new LinkedHashMap<>(); BufferedReader br=new BufferedReader(IOUtils.getDecodingReader(is,StandardCharsets.UTF_8)); String line; try { int linenum=0; while ((line=br.readLine()) != null) { linenum++; String[] arr=line.split("#"); if (arr.length > 0) line=arr[0].trim(); if (line.length() == 0) continue; int sep=line.indexOf("="); if (sep <= 0) { log.warn("Wrong format of password line " + linenum); continue; } String pass=line.substring(sep + 1).trim(); String regex=line.substring(0,sep).trim(); try { Pattern pattern=Pattern.compile(regex); rules.put(pattern,pass); } catch ( PatternSyntaxException pse) { log.warn("Key of line " + linenum + " was not a valid regex pattern",pse); continue; } } is.close(); } catch ( IOException e) { throw new RuntimeException(e); } return rules; }
Parses rule file from stream and returns a Map of all rules found
public boolean isItemForce(){ return true; }
Returns true.
public Builder document(InputStream document,String mediaType){ documentInputStream=document; this.mediaType=mediaType; return this; }
Sets the document as an input stream and its media type.
public final String toString(){ StringBuffer text=new StringBuffer(); text.append("Print statistic values of instances (" + first + "-"+ last+ "\n"); text.append(" Number of instances:\t" + numInstances + "\n"); text.append(" NUmber of instances with unknowns:\t" + missingInstances + "\n"); text.append(" Attribute:\t\t\t:" + attr + "\n"); text.append(" Sum:\t\t\t" + sum + "\n"); text.append(" Squared sum:\t\t" + sqrSum + "\n"); text.append(" Stanard Deviation:\t\t" + sd + "\n"); return text.toString(); }
Converts the stats to a string
private void scanAndLock(Object key,int hash){ HashEntry<K,V> first=entryForHash(this,hash); HashEntry<K,V> e=first; int retries=-1; while (!tryLock()) { HashEntry<K,V> f; if (retries < 0) { if (e == null || key.equals(e.key)) retries=0; else e=e.next; } else if (++retries > MAX_SCAN_RETRIES) { lock(); break; } else if ((retries & 1) == 0 && (f=entryForHash(this,hash)) != first) { e=first=f; retries=-1; } } }
Scans for a node containing the given key while trying to acquire lock for a remove or replace operation. Upon return, guarantees that lock is held. Note that we must lock even if the key is not found, to ensure sequential consistency of updates.
public IntentBuilder oldColor(int oldColor){ mOldColor=oldColor; return this; }
Sets the old color to show on the bottom "Cancel" half circle, and also the initial value for the picked color. The default value is black.
public void __setDaoSession(DaoSession daoSession){ this.daoSession=daoSession; myDao=daoSession != null ? daoSession.getUserDBDao() : null; }
called by internal mechanisms, do not call yourself.
@Override public boolean equals(Object obj){ if (obj == this) { return true; } if (!(obj instanceof TimeTableXYDataset)) { return false; } TimeTableXYDataset that=(TimeTableXYDataset)obj; if (this.domainIsPointsInTime != that.domainIsPointsInTime) { return false; } if (this.xPosition != that.xPosition) { return false; } if (!this.workingCalendar.getTimeZone().equals(that.workingCalendar.getTimeZone())) { return false; } if (!this.values.equals(that.values)) { return false; } return true; }
Tests this dataset for equality with an arbitrary object.
private void startContext(CrawlJob crawlJob){ LOGGER.debug("Starting context"); PathSharingContext ac=crawlJob.getJobContext(); ac.addApplicationListener(this); try { ac.start(); } catch ( BeansException be) { LOGGER.warn(be.getMessage()); ac.close(); } catch ( Exception e) { LOGGER.warn(e.getMessage()); try { ac.close(); } catch ( Exception e2) { e2.printStackTrace(System.err); } finally { } } LOGGER.debug("Context started"); }
Start the context, catching and reporting any BeansExceptions.