code
stringlengths
10
174k
nl
stringlengths
3
129k
@Override public void close(){ try { super.close(); if (!emptyPages.isEmpty() && header instanceof TreeIndexHeader) { ((TreeIndexHeader)header).writeEmptyPages(emptyPages,file); } ((TreeIndexHeader)header).setLargestPageID(nextPageID); header.writeHeader(file); file.close(); } catch ( IOException e) { throw new RuntimeException(e); } }
Closes this file.
@Override public String toString(){ return buf.toString(); }
Gets a copy of the contents of this writer as a string.
public void endEntity(String name) throws org.xml.sax.SAXException { }
Report the end of an entity.
public void runTest() throws Throwable { Document doc; NodeList elementList; Node nameNode; CharacterData child; String badString; doc=(Document)load("staff",false); elementList=doc.getElementsByTagName("address"); nameNode=elementList.item(0); child=(CharacterData)nameNode.getFirstChild(); { boolean success=false; try { badString=child.substringData(-5,3); } catch ( DOMException ex) { success=(ex.code == DOMException.INDEX_SIZE_ERR); } assertTrue("throws_INDEX_SIZE_ERR",success); } }
Runs the test case.
public void stateChanged(ChangeEvent e){ int index=tabbedPane.getSelectedIndex(); genForm.setSelectionActive(index == 0); }
Change Listener (Tab changed)
public String toString(){ StringBuffer sb=new StringBuffer("MInterestArea[").append(get_ID()).append(" - ").append(getName()).append("]"); return sb.toString(); }
String representation
public static PcRunner serializableInstance(){ return PcRunner.serializableInstance(); }
Generates a simple exemplar of this class to test serialization.
public int addItemToEnd(String productId,BigDecimal amount,BigDecimal quantity,BigDecimal unitPrice,Timestamp reservStart,BigDecimal reservLength,BigDecimal reservPersonsDbl,String accommodationMapId,String accommodationSpotId,HashMap<String,GenericValue> features,HashMap<String,Object> attributes,String prodCatalogId,ProductConfigWrapper configWrapper,String itemType,LocalDispatcher dispatcher,Boolean triggerExternalOps,Boolean triggerPriceRules,Boolean skipInventoryChecks,Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { return addItemToEnd(ShoppingCartItem.makeItem(null,productId,amount,quantity,unitPrice,reservStart,reservLength,reservPersonsDbl,accommodationMapId,accommodationSpotId,null,null,features,attributes,prodCatalogId,configWrapper,itemType,null,dispatcher,this,triggerExternalOps,triggerPriceRules,null,skipInventoryChecks,skipProductChecks)); }
Add an accommodation(rental/aggregated)item to the shopping cart.
private JsonObject broadlinkExecuteCommand(JsonObject params){ if (mBlNetwork == null) { Log.e(this.getClass().getSimpleName(),"mBlNetwork is uninitialized, check app permissions"); return null; } String responseString=mBlNetwork.requestDispatch(params.toString()); JsonObject responseJsonObject=new JsonParser().parse(responseString).getAsJsonObject(); Log.d(this.getClass().getSimpleName(),responseString); return responseJsonObject; }
Execute a Broadlink API with the given parameters
public static PcRunner serializableInstance(){ return PcRunner.serializableInstance(); }
Generates a simple exemplar of this class to test serialization.
boolean containsNode(Node check){ if (this.nodes != null) { return nodes.contains(check); } else { return false; } }
Safely checks to see if the provided Node participates in the PartitionedRegion return true if the Node participates in the PartitionedRegion
public void skippedEntity(String name) throws SAXException { }
Adapt a SAX2 skipped entity event.
private ValueBuffer combineChunks(final LinkedList<ValueBuffer> coll){ final ValueBuffer b; if (coll.size() == 1) { b=coll.getFirst(); } else { int nvalues=0; for ( ValueBuffer t : coll) nvalues+=t.nvalues; final List<IMemoryManager> contexts=new LinkedList<IMemoryManager>(); final LinkedHashMap<byte[],Bucket> addrMap=new LinkedHashMap<byte[],Bucket>(); for ( ValueBuffer t : coll) { contexts.addAll(t.contexts); nvalues+=t.nvalues; for ( Bucket bucket : t.addrMap.values()) { final Bucket tmp=addrMap.get(bucket.key); if (tmp == null) { addrMap.put(bucket.key,bucket); } else { tmp.addrs.addAll(bucket.addrs); } } } b=new ValueBuffer(contexts,nvalues,addrMap); } return b; }
Combine chunks from the queue into a single chunk.
public void resetToCheckpoint(){ if (checkPoint != -1) { current_item=checkPoint; } checkPoint=-1; }
used to store end of PDF components
void addParsedQuery(ParserRuleContext currentContext,Query<O> parsedQuery){ ParserRuleContext parentContext=getParentContextOfType(currentContext,getAndOrNotContextClasses()); Collection<Query<O>> childrenOfParent=this.childQueries.get(parentContext); if (childrenOfParent == null) { childrenOfParent=new ArrayList<Query<O>>(); this.childQueries.put(parentContext,childrenOfParent); } childrenOfParent.add(parsedQuery); numQueriesParsed++; }
Adds the given query to a list of child queries which have not yet been wrapped in a parent query.
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:02.455 -0500",hash_original_method="A486C536CC2BBF7E5EE5092C736031C8",hash_generated_method="70FFFC2D075451B0F1CD7FCCB9EFC19E") private Combined(){ }
This utility class cannot be instantiated
public DeclutterMatrix(int width,int height,int x_pix_interval,int y_pix_interval){ this.width=width; this.height=height; if (x_pix_interval != 0) { this.x_pix_interval=x_pix_interval; } else { x_pix_interval=1; } if (y_pix_interval != 0) { this.y_pix_interval=y_pix_interval; } else { y_pix_interval=1; } this.matrix=null; this.maxx=(this.width / this.x_pix_interval) - 1; this.maxy=(this.height / this.y_pix_interval) - 1; create(); Debug.message("declutter","Decluttering matrix created." + " Width = " + width + " Height = "+ height); }
Construct a new DeclutterMatrix, given the screen dimensions and the size of the matrix cells
private DSSUtils(){ }
This class is an utility class and cannot be instantiated.
public void testRead(){ int count=1024; byte[] wData=getWData(count); ByteFifoBuffer instance=new ByteFifoBuffer(count); instance.write(wData,count); byte[] readBuff=new byte[count]; int expResult=count; int result=instance.read(readBuff,count); assertEquals(expResult,result); assertArrayEquals(wData,readBuff); }
Test of Read method, of class ByteFifoBuffer.
public static int hashIntArray(int[] array){ int intHash=0; for (int i=0; i < array.length && i < 4; i++) { intHash+=array[i] << (8 * i); } return intHash & 0x7FFFFFFF; }
Returns hash code for array of integers
public RepositoryStateMachinePersist(StateMachineContextRepository<S,E,StateMachineContext<S,E>> repository){ this.repository=repository; }
Instantiates a new repository state machine persist.
public void addOffset(int off){ prep(SIZEOF_INT,0); assert off <= offset(); off=offset() - off + SIZEOF_INT; putInt(off); }
Adds on offset, relative to where it will be written.
public MysqlPooledConnection(com.mysql.jdbc.Connection connection){ this.logicalHandle=null; this.physicalConn=connection; this.connectionEventListeners=new HashMap<ConnectionEventListener,ConnectionEventListener>(); this.exceptionInterceptor=this.physicalConn.getExceptionInterceptor(); }
Construct a new MysqlPooledConnection and set instance variables
@Override public RabbitGroup makeNewGroup(String name){ return groupRepository.insert(new RabbitGroup(name)); }
Make new rabbit group
public boolean hasStatement(Resource subj,IRI pred,Value obj,Resource... contexts) throws RepositoryException { if (isAllContext(contexts)) { return super.hasStatement(subj,pred,obj,isIncludeInferred(),getReadContexts()); } else { return super.hasStatement(subj,pred,obj,isIncludeInferred(),contexts); } }
Checks whether the repository contains statements with a specific subject, predicate and/or object, optionally in the specified contexts.
public ImageInfo withSize(int cols,int rows){ return new ImageInfo(cols > 0 ? cols : this.cols,rows > 0 ? rows : this.rows,this.bitDepth,this.alpha,this.greyscale,this.indexed); }
returns a copy with different size
public CannotFindMethodException(SpecialInvokeExpr invoke,SootMethod method){ super(String.format("Cannot find or resolve %s in %s.",invoke,method)); }
Create new exception for a special invoke.
private ManagedObjectReference createVm() throws Exception { ManagedObjectReference folder=getVmFolder(); ManagedObjectReference resourcePool=getResourcePoolForVm(); ManagedObjectReference datastore=getDatastore(); String datastoreName=this.get.entityProp(datastore,"name"); VirtualMachineConfigSpec spec=buildVirtualMachineConfigSpec(datastoreName); populateCloudConfig(spec); ManagedObjectReference vmTask=getVimPort().createVMTask(folder,spec,resourcePool,null); TaskInfo info=waitTaskEnd(vmTask); if (info.getState() == TaskInfoState.ERROR) { MethodFault fault=info.getError().getFault(); if (fault instanceof FileAlreadyExists) { return null; } else { return VimUtils.rethrow(info.getError()); } } return (ManagedObjectReference)info.getResult(); }
Creates a VM in vsphere. This method will block until the CreateVM_Task completes. The path to the .vmx file is explicitly set and its existence is iterpreted as if the VM has been successfully created and returns null.
protected void cleanup(){ ArrayList<Long> deleteList; long valueReplace; synchronized (this) { if (incrementRecords.size() <= FLUSH_COUNTER) { return; } valueReplace=value.get(); deleteList=new ArrayList<>(incrementRecords); incrementRecords.clear(); } long newRecordID=-1; long txCleanup=storage.generateID(); try { for ( Long value1 : deleteList) { storage.deleteIncrementRecord(txCleanup,value1); } if (recordID >= 0) { storage.deletePageCounter(txCleanup,recordID); } newRecordID=storage.storePageCounter(txCleanup,subscriptionID,valueReplace); if (logger.isTraceEnabled()) { logger.trace("Replacing page-counter record = " + recordID + " by record = "+ newRecordID+ " on subscriptionID = "+ this.subscriptionID+ " for queue = "+ this.subscription.getQueue().getName()); } storage.commit(txCleanup); } catch ( Exception e) { newRecordID=recordID; ActiveMQServerLogger.LOGGER.problemCleaningPagesubscriptionCounter(e); try { storage.rollback(txCleanup); } catch ( Exception ignored) { } } finally { recordID=newRecordID; } }
This method should always be called from a single threaded executor
public void performCirculize(Way way){ if (way.getNodes().size() < 3) return; createCheckpoint(R.string.undo_action_circulize); int[] center=centroid(map.getWidth(),map.getHeight(),viewBox,way); getDelegator().circulizeWay(center,way); map.invalidate(); }
Arrange way points in a circle
public static String executeCommand(List<String> cmdArray) throws IOException, InterruptedException { ProcessBuilder builder=new ProcessBuilder(cmdArray); builder.redirectErrorStream(true); Process process=builder.start(); try (InputStream is=process.getInputStream();Scanner scanner=new Scanner(is).useDelimiter("$")){ String output=scanner.hasNext() ? scanner.next() : ""; process.waitFor(); int exitValue=process.exitValue(); if (exitValue != 0) { throw new IllegalArgumentException(String.format("Command execution failed with status: %d\n%s",exitValue,output)); } return output; } }
Execute a command and return all the output.
public ExpressionException(ExpressionParsingException cause){ super(cause.getMessage(),cause); if (cause.getErrorContext() != null) { errorLine=cause.getErrorContext().getStart().getLine(); } else { errorLine=-1; } }
Creates an ExpressionException with the cause, associated error message and unknown line for where the error happened.
public static IntervalCategoryDataset createDataset(){ TaskSeries s1=new TaskSeries("Scheduled"); s1.add(new Task("Write Proposal",new SimpleTimePeriod(date(1,Calendar.APRIL,2001),date(5,Calendar.APRIL,2001)))); s1.add(new Task("Obtain Approval",new SimpleTimePeriod(date(9,Calendar.APRIL,2001),date(9,Calendar.APRIL,2001)))); s1.add(new Task("Requirements Analysis",new SimpleTimePeriod(date(10,Calendar.APRIL,2001),date(5,Calendar.MAY,2001)))); s1.add(new Task("Design Phase",new SimpleTimePeriod(date(6,Calendar.MAY,2001),date(30,Calendar.MAY,2001)))); s1.add(new Task("Design Signoff",new SimpleTimePeriod(date(2,Calendar.JUNE,2001),date(2,Calendar.JUNE,2001)))); s1.add(new Task("Alpha Implementation",new SimpleTimePeriod(date(3,Calendar.JUNE,2001),date(31,Calendar.JULY,2001)))); s1.add(new Task("Design Review",new SimpleTimePeriod(date(1,Calendar.AUGUST,2001),date(8,Calendar.AUGUST,2001)))); s1.add(new Task("Revised Design Signoff",new SimpleTimePeriod(date(10,Calendar.AUGUST,2001),date(10,Calendar.AUGUST,2001)))); s1.add(new Task("Beta Implementation",new SimpleTimePeriod(date(12,Calendar.AUGUST,2001),date(12,Calendar.SEPTEMBER,2001)))); s1.add(new Task("Testing",new SimpleTimePeriod(date(13,Calendar.SEPTEMBER,2001),date(31,Calendar.OCTOBER,2001)))); s1.add(new Task("Final Implementation",new SimpleTimePeriod(date(1,Calendar.NOVEMBER,2001),date(15,Calendar.NOVEMBER,2001)))); s1.add(new Task("Signoff",new SimpleTimePeriod(date(28,Calendar.NOVEMBER,2001),date(30,Calendar.NOVEMBER,2001)))); TaskSeries s2=new TaskSeries("Actual"); s2.add(new Task("Write Proposal",new SimpleTimePeriod(date(1,Calendar.APRIL,2001),date(5,Calendar.APRIL,2001)))); s2.add(new Task("Obtain Approval",new SimpleTimePeriod(date(9,Calendar.APRIL,2001),date(9,Calendar.APRIL,2001)))); s2.add(new Task("Requirements Analysis",new SimpleTimePeriod(date(10,Calendar.APRIL,2001),date(15,Calendar.MAY,2001)))); s2.add(new Task("Design Phase",new SimpleTimePeriod(date(15,Calendar.MAY,2001),date(17,Calendar.JUNE,2001)))); s2.add(new Task("Design Signoff",new SimpleTimePeriod(date(30,Calendar.JUNE,2001),date(30,Calendar.JUNE,2001)))); s2.add(new Task("Alpha Implementation",new SimpleTimePeriod(date(1,Calendar.JULY,2001),date(12,Calendar.SEPTEMBER,2001)))); s2.add(new Task("Design Review",new SimpleTimePeriod(date(12,Calendar.SEPTEMBER,2001),date(22,Calendar.SEPTEMBER,2001)))); s2.add(new Task("Revised Design Signoff",new SimpleTimePeriod(date(25,Calendar.SEPTEMBER,2001),date(27,Calendar.SEPTEMBER,2001)))); s2.add(new Task("Beta Implementation",new SimpleTimePeriod(date(27,Calendar.SEPTEMBER,2001),date(30,Calendar.OCTOBER,2001)))); s2.add(new Task("Testing",new SimpleTimePeriod(date(31,Calendar.OCTOBER,2001),date(17,Calendar.NOVEMBER,2001)))); s2.add(new Task("Final Implementation",new SimpleTimePeriod(date(18,Calendar.NOVEMBER,2001),date(5,Calendar.DECEMBER,2001)))); s2.add(new Task("Signoff",new SimpleTimePeriod(date(10,Calendar.DECEMBER,2001),date(11,Calendar.DECEMBER,2001)))); TaskSeriesCollection collection=new TaskSeriesCollection(); collection.add(s1); collection.add(s2); return collection; }
Creates a sample dataset for a Gantt chart.
public Iterator<Bucket> buckets(){ return map.values().iterator(); }
Visit all buckets in the hash index.
public JsonObjectRequest(String url,Listener<JSONObject> listener,ErrorListener errorListener){ super(Method.GET,url,null,listener,errorListener); }
Creates a new request.
@Override public void render(final int text_fill_type,final Graphics2D g2,final float scaling,final boolean isFormGlyph){ if (cached_current_path != null) { final GeneralPath[] paths=cached_current_path.get(); for ( final GeneralPath path : paths) { if (path == null) { break; } if ((text_fill_type == GraphicsState.FILL)) { if (isStroked) { final Paint fillPaint=g2.getPaint(); if (!(fillPaint instanceof PdfTexturePaint) && ((Color)strokePaint).getRGB() != ((Color)fillPaint).getRGB() && strokedPositions.containsKey(String.valueOf((int)g2.getTransform().getTranslateX()) + '-' + (int)g2.getTransform().getTranslateY())) { g2.setPaint(strokePaint); g2.draw(path); g2.setPaint(fillPaint); } } g2.fill(path); } if (text_fill_type == GraphicsState.STROKE) { g2.draw(path); strokePaint=g2.getPaint(); strokedPositions.put(String.valueOf((int)g2.getTransform().getTranslateX()) + '-' + (int)g2.getTransform().getTranslateY(),"x"); } } } }
turn shape commands into a Shape object, storing info for later. Has to be done this way because we need the winding rule to initialise the shape in Java, and it could be set awywhere in the command stream
public Bindings add(String property,JComboBox combo){ combo.addActionListener(this); return add(new JComboBoxBinding(property,combo,0)); }
Handles JComboBox
public AsyncHttpClient(boolean fixNoHttpResponseException,int httpPort,int httpsPort){ this(getDefaultSchemeRegistry(fixNoHttpResponseException,httpPort,httpsPort)); }
Creates new AsyncHttpClient using given params
protected void selectRenderables(DrawContext dc){ ArrayList<GraticuleTile> tileList=getVisibleTiles(dc); if (tileList.size() > 0) { for ( GraticuleTile gz : tileList) { gz.selectRenderables(dc); } } }
Select the visible grid elements
public static Element addChildElementNSElement(Element element,String childElementName,Document document,String nameSpaceUrl){ Element newElement=document.createElementNS(nameSpaceUrl,childElementName); element.appendChild(newElement); return element; }
Creates a child element with the given namespace supportive name and appends it to the element child node list.
public DifferentialEvolution(double CR,double F){ this.CR=CR; this.F=F; }
Constructs a differential evolution operator with the specified crossover rate and scaling factor.
public static MethodIdentifier ofStatic(final String containingClass,final String methodName,final String returnType,final String... parameterTypes){ return of(containingClass,methodName,returnType,true,parameterTypes); }
Creates an identifier of a static method.
private void writeQName(javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI=qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix=xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix=generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix,namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0) { xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } }
method to handle Qnames
@Deprecated public ServiceRequestBufferImp(){ super(SrbMetaData.SRB_VERSION_2); }
Creates an empty service request buffer.
private static float[] rgbToHLS(int rgb,float[] hls){ float r=((rgb & 0xFF0000) >> 16) / 255.0f; float g=((rgb & 0xFF00) >> 8) / 255.0f; float b=(rgb & 0xFF) / 255.0f; float max=Math.max(Math.max(r,g),b); float min=Math.min(Math.min(r,g),b); float l=(max + min) / 2.0f; float s=0; float h=0; if (max != min) { float delta=max - min; s=(l <= .5f) ? (delta / (max + min)) : (delta / (2.0f - max - min)); if (r == max) { h=(g - b) / delta; } else if (g == max) { h=2.0f + (b - r) / delta; } else { h=4.0f + (r - g) / delta; } h*=60.0f; if (h < 0) { h+=360.0f; } } if (hls == null) { hls=new float[3]; } hls[0]=h; hls[1]=l; hls[2]=s; return hls; }
Converts from RGB color space to HLS colorspace.
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public String toString(){ return String.format("key '%s' for %s",name,owner); }
This returns a string representation of this key. It contains the name and the declaring class for the method or field. This is primarily used for debugging purposes.
public static Calendar parse(String dateString,final int timezoneOffset) throws ParseException { Calendar cal=Calendar.getInstance(UTCtimeZone); if ("now".equals(dateString)) return cal; if ("hour".equals(dateString)) { cal.setTime(oneHourAgo()); return cal; } if ("day".equals(dateString)) { cal.setTime(oneDayAgo()); return cal; } if ("week".equals(dateString)) { cal.setTime(oneWeekAgo()); return cal; } dateString=dateString.replaceAll("_"," "); int p=-1; if ((p=dateString.indexOf(':')) > 0) { if (dateString.indexOf(':',p + 1) > 0) synchronized (secondDateFormat) { cal.setTime(secondDateFormat.parse(dateString)); } else synchronized (minuteDateFormat) { cal.setTime(minuteDateFormat.parse(dateString)); } } else synchronized (dayDateFormat) { cal.setTime(dayDateFormat.parse(dateString)); } cal.add(Calendar.MINUTE,timezoneOffset); return cal; }
parse a date string for a given time zone
public boolean translateFile(String relFilepath){ assert loadedLng != null; assert mainTransLists != null; boolean result=false; if (mainTransLists.containsKey(relFilepath)) { Switchboard sb=Switchboard.getSwitchboard(); if (sb != null) { final String htRootPath=sb.getConfig(SwitchboardConstants.HTROOT_PATH,SwitchboardConstants.HTROOT_PATH_DEFAULT); final File sourceDir=new File(sb.getAppPath(),htRootPath); final File destDir=new File(sb.getDataPath("locale.translated_html","DATA/LOCALE/htroot"),loadedLng); final File sourceFile=new File(sourceDir,relFilepath); final File destFile=new File(destDir,relFilepath); result=translateFile(sourceFile,destFile,mainTransLists.get(relFilepath)); } } return result; }
Translates one file. The relFilepath is the file name as given in the translation source lists. The source (english) file is expected under htroot path. The destination file is under DATA/LOCALE and calculated using the language of loaded data.
public Polynomial(double[] a){ order=a.length - 1; this.a=new double[a.length]; System.arraycopy(a,0,this.a,0,a.length); }
Instantiates a new polynomial from a double array containing the coefficients.
private double calculateLogLikelihood(){ double logL=0; if (!isValidate(indexVariable.getValues())) { return Double.NEGATIVE_INFINITY; } for (int i=0; i < trees.size(); i++) { MaskableSpeciationModel model=speciationModels.get(i); if (i > 0) { SpeciationModel mask=speciationModels.get(indexVariable.getValue(i - 1)); if (model != mask) { model.mask(mask); } else { model.unmask(); } } logL+=model.calculateTreeLogLikelihood(trees.get(i)); } Double maxI=(double)(int)getMaxIndex(indexVariable.getValues()); maxIndexVariable.setValue(0,maxI); return logL; }
Calculates the log likelihood of this set of coalescent intervals, given a demographic model.
private LinkTableConfiguration(Builder builder){ setColumnPathes(builder.getColumnPathes()); setLinkTypeIds(builder.getLinkTypeIds()); setScopeIds(builder.getScopeIds()); }
Use LinkTableConfiguration.Builder to create instances of this class.
public static CustomChannel run(AdSenseHost service,String adClientId) throws Exception { System.out.println("================================================================="); System.out.printf("Adding custom channel to ad client %s\n",adClientId); System.out.println("================================================================="); CustomChannel newCustomChannel=new CustomChannel().setName("Sample Channel #" + AdSenseHostSample.getUniqueName()); CustomChannel customChannel=service.customchannels().insert(adClientId,newCustomChannel).execute(); System.out.printf("Custom channel with id \"%s\", code \"%s\" and name \"%s\" was created.\n",customChannel.getId(),customChannel.getCode(),customChannel.getName()); System.out.println(); return customChannel; }
Runs this sample.
public boolean hasAnyFlags(int bits){ return (flags & bits) != 0; }
Update if any oft these flags is set.
boolean needsAltMetafactory(){ return tree.targets.length() > 1 || isSerializable() || bridges.length() > 1; }
does this functional expression need to be created using alternate metafactory?
@Override public void doInit() throws ResourceException { super.doInit(); String resourceId=resolveResourceId(getRequest()); RestManager restManager=RestManager.getRestManager(SolrRequestInfo.getRequestInfo()); managedResource=restManager.getManagedResourceOrNull(resourceId); if (managedResource == null) { int lastSlashAt=resourceId.lastIndexOf('/'); if (lastSlashAt != -1) { String parentResourceId=resourceId.substring(0,lastSlashAt); log.info("Resource not found for {}, looking for parent: {}",resourceId,parentResourceId); managedResource=restManager.getManagedResourceOrNull(parentResourceId); if (managedResource != null) { if (!(managedResource instanceof ManagedResource.ChildResourceSupport)) { String errMsg=String.format(Locale.ROOT,"%s does not support child resources!",managedResource.getResourceId()); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,errMsg); } childId=resourceId.substring(lastSlashAt + 1); log.info("Found parent resource {} for child: {}",parentResourceId,childId); } } } if (managedResource == null) { if (Method.PUT.equals(getMethod()) || Method.POST.equals(getMethod())) { managedResource=restManager.endpoint; } else { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND,"No REST managed resource registered for path " + resourceId); } } log.info("Found ManagedResource [" + managedResource + "] for "+ resourceId); }
Initialize objects needed to handle a request to the REST API. Specifically, we lookup the RestManager using the ThreadLocal SolrRequestInfo and then dynamically locate the ManagedResource associated with the request URI.
public void testSingleChar() throws Exception { CharacterRunAutomaton single=new CharacterRunAutomaton(new RegExp(".").toAutomaton()); Analyzer a=new MockAnalyzer(random(),single,false); assertAnalyzesTo(a,"foobar",new String[]{"f","o","o","b","a","r"},new int[]{0,1,2,3,4,5},new int[]{1,2,3,4,5,6}); checkRandomData(random(),a,100); }
Test a configuration where each character is a term
public static void main(String[] argv){ ArgsBaratine args=new ArgsBaratine(argv); args.doMain(); }
The main start of the baratine server.
protected int addHeaderToOutput(byte[] msg,AbstractMRMessage m){ return 0; }
Add header to the outgoing byte stream.
@Override public void mouseDoubleClick(int x,int y,int mouseButton){ if (mouseButton != 1) { return; } if ((tape != null) || (path != null)) { return; } if ((lastSelection != null) && ((lastSelection instanceof Landmark) || (lastSelection instanceof Tool) || (lastSelection instanceof Waypoint))) { MapElement mElement=(MapElement)lastSelection; mElement.getState().openAnnotation(); } }
Mouse button was double-clicked
public MLOutput execute(String dmlScriptFilePath,boolean parsePyDML,String configFilePath) throws IOException, DMLException, ParseException { return compileAndExecuteScript(dmlScriptFilePath,null,false,parsePyDML,configFilePath); }
Experimental: Execute DML script without any arguments if parsePyDML=true, using specified config path.
@Override public void writeXML(@WillClose Writer out) throws IOException { assert project != null; bugsPopulated(); XMLOutput xmlOutput; if (withMessages && cloud != null) { cloud.bugsPopulated(); cloud.initiateCommunication(); cloud.waitUntilIssueDataDownloaded(); String token=SystemProperties.getProperty("findbugs.cloud.token"); if (token != null && token.trim().length() > 0) { LOGGER.info("Cloud token specified - uploading new issues, if necessary..."); cloud.waitUntilNewIssuesUploaded(); } xmlOutput=new OutputStreamXMLOutput(out,"http://findbugs.sourceforge.net/xsl/default.xsl"); } else { xmlOutput=new OutputStreamXMLOutput(out); } writeXML(xmlOutput); }
Write the BugCollection to given output stream as XML. The output stream will be closed, even if an exception is thrown.
public Pattern createPattern(){ PatternImpl pattern=new PatternImpl(); return pattern; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void clean(int size){ if (fifo.size() > size) { while (size > 0) { fifo.removeElementAt(0); nbObjects--; size--; } } }
clean FIFO
public boolean needsUpgrading(final DatabaseVersion fromVersion){ return fromVersion.getString().equals("4.0.0") || fromVersion.getString().equals("5.0.0"); }
Checks whether a given database version needs upgrading.
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case N4JSPackage.CAST_EXPRESSION__EXPRESSION: return basicSetExpression(null,msgs); case N4JSPackage.CAST_EXPRESSION__TARGET_TYPE_REF: return basicSetTargetTypeRef(null,msgs); } return super.eInverseRemove(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
protected ExifTag addTag(ExifTag tag,int ifdId){ if (tag != null && ExifTag.isValidIfd(ifdId)) { IfdData ifdData=getOrCreateIfdData(ifdId); return ifdData.setTag(tag); } return null; }
Adds the given ExifTag to the given IFD and returns an existing ExifTag with the same TID or null if none exist.
@Override public void removeListener(final IEventLayerListener e){ }
Method removeMouseListener()
public void pushOntoIntStack(Interpreter interpreter,int val){ interpreter.intStack().push(val); }
Pushes a value onto the top of the int stack of the interpreter.
public UnsupportedClassVersionError(){ super(); }
Constructs a <code>UnsupportedClassVersionError</code> with no detail message.
public SendableTextMessage.SendableTextMessageBuilder disableNotification(boolean disableNotification){ this.disableNotification=disableNotification; return this; }
*Optional Sets whether or not to disable any notification this message might usually cause. Defaults to False
public boolean areEqual(final AnnotatedTypeMirror type1,final AnnotatedTypeMirror type2){ return AtmCombo.accept(type1,type2,new VisitHistory(),this); }
Returns true if type1 and type2 are structurally equivalent. With one exception, type1.getClass().equals(type2.getClass()) must be true. However, because the Checker Framework sometimes "infers" Typevars to be Wildcards, we allow the combination Wildcard,Typevar. In this case, the two types are "equal" if their bounds are.
public void addProperty(String key,Object token){ deprecationCrutch.addProperty(key,token); Object o=this.get(key); if (o instanceof String) { Vector v=new Vector(2); v.addElement(o); v.addElement(token); put(key,v); } else if (o instanceof Vector) { ((Vector)o).addElement(token); } else { if (token instanceof String && ((String)token).indexOf(PropertiesTokenizer.DELIMITER) > 0) { PropertiesTokenizer tokenizer=new PropertiesTokenizer((String)token); while (tokenizer.hasMoreTokens()) { String value=tokenizer.nextToken(); addStringProperty(key,value); } } else { if (!containsKey(key)) { keysAsListed.add(key); } put(key,token); } } }
Add a property to the configuration. If it already exists then the value stated here will be added to the configuration entry. For example, if resource.loader = file is already present in the configuration and you addProperty("resource.loader", "classpath") Then you will end up with a Vector like the following: ["file", "classpath"]
public static void printMagnitudes(){ printMagnitudes(System.out); }
Prints the relative magnitudes of the collected timer data to the standard output stream.
public PrefixStringMatcher(String[] prefixes){ super(); for (int i=0; i < prefixes.length; i++) addPatternForward(prefixes[i]); }
Creates a new <code>PrefixStringMatcher</code> which will match <code>String</code>s with any prefix in the supplied array. Zero-length <code>Strings</code> are ignored.
@Override protected EClass eStaticClass(){ return UmplePackage.eINSTANCE.getInlineAssociationEnd_(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public boolean hasLocalInterestBeenComputed(){ return this.hasLocalInterestBeenComputed; }
returns true if local interest has been computed
public void testDeletePackage2(){ int originalAppIdValue=mAppIdValue; int originalContentTypeValue=mContentTypeValue; try { IWapPushManager iwapman=getInterface(); iwapman.addPackage(Integer.toString(mAppIdValue),Integer.toString(mContentTypeValue),mPackageName,mClassName,0,false,false); assertFalse(iwapman.deletePackage(Integer.toString(mAppIdValue + 10),Integer.toString(mContentTypeValue),mPackageName,mClassName)); assertFalse(iwapman.deletePackage(Integer.toString(mAppIdValue),Integer.toString(mContentTypeValue + 20),mPackageName,mClassName)); assertFalse(iwapman.deletePackage(Integer.toString(mAppIdValue + 10),Integer.toString(mContentTypeValue + 20),mPackageName,mClassName)); iwapman.deletePackage(Integer.toString(mAppIdValue),Integer.toString(mContentTypeValue),mPackageName,mClassName); } catch ( RemoteException e) { assertTrue(false); } }
Deleting invalid package test
public void evaluate(EvolutionState state,Individual ind,int subpopulation,int threadnum){ if (ind.evaluated) return; VectorSpeciesCGP s=(VectorSpeciesCGP)ind.species; VectorIndividualCGP ind2=(VectorIndividualCGP)ind; float diff=0f; Float[] inputs=new Float[2]; float fn=0f; for (int i=0; i < testPoints.length; i++) { inputs[0]=testPoints[i]; inputs[1]=1.0f; Object[] outputs=Evaluator.evaluate(state,threadnum,inputs,ind2); if (function == 1) fn=function1(testPoints[i]); else if (function == 2) fn=function2(testPoints[i]); else if (function == 3) fn=function3(testPoints[i]); diff+=Math.abs((Float)outputs[0] - fn); } ((FitnessCGP)ind.fitness).setFitness(state,diff,diff <= 0.01); ind.evaluated=true; }
Evaluate the CGP and compute fitness
public ProcessingInstruction createProcessingInstruction(String target,String data) throws DOMException { error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED); return null; }
Unimplemented. See org.w3c.dom.Document
public SegmentIntersectionDetector(LineIntersector li){ this.li=li; }
Creates an intersection finder using a given LineIntersector.
public static boolean isFileExist(String filePath){ if (Handler_String.isBlank(filePath)) { return false; } File file=new File(filePath); return (file.exists() && file.isFile()); }
Indicates if this file represents a file on the underlying file system.
@Override public final void write(byte[] source,int offset,int len){ if (this.overflowBuf != null) { this.overflowBuf.write(source,offset,len); return; } while (len > 0) { int remainingSpace=this.buffer.capacity() - this.buffer.position(); if (remainingSpace == 0) { realFlush(false); if (this.overflowBuf != null) { this.overflowBuf.write(source,offset,len); return; } } else { int chunkSize=remainingSpace; if (len < chunkSize) { chunkSize=len; } this.buffer.put(source,offset,chunkSize); offset+=chunkSize; len-=chunkSize; } } }
override OutputStream's write()
public static void addView(Context context,View view){ addView(context,view,createDefaultLayoutParams()); }
Adds a child view with the specified layout parameters.
public Object generate(Element element,ElementMetadata<?,?> metadata){ Path bound=path.toAbsolute(metadata); element=getFinalElement(bound,element); if (element == null) { return null; } if (bound.selectsAttribute()) { return generateAttributeValue(element,bound.getSelectedElement(),bound.getSelectedAttributeKey(),bound.getSelectedAttribute()); } else { return generateTextValue(element,bound.getSelectedElement()); } }
Generate a text value through the path. If the path ends in an element, the value will be the text content of the final element. If the path ends in an attribute, the value will be the value of that attribute.
protected void fireAncestorMoved(JComponent source,int id,Container ancestor,Container ancestorParent){ Object[] listeners=listenerList.getListenerList(); for (int i=listeners.length - 2; i >= 0; i-=2) { if (listeners[i] == AncestorListener.class) { AncestorEvent ancestorEvent=new AncestorEvent(source,id,ancestor,ancestorParent); ((AncestorListener)listeners[i + 1]).ancestorMoved(ancestorEvent); } } }
Notify all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.
@Override public Set<K> keySet(){ HashSet<K> set=new HashSet<K>(); for ( Segment<K,V> s : segments) { set.addAll(s.keySet()); } return set; }
Get the set of keys for resident entries.
public int tableLength(){ return ByteArray.readU16bit(info,0); }
Returns <code>line_number_table_length</code>. This represents the number of entries in the table.
public TetradMatrix pruneEdgesByResampling(TetradMatrix data){ TetradMatrix X=new TetradMatrix(data.transpose().toArray()); int npieces=10; int cols=X.columns(); int rows=X.rows(); int piecesize=(int)Math.floor(cols / npieces); List<TetradMatrix> bpieces=new ArrayList<>(); List<TetradVector> diststdpieces=new ArrayList<>(); List<TetradVector> cpieces=new ArrayList<>(); for (int p=0; p < npieces; p++) { int p0=(p) * piecesize; int p1=(p + 1) * piecesize - 1; int[] range=range(p0,p1); TetradMatrix Xp=X; TetradVector Xpm=new TetradVector(rows); for (int i=0; i < rows; i++) { double sum=0.0; for (int j=0; j < Xp.columns(); j++) { sum+=Xp.get(i,j); } Xpm.set(i,sum / Xp.columns()); } for (int i=0; i < rows; i++) { for (int j=0; j < Xp.columns(); j++) { Xp.set(i,j,Xp.get(i,j) - Xpm.get(i)); } } TetradMatrix Xpt=Xp.transpose(); TetradMatrix cov=Xp.times(Xpt); for (int i=0; i < cov.rows(); i++) { for (int j=0; j < cov.columns(); j++) { cov.set(i,j,cov.get(i,j) / Xp.columns()); } } boolean posDef=LingUtils.isPositiveDefinite(cov); if (!posDef) { System.out.println("Covariance matrix is not positive definite."); } TetradMatrix sqrt=cov.sqrt(); ; TetradMatrix I=TetradMatrix.identity(rows); TetradMatrix AI=I.copy(); TetradMatrix invSqrt=sqrt.inverse(); QRDecomposition qr=new QRDecomposition(invSqrt.getRealMatrix()); RealMatrix r=qr.getR(); TetradVector newestdisturbancestd=new TetradVector(rows); for (int t=0; t < rows; t++) { newestdisturbancestd.set(t,1.0 / Math.abs(r.getEntry(t,t))); } for (int s=0; s < rows; s++) { for (int t=0; t < min(s,cols); t++) { r.setEntry(s,t,r.getEntry(s,t) / r.getEntry(s,s)); } } TetradMatrix bnewest=TetradMatrix.identity(rows); bnewest=bnewest.minus(new TetradMatrix(r)); TetradVector cnewest=new TetradMatrix(r).times(Xpm); bpieces.add(bnewest); diststdpieces.add(newestdisturbancestd); cpieces.add(cnewest); } TetradMatrix means=new TetradMatrix(rows,rows); TetradMatrix stds=new TetradMatrix(rows,rows); TetradMatrix BFinal=new TetradMatrix(rows,rows); for (int i=0; i < rows; i++) { for (int j=0; j < rows; j++) { double sum=0.0; for (int y=0; y < npieces; y++) { sum+=bpieces.get(y).get(i,j); } double themean=sum / (npieces); double sumVar=0.0; for (int y=0; y < npieces; y++) { sumVar+=Math.pow((bpieces.get(y).get(i,j)) - themean,2); } double thestd=Math.sqrt(sumVar / (npieces)); means.set(i,j,themean); stds.set(i,j,thestd); if (Math.abs(themean) < threshold * thestd) { BFinal.set(i,j,0); } else { BFinal.set(i,j,themean); } } } return BFinal; }
This is the method used in Patrik's code.
private String createIndentation(int numChars){ StringBuilder sb=new StringBuilder(); for (int i=0; i < numChars; i++) sb.append(" "); return sb.toString(); }
Adds spaces to create indentation.
public void firePropertyChangedEvent(){ for ( WorldListener listener : listenerList) { listener.propertyChanged(); } }
Fire a property changed event.
@Override protected void beforeShow(){ super.beforeShow(); m_Option=CANCEL_OPTION; }
Hook method just before the dialog is made visible.
protected void fireTreeNodesChanged(Object source,Object[] path,int[] childIndices,Object[] children){ Object[] listeners=listenerList.getListenerList(); TreeModelEvent e=null; for (int i=listeners.length - 2; i >= 0; i-=2) { if (listeners[i] == TreeModelListener.class) { if (e == null) e=new TreeModelEvent(source,path,childIndices,children); ((TreeModelListener)listeners[i + 1]).treeNodesChanged(e); } } }
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.
String renameTypeDesc(String desc){ if (desc == null) { return null; } return renameType(Type.getType(desc)); }
Renames a type descriptor, e.g. "Lcom.package.MyClass;" If the type doesn't need to be renamed, returns the input string as-is.
public void addAlias(String field,float tiebreaker,Map<String,Float> fieldBoosts){ Alias a=new Alias(); a.tie=tiebreaker; a.fields=fieldBoosts; aliases.put(field,a); }
Add an alias to this query parser.
private void cloneReachableNonHiddenAncestorMethods(SootClass ancestor){ if (ClassCloner.isClonedClass(ancestor)) { logger.error("Cloning method from clone: {}",ancestor); droidsafe.main.Main.exit(1); } for ( SootMethod ancestorM : ancestor.getMethods()) { if (ancestorM.isAbstract() || ancestorM.isPhantom() || !ancestorM.isConcrete()|| SootUtils.isRuntimeStubMethod(ancestorM)) continue; if (ancestorM.isStatic()) continue; if (!cloneAllMethods && !PTABridge.v().getReachableMethods().contains(ancestorM)) continue; if (containsMethod(ancestorM.getSignature())) { continue; } if (ancestorM.isFinal()) ancestorM.setModifiers(ancestorM.getModifiers() ^ Modifier.FINAL); try { cloneMethod(ancestorM,ancestorM.getName()); } catch ( Exception e) { } } }
Clone non-static ancestor methods that are not hidden by virtual dispatch and that are reachable based on a pta run.
public void writeExif(InputStream jpegStream,String exifOutFileName) throws FileNotFoundException, IOException { if (jpegStream == null || exifOutFileName == null) { throw new IllegalArgumentException(NULL_ARGUMENT_STRING); } OutputStream s=null; try { s=getExifWriterStream(exifOutFileName); doExifStreamIO(jpegStream,s); s.flush(); } catch ( IOException e) { closeSilently(s); throw e; } s.close(); }
Writes the tags from this ExifInterface object into a jpeg stream, removing prior exif tags.
public boolean isPrimary(){ return primary; }
Gets whether the effect is a primary beacon effect.
public boolean applyOptions() throws IOException { URLHandlerSettings.IMAGE_VIEWER.setValue(_viewerField.getText()); return false; }
Applies the options currently set in this <tt>PaneItem</tt>.
public void testAlgorithmParameterGenerator08(){ if (!DSASupported) { fail(validAlgName + " algorithm is not supported"); return; } try { AlgorithmParameterGenerator.getInstance(null,validProvider); fail("NullPointerException or NoSuchAlgorithmException should be thrown"); } catch ( NullPointerException e) { } catch ( NoSuchAlgorithmException e) { } for (int i=0; i < invalidValues.length; i++) { try { AlgorithmParameterGenerator.getInstance(invalidValues[i],validProvider); fail("NoSuchAlgorithmException must be thrown (algorithm: ".concat(invalidValues[i]).concat(")")); } catch ( NoSuchAlgorithmException e) { } } }
Test for <code>getInstance(String algorithm, Provider provider)</code> method Assertion: throws NullPointerException must be thrown is null throws NoSuchAlgorithmException must be thrown if algorithm is not available