code
stringlengths
10
174k
nl
stringlengths
3
129k
public boolean isALevelTechnicallyValid(final String signatureId){ SignatureWrapper signatureWrapper=getSignatureByIdNullSafe(signatureId); return signatureWrapper.isALevelTechnicallyValid(); }
Indicates if the -A (-LTA) level is technically valid. It means that the signature of the archive timestamps are valid and their imprint is valid too.
public void onDrawerOpened(View drawerView){ super.onDrawerOpened(drawerView); }
Called when a drawer has settled in a completely open state.
public void addEmotion(final String trigger,final String npcAction){ add(ConversationStates.IDLE,Arrays.asList(trigger),ConversationStates.IDLE,null,new NPCEmoteAction(npcAction)); add(ConversationStates.ATTENDING,Arrays.asList(trigger),ConversationStates.ATTENDING,null,new NPCEmoteAction(npcAction)); }
make npc's emotion
public static void copyFile(File sourceFile,File destFile) throws IOException { FileInputStream fis=new FileInputStream(sourceFile); FileOutputStream fos=new FileOutputStream(destFile); fis.getChannel().transferTo(0,sourceFile.length(),fos.getChannel()); fis.close(); fos.close(); }
Copies a file.
public boolean remove(T value){ if (value == null) { throw new IllegalArgumentException("BinaryTree cannot store 'null' values."); } if (root == null) { return false; } RightThreadedBinaryNode<T> node=root; RightThreadedBinaryNode<T> parent=null; RightThreadedBinaryNode<T> n; do { int c=value.compareTo((T)node.value); if (c < 0) { if ((n=node.getLeftSon()) == null) { break; } else { parent=node; node=n; } } else if (c > 0) { if ((n=node.getRightSon()) == null) { break; } else { parent=node; node=n; } } else { removeHelper(node,parent); return true; } } while (n != null); return false; }
Remove the value from the tree. The key is to find the predecessor-value (pv) to the target-value (tv). You can set the value of 'tv' to be 'pv' and then delete the original 'pv' node by considering the following two cases (note that the original pv node cannot have a right child because it is the predecessor to tv). The two cases are: 1. If pv has no children just delete it 2. If pv has a left child, then have pv's parent's right child become the left child of pv. Must properly manage deletions
private static String lz(int num){ return String.format("%02d",num); }
add leadingZero if only 1 char
public int read(InputStream is){ init(); if (is != null) { if (!(is instanceof BufferedInputStream)) is=new BufferedInputStream(is); in=(BufferedInputStream)is; readHeader(); if (!err()) { readContents(); if (frameCount < 0) { status=STATUS_FORMAT_ERROR; } } } else { status=STATUS_OPEN_ERROR; } try { is.close(); } catch ( IOException e) { } return status; }
Reads GIF image from stream
public CEventTableMenu(final JTable table,final List<ITraceEvent> traces){ addOpenFunction(SwingUtilities.getWindowAncestor(table),traces); add(new JMenuItem(CActionProxy.proxy(new CSearchTableAction(SwingUtilities.getWindowAncestor(table),table)))); add(new CopySelectionAction(table)); }
Creates a new menu object.
public Set<PersonUser> findPersonUsersByNameInGroup(String tenantName,PrincipalId groupId,String searchString,int limit) throws Exception { return getService().findPersonUsersByNameInGroup(tenantName,groupId,searchString,limit,this.getServiceContext()); }
Finds regular users in a particular group of the tenant Utilizes 'starts with'-style queries Regular expressions are not allowed in the search string at this time.
public boolean scale(@NonNull TextureView view,@NonNull ScaleType scaleType){ if (!ready()) { requestedScaleType=scaleType; requestedModificationView=new WeakReference<>(view); return false; } if (view.getHeight() == 0 || view.getWidth() == 0) { Log.d(TAG,"Unable to apply scale with a view size of (" + view.getWidth() + ", "+ view.getHeight()+ ")"); return false; } currentScaleType=scaleType; switch (scaleType) { case CENTER: applyCenter(view); break; case CENTER_CROP: applyCenterCrop(view); break; case CENTER_INSIDE: applyCenterInside(view); break; case FIT_CENTER: applyFitCenter(view); break; case NONE: setScale(view,1,1); break; } return true; }
Performs the requested scaling on the <code>view</code>'s matrix
protected Control createTitleControl(Composite parent){ titleLabel=new Label(parent,SWT.NONE); GridDataFactory.fillDefaults().align(SWT.FILL,SWT.CENTER).grab(true,false).span(showDialogMenu ? 1 : 2,1).applyTo(titleLabel); if (titleText != null) { titleLabel.setText(titleText); } return titleLabel; }
Creates the control to be used to represent the dialog's title text. Subclasses may override if a different control is desired for representing the title text, or if something different than the title should be displayed in location where the title text typically is shown. <p> If this method is overridden, the returned control's layout data must be an instance of <code>GridData</code>. This method must not modify the parent's layout.
public boolean isCodeAttribute(){ return false; }
Returns <tt>true</tt> if this type of attribute is a code attribute.
static void checkCompatible(FieldInfo fieldInfo){ if (fieldInfo.getDocValuesType() != DocValuesType.NONE && fieldInfo.getDocValuesType() != TYPE.docValuesType()) { throw new IllegalArgumentException("field=\"" + fieldInfo.name + "\" was indexed with docValuesType="+ fieldInfo.getDocValuesType()+ " but this type has docValuesType="+ TYPE.docValuesType()+ ", is the field really a LatLonDocValuesField?"); } }
helper: checks a fieldinfo and throws exception if its definitely not a LatLonDocValuesField
public Vec3D applyTo(ReadonlyVec3D v){ return applyToSelf(new Vec3D(v)); }
Creates a copy of the given vector, transformed by this matrix.
public Boolean shouldOpenExternalUrl(String url){ return null; }
Hook for blocking the launching of Intents by the Cordova application. This will be called when the WebView will not navigate to a page, but could launch an intent to handle the URL. Return false to block this: if any plugin returns false, Cordova will block the navigation. If all plugins return null, the default policy will be enforced. If at least one plugin returns true, and no plugins return false, then the URL will be opened.
public CacheClosedException(String msg){ super(msg); GemFireCacheImpl cache=GemFireCacheImpl.getInstance(); if (cache != null) { initCause(cache.getDisconnectCause()); } }
Constructs a new <code>CacheClosedException</code> with a message string.
public BufferedShapeLayer(){ super(); setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this)); }
Initializes an empty shape layer.
private void doScroll(int delta){ scrollingOffset+=delta; int itemHeight=getItemHeight(); int count=scrollingOffset / itemHeight; int pos=currentItem - count; int itemCount=viewAdapter.getItemsCount(); int fixPos=scrollingOffset % itemHeight; if (Math.abs(fixPos) <= itemHeight / 2) { fixPos=0; } if (isCyclic && itemCount > 0) { if (fixPos > 0) { pos--; count++; } else if (fixPos < 0) { pos++; count--; } while (pos < 0) { pos+=itemCount; } pos%=itemCount; } else { if (pos < 0) { count=currentItem; pos=0; } else if (pos >= itemCount) { count=currentItem - itemCount + 1; pos=itemCount - 1; } else if (pos > 0 && fixPos > 0) { pos--; count++; } else if (pos < itemCount - 1 && fixPos < 0) { pos++; count--; } } int offset=scrollingOffset; if (pos != currentItem) { setCurrentItem(pos,false); } else { invalidate(); } scrollingOffset=offset - count * itemHeight; if (scrollingOffset > getHeight()) { scrollingOffset=scrollingOffset % getHeight() + getHeight(); } }
Scrolls the wheel
public RtpPacket readRtpPacket() throws TimeoutException { byte[] data=(byte[])mBuffer.getObject(mTimeout); if (data == null) { throw new TimeoutException("Unable to fetch packet from FIFO queue!"); } RtpPacket pkt=parseRtpPacket(data); if (pkt != null) { mStats.numPackets++; mStats.numBytes+=data.length; RtpSource s=mRtcpSession.getMySource(); s.setSsrc(pkt.ssrc); s.activeSender=true; s.receiveRtpPacket(pkt); pkt.seqnum=s.generateExtendedSequenceNumber(pkt.seqnum); return pkt; } return readRtpPacket(); }
Read a RTP packet (blocking method)
public NestableRuntimeException(String msg,Throwable cause){ super(msg); this.cause=cause; }
Constructs a new <code>NestableRuntimeException</code> with specified detail message and nested <code>Throwable</code>.
protected DoubleMatrix2D viewSelectionLike(int[] rowOffsets,int[] columnOffsets){ return new SelectedDenseDoubleMatrix2D(this.elements,rowOffsets,columnOffsets,0); }
Construct and returns a new selection view.
public T process(ResultSet rs) throws SQLException { return (T)JdbcUtils.getResultSetValue(rs,this.mIndex,this.mExpectedType); }
The actual implementation of retrieving a column from the current row in the ResultSet.
public final void increaseReadBytes(long nbBytesRead,long currentTime){ throughputCalculationLock.lock(); try { readBytes+=nbBytesRead; lastReadTime=currentTime; } finally { throughputCalculationLock.unlock(); } }
Increases the count of read bytes by <code>nbBytesRead</code> and sets the last read time to <code>currentTime</code>.
public static DoubleMatrix2D minus(DoubleMatrix2D A,double s){ return A.assign(F.minus(s)); }
<tt>A = A - s <=> A[row,col] = A[row,col] - s</tt>.
public String toString(){ return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
Return a string-ified representation of the MapBean.
public BoundedFifoBuffer(){ this(32); }
Constructs a new <code>BoundedFifoBuffer</code> big enough to hold 32 elements.
@Deprecated public static Configuration create(){ return createConfiguration(); }
For now we need to manually construct our Configuration, because we need to override the default one and it is currently not possible to use dynamically set values.
public boolean userCanDeleteGroup(int connectedUserId,int GroupId,String entidad) throws Exception { boolean can=false; int mgrGroup=Defs.NULL_ID; try { mgrGroup=this.getGroupMgrId(GroupId,entidad); can=hasUserGroupAuth(connectedUserId,USER_ACTION_ID_CREATE,mgrGroup,entidad); } catch ( Exception e) { _logger.error(e); throw e; } return can; }
Obtiene si el usuario conectado puede eliminar el grupo indicado.
public void consumer(Class<?> api,@Pin ServiceRefAmp serviceRef,Result<? super Cancel> result){ String path=api.getName(); String address=address(path); EventNodeAsset node=lookupPubSubNode(address); Cancel cancel=node.consumeImpl(serviceRef); result.ok(cancel); }
Consume a callback to a location.
public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (; ; ) { c=x.nextClean(); switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': return; default : x.back(); key=x.nextValue().toString(); } c=x.nextClean(); if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } this.putOnce(key,x.nextValue()); switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == '}') { return; } x.back(); break; case '}': return; default : throw x.syntaxError("Expected a ',' or '}'"); } } }
Construct a JSONObject from a JSONTokener.
private File testWriteInDefinedFormat(final GamaGraph graph,final String extension){ System.out.println("testing the writing in this format: " + format); File file=TestUtils.getTmpFile("emptyGraph",extension); IGraphWriter writer=AvailableGraphWriters.getGraphWriter(format); System.out.println("will use writer: " + writer.getClass().getCanonicalName()); writer.writeGraph(null,graph,null,file.getAbsolutePath()); assertTrue(file.exists()); assertFalse(file.isDirectory()); System.out.println("(file was created)"); return file; }
Attempts to write the graph in the current format. ensures a file was created and returns its path.
public UnixNumericGroupPrincipal(String name,boolean primaryGroup){ if (name == null) { java.text.MessageFormat form=new java.text.MessageFormat(sun.security.util.ResourcesMgr.getString("invalid.null.input.value","sun.security.util.AuthResources")); Object[] source={"name"}; throw new NullPointerException(form.format(source)); } this.name=name; this.primaryGroup=primaryGroup; }
Create a <code>UnixNumericGroupPrincipal</code> using a <code>String</code> representation of the user's group identification number (GID). <p>
AbstractBufferStrategy(long initialExtent,long maximumExtent,int offsetBits,long nextOffset,BufferMode bufferMode,boolean readOnly){ super(offsetBits); assert nextOffset >= 0; if (bufferMode == null) throw new IllegalArgumentException(); this.initialExtent=initialExtent; this.maximumExtent=maximumExtent; this.nextOffset=new AtomicLong(nextOffset); this.commitOffset=new AtomicLong(nextOffset); this.bufferMode=bufferMode; this.open=true; this.readOnly=readOnly; }
(Re-)open a buffer.
public void testAddExtraClasspathWorksWithNoPreviousPath() throws Exception { AbstractInstalledLocalContainer container=new AbstractInstalledLocalContainerStub(configuration); container.setFileHandler(fileHandler); container.addExtraClasspath(TEST_FILE); assertEquals(1,container.getExtraClasspath().length); assertEquals(TEST_FILE,container.getExtraClasspath()[0]); }
Tests adding a JAR to the extra classpath when no path was set.
public static GitCommittedChangeList parseChangeList(Project project,VirtualFile root,StringScanner s,boolean skipDiffsForMerge,GitHandler handler,boolean local,boolean revertable) throws VcsException { ArrayList<Change> changes=new ArrayList<Change>(); final Date commitDate=GitUtil.parseTimestampWithNFEReport(s.line(),handler,s.getAllText()); final String revisionNumber=s.line(); final String parentsLine=s.line(); final String[] parents=parentsLine.length() == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : parentsLine.split(" "); String authorName=s.line(); String committerName=s.line(); committerName=GitUtil.adjustAuthorName(authorName,committerName); String commentSubject=s.boundedToken('\u0003',true); s.nextLine(); String commentBody=s.boundedToken('\u0003',true); String fullComment; if (commentSubject.length() == 0) { fullComment=commentBody; } else if (commentBody.length() == 0) { fullComment=commentSubject; } else { fullComment=commentSubject + "\n" + commentBody; } GitRevisionNumber thisRevision=new GitRevisionNumber(revisionNumber,commitDate); if (skipDiffsForMerge || (parents.length <= 1)) { final GitRevisionNumber parentRevision=parents.length > 0 ? resolveReference(project,root,parents[0]) : null; parseChanges(project,root,thisRevision,local ? null : parentRevision,s,changes,null); } else { for ( String parent : parents) { final GitRevisionNumber parentRevision=resolveReference(project,root,parent); GitSimpleHandler diffHandler=new GitSimpleHandler(project,root,GitCommand.DIFF); diffHandler.setSilent(true); diffHandler.addParameters("--name-status","-M",parentRevision.getRev(),thisRevision.getRev()); String diff=diffHandler.run(); parseChanges(project,root,thisRevision,parentRevision,diff,changes,null); if (changes.size() > 0) { break; } } } String changeListName=String.format("%s(%s)",commentSubject,revisionNumber); return new GitCommittedChangeList(changeListName,fullComment,committerName,thisRevision,commitDate,changes,revertable); }
Parse changelist
public void storeCommonAttributes(Positionable p,Element element){ element.setAttribute("x","" + p.getX()); element.setAttribute("y","" + p.getY()); element.setAttribute("level",String.valueOf(p.getDisplayLevel())); element.setAttribute("forcecontroloff",!p.isControlling() ? "true" : "false"); element.setAttribute("hidden",p.isHidden() ? "yes" : "no"); element.setAttribute("positionable",p.isPositionable() ? "true" : "false"); element.setAttribute("showtooltip",p.showTooltip() ? "true" : "false"); element.setAttribute("editable",p.isEditable() ? "true" : "false"); ToolTip tip=p.getTooltip(); String txt=tip.getText(); if (txt != null) { Element elem=new Element("tooltip").addContent(txt); element.addContent(elem); } if (p.getDegrees() != 0) { element.setAttribute("degrees","" + p.getDegrees()); } }
Default implementation for storing the common contents of an Icon
public void popCurrentMatched(){ m_currentMatchTemplates.pop(); m_currentMatchedNodes.pop(); }
Pop the elements that were pushed via pushPairCurrentMatched.
public T id(View view){ this.view=view; reset(); return self(); }
Points the current operating view to the specified view.
ExternalProblem(Process process){ this(process.getInputStream(),process.getOutputStream()); RedirectStream.redirect(process.getErrorStream(),System.err); }
Constructs an external problem using the specified process.
public void endEntity(String name) throws org.xml.sax.SAXException { }
Report the end of an entity.
public void initFromStrings(String[] initData){ Long key; String value; String[] data; hashData.clear(); for ( String anInitData : initData) { data=anInitData.split(";"); for ( String aData : data) { String[] words=aData.split("="); key=Long.valueOf(words[0]); value=words[1]; String xlatKey=value; xlatKey=xlatKey.replaceAll("[ -]","_").toLowerCase(); value=Messages.getString(xlatKey,value); log.debug(String.format("%s=%s\n",xlatKey,value)); hashData.put(key,value); } } }
initialize hash map with values from an array of strings in the format "key=value"
public GreaterConstraint(Number constraintValue){ super(constraintValue); }
Creates a Greater-Than-Number parameter constraint. <p/> That is, the value of the number parameter has to be greater than the given constraint value.
public static boolean isCommand(final String name){ return (valueOfName(name) != null); }
Determines whether the specified name refers to a valid Locator launcher command, as defined by this enumerated type.
public AlgorithmException(Algorithm algorithm,String message){ this(algorithm,message,null); }
Constructs an algorithm exception originating from the specified algorithm with the given message.
@Override public int hashCode(){ return getName().hashCode(); }
Answers an integer hash code for the receiver. Objects which are equal answer the same value for this method. <p> The hash code for a Field is the hash code of the field's name.
public int size(){ return m_size; }
Return the number of elements in the map
public void decodeContinuous(BarcodeCallback callback){ this.decodeMode=DecodeMode.CONTINUOUS; this.callback=callback; startDecoderThread(); }
Continuously decode barcodes. The same barcode may be returned multiple times per second. The callback will only be called on the UI thread.
static Object[] toArrayImpl(Collection<?> c){ return fillArray(c,new Object[c.size()]); }
Returns an array containing all of the elements in the specified collection. This method returns the elements in the order they are returned by the collection's iterator. The returned array is "safe" in that no references to it are maintained by the collection. The caller is thus free to modify the returned array. <p>This method assumes that the collection size doesn't change while the method is running. <p>TODO(kevinb): support concurrently modified collections?
public void declareExtensions(ExtensionProfile extProfile){ extProfile.declare(CellFeed.class,RowCount.getDefaultDescription()); extProfile.declare(CellFeed.class,ColCount.getDefaultDescription()); super.declareExtensions(extProfile); BatchUtils.declareExtensions(extProfile); }
Declares relevant extensions into the extension profile.
private MapUtil(){ }
Do not instantiate this class
public boolean test_autoselection(String package_name,List<String> details){ if (_autoselect_conditions == null || !is_applicable(package_name)) { return false; } if (_autoselect_conditions.contains("applicable")) { return true; } for ( String detail : details) { if (_autoselect_conditions.contains(detail)) { return true; } } return false; }
Checks whether this update source should be used as a default for the given app. This is a very primitive DSL related to source.json's "autoselect_if" information. A list of conditions is given in the file, and if any of them match, the update source is selected. Conditions may be related to the APK's signature (tests on its CN, O, etc.), metadata present in the manifest or the hardcoded keyword "applicable", which means that the update source should be used as default for any applicable packages.
public void verifyKey(VerifyEvent event){ try { event.doit=false; System.out.println("Heard keystroke."); IBindingService ibindingService=(IBindingService)UIHelper.getActivePage().getActivePart().getSite().getService(IBindingService.class); KeyStroke keyStroke=SWTKeySupport.convertAcceleratorToKeyStroke(SWTKeySupport.convertEventToUnmodifiedAccelerator(event)); Binding binding=ibindingService.getPerfectMatch(KeySequence.getInstance(keyStroke)); ParameterizedCommand pcommand=binding.getParameterizedCommand(); IHandlerService ihandlerService=(IHandlerService)UIHelper.getActivePage().getActivePart().getSite().getService(IHandlerService.class); ihandlerService.executeCommand(pcommand,null); } catch ( ExecutionException e) { e.printStackTrace(); } catch ( NotDefinedException e) { e.printStackTrace(); } catch ( NotEnabledException e) { e.printStackTrace(); } catch ( NotHandledException e) { e.printStackTrace(); } finally { uninstall(); } }
Listens for the first key to be pressed. If it is a digit, it finds the word currently containing the caret and repeats that word the number of times equal to the digit pressed. If the key pressed is not a digit, this does nothing to the document and removes itself from subsequent key events.
public T caseActionArguments(ActionArguments object){ return null; }
Returns the result of interpreting the object as an instance of '<em>Action Arguments</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
@Override public void run(){ amIActive=true; String slopeHeader=null; String aspectHeader=null; String outputHeader=null; String horizonAngleHeader=null; double z; int progress; int[] dY={-1,0,1,1,1,0,-1,-1}; int[] dX={1,1,1,0,-1,-1,-1,0}; int row, col; double azimuth=0; boolean blnSlope=false; double relativeAspect=0; double slopeVal=0; double aspectVal=0; double HAval=0; double gridRes=0; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (int i=0; i < args.length; i++) { if (i == 0) { slopeHeader=args[i]; } else if (i == 1) { aspectHeader=args[i]; } else if (i == 2) { outputHeader=args[i]; } else if (i == 2) { azimuth=Math.toRadians(Double.parseDouble(args[i]) - 90); } else if (i == 3) { if (args[i].toLowerCase().contains("slope")) { blnSlope=true; } else { blnSlope=false; } } else if (i == 4) { if (blnSlope) { if (args[i].toLowerCase().contains("not specified")) { showFeedback("The horizon angle raster must be specified"); break; } horizonAngleHeader=args[i]; } } } if ((slopeHeader == null) || aspectHeader == null || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster slope=new WhiteboxRaster(slopeHeader,"r"); int rows=slope.getNumberRows(); int cols=slope.getNumberColumns(); gridRes=(slope.getCellSizeX() + slope.getCellSizeY()) / 2; double slopeNoData=slope.getNoDataValue(); WhiteboxRaster aspect=new WhiteboxRaster(aspectHeader,"r"); if (aspect.getNumberRows() != rows || aspect.getNumberColumns() != cols) { showFeedback("the input images must have the same dimensions (i.e. rows and columns)."); return; } double aspectNoData=aspect.getNoDataValue(); WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",slopeHeader,WhiteboxRaster.DataType.FLOAT,slopeNoData); output.setPreferredPalette("grey.pal"); double[] slopeData; double[] aspectData; if (blnSlope) { WhiteboxRaster horizonAngle=new WhiteboxRaster(horizonAngleHeader,"r"); if (horizonAngle.getNumberRows() != rows || horizonAngle.getNumberColumns() != cols) { showFeedback("the input images must have the same dimensions (i.e. rows and columns)."); return; } double HANoData=horizonAngle.getNoDataValue(); double[] HAdata; for (row=0; row < rows; row++) { slopeData=slope.getRowValues(row); aspectData=aspect.getRowValues(row); HAdata=horizonAngle.getRowValues(row); for (col=0; col < cols; col++) { relativeAspect=azimuth - aspectData[col]; if (relativeAspect > 180) { relativeAspect=360 - relativeAspect; if (slopeData[col] != slopeNoData && aspectData[col] != aspectNoData && HAdata[col] != HANoData) { slopeVal=Math.toRadians(slopeData[col]); aspectVal=Math.toRadians(aspectData[col]); HAval=Math.toRadians(HAdata[col]); relativeAspect=Math.toRadians(relativeAspect); output.setValue(row,col,Math.cos(slopeVal) * Math.sin(HAval) + Math.sin(slopeVal) * Math.cos(HAval) * Math.cos(relativeAspect)); } else { output.setValue(row,col,slopeNoData); } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress(progress); } horizonAngle.close(); } else { HAval=0; for (row=0; row < rows; row++) { slopeData=slope.getRowValues(row); aspectData=aspect.getRowValues(row); for (col=0; col < cols; col++) { relativeAspect=azimuth - aspectData[col]; if (relativeAspect > 180) { relativeAspect=360 - relativeAspect; } if (slopeData[col] != slopeNoData && aspectData[col] != aspectNoData) { slopeVal=Math.toRadians(slopeData[col]); aspectVal=Math.toRadians(aspectData[col]); relativeAspect=Math.toRadians(relativeAspect); output.setValue(row,col,Math.cos(slopeVal) * Math.sin(HAval) + Math.sin(slopeVal) * Math.cos(HAval) * Math.cos(relativeAspect)); } else { output.setValue(row,col,slopeNoData); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress(progress); } } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); slope.close(); aspect.close(); output.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public SearchRequestBuilder addHighlightedField(String name){ highlightBuilder().field(name); return this; }
Adds a field to be highlighted with default fragment size of 100 characters, and default number of fragments of 5.
public List<ResultSet> query(String table,String[] columns,String selection,String[] selectionArgs){ return query(table,columns,selection,selectionArgs,null,null,null); }
a simple query by condition
public static double avg(Array array) throws ExpressionException { if (array.size() == 0) return 0; return sum(array) / array.size(); }
average of all values of the array, only work when all values are numeric
private static void readEventTypeMap(final BufferedReader in,final Map<Integer,Pair<Integer,String>> eventTypeMap,final String prefixToStrip,final String postfixToStrip) throws IOException { String line; while (!(line=in.readLine()).isEmpty()) { final int i=line.indexOf(':'); final int j=line.indexOf('(',i + 1); final int k=line.indexOf(',',j + 1); final int l=line.indexOf('\'',k + 1); final int m=line.indexOf('\'',l + 1); final String name=line.substring(l + 1 + prefixToStrip.length(),m - postfixToStrip.length()).intern(); eventTypeMap.put(Integer.parseInt(line.substring(0,i)),new Pair<>(Integer.parseInt(line.substring(j + 1,k)),name)); } }
Reads an event type map from the specified input, and puts entries to the speicified even type map.
public static void passedMutation(double distance,int mutationId){ ExecutionTracer tracer=getExecutionTracer(); if (tracer.disabled) return; if (isThreadNeqCurrentThread()) return; checkTimeout(); tracer.trace.mutationPassed(mutationId,distance); }
<p> passedMutation </p>
public String sqlMetadata_tableNames(String vendorName,String catalogName,String schemaName){ return m_interfaces.get(getDBVendorID(vendorName)).sqlMetadata_tableNames(catalogName,schemaName); }
gets the database specific SQL command to find table names
@Override public void run(){ amIActive=true; String outputHeader=""; int row, col; double rowYCoord, value; int progress=0; double cellSizeX, cellSizeY; int rows, topRow, bottomRow; int cols; int inputRow, inputCol; double inputX, inputY; double east; double west; double north; double south; BoundingBox box; double[][] geometry; int numPoints, numParts, i, part, numEdges; int stCol, endCol; int startingPointInPart, endingPointInPart; double x1, y1, x2, y2, xPrime; boolean foundIntersection; ArrayList<Integer> edgeList=new ArrayList<>(); DecimalFormat df=new DecimalFormat("###,###,###,###"); if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } String inputFilesString=args[0]; String[] inputFiles=inputFilesString.split(";"); int numFiles=inputFiles.length; String clipFile=args[1]; boolean maintainInputDimensions=Boolean.parseBoolean(args[2]); if (inputFilesString.isEmpty() || numFiles < 1) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { long heapSize=Runtime.getRuntime().totalMemory(); int flushSize=(int)(heapSize / 32); int j, numCellsToWrite; PriorityQueue<RowPriorityGridCell> pq=new PriorityQueue<>(flushSize); ShapeFile clip=new ShapeFile(clipFile); BoundingBox clipBox=new BoundingBox(); clipBox.setMaxX(clip.getxMax()); clipBox.setMaxY(clip.getyMax()); clipBox.setMinX(clip.getxMin()); clipBox.setMinY(clip.getyMin()); if (clip.getShapeType().getBaseType() != ShapeType.POLYGON) { showFeedback("The input shapefile must be of a 'polygon' data type."); return; } ArrayList<RecordInfo> myList=new ArrayList<>(); for ( ShapeFileRecord record : clip.records) { i=record.getRecordNumber(); box=getBoundingBoxFromShapefileRecord(record); myList.add(new RecordInfo(box.getMaxY(),i)); } Collections.sort(myList); for (int k=0; k < numFiles; k++) { WhiteboxRaster input=new WhiteboxRaster(inputFiles[k],"r"); outputHeader=inputFiles[k].replace(".dep","_clipped.dep"); double noData=input.getNoDataValue(); DataType dataType=input.getDataType(); WhiteboxRaster output; if (!maintainInputDimensions) { cellSizeX=input.getCellSizeX(); cellSizeY=input.getCellSizeY(); north=clip.getyMax() + cellSizeY / 2.0; if (input.getNorth() < north) { north=input.getNorth(); } south=clip.getyMin() - cellSizeY / 2.0; if (input.getSouth() > south) { south=input.getSouth(); } east=clip.getxMax() + cellSizeX / 2.0; if (input.getEast() < east) { east=input.getEast(); } west=clip.getxMin() - cellSizeX / 2.0; if (input.getWest() > west) { west=input.getWest(); } rows=(int)(Math.ceil((north - south) / cellSizeY)); cols=(int)(Math.ceil((east - west) / cellSizeX)); east=west + cols * cellSizeX; south=north - rows * cellSizeY; output=new WhiteboxRaster(outputHeader,north,south,east,west,rows,cols,input.getDataScale(),dataType,noData,noData); } else { output=new WhiteboxRaster(outputHeader,"rw",inputFiles[k],dataType,noData); } output.setPreferredPalette(input.getPreferredPalette()); pq.clear(); RowPriorityGridCell cell; int numRecords=clip.getNumberOfRecords(); int count=0; int progressCount=(int)(numRecords / 100.0); if (progressCount <= 0) { progressCount=1; } ShapeFileRecord record; for ( RecordInfo ri : myList) { record=clip.getRecord(ri.recNumber - 1); geometry=getXYFromShapefileRecord(record); numPoints=geometry.length; numParts=partData.length; for (part=0; part < numParts; part++) { if (!partHoleData[part]) { box=new BoundingBox(); startingPointInPart=partData[part]; if (part < numParts - 1) { endingPointInPart=partData[part + 1]; } else { endingPointInPart=numPoints; } for (i=startingPointInPart; i < endingPointInPart; i++) { if (geometry[i][1] < box.getMinY()) { box.setMinY(geometry[i][1]); } if (geometry[i][1] > box.getMaxY()) { box.setMaxY(geometry[i][1]); } } topRow=output.getRowFromYCoordinate(box.getMaxY()); bottomRow=output.getRowFromYCoordinate(box.getMinY()); for (row=topRow; row <= bottomRow; row++) { edgeList.clear(); foundIntersection=false; rowYCoord=output.getYCoordinateFromRow(row); for (i=startingPointInPart; i < endingPointInPart - 1; i++) { if (isBetween(rowYCoord,geometry[i][1],geometry[i + 1][1])) { y1=geometry[i][1]; y2=geometry[i + 1][1]; if (y2 != y1) { x1=geometry[i][0]; x2=geometry[i + 1][0]; xPrime=(x1 + (rowYCoord - y1) / (y2 - y1) * (x2 - x1)); edgeList.add(new Integer(output.getColumnFromXCoordinate(xPrime))); foundIntersection=true; } } } if (foundIntersection) { numEdges=edgeList.size(); if (numEdges == 2) { stCol=Math.min(edgeList.get(0),edgeList.get(1)); endCol=Math.max(edgeList.get(0),edgeList.get(1)); for (col=stCol; col <= endCol; col++) { if (maintainInputDimensions) { value=input.getValue(row,col); } else { inputX=output.getXCoordinateFromColumn(col); inputCol=input.getColumnFromXCoordinate(inputX); inputY=output.getYCoordinateFromRow(row); inputRow=input.getRowFromYCoordinate(inputY); value=input.getValue(inputRow,inputCol); } pq.add(new RowPriorityGridCell(row,col,value)); } } else { Integer[] edgeArray=new Integer[numEdges]; edgeList.toArray(edgeArray); Arrays.sort(edgeArray); boolean fillFlag=true; for (i=0; i < numEdges - 1; i++) { stCol=edgeArray[i]; endCol=edgeArray[i + 1]; if (fillFlag) { for (col=stCol; col <= endCol; col++) { if (maintainInputDimensions) { value=input.getValue(row,col); } else { inputX=output.getXCoordinateFromColumn(col); inputCol=input.getColumnFromXCoordinate(inputX); inputY=output.getYCoordinateFromRow(row); inputRow=input.getRowFromYCoordinate(inputY); value=input.getValue(inputRow,inputCol); } pq.add(new RowPriorityGridCell(row,col,value)); } } fillFlag=!fillFlag; } } } } } } if (pq.size() >= flushSize) { j=0; numCellsToWrite=pq.size(); do { cell=pq.poll(); output.setValue(cell.row,cell.col,cell.z); j++; if (j % 1000 == 0) { if (cancelOp) { cancelOperation(); return; } updateProgress("Writing to Output (" + df.format(j) + " of "+ df.format(numCellsToWrite)+ "):",(int)(j * 100.0 / numCellsToWrite)); } } while (pq.size() > 0); } if (cancelOp) { cancelOperation(); return; } count++; if (count % progressCount == 0) { progress++; updateProgress(progress); } } j=0; numCellsToWrite=pq.size(); do { cell=pq.poll(); output.setValue(cell.row,cell.col,cell.z); j++; if (j % 1000 == 0) { if (cancelOp) { cancelOperation(); return; } updateProgress("Writing to Output (" + df.format(j) + " of "+ df.format(numCellsToWrite)+ "):",(int)(j * 100.0 / numCellsToWrite)); } } while (pq.size() > 0); output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); output.flush(); output.close(); } returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public boolean match(Element e,String pseudoE){ String val=getValue(); if (val == null) { return !e.getAttribute(getLocalName()).equals(""); } return e.getAttribute(getLocalName()).equals(val); }
Tests whether this condition matches the given element.
public void generateOptimizedGreaterThan(BlockScope currentScope,BranchLabel trueLabel,BranchLabel falseLabel,boolean valueRequired){ int promotedTypeID=(this.left.implicitConversion & TypeIds.IMPLICIT_CONVERSION_MASK) >> 4; if (promotedTypeID == TypeIds.T_int) { if ((this.left.constant != Constant.NotAConstant) && (this.left.constant.intValue() == 0)) { this.right.generateCode(currentScope,valueRequired); return; } if ((this.right.constant != Constant.NotAConstant) && (this.right.constant.intValue() == 0)) { this.left.generateCode(currentScope,valueRequired); return; } } this.left.generateCode(currentScope,valueRequired); this.right.generateCode(currentScope,valueRequired); }
Boolean generation for >
int[] determineDimensions(int sourceCodeWords,int errorCorrectionCodeWords) throws WriterException { float ratio=0.0f; int[] dimension=null; for (int cols=minCols; cols <= maxCols; cols++) { int rows=calculateNumberOfRows(sourceCodeWords,errorCorrectionCodeWords,cols); if (rows < minRows) { break; } if (rows > maxRows) { continue; } float newRatio=((17 * cols + 69) * DEFAULT_MODULE_WIDTH) / (rows * HEIGHT); if (dimension != null && Math.abs(newRatio - PREFERRED_RATIO) > Math.abs(ratio - PREFERRED_RATIO)) { continue; } ratio=newRatio; dimension=new int[]{cols,rows}; } if (dimension == null) { int rows=calculateNumberOfRows(sourceCodeWords,errorCorrectionCodeWords,minCols); if (rows < minRows) { dimension=new int[]{minCols,minRows}; } } if (dimension == null) { throw new WriterException("Unable to fit message in columns"); } return dimension; }
Determine optimal nr of columns and rows for the specified number of codewords.
@Override protected Rectangle makeShape(){ double xmin=PackedQuadPrefixTree.this.xmin; double ymin=PackedQuadPrefixTree.this.ymin; int level=getLevel(); byte b; for (short l=0, i=1; l < level; ++l, ++i) { b=(byte)((term >>> (64 - (i << 1))) & 0x3L); switch (b) { case 0x00: ymin+=levelH[l]; break; case 0x01: xmin+=levelW[l]; ymin+=levelH[l]; break; case 0x02: break; case 0x03: xmin+=levelW[l]; break; default : throw new RuntimeException("unexpected quadrant"); } } double width, height; if (level > 0) { width=levelW[level - 1]; height=levelH[level - 1]; } else { width=gridW; height=gridH; } return new RectangleImpl(xmin,xmin + width,ymin,ymin + height,ctx); }
Constructs a bounding box shape out of the encoded cell
@Override public boolean isComplete(){ return (status == STATUS_COMPLETE || status == STATUS_ERROR); }
NTLM2 is complete once we've delivered our authentication response (the Type3 message) or we've failed, whichever comes first.
public static int dehexchar(char hex){ if (hex >= '0' && hex <= '9') { return hex - '0'; } else if (hex >= 'A' && hex <= 'F') { return hex - 'A' + 10; } else if (hex >= 'a' && hex <= 'f') { return hex - 'a' + 10; } else { return -1; } }
Returns the integer [0..15] value for the given hex character, or -1 for non-hex input.
public static Number unaryMinus(Number left){ return NumberMath.unaryMinus(left); }
Negates the number. Equivalent to the '-' operator when it preceeds a single operand, i.e. <code>-10</code>
public boolean isQuery(){ return (_flags & DNSConstants.FLAGS_QR_MASK) == DNSConstants.FLAGS_QR_QUERY; }
Check if the message is a query.
public Geometry next() throws IOException { Geometry geom=null; try { recordNumber=file.readIntBE(); int contentLength=file.readIntBE(); try { geom=handler.read(file,geomFactory,contentLength); } catch ( IllegalArgumentException r2d2) { geom=new GeometryCollection(null,null,-1); } catch ( Exception c3p0) { System.out.println("Error processing record (a):" + recordNumber); System.out.println(c3p0.getMessage()); c3p0.printStackTrace(); geom=new GeometryCollection(null,null,-1); } } catch ( EOFException e) { close(); } return geom; }
Returns the next geometry in the shapefile stream
public void readData(RowSetInternal caller) throws SQLException { Connection con=null; try { CachedRowSet crs=(CachedRowSet)caller; if (crs.getPageSize() == 0 && crs.size() > 0) { crs.close(); } writerCalls=0; userCon=false; con=this.connect(caller); if (con == null || crs.getCommand() == null) throw new SQLException(resBundle.handleGetObject("crsreader.connecterr").toString()); try { con.setTransactionIsolation(crs.getTransactionIsolation()); } catch ( Exception ex) { ; } PreparedStatement pstmt=con.prepareStatement(crs.getCommand()); decodeParams(caller.getParams(),pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch ( Exception ex) { throw new SQLException(ex.getMessage()); } if (crs.getCommand().toLowerCase().indexOf("select") != -1) { ResultSet rs=pstmt.executeQuery(); if (crs.getPageSize() == 0) { crs.populate(rs); } else { pstmt=con.prepareStatement(crs.getCommand(),ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); decodeParams(caller.getParams(),pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch ( Exception ex) { throw new SQLException(ex.getMessage()); } rs=pstmt.executeQuery(); crs.populate(rs,startPosition); } rs.close(); } else { pstmt.executeUpdate(); } pstmt.close(); try { con.commit(); } catch ( SQLException ex) { ; } if (getCloseConnection() == true) con.close(); } catch ( SQLException ex) { throw ex; } finally { try { if (con != null && getCloseConnection() == true) { try { if (!con.getAutoCommit()) { con.rollback(); } } catch ( Exception dummy) { } con.close(); con=null; } } catch ( SQLException e) { } } }
Reads data from a data source and populates the given <code>RowSet</code> object with that data. This method is called by the rowset internally when the application invokes the method <code>execute</code> to read a new set of rows. <P> After clearing the rowset of its contents, if any, and setting the number of writer calls to <code>0</code>, this reader calls its <code>connect</code> method to make a connection to the rowset's data source. Depending on which of the rowset's properties have been set, the <code>connect</code> method will use a <code>DataSource</code> object or the <code>DriverManager</code> facility to make a connection to the data source. <P> Once the connection to the data source is made, this reader executes the query in the calling <code>CachedRowSet</code> object's <code>command</code> property. Then it calls the rowset's <code>populate</code> method, which reads data from the <code>ResultSet</code> object produced by executing the rowset's command. The rowset is then populated with this data. <P> This method's final act is to close the connection it made, thus leaving the rowset disconnected from its data source.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case GamlPackage.TYPE_REF__REF: if (resolve) return getRef(); return basicGetRef(); case GamlPackage.TYPE_REF__PARAMETER: return getParameter(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static boolean hasHttpTimerData(InvocationSequenceData data){ return data.getTimerData() instanceof HttpTimerData; }
Checks whether this data object contains a http timer data object.
public static boolean checkSequence(SequencesReader sequences,File outputFile) throws IOException { return checkPrereadNames(sequences.names(),outputFile); }
Run the duplicate detection on one set of input sequences.
public AdditiveOperator createAdditiveOperatorFromString(EDataType eDataType,String initialValue){ AdditiveOperator result=AdditiveOperator.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '"+ eDataType.getName()+ "'"); return result; }
<!-- begin-user-doc --> <!-- end-user-doc -->
@Override protected EClass eStaticClass(){ return TypeRefsPackage.Literals.UNKNOWN_TYPE_REF; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public GlobalVisualEffectEvent(String effectName,int duration){ super(Events.GLOBAL_VISUAL); put(NAME_ATTR,effectName); put(DURATION_ATTR,duration); }
Create a new GlobalVisualEffectEvent.
public MetacatException(Response.Status status){ this(Response.status(status).type(MediaType.APPLICATION_JSON_TYPE).entity(EMPTY_ERROR).build(),null); }
Construct a new client error exception.
private byte[] generateDerivedKey(){ byte[] digestBytes=new byte[digest.getDigestSize()]; digest.update(password,0,password.length); digest.update(salt,0,salt.length); digest.doFinal(digestBytes,0); for (int i=1; i < iterationCount; i++) { digest.update(digestBytes,0,digestBytes.length); digest.doFinal(digestBytes,0); } return digestBytes; }
the derived key function, the ith hash of the password and the salt.
private int decodeBandTypes(int bandType[],int bandTypeRunEnd[],IndividualChannelStream ics){ int idx=0; final int bits=(ics.windowSequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5; for (int g=0; g < ics.numWindowGroups; g++) { int k=0; while (k < ics.maxSfb) { int sectEnd=k; int sectBandType=br.read(4); if (sectBandType == 12) { log.error(String.format("invalid band type")); return AAC_ERROR; } int sectLenIncr; do { sectLenIncr=br.read(bits); sectEnd+=sectLenIncr; if (br.getBitsLeft() < 0) { log.error(String.format("decodeBandTypes overread error")); return AAC_ERROR; } if (sectEnd > ics.maxSfb) { log.error(String.format("Number of bands (%d) exceeds limit (%d)",sectEnd,ics.maxSfb)); return AAC_ERROR; } } while (sectLenIncr == (1 << bits) - 1); for (; k < sectEnd; k++) { bandType[idx]=sectBandType; bandTypeRunEnd[idx++]=sectEnd; } } } return 0; }
Decode band types (section_data payload); reference: table 4.46.
public IMultimediaMessagingSession initiateMessagingSession(String serviceId,ContactId contact) throws RemoteException { return initiateMessagingSession2(serviceId,contact,null,null); }
Initiates a new session for real time messaging with a remote contact and for a given service extension. The messages are exchanged in real time during the session and may be from any type. The parameter contact supports the following formats: MSISDN in national or international format, SIP address, SIP-URI or Tel-URI. If the format of the contact is not supported an exception is thrown.
public static FunctionalReadWriteLock reentrant(){ return create(new ReentrantReadWriteLock()); }
Create a read-write lock that supports reentrancy.
public JSONObject put(String key,int value) throws JSONException { this.put(key,new Integer(value)); return this; }
Put a key/int pair in the JSONObject.
public UUID generateUUID(){ String uuidString=""; UUID uuid=null; while (!uuidString.matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") || assignedUUIDs.contains(uuid)) { uuid=UUID.randomUUID(); uuidString=uuid.toString(); } assignedUUIDs.add(uuid); return uuid; }
A method that generates a UUID Note: This method does not guarantee uniqueness across multiple invocations of the Photon library
public final void testValidateSucceeds(){ EmailAddressValidator emailAddressValidator=new EmailAddressValidator("foo"); assertTrue(emailAddressValidator.validate("")); assertTrue(emailAddressValidator.validate("foo@bar.com")); assertTrue(emailAddressValidator.validate("foo-100@bar.com")); assertTrue(emailAddressValidator.validate("foo.100@bar.com")); assertTrue(emailAddressValidator.validate("foo100@bar.com")); assertTrue(emailAddressValidator.validate("foo-100@bar.net")); assertTrue(emailAddressValidator.validate("foo.100@bar.com.au")); assertTrue(emailAddressValidator.validate("foo@123.com")); assertTrue(emailAddressValidator.validate("foo@bar.com.com")); assertTrue(emailAddressValidator.validate("foo+100@bar.com")); assertTrue(emailAddressValidator.validate("foo-100@bar-test.com")); }
Tests the functionality of the validate-method, if it succeeds.
public boolean equivalentTo(Fitness _fitness){ MultiObjectiveFitness other=(MultiObjectiveFitness)_fitness; boolean abeatsb=false; boolean bbeatsa=false; if (objectives.length != other.objectives.length) throw new RuntimeException("Attempt made to compare two multiobjective fitnesses; but they have different numbers of objectives."); for (int x=0; x < objectives.length; x++) { if (maximize[x] != other.maximize[x]) throw new RuntimeException("Attempt made to compare two multiobjective fitnesses; but for objective #" + x + ", one expects higher values to be better and the other expectes lower values to be better."); if (maximize[x]) { if (objectives[x] > other.objectives[x]) abeatsb=true; if (objectives[x] < other.objectives[x]) bbeatsa=true; if (abeatsb && bbeatsa) return true; } else { if (objectives[x] < other.objectives[x]) abeatsb=true; if (objectives[x] > other.objectives[x]) bbeatsa=true; if (abeatsb && bbeatsa) return true; } } if (abeatsb || bbeatsa) return false; return true; }
Returns true if I'm equivalent in fitness (neither better nor worse) to _fitness. The rule I'm using is this: If one of us is better in one or more criteria, and we are equal in the others, then equivalentTo is false. If each of us is better in one or more criteria each, or we are equal in all criteria, then equivalentTo is true. Multiobjective optimization algorithms may choose to override this to do something else.
public static void initConfig(Config config){ config.registerForUpdates(null); }
Must be called before logger objects are created.
public void tuneMemory(double m){ if (m == 0) memoryA=0.0; else memoryA=Math.pow(memoryA,1.0 / m); }
Values greater than 1.0 (towards infinite) increase the memory towards 1. Values smaller than 1.0 (towards zero) decreases the memory .
public void createPictScenario03_3() throws Exception { long usageStartTime=DateTimeHandling.calculateMillis("2013-03-01 00:00:00"); BillingIntegrationTestBase.setDateFactoryInstance(usageStartTime); String supplierAdminId="Pict03_3Supplier"; VOOrganization supplier=orgSetup.createOrganization(basicSetup.getPlatformOperatorUserKey(),supplierAdminId,"Pict03_3SupplierOrg",TestOrganizationSetup.ORGANIZATION_DOMICILE_DE,OrganizationRoleType.TECHNOLOGY_PROVIDER,OrganizationRoleType.SUPPLIER); VOUser supplierAdmin=orgSetup.getUser(supplierAdminId,true); VOMarketplace supplMarketplace=orgSetup.createMarketplace("Pict03_3Supplier_MP",false,supplier); paymentSetup.createPaymentForSupplier(basicSetup.getPlatformOperatorUserKey(),supplierAdmin.getKey(),supplier); container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER,ROLE_TECHNOLOGY_MANAGER); serviceSetup.importTechnicalServices(BaseAdmUmTest.TECHNICAL_SERVICE_EXAMPLE2_XML); VOTechnicalService example2TechService=serviceSetup.getTechnicalService(VOTechServiceFactory.TECH_SERVICE_EXAMPLE2_ID); setCutOffDay(supplierAdmin.getKey(),1); String customerAdminId="PIC03_3Customer"; VOOrganization customer=orgSetup.registerCustomer("PIC03_3CustomerOrg",TestOrganizationSetup.ORGANIZATION_DOMICILE_UK,customerAdminId,supplMarketplace.getMarketplaceId(),supplier.getOrganizationId()); VOUser customerAdmin=orgSetup.getUser(customerAdminId,true); VOServiceDetails serviceDetailsTemp=serviceSetup.createAndPublishMarketableService(supplierAdmin.getKey(),"PICT_TEST_03_3",TestService.EXAMPLE2,TestPriceModel.FREE,example2TechService,supplMarketplace); VOServiceDetails serviceDetails=serviceSetup.savePriceModelForCustomer(serviceDetailsTemp,TestPriceModel.EXAMPLE_PICT03_UNIT_HOUR,customer); serviceDetails=serviceSetup.activateMarketableService(serviceDetails); VORoleDefinition role=VOServiceFactory.getRole(serviceDetails,"ADMIN"); container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN); VOSubscriptionDetails subDetails=subscrSetup.subscribeToService("PICT_TEST_03_3",serviceDetails,customerAdmin,role); long userDeassignedTime=DateTimeHandling.calculateMillis("2013-03-02 10:00:00"); BillingIntegrationTestBase.setDateFactoryInstance(userDeassignedTime); subscrSetup.revokeUser(customerAdmin,subDetails.getSubscriptionId()); long userAssignedTime=DateTimeHandling.calculateMillis("2013-03-02 12:00:00"); BillingIntegrationTestBase.setDateFactoryInstance(userAssignedTime); role=VOServiceFactory.getRole(serviceDetails,"USER"); subDetails=subscrSetup.addUser(customerAdmin,role,subDetails.getSubscriptionId()); userDeassignedTime=DateTimeHandling.calculateMillis("2013-03-02 13:00:00"); BillingIntegrationTestBase.setDateFactoryInstance(userDeassignedTime); subscrSetup.revokeUser(customerAdmin,subDetails.getSubscriptionId()); userAssignedTime=DateTimeHandling.calculateMillis("2013-03-02 14:00:00"); BillingIntegrationTestBase.setDateFactoryInstance(userAssignedTime); subDetails=subscrSetup.addUser(customerAdmin,role,subDetails.getSubscriptionId()); userDeassignedTime=DateTimeHandling.calculateMillis("2013-03-22 10:10:00"); BillingIntegrationTestBase.setDateFactoryInstance(userDeassignedTime); subscrSetup.revokeUser(customerAdmin,subDetails.getSubscriptionId()); userAssignedTime=DateTimeHandling.calculateMillis("2013-03-22 10:20:00"); BillingIntegrationTestBase.setDateFactoryInstance(userAssignedTime); role=VOServiceFactory.getRole(serviceDetails,"ADMIN"); subDetails=subscrSetup.addUser(customerAdmin,role,subDetails.getSubscriptionId()); container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN); long userterminateTime=DateTimeHandling.calculateMillis("2013-04-01 10:00:00"); BillingIntegrationTestBase.setDateFactoryInstance(userterminateTime); subscrSetup.unsubscribeToService(subDetails.getSubscriptionId()); BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-04-01 13:00:01")); container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER); serviceSetup.deleteMarketableService(serviceDetails); BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-11-01 13:00:02")); container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER); serviceSetup.deleteMarketableService(serviceDetailsTemp); BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-04-01 13:00:03")); container.login(supplierAdmin.getKey(),ROLE_TECHNOLOGY_MANAGER); serviceSetup.deleteTechnicalService(example2TechService); resetCutOffDay(supplierAdmin.getKey()); BillingIntegrationTestBase.updateSubscriptionListForTests("PICT_TEST_03_3",subDetails); BillingIntegrationTestBase.updateCustomerListForTests("PICT_TEST_03_3",customer); }
See testcase #3 of BESBillingFactorCombinations.xlsx variation of testcase #3 with role change within time-unit hour w daylight savings change in same month March (simple version)
protected void addLiteralValuePropertyDescriptor(Object object){ itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),getResourceLocator(),getString("_UI_Enumerator_literalValue_feature"),getString("_UI_PropertyDescriptor_description","_UI_Enumerator_literalValue_feature","_UI_Enumerator_type"),TypesPackage.Literals.ENUMERATOR__LITERAL_VALUE,false,false,false,ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE,null,null)); }
This adds a property descriptor for the Literal Value feature. <!-- begin-user-doc --> <!-- end-user-doc -->
private void decodeRules(){ decodeStartRule(); decodeEndRule(); }
Given a set of encoded rules in startDay and startDayOfMonth, decode them and set the startMode appropriately. Do the same for endDay and endDayOfMonth. Upon entry, the day of week variables may be zero or negative, in order to indicate special modes. The day of month variables may also be negative. Upon exit, the mode variables will be set, and the day of week and day of month variables will be positive. This method also recognizes a startDay or endDay of zero as indicating no DST.
public void add(String item,int index){ addItem(item,index); }
Adds the specified item to the the scrolling list at the position indicated by the index. The index is zero-based. If the value of the index is less than zero, or if the value of the index is greater than or equal to the number of items in the list, then the item is added to the end of the list.
public RtpPacket readRtpPacket() throws TimeoutException { try { byte[] data=(byte[])fifo.getObject(timeout); if (data == null) { throw new TimeoutException(); } RtpPacket pkt=parseRtpPacket(data); if (pkt != null) { stats.numPackets++; stats.numBytes+=data.length; RtpSource s=rtcpSession.getMySource(); s.setSsrc(pkt.ssrc); s.activeSender=true; s.receiveRtpPacket(pkt); pkt.seqnum=s.generateExtendedSequenceNumber(pkt.seqnum); return pkt; } else { return readRtpPacket(); } } catch ( Exception e) { if (!isClosed) { stats.numBadRtpPkts++; } return null; } }
Read a RTP packet (blocking method)
public boolean canChangeTo(OnlineStatus newStatus){ if (this.equals(newStatus)) { return false; } if (newStatus.equals(UNKNOWN)) { return false; } switch (this) { case OFFLINE: if (newStatus.equals(ONLINE)) { return false; } case ONLINE: if (newStatus.equals(OFFLINE)) { return false; } default : return true; } }
Defines if the status can be changed.
public ItemStack addItem(ItemStack drive,ItemStack item){ if (getMaxKilobits(drive) == -1) { if (getPartitioningMode(drive) == PartitioningMode.NONE || findDataIndexForPrototype(drive,createPrototype(item)) != -1) { item.stackSize=0; return null; } else { return item; } } int bitsFree=getKilobitsFreeFor(drive,item); int amountTaken=Math.min(item.stackSize,bitsFree); int current=getAmountStored(drive,item); if (amountTaken > 0) { setAmountStored(drive,item,current + amountTaken); item.stackSize-=amountTaken; markDirty(drive); } if (item.stackSize <= 0) { return null; } else { return item; } }
Insert as many items as possible from the given stack into a drive. <p> The stackSize of the passed stack will be affected. Return value is for convenience, and will be null if all items are taken.
public void println(String s){ long now=System.currentTimeMillis(); if (now > lastPrint + 1000) { lastPrint=now; long time=now - start; printlnWithTime(time,getClass().getName() + " " + s); } }
Print a message to system out.
@SkipValidation @Action(value="/modifyProperty-modifyDataEntry") public String modifyDataEntry(){ LOGGER.debug("Entered into modifyForm, \nIndexNumber: " + indexNumber + ", BasicProperty: "+ basicProp+ ", OldProperty: "+ oldProperty+ ", PropertyModel: "+ propertyModel); String target=""; target=populateFormData(Boolean.FALSE); LOGGER.debug("modifyForm: IsAuthProp: " + getIsAuthProp() + ", AreaOfPlot: "+ getAreaOfPlot()+ ", PropTypeId: "+ getPropTypeId()+ ", PropTypeCategoryId: "+ getPropertyCategory()+ ", PropUsageId: "+ getPropUsageId()+ ", PropOccId: "+ getPropOccId()); LOGGER.debug("Exiting from modifyForm"); return target; }
Returns modify data entry form
default Map<String,?> toMap(){ try { final Object o=unwrap(); final Map<String,Object> result=new HashMap<>(); for ( final Field f : ReflectionCache.getFields(o.getClass())) { result.put(f.getName(),f.get(o)); } return result; } catch ( final Exception e) { throw ExceptionSoftener.throwSoftenedException(e); } }
default implementation maps field values on the host object by name
void createAnimationImage(){ GraphicsConfiguration gc=getGraphicsConfiguration(); image=gc.createCompatibleImage(imageW,imageH,Transparency.TRANSLUCENT); Graphics2D gImg=image.createGraphics(); if (useImage) { try { URL url=getClass().getResource("images/duke.gif"); Image originalImage=ImageIO.read(url); gImg.drawImage(originalImage,0,0,imageW,imageH,null); } catch ( Exception e) { } } else { Color graphicsColor; if (alterColor) { graphicsColor=Color.LIGHT_GRAY; } else { graphicsColor=Color.BLACK; } gImg.setColor(graphicsColor); gImg.fillRect(0,0,imageW,imageH); if (useAA) { gImg.setComposite(AlphaComposite.Src); int red=graphicsColor.getRed(); int green=graphicsColor.getRed(); int blue=graphicsColor.getRed(); gImg.setColor(new Color(red,green,blue,50)); gImg.drawRect(0,0,imageW - 1,imageH - 1); gImg.setColor(new Color(red,green,blue,100)); gImg.drawRect(1,1,imageW - 3,imageH - 3); gImg.setColor(new Color(red,green,blue,150)); gImg.drawRect(2,2,imageW - 5,imageH - 5); gImg.setColor(new Color(red,green,blue,200)); gImg.drawRect(3,3,imageW - 7,imageH - 7); gImg.setColor(new Color(red,green,blue,225)); gImg.drawRect(4,4,imageW - 9,imageH - 9); } } gImg.dispose(); }
Create the image that will be animated. This image may be an actual image (duke.gif), or some graphics (a variation on a black filled rectangle) that are rendered into an image. The contents of this image are dependent upon the runtime toggles that have been set when this method is called.
public boolean isIncludeTrailingSemicolons(){ return includeTrailingSemicolons; }
Gets whether to include trailing semicolon delimiters for structured property values whose list of values end with null or empty values.