code
stringlengths
10
174k
nl
stringlengths
3
129k
protected void doAfter(){ }
Do something after each test run.
public String toXML(boolean header){ XmlTextBuilder bdr; String tagName="Document"; bdr=new XmlTextBuilder(); if (header) bdr.setStandardHeader(); bdr.addOpeningTag(tagName); bdr.addSimpleElement("ContentSize","" + content.length); bdr.addSimpleElement("Extension",extension); bdr.addSimpleElement("MimeType",mimeType); bdr.addClosingTag(tagName); return bdr.getText(); }
Recoge los valores de la instancia en una cadena xml
public abbr addElement(String hashcode,String element){ addElementToRegistry(hashcode,element); return (this); }
Adds an Element to the element.
void encodeYUV420(byte[] yuv420sp,int[] argb,int width,int height){ final int frameSize=width * height; int yIndex=0; int uvIndex=frameSize; int vuIndex=frameSize + frameSize / 4; int a, R, G, B, Y, U, V; int index=0; for (int y=0; y < height; y++) { for (int x=0; x < width; x++) { a=(argb[index] & 0xff000000) >> 24; R=(argb[index] & 0xff0000) >> 16; G=(argb[index] & 0xff00) >> 8; B=(argb[index] & 0xff) >> 0; Y=((66 * R + 129 * G + 25 * B + 128) >> 8) + 16; U=((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128; V=((112 * R - 94 * G - 18 * B + 128) >> 8) + 128; yuv420sp[yIndex]=(byte)((Y < 0) ? 0 : ((Y > 255) ? 255 : Y)); if (y % 2 == 0 && x % 2 == 0) { yuv420sp[uvIndex]=(byte)((V < 0) ? 0 : ((V > 255) ? 255 : V)); yuv420sp[vuIndex]=(byte)((U < 0) ? 0 : ((U > 255) ? 255 : U)); } yIndex++; if (y % 2 == 0 && x % 2 == 0) { uvIndex++; vuIndex++; } index++; } } }
This draws the 'lastImage' member into the incoming buffer while customizing pixels
private AbstractBURS_TreeNode buildTree(Instruction s){ AbstractBURS_TreeNode root=AbstractBURS_TreeNode.create(new DepGraphNode(s)); AbstractBURS_TreeNode cur=root; for (Enumeration<Operand> uses=s.getUses(); uses.hasMoreElements(); ) { Operand op=uses.nextElement(); if (op == null) continue; AbstractBURS_TreeNode child; if (op instanceof RegisterOperand) { if (op.asRegister().getRegister().isValidation()) continue; child=Register; } else if (op instanceof IntConstantOperand) { child=new BURS_IntConstantTreeNode(((IntConstantOperand)op).value); } else if (op instanceof LongConstantOperand) { child=LongConstant; } else if (op instanceof AddressConstantOperand) { child=AddressConstant; } else if (op instanceof BranchOperand && s.isCall()) { child=BranchTarget; } else if (op instanceof InlinedOsrTypeInfoOperand && s.isYieldPoint()) { child=NullTreeNode; } else { continue; } if (cur.child1 == null) { cur.child1=child; } else if (cur.child2 == null) { cur.child2=child; } else { AbstractBURS_TreeNode child1=cur.child2; AbstractBURS_TreeNode aux=AbstractBURS_TreeNode.create(OTHER_OPERAND_opcode); cur.child2=aux; cur=aux; cur.child1=child1; cur.child2=child; } } switch (s.getOpcode()) { case CALL_opcode: case SYSCALL_opcode: case YIELDPOINT_OSR_opcode: if (cur.child2 == null) { cur.child2=NullTreeNode; } case RETURN_opcode: if (cur.child1 == null) { cur.child1=NullTreeNode; } } return root; }
Build a BURS Tree for each Instruction. Complete BURS trees by adding leaf nodes as needed, and creating tree edges by calling insertChild1() or insertChild2() This step is also where we introduce intermediate tree nodes for any LIR instruction that has &gt; 2 "real" operands e.g., a CALL.
private static boolean isFourBytesSequence(byte b){ return -16 <= b && b <= -9; }
If the byte has the form 11110xx, then it's the first byte of a four-bytes sequence character.
public void write(byte[] data,int offset,int length) throws IOException { assert data.length >= offset + length; while (length > 0) { int toWrite=Math.min(length,NfcClient.MAX_XFER_SIZE); writeInt(data,offset,toWrite); offset+=toWrite; length-=toWrite; } }
Write data. FILE_DATA message is sent immediately, so caller should buffer as necessary.
public final void close(){ try { log.info("Closing ..."); assert (writer != null); writer.flush(); writer.close(); log.info("... done!"); } catch ( IOException e) { e.printStackTrace(); } }
finalize and close csv file
public PeopleInfo(){ m_sID=null; m_sName=null; }
Creates a new instance of RoleInfo
public DatagramPacket responseReceive() throws IOException { byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,buf.length); datagramSocket.receive(dp); return dp; }
Used to receive SSDP Response packet
public PLSTTest(String name){ super(name); }
Initializes the test.
public static ResultSet varArgsFunctionTable(int... values) throws SQLException { if (values.length != 6) { throw new SQLException("Unexpected argument count"); } SimpleResultSet result=new SimpleResultSet(); result.addColumn("A",Types.INTEGER,0,0); for ( int value : values) { result.addRow(value); } return result; }
This method is called via reflection from the database.
static void loadActionMap(LazyActionMap map){ map.put(new Actions(Actions.PRESS)); map.put(new Actions(Actions.RELEASE)); }
Populates Buttons actions.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public DrawerBuilder withStickyFooterShadow(boolean stickyFooterShadow){ this.mStickyFooterShadow=stickyFooterShadow; return this; }
Set this to false if you don't want the shadow on top of the sticky footer
public static SimpleDataSet read(Path path,int lines_to_skip,Set<Integer> cat_cols) throws IOException { return read(path,DEFAULT_DELIMITER,lines_to_skip,DEFAULT_COMMENT,cat_cols); }
Reads in the given CSV dataset as a simple CSV file
public com.linkedin.camus.example.records.DummyLog.Builder clearId(){ fieldSetFlags()[0]=false; return this; }
Clears the value of the 'id' field
@SmallTest public void testCreateSpeechRules_dropEventIfNoFormatter() throws Exception { final String strategy="<ss:rule>" + " <ss:filter>" + " <ss:eventType>TYPE_VIEW_CLICKED</ss:eventType>"+ " </ss:filter>"+ "</ss:rule>"; final AccessibilityEvent event=AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_CLICKED); final EventSpeechRuleProcessor processor=createProcessorWithStrategy(strategy,1); final Utterance utterance=new Utterance(); final boolean processed=processor.processEvent(event,utterance); assertTrue("The event must match the filter",processed); assertTrue("No utterance should be produced",TextUtils.isEmpty(StringBuilderUtils.getAggregateText(utterance.getSpoken()))); }
Test if an event is dropped on the floor if no formatter is specified.
@VisibleForTesting void simulateAttachForTesting(){ mIsAttachedToInstance=true; mWasMeasured=true; }
Is used by unit test to setup mWasMeasured and mIsAttachedToWindow flags, that will let this view to be properly attached to catalyst instance by startReactApplication call
private double computeDepth() throws WikiApiException { Category root=wiki.getMetaData().getMainCategory(); if (root == null) { logger.error("There is no root node for this wiki. Check the parameter that provides the name of the root node."); return 0.0; } if (!graph.containsVertex(root.getPageId())) { logger.error("The root node is not part of this graph. Cannot compute depth of this graph. Setting depth to 0.0"); return 0.0; } double maxPathLength=0.0; double[] returnValues=computeShortestPathLenghts(root.getPageId(),0.0,maxPathLength,new HashSet<Integer>()); maxPathLength=returnValues[1]; return maxPathLength; }
Computes the depth of the category graph, i.e. the maximum path length starting with the root node.
private void updateProgress(String progressLabel,int progress){ if (myHost != null) { myHost.updateProgress(progressLabel,progress); } else { System.out.println(progressLabel + " " + progress+ "%"); } }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public String processCallOut(GridField field,Object value,Object oldValue,int currentRow,int currentColumn){ String callout=field.getCallout(); if (callout.length() == 0) return ""; logger.fine(field.getColumnName() + "=" + value+ " ("+ callout+ ") - old="+ oldValue); StringTokenizer st=new StringTokenizer(callout,";,",false); while (st.hasMoreTokens()) { String cmd=st.nextToken().trim(); if (activeCallOuts.contains(cmd)) continue; String retValue=""; if (cmd.toLowerCase().startsWith(MRule.SCRIPT_PREFIX)) { MRule rule=MRule.get(ctx,cmd.substring(MRule.SCRIPT_PREFIX.length())); if (rule == null) { retValue="Callout " + cmd + " not found"; logger.log(Level.SEVERE,retValue); return retValue; } if (!(rule.getEventType().equals(MRule.EVENTTYPE_Callout) && rule.getRuleType().equals(MRule.RULETYPE_JSR223ScriptingAPIs))) { retValue="Callout " + cmd + " must be of type JSR 223 and event Callout"; logger.log(Level.SEVERE,retValue); return retValue; } ScriptEngine engine=rule.getScriptEngine(); MRule.setContext(engine,ctx,browser.getWindowNo()); engine.put(MRule.ARGUMENTS_PREFIX + "WindowNo",browser.getWindowNo()); engine.put(MRule.ARGUMENTS_PREFIX + "Tab",this); engine.put(MRule.ARGUMENTS_PREFIX + "Field",field); engine.put(MRule.ARGUMENTS_PREFIX + "Value",value); engine.put(MRule.ARGUMENTS_PREFIX + "OldValue",oldValue); engine.put(MRule.ARGUMENTS_PREFIX + "currentRow",currentRow); engine.put(MRule.ARGUMENTS_PREFIX + "currentColumn",currentColumn); engine.put(MRule.ARGUMENTS_PREFIX + "Ctx",ctx); try { activeCallOuts.add(cmd); retValue=engine.eval(rule.getScript()).toString(); } catch ( Exception e) { logger.log(Level.SEVERE,"",e); retValue="Callout Invalid: " + e.toString(); return retValue; } finally { activeCallOuts.remove(cmd); } } else { WBrowserCallout call=null; String method=null; int methodStart=cmd.lastIndexOf('.'); try { if (methodStart != -1) { Class<?> cClass=Class.forName(cmd.substring(0,methodStart)); call=(WBrowserCallout)cClass.newInstance(); method=cmd.substring(methodStart + 1); } } catch ( Exception e) { logger.log(Level.SEVERE,"class",e); return "Callout Invalid: " + cmd + " ("+ e.toString()+ ")"; } if (call == null || method == null || method.length() == 0) return "Callout Invalid: " + method; try { activeCallOuts.add(cmd); activeCallOutInstance.add(call); retValue=call.start(ctx,method,browser.getWindowNo(),browserRows,field,value,oldValue,currentRow,currentColumn); } catch ( Exception e) { logger.log(Level.SEVERE,"start",e); retValue="Callout Invalid: " + e.toString(); return retValue; } finally { activeCallOuts.remove(cmd); activeCallOutInstance.remove(call); } } if (!Util.isEmpty(retValue)) { logger.severe(retValue); return retValue; } } return ""; }
Carlos Parada Adapted for Browse Callouts Process Callout(s) Adapted. <p> The Callout is in the string of "class.method;class.method;" If there is no class name, i.e. only a method name, the class is regarded as CalloutSystem. The class needs to comply with the Interface Callout. For a limited time, the old notation of Sx_matheod / Ux_menthod is maintained.
protected SVGDocument cloneDocument(){ return (SVGDocument)new CloneNoExport().cloneDocument(getDomImpl(),document); }
Clone the SVGPlot document for transcoding. This will usually be necessary for exporting the SVG document if it is currently being displayed: otherwise, we break the Batik rendering trees. (Discovered by Simon).
public StrBuilder trim(){ if (size == 0) { return this; } int len=size; char[] buf=buffer; int pos=0; while (pos < len && buf[pos] <= ' ') { pos++; } while (pos < len && buf[len - 1] <= ' ') { len--; } if (len < size) { delete(len,size); } if (pos > 0) { delete(0,pos); } return this; }
Trims the builder by removing characters less than or equal to a space from the beginning and end.
public static String mapLibraryName(String userLibName){ return VMCommonLibrarySupport.mapLibraryName(userLibName); }
Answers the platform specific file name format for the shared library named by the argument.
public boolean isNeighbourMutual(int i){ return neighbours.get(i).isMutual(); }
Is our neighbouring block at index i a mutual neighbour, ie both blocks have each other registered as neighbours and are exchaning information.
public boolean hasLayer(final String layername){ return getLayer(layername) != null; }
Return true if the layer with given name exists.
public boolean needsLayouting(){ return m_needsLayouting; }
Returns whether the graph needs to be layouted again to make the changes happen.
private ArrayList<ArrayDBIDs> buildOneDimIndexes(Relation<? extends NumberVector> relation){ final int dim=RelationUtil.dimensionality(relation); ArrayList<ArrayDBIDs> subspaceIndex=new ArrayList<>(dim + 1); SortDBIDsBySingleDimension comp=new VectorUtil.SortDBIDsBySingleDimension(relation); for (int i=0; i < dim; i++) { ArrayModifiableDBIDs amDBIDs=DBIDUtil.newArray(relation.getDBIDs()); comp.setDimension(i); amDBIDs.sort(comp); subspaceIndex.add(amDBIDs); } return subspaceIndex; }
Calculates "index structures" for every attribute, i.e. sorts a ModifiableArray of every DBID in the database for every dimension and stores them in a list
public LinkIcon(boolean linked){ this.linked=linked; link=linked ? linkedImIc.getImage() : unlinkedImIc.getImage(); addMouseListener(this); Dimension dim=new Dimension((int)link.getWidth(null),link.getHeight(null)); setPreferredSize(dim); setMinimumSize(dim); setMaximumSize(dim); setSize(dim); setLayout(null); repaint(); }
Create a lock icon either in the locked or unlocked state.
public synchronized FileSetSetting createFileSetSetting(String key,File[] defaultValue){ FileSetSetting result=new FileSetSetting(DEFAULT_PROPS,PROPS,key,defaultValue); handleSettingInternal(result,null); return result; }
Creates a new <tt>FileSetSetting</tt> instance for a File array setting with the specified key and default value.
void initFirstBlock(int maxStack,int maxLocals,String className,String methodDesc,boolean isStatic,boolean isConstructor) throws BadBytecode { if (methodDesc.charAt(0) != '(') throw new BadBytecode("no method descriptor: " + methodDesc); stackTop=0; stackTypes=TypeData.make(maxStack); TypeData[] locals=TypeData.make(maxLocals); if (isConstructor) locals[0]=new TypeData.UninitThis(className); else if (!isStatic) locals[0]=new TypeData.ClassName(className); int n=isStatic ? -1 : 0; int i=1; try { while ((i=descToTag(methodDesc,i,++n,locals)) > 0) if (locals[n].is2WordType()) locals[++n]=TypeTag.TOP; } catch ( StringIndexOutOfBoundsException e) { throw new BadBytecode("bad method descriptor: " + methodDesc); } numLocals=n; localsTypes=locals; }
Initializes the first block by the given method descriptor.
public synchronized ByteSetting createByteSetting(String key,byte defaultValue){ ByteSetting result=new ByteSetting(DEFAULT_PROPS,PROPS,key,defaultValue); handleSettingInternal(result,null); return result; }
Creates a new <tt>ByteSetting</tt> instance with the specified key and default value.
public ChangeCorrectionProposal(String name,Change change,int relevance,Images image){ if (name == null) { throw new IllegalArgumentException("Name must not be null"); } fName=name; fChange=change; fRelevance=relevance; fImage=image; fCommandId=null; }
Constructs a change correction proposal.
public FontFace(List srcs,String familyName,float unitsPerEm,String fontWeight,String fontStyle,String fontVariant,String fontStretch,float slope,String panose1,float ascent,float descent,float strikethroughPosition,float strikethroughThickness,float underlinePosition,float underlineThickness,float overlinePosition,float overlineThickness){ super(familyName,unitsPerEm,fontWeight,fontStyle,fontVariant,fontStretch,slope,panose1,ascent,descent,strikethroughPosition,strikethroughThickness,underlinePosition,underlineThickness,overlinePosition,overlineThickness); this.srcs=srcs; }
Constructes an SVGFontFace with the specfied font-face attributes.
public static int determineThreads(Output output,ParameterDatabase parameters,Parameter threadParameter){ int thread=1; String tmp_s=parameters.getString(threadParameter,null); if (tmp_s == null) { output.fatal("Threads number must exist.",threadParameter,null); } else if (V_THREADS_AUTO.equalsIgnoreCase(tmp_s)) { Runtime runtime=Runtime.getRuntime(); try { return ((Integer)runtime.getClass().getMethod("availableProcessors",(Class[])null).invoke(runtime,(Object[])null)).intValue(); } catch ( Exception e) { output.fatal("Whoa! This Java version is to old to have the Runtime.availableProcessors() method available.\n" + "This means you can't use 'auto' as a threads option.",threadParameter,null); } } else { try { thread=parameters.getInt(threadParameter,null); } catch ( NumberFormatException e) { output.fatal("Invalid, non-integer threads value (" + thread + ")",threadParameter,null); } } return thread; }
Loads the number of threads.
public static List<Initiator> findIfInitiatorsAreUserAddedInAnotherMask(ExportMask exportMask,List<Initiator> newInitiators,DbClient dbClient){ List<Initiator> userAddedInitiators=new ArrayList<>(); for ( ExportMask matchedMask : ExportMaskUtils.getExportMasksWithInitiators(dbClient,newInitiators).values()) { if (matchedMask.getId().equals(exportMask.getId()) || !matchedMask.getStorageDevice().equals(exportMask.getStorageDevice())) { continue; } Iterator<Initiator> iterator=newInitiators.iterator(); while (iterator.hasNext()) { Initiator initiator=iterator.next(); if (matchedMask.hasUserInitiator(initiator.getId())) { userAddedInitiators.add(initiator); iterator.remove(); } } } Collection portNames=Collections2.transform(userAddedInitiators,CommonTransformerFunctions.fctnInitiatorToPortName()); if (!portNames.isEmpty()) { _log.info(String.format("The following initiators were found in another ExportMask as user-added initiators: %s",CommonTransformerFunctions.collectionToString(portNames))); } return userAddedInitiators; }
Given a list of Initiators, find if any are in an ExportMask's userAddedInitiators list- other than the 'exportMask' passed into the routine. If such an ExportMask is found, then the initiator will be removed from 'newInitiators' and added to the result list.
private void runCommand(LibertyInstall install,String command,Map<String,String> env) throws Exception { Process p=install.runCommand(command,env); if (!"run".equals(command)) { int retVal=p.waitFor(); if (retVal != 0) { throw new Exception("WebSphere Liberty failed to start with return code " + retVal); } } else { } }
Run the specified server command on WebSphere Liberty waiting for it to complete.
private void ensureCapacity(){ if (size >= data.length) { E[] newData=(E[])(new Object[size * 2 + 1]); System.arraycopy(data,0,newData,0,size); data=newData; } }
Create a new larger array, double the current size + 1
void sendLocationUpdate(Location location){ if (location == null) { return; } XmppMsg msg=new XmppMsg(); if (_settingsManager.useGoogleMapUrl) { msg.appendLine("http://maps.google.com/maps?q=" + location.getLatitude() + ","+ location.getLongitude()); } if (_settingsManager.useOpenStreetMapUrl) { msg.appendLine("http://www.openstreetmap.org/?mlat=" + location.getLatitude() + "&mlon="+ location.getLongitude()+ "&zoom=14&layers=M"); } msg.appendLine(getString(R.string.chat_geo_accuracy,location.getAccuracy())); msg.appendLine(getString(R.string.chat_geo_altitude,location.getAltitude())); msg.appendLine(getString(R.string.chat_geo_speed,location.getSpeed())); msg.appendLine(getString(R.string.chat_geo_provider,location.getProvider())); send(msg); }
Sends the location to the user.
@Override public int read() throws IOException { if (read_pos == read_pos_end) { throw new EndOfBufferException(); } return buffer[read_pos++] & 0xFF; }
read an opaque value;
void log(String msg){ System.err.println(msg); }
Write a message to stderr.
public int priority(){ return numObjects(); }
Returns the priority of this interval (used as key in the heap).
private boolean pauseTrue(int lo,int hi) throws Exception { super.pause(lo,hi); return true; }
A version of pause() that makes it easier to ensure that we pause exactly the right number of times.
protected static void resetLockedMeta(Spannable content){ resetLock(content,CAP); resetLock(content,ALT); resetLock(content,SYM); resetLock(content,SELECTING); }
Call this if you are a method that ignores the locked meta state (arrow keys, for example) and you handle a key.
public NoPermissionException(){ super(); }
Constructs a new instance of NoPermissionException. All fields are initialized to null.
private boolean doGroupSnapshotSessionCreation(List<BlockSnapshotSession> snapSessions){ boolean doGroupCreation=false; if (snapSessions.size() > 1) { doGroupCreation=true; } else { BlockSnapshotSession snapSession=snapSessions.get(0); URI sourceObjURI=snapSession.getParent().getURI(); BlockObject sourceObj=BlockObject.fetch(_dbClient,sourceObjURI); URI cgURI=sourceObj.getConsistencyGroup(); if (!NullColumnValueGetter.isNullURI(cgURI)) { doGroupCreation=true; } } return doGroupCreation; }
Determines whether we do group snapshot session creation on the array.
public JSONArray put(Map value){ this.put(new JSONObject(value)); return this; }
Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.
public void updateDouble(String columnName,double x) throws SQLException { updateDouble(findColumn(columnName),x); }
JDBC 2.0 Update a column with a double value. The updateXXX() methods are used to update column values in the current row, or the insert row. The updateXXX() methods do not update the underlying database, instead the updateRow() or insertRow() methods are called to update the database.
<T extends VPlexResourceInfo>T renameVPlexResource(T resourceInfo,String newName) throws VPlexApiException { StringBuilder pathBuilder=new StringBuilder(); pathBuilder.append(VPlexApiConstants.VPLEX_PATH); pathBuilder.append(resourceInfo.getPath()); pathBuilder.append("?"); pathBuilder.append(VPlexApiConstants.ATTRIBUTE_NAME_JSON_KEY); pathBuilder.append("="); pathBuilder.append(newName); URI requestURI=_vplexApiClient.getBaseURI().resolve(URI.create(pathBuilder.toString())); s_logger.info("Update name URI is {}",requestURI.toString()); int retryCount=0; while (++retryCount <= VPlexApiConstants.RENAME_RESOURCE_MAX_TRIES) { ClientResponse response=_vplexApiClient.put(requestURI); String responseStr=response.getEntity(String.class); s_logger.info("Update name response is {}",responseStr); if (response.getStatus() != VPlexApiConstants.SUCCESS_STATUS) { if (response.getStatus() == VPlexApiConstants.ASYNC_STATUS) { s_logger.info("Update name is completing asynchronously"); _vplexApiClient.waitForCompletion(response); response.close(); } else { response.close(); if (retryCount == VPlexApiConstants.RENAME_RESOURCE_MAX_TRIES) { String cause=VPlexApiUtils.getCauseOfFailureFromResponse(responseStr); throw VPlexApiException.exceptions.renameResourceFailureStatus(String.valueOf(response.getStatus()),cause); } else { s_logger.info(String.format("Update name for resource %s failed on attempt %d of %d, retrying...",resourceInfo.getName(),retryCount,VPlexApiConstants.RENAME_RESOURCE_MAX_TRIES)); VPlexApiUtils.pauseThread(VPlexApiConstants.RENAME_RESOURCE_SLEEP_TIME_MS); continue; } } } String newPath=resourceInfo.getPath().replaceFirst(resourceInfo.getName(),newName); resourceInfo.setPath(newPath); resourceInfo.setName(newName); break; } return resourceInfo; }
Rename a VPlex resource that subclasses VPlexResourceInfo. Adjusts the path and name in the resourceInfo and returns the original object.
public Builder cacheInMemory(boolean cacheInMemory){ this.cacheInMemory=cacheInMemory; return this; }
Sets whether loaded image will be cached in memory
public FileChannelImpl(Object stream,FileDescriptor fd,int mode){ this.fd=fd; this.stream=stream; this.mode=mode; }
Create a new file channel implementation class that wraps the given fd and operates in the specified mode.
final int measureHeightOfChildrenCompat(int widthMeasureSpec,int startPosition,int endPosition,final int maxHeight,int disallowPartialChildPosition){ final int paddingTop=getListPaddingTop(); final int paddingBottom=getListPaddingBottom(); final int paddingLeft=getListPaddingLeft(); final int paddingRight=getListPaddingRight(); final int reportedDividerHeight=getDividerHeight(); final Drawable divider=getDivider(); final ListAdapter adapter=getAdapter(); if (adapter == null) { return paddingTop + paddingBottom; } int returnedHeight=paddingTop + paddingBottom; final int dividerHeight=((reportedDividerHeight > 0) && divider != null) ? reportedDividerHeight : 0; int prevHeightWithoutPartialChild=0; View child=null; int viewType=0; int count=adapter.getCount(); for (int i=0; i < count; i++) { int newType=adapter.getItemViewType(i); if (newType != viewType) { child=null; viewType=newType; } child=adapter.getView(i,child,this); ; int heightMeasureSpec; int childHeight=child.getLayoutParams().height; if (childHeight > 0) { heightMeasureSpec=MeasureSpec.makeMeasureSpec(childHeight,MeasureSpec.EXACTLY); } else { heightMeasureSpec=MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED); } child.measure(widthMeasureSpec,heightMeasureSpec); if (i > 0) { returnedHeight+=dividerHeight; } returnedHeight+=child.getMeasuredHeight(); if (returnedHeight >= maxHeight) { return (disallowPartialChildPosition >= 0) && (i > disallowPartialChildPosition) && (prevHeightWithoutPartialChild > 0)&& (returnedHeight != maxHeight) ? prevHeightWithoutPartialChild : maxHeight; } if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) { prevHeightWithoutPartialChild=returnedHeight; } } return returnedHeight; }
Measures the height of the given range of children (inclusive) and returns the height with this ListView's padding and divider heights included. If maxHeight is provided, the measuring will stop when the current height reaches maxHeight.
public static int roundUpInt(int x,int blockSizePowerOf2){ return (x + blockSizePowerOf2 - 1) & (-blockSizePowerOf2); }
Round the value up to the next block size. The block size must be a power of two. As an example, using the block size of 8, the following rounding operations are done: 0 stays 0; values 1..8 results in 8, 9..16 results in 16, and so on.
public TLSARecord(Name name,int dclass,long ttl,int certificateUsage,int selector,int matchingType,byte[] certificateAssociationData){ super(name,Type.TLSA,dclass,ttl); this.certificateUsage=checkU8("certificateUsage",certificateUsage); this.selector=checkU8("selector",selector); this.matchingType=checkU8("matchingType",matchingType); this.certificateAssociationData=checkByteArrayLength("certificateAssociationData",certificateAssociationData,0xFFFF); }
Creates an TLSA Record from the given data
public static void main(final String[] args){ DOMTestCase.doMain(hc_nodeappendchildchildexists.class,args); }
Runs this test from the command line.
public void initializeClassifier(Instances data) throws Exception { getCapabilities().testWithFail(data); m_Data=new Instances(data); m_Data.deleteWithMissingClass(); m_zeroR=new ZeroR(); m_zeroR.buildClassifier(m_Data); if (m_Data.numAttributes() == 1) { System.err.println("Cannot build model (only class attribute present in data!), " + "using ZeroR model instead!"); m_SuitableData=false; return; } else { m_SuitableData=true; } m_Classifiers=new ArrayList<Classifier>(m_NumIterations); m_Data=residualReplace(m_Data,m_zeroR,false); m_SSE=0; m_Diff=Double.MAX_VALUE; for (int i=0; i < m_Data.numInstances(); i++) { m_SSE+=m_Data.instance(i).weight() * m_Data.instance(i).classValue() * m_Data.instance(i).classValue(); } if (m_Debug) { System.err.println("Sum of squared residuals " + "(predicting the mean) : " + m_SSE); } }
Initialize classifier.
public static OMDBApiService newApi(){ return newApi(new OkHttpClient()); }
Creates a fresh OMDBApiService instance.
@Override public Blob createBlob() throws SQLException { try { int id=getNextId(TraceObject.BLOB); debugCodeAssign("Blob",TraceObject.BLOB,id,"createClob()"); checkClosed(); try { Value v=ValueLobDb.createTempBlob(new ByteArrayInputStream(Utils.EMPTY_BYTES),0); session.addTemporaryLob(v); return new JdbcBlob(this,v,id); } finally { afterWriting(); } } catch ( Exception e) { throw logAndConvert(e); } }
Create a new empty Blob object.
public static FilterSpecCompiled makeFilterSpec(EventType eventType,String eventTypeName,List<ExprNode> filterExpessions,PropertyEvalSpec optionalPropertyEvalSpec,LinkedHashMap<String,Pair<EventType,String>> taggedEventTypes,LinkedHashMap<String,Pair<EventType,String>> arrayEventTypes,StreamTypeService streamTypeService,String optionalStreamName,StatementContext statementContext,Collection<Integer> assignedTypeNumberStack) throws ExprValidationException { List<ExprNode> validatedNodes=validateAllowSubquery(ExprNodeOrigin.FILTER,filterExpessions,streamTypeService,statementContext,taggedEventTypes,arrayEventTypes); return build(validatedNodes,eventType,eventTypeName,optionalPropertyEvalSpec,taggedEventTypes,arrayEventTypes,streamTypeService,optionalStreamName,statementContext,assignedTypeNumberStack); }
Factory method for compiling filter expressions into a filter specification for use with filter service.
protected double lnXpluslnY(double lnX,double lnY){ double lnYminusLnX, temp; if (lnY > lnX) { temp=lnX; lnX=lnY; lnY=temp; } lnYminusLnX=lnY - lnX; if (lnYminusLnX < MININUM_EXPONENT) { return lnX; } else { return Math.log1p(Math.exp(lnYminusLnX)) + lnX; } }
Takes ln(x) and ln(y) as input, and returns ln(x + y)
public static void main(String[] args){ TestRunner.run(EnricherTest.class); }
<!-- begin-user-doc --> <!-- end-user-doc -->
protected byte[] hexStringToByteArray(String hexString){ int len=hexString.length(); byte[] data=new byte[len / 2]; for (int i=0; i < len; i+=2) { data[i / 2]=(byte)((Character.digit(hexString.charAt(i),16) << 4) + Character.digit(hexString.charAt(i + 1),16)); } return data; }
Converts hex values from strings to byte arra
public MockFlapListener(long threshold,int flapInterval,float flapStartThreshold,float flapStopThreshold,float lowWeight,float highWeight){ this.threshold=threshold; setDefaultFlapInterval(flapInterval); setDefaultFlapStartThreshold(flapStartThreshold); setDefaultFlapStopThreshold(flapStopThreshold); setDefaultFlapLowWeight(lowWeight); setDefaultFlapHighWeight(highWeight); }
Instantiates a new mock flap listener.
@SuppressWarnings("unchecked") public SortedSet<E> headSet(E end){ return headSet(end,false); }
Answers a SortedSet of the specified portion of this TreeSet which contains elements less than the end element. The returned SortedSet is backed by this TreeSet so changes to one are reflected by the other.
@Override public Range findRangeBounds(CategoryDataset dataset){ if (dataset == null) { return null; } Range r=DatasetUtilities.findStackedRangeBounds(dataset,this.seriesToGroupMap); return r; }
Returns the range of values the renderer requires to display all the items from the specified dataset.
public TourDisplaySetting(Paint paint){ this(paint,new BasicStroke()); }
Constructs a new tour display setting with the specified paint.
public TaskErrorHandlingException(String message,Exception cause){ super(message,cause); }
Constructs a new exception with the specified detail message. The cause is not initialized.
public SchemaResource(UserContext userContext){ this.userContext=userContext; }
Creates a new SchemaResource which exposes meta information describing the kind of data within the given UserContext.
public static void hideKeyboard(Activity activity,IBinder windowToken){ InputMethodManager mgr=(InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(windowToken,0); }
This method is used to hide a keyboard after a user has finished typing the url.
public void testConfigureSetsDefaultAJPPort() throws Exception { configuration.configure(container); String config=configuration.getFileHandler().readTextFile(configuration.getHome() + "/conf/server.xml","UTF-8"); XMLAssert.assertXpathEvaluatesTo(configuration.getPropertyValue(TomcatPropertySet.AJP_PORT),"//Connector[@className='org.apache.ajp.tomcat4.Ajp13Connector']/@port",config); }
Test AJP configuration.
public static void deleteBlockSelection(Editor editor){ }
Does nothing currently.
public static final XPATHErrorResources loadResourceBundle(String className) throws MissingResourceException { Locale locale=Locale.getDefault(); String suffix=getResourceSuffix(locale); try { return (XPATHErrorResources)ResourceBundle.getBundle(className + suffix,locale); } catch ( MissingResourceException e) { try { return (XPATHErrorResources)ResourceBundle.getBundle(className,new Locale("en","US")); } catch ( MissingResourceException e2) { throw new MissingResourceException("Could not load any resource bundles.",className,""); } } }
Return a named ResourceBundle for a particular locale. This method mimics the behavior of ResourceBundle.getBundle().
private void finishNestedMode() throws SAXException { md=(ModeData)modeDataStack.pop(); }
Notification that the mode element ends.
public static void UNREACHABLE(String module,String err1,String err2) throws OptimizingCompilerException { throw new OptimizingCompilerException(module,"Executed UNREACHABLE code",err1,err2); }
Use the UNREACHABLE methods to mark code that should never execute e.g., unexpected cases of switch statements and nested if/then/else
public static Element createDiv(int id){ Element e=Document.get().createDivElement(); e.setId(Integer.toString(id)); return e; }
Creates a div with the integer id as its id.
public void incrementCursor(){ if (attributes.print == DTVCCDirection.LEFT_TO_RIGHT) { penX++; } else if (attributes.print == DTVCCDirection.RIGHT_TO_LEFT) { penX--; } else if (attributes.print == DTVCCDirection.TOP_TO_BOTTOM) { penY++; } else if (attributes.print == DTVCCDirection.BOTTOM_TO_TOP) { penY--; } }
The pen is allowed to move off the page, we just ignore any characters written there
public byte[] generateSignature() throws CryptoException, DataLengthException { if (!forSigning) { throw new IllegalStateException("RSADigestSigner not initialised for signature generation."); } byte[] hash=new byte[digest.getDigestSize()]; digest.doFinal(hash,0); try { byte[] data=derEncode(hash); return rsaEngine.processBlock(data,0,data.length); } catch ( IOException e) { throw new CryptoException("unable to encode signature: " + e.getMessage(),e); } }
Generate a signature for the message we've been loaded with using the key we were initialised with.
public static String utf8BytesWithUtf16LengthToString(@Nonnull byte[] bytes,int start,int utf16Length,@Nullable int[] readLength){ char[] chars=localBuffer.get(); if (chars == null || chars.length < utf16Length) { chars=new char[utf16Length]; localBuffer.set(chars); } int outAt=0; int at=0; for (at=start; utf16Length > 0; utf16Length--) { int v0=bytes[at] & 0xFF; char out; switch (v0 >> 4) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: { if (v0 == 0) { return throwBadUtf8(v0,at); } out=(char)v0; at++; break; } case 0x0c: case 0x0d: { int v1=bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1,at + 1); } int value=((v0 & 0x1f) << 6) | (v1 & 0x3f); if ((value != 0) && (value < 0x80)) { return throwBadUtf8(v1,at + 1); } out=(char)value; at+=2; break; } case 0x0e: { int v1=bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1,at + 1); } int v2=bytes[at + 2] & 0xFF; if ((v2 & 0xc0) != 0x80) { return throwBadUtf8(v2,at + 2); } int value=((v0 & 0x0f) << 12) | ((v1 & 0x3f) << 6) | (v2 & 0x3f); if (value < 0x800) { return throwBadUtf8(v2,at + 2); } out=(char)value; at+=3; break; } default : { return throwBadUtf8(v0,at); } } chars[outAt]=out; outAt++; } if (readLength != null && readLength.length > 0) { readLength[0]=at - start; readLength[0]=at - start; } return new String(chars,0,outAt); }
Converts an array of UTF-8 bytes into a string.
public boolean save(String trxName){ m_trxName=trxName; for (int i=0; i < m_lines.size(); i++) { FactLine fl=(FactLine)m_lines.get(i); if (!fl.save(trxName)) return false; } return true; }
Save Fact
@Override public void trigger(DialogueState state,Collection<String> updatedVars){ String userSpeechVar=system.getSettings().userSpeech; String outputVar=system.getSettings().systemOutput; if (updatedVars.contains(userSpeechVar) && state.hasChanceNode(userSpeechVar) && !paused) { Value speechVal=system.getContent(userSpeechVar).getBest(); if (speechVal instanceof SpeechData) { Thread t=new Thread(null); t.start(); } } else if (updatedVars.contains(outputVar) && state.hasChanceNode(outputVar) && !paused) { Value utteranceVal=system.getContent(outputVar).getBest(); if (utteranceVal instanceof StringVal) { synthesise(utteranceVal.toString()); } } }
If the system output has been updated, trigger the speech synthesis.
public static SetExpression in(String propertyName,Collection<? extends Object> values){ return in(propertyName,values.toArray()); }
Apply an "in" constraint to the named property
public int read(char[] cbuf,int off,int len) throws java.io.IOException { return 0; }
Read characters into a portion of an array.
synchronized void deallocate(GlowEntity entity){ if (entity.id == 0) { throw new IllegalStateException("Entity does not have an id assigned."); } usedIds.remove(entity.id); }
Deallocates the id for an entity.
public void storeInRegister(int registerNumber) throws IOException { writeCode(REGISTER); out.writeUI16(1); out.writeUI8(registerNumber); }
SWFActions interface
public Kernel negate(){ mul(-1.0); return this; }
Returns a Kernel with all values being negated.
public void collapseUnder(NodeRenderingProperty node,NodeRenderingProperty parent){ if (parent == node) { return; } node.collapsedUnder=parent; parent.hasCollapsedNodeUnder=true; node.pluginStore.put(this,new DeltaCollapse(parent.positionX - node.positionX,parent.positionY - node.positionY)); }
Collapse the node <code>node</code> under the given <code>parent</code>
public void delete(int i){ if (i < 0 || i >= n) throw new IndexOutOfBoundsException(); if (!contains(i)) throw new NoSuchElementException("Specified index is not in the queue"); Node<Key> x=nodes[i]; x.key=null; if (x.parent != null) { cut(i); } head=cut(x,head); if (x.child != null) { Node<Key> child=x.child; x.child=null; x=child; do { child.parent=null; child=child.next; } while (child != x); head=meld(head,child); } if (!isEmpty()) consolidate(); else min=null; nodes[i]=null; size--; }
Deletes the key associated the given index Worst case is O(log(n)) (amortized)
public Element create(String prefix,Document doc){ return new SVGOMFEColorMatrixElement(prefix,(AbstractDocument)doc); }
Creates an instance of the associated element type.
public static void shareChannel(Context context,Channel channel,Uri bitmapUri){ String shareText=String.format(context.getString(R.string.share_channel_text),channel.getTitle(),channel.getSiteUrl()); Intent intent=new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,shareText); if (bitmapUri != null) { intent.putExtra(Intent.EXTRA_STREAM,bitmapUri); } Intent chooser=Intent.createChooser(intent,context.getString(R.string.share_with)); if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(chooser); } }
Shares a channel to the Android app of choice
synchronized boolean connectedToPrimaryHost(){ return isPrimaryHostIndex(this.currentHostIndex); }
Checks if this proxy is using the primary host in the underlying connection.
public ShingleFilter(TokenStream input,String tokenType){ this(input,DEFAULT_MIN_SHINGLE_SIZE,DEFAULT_MAX_SHINGLE_SIZE); setTokenType(tokenType); }
Construct a ShingleFilter with the specified token type for shingle tokens and the default shingle size: 2
public boolean loadLines(){ boolean result=false; log.info("MBankStatementLoader.loadLines"); if (m_loader == null) { errorMessage="ClassNotLoaded"; return result; } if (!m_loader.init(this)) { errorMessage=m_loader.getLastErrorMessage(); errorDescription=m_loader.getLastErrorDescription(); return result; } if (!m_loader.isValid()) { errorMessage=m_loader.getLastErrorMessage(); errorDescription=m_loader.getLastErrorDescription(); return result; } if (!m_loader.loadLines()) { errorMessage=m_loader.getLastErrorMessage(); errorDescription=m_loader.getLastErrorDescription(); return result; } result=true; return result; }
Start loading Bankstatements
public void play(){ play=true; if (!ignoreRepeatSetting) { repeatCount=0; } }
Begin playing the animation, with no repeat.
private void findClassesInJar(File jarFile,String pathPrefix,Set<String> classNames,Set<String> subpackageNames) throws IOException { Set<String> entryNames=getJarEntries(jarFile); if (!entryNames.contains(pathPrefix)) { return; } int prefixLength=pathPrefix.length(); for ( String entryName : entryNames) { if (entryName.startsWith(pathPrefix)) { if (entryName.endsWith(CLASS_EXTENSION)) { int index=entryName.indexOf('/',prefixLength); if (index >= 0) { String p=entryName.substring(0,index).replace('/','.'); subpackageNames.add(p); } else if (isToplevelClass(entryName)) { classNames.add(getClassName(entryName).replace('/','.')); } } } } }
Finds all classes and sub packages that are below the packageName and add them to the respective sets. Searches the package in a single jar file.
public void writeEntryHeader(byte[] outbuf){ int offset=0; offset=TarUtils.getNameBytes(name,outbuf,offset,NAMELEN); offset=TarUtils.getOctalBytes(mode,outbuf,offset,MODELEN); offset=TarUtils.getOctalBytes(userId,outbuf,offset,UIDLEN); offset=TarUtils.getOctalBytes(groupId,outbuf,offset,GIDLEN); offset=TarUtils.getLongOctalBytes(size,outbuf,offset,SIZELEN); offset=TarUtils.getLongOctalBytes(modTime,outbuf,offset,MODTIMELEN); int csOffset=offset; for (int c=0; c < CHKSUMLEN; ++c) { outbuf[offset++]=(byte)' '; } outbuf[offset++]=linkFlag; offset=TarUtils.getNameBytes(linkName,outbuf,offset,NAMELEN); offset=TarUtils.getNameBytes(magic,outbuf,offset,MAGICLEN); offset=TarUtils.getNameBytes(userName,outbuf,offset,UNAMELEN); offset=TarUtils.getNameBytes(groupName,outbuf,offset,GNAMELEN); offset=TarUtils.getOctalBytes(devMajor,outbuf,offset,DEVLEN); offset=TarUtils.getOctalBytes(devMinor,outbuf,offset,DEVLEN); while (offset < outbuf.length) { outbuf[offset++]=0; } long chk=TarUtils.computeCheckSum(outbuf); TarUtils.getCheckSumOctalBytes(chk,outbuf,csOffset,CHKSUMLEN); }
Write an entry's header information to a header buffer.
public static void showAboutWindow(){ new AboutWindow().showDialog(); }
Shows the "About" menu with more information about the program.
public Cell<?> applySpacing(final Cell<?> cell){ cell.space(top,left,bottom,right); return cell; }
Allows to set Cell's spacing with the Padding object, which has be done externally, as it's not part of the standard libGDX API. Padding holds 4 floats for each direction, so it's compatible with both padding and spacing settings without any additional changes.
public static PlayerBucketEmptyEvent callPlayerBucketEmptyEvent(net.minecraft.entity.player.EntityPlayer who,int clickedX,int clickedY,int clickedZ,int clickedFace,net.minecraft.item.ItemStack itemInHand){ return (PlayerBucketEmptyEvent)getPlayerBucketEvent(false,who,clickedX,clickedY,clickedZ,clickedFace,itemInHand,net.minecraft.init.Items.bucket); }
Bucket methods
public FileLinesList(final CharSequence filename,final String encoding,final int bufferSize) throws IOException { this(filename,encoding,bufferSize,FastBufferedInputStream.ALL_TERMINATORS); }
Creates a file-lines collection for the specified filename with the specified encoding, buffer size and with all terminators.