code
stringlengths
10
174k
nl
stringlengths
3
129k
public static String escapeHTML(String str,short version){ String[][] data; int[] offset; StringBuilder rtn=new StringBuilder(str.length()); char[] chars=str.toCharArray(); if (version == HTMLV20) { data=HTML20_DATA; offset=HTML20_OFFSET; } else if (version == HTMLV32) { data=HTML32_DATA; offset=HTML32_OFFSET; } else { data=HTML40_DATA; offset=HTML40_OFFSET; } outer: for (int i=0; i < chars.length; i++) { char c=chars[i]; if (c == CR) continue; for (int y=0; y < offset.length; y++) { if (c >= offset[y] && c < data[y].length + offset[y]) { String replacement=data[y][c - offset[y]]; if (replacement != null) { rtn.append('&'); rtn.append(replacement); rtn.append(';'); continue outer; } } } rtn.append(c); } return rtn.toString(); }
escapes html character inside a string
public static void removeMapping(TransitSchedule schedule){ log.info("... Removing reference links and link sequences from schedule"); for ( TransitStopFacility stopFacility : schedule.getFacilities().values()) { stopFacility.setLinkId(null); } for ( TransitLine line : schedule.getTransitLines().values()) { for ( TransitRoute route : line.getRoutes().values()) { route.setRoute(null); } } }
Changes the schedule to an unmapped schedule by removes all link sequences from a transit schedule and removing referenced links from stop facilities.
public static <A,B>Pair<A,B> create(A a,B b){ return new Pair<A,B>(a,b); }
Convenience method for creating an appropriately typed pair.
public IBlockState withRotation(IBlockState state,Rotation rot){ switch (rot) { case CLOCKWISE_180: return state.withProperty(NORTH,state.getValue(SOUTH)).withProperty(EAST,state.getValue(WEST)).withProperty(SOUTH,state.getValue(NORTH)).withProperty(WEST,state.getValue(EAST)); case COUNTERCLOCKWISE_90: return state.withProperty(NORTH,state.getValue(EAST)).withProperty(EAST,state.getValue(SOUTH)).withProperty(SOUTH,state.getValue(WEST)).withProperty(WEST,state.getValue(NORTH)); case CLOCKWISE_90: return state.withProperty(NORTH,state.getValue(WEST)).withProperty(EAST,state.getValue(NORTH)).withProperty(SOUTH,state.getValue(EAST)).withProperty(WEST,state.getValue(SOUTH)); default : return state; } }
Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed blockstate.
public int count(){ if (root == null) return 0; return count(root); }
Counts the number of items in the tree.
private String defaultPrimitiveValue(Class<?> clazz){ return clazz == byte.class || clazz == short.class || clazz == int.class ? "0" : clazz == long.class ? "0L" : clazz == float.class ? "0.0f" : clazz == double.class ? "0.0d" : clazz == char.class ? "'\u0000'" : clazz == boolean.class ? "false" : "null"; }
Returns the default values of primitive types in the form of strings.
private void writeQName(javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI=qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix=xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix=generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix,namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0) { xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } }
method to handle Qnames
public Camping(){ super(); }
Needed by CGLib
protected SVGDescriptiveElement(String prefix,AbstractDocument owner){ super(prefix,owner); }
Creates a new SVGDescriptiveElement object.
public KeyPair generateKeyPair(KeyPairGenerator keyPairGen){ try { keyPair=keyPairGen.genKeyPair(); privateKey=keyPair.getPrivate(); publicKey=keyPair.getPublic(); } catch ( Exception e) { LOG.error("Error generating KeyPair",e); } return keyPair; }
* *
public static void deleteDirectory(final File dir){ deleteDirectory(dir,true); }
shortcut for deleteDirectory( dir, true )
public void closeParent(){ Dialog dialog; Frame frame; if (getParentDialog() != null) { dialog=getParentDialog(); dialog.setVisible(false); dialog.dispose(); } else if (getParentFrame() != null) { frame=getParentFrame(); frame.setVisible(false); frame.dispose(); } }
Closes the parent dialog/frame. Dispose the parent!
private XmlHandler deleteAnnotatedClass(Class<?> aClass) throws LoadingFileException, IOException { String path=getElement(FilesManager.classesPath(),getClassPath(aClass)); if (FilesManager.isFileAnnotated(path,aClass)) deleteClasses(aClass); for ( Class<?> it : aClass.getClasses()) if (it.isMemberClass()) deleteAnnotatedClass(it); return this; }
Deletes the Class, given in input, from xml mapping file, only if it's annotated.
public boolean isUnicodeAware(){ return unicodeAware; }
Return true if lengths are measured in unicode code-points rather than bytes
private boolean isDeprecatedComponent(String name){ String json=catalog.componentJSonSchema(name); List<Map<String,String>> rows=JsonSchemaHelper.parseJsonSchema("component",json,false); for ( Map<String,String> row : rows) { if (row.get("deprecated") != null) { return "true".equals(row.get("deprecated")); } } return false; }
Is the component deprecated?
public static LocalAttribute localAttribute(String name){ return new LocalAttribute(name); }
Permits to define a local attribute.
public static <T>Class<T> loadClass(String className) throws ClassNotFoundException { Class<T> clazz=null; try { clazz=(Class<T>)Thread.currentThread().getContextClassLoader().loadClass(className); } catch ( ClassNotFoundException nf) { clazz=(Class<T>)Class.forName(className); } return clazz; }
Loads a class with the given name.
void updateMatcher(){ int begin=getPosition(); int end=getText().length(); matcher.reset(getText()); matcher.region(begin,end); }
Reset the parser and specify the region focused on by it, to go from the current cursor position to the end of the text.
private String toIndentedString(Object o){ if (o == null) { return "null"; } return o.toString().replace("\n","\n "); }
Convert the given object to string with each line indented by 4 spaces (except the first line).
private Coord calculateInitLocation(LinearFormation proto){ double dx, dy; double placementFraction; int formationIndex=proto.lastIndex++; Coord c=proto.startLoc.clone(); placementFraction=(1.0 * formationIndex / proto.nodeCount); dx=placementFraction * (proto.endLoc.getX() - proto.startLoc.getX()); dy=placementFraction * (proto.endLoc.getY() - proto.startLoc.getY()); c.translate(dx,dy); return c; }
Calculates and returns the location of this node in the formation
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data,int width,int height){ Rect rect=getFramingRectInPreview(); int previewFormat=configManager.getPreviewFormat(); String previewFormatString=configManager.getPreviewFormatString(); switch (previewFormat) { case PixelFormat.YCbCr_420_SP: case PixelFormat.YCbCr_422_SP: return new PlanarYUVLuminanceSource(data,width,height,rect.left,rect.top,rect.width(),rect.height()); default : if ("yuv420p".equals(previewFormatString)) { return new PlanarYUVLuminanceSource(data,width,height,rect.left,rect.top,rect.width(),rect.height()); } } throw new IllegalArgumentException("Unsupported picture format: " + previewFormat + '/'+ previewFormatString); }
A factory method to build the appropriate LuminanceSource object based on the format of the preview buffers, as described by Camera.Parameters.
private Set<StoragePort> andStoragePortSets(Set<StoragePort> a,Set<StoragePort> b){ Set<StoragePort> result=new HashSet<StoragePort>(); for ( StoragePort port : a) { if (b.contains(port)) { result.add(port); } } return result; }
Logical AND of a and b
public static void main(final String[] args){ DOMTestCase.doMain(setAttributeNS09.class,args); }
Runs this test from the command line.
protected boolean afterDelete(boolean success){ if (!success) return success; StringBuffer sb=new StringBuffer("DELETE FROM AD_TreeNodeCMS ").append(" WHERE Node_ID=").append(get_IDOld()).append(" AND AD_Tree_ID=").append(getAD_Tree_ID()); int no=DB.executeUpdate(sb.toString(),get_TrxName()); if (no > 0) log.fine("#" + no + " - TreeType=CMS"); else log.warning("#" + no + " - TreeType=CMS"); return no > 0; }
After Delete
public static Double calculate(CpuStats previous,CpuStats current){ if (previous == null || current == null) { return null; } double userDiff=current.getUser() - previous.getUser(); double niceDiff=current.getNice() - previous.getNice(); double systemDiff=current.getSystem() - previous.getSystem(); double idleDiff=getIdleDiff(previous,current); double iowaitDiff=current.getIowait() - previous.getIowait(); double irqDiff=current.getIrq() - previous.getIrq(); double softirqDiff=current.getSoftirq() - previous.getSoftirq(); double stealDiff=current.getSteal() - previous.getSteal(); double totalDiff=userDiff + niceDiff + systemDiff+ idleDiff+ iowaitDiff+ irqDiff+ softirqDiff+ stealDiff; if (totalDiff < 1) { totalDiff=1; } double scale=MAX_SCALE / totalDiff; return idleDiff * scale; }
Calculates idle percent the same way as UNIX 'top' utility does.
public InputStream fetchQuotaDirInfo(final Argument argument,final Map<String,Object> keyMap,int index) throws VNXFilePluginException { _logger.info("Creating quota tree info query"); InputStream iStream=null; try { Query query=new Query(); verifyPreviousResults(keyMap); TreeQuotaQueryParams queryParam=new TreeQuotaQueryParams(); TreeQuotaQueryParams.AspectSelection selection=new TreeQuotaQueryParams.AspectSelection(); selection.setTreeQuotas(true); queryParam.setAspectSelection(selection); String fsId=(String)keyMap.get(VNXFileConstants.FILESYSTEM_ID); if (!isInValid(fsId)) { queryParam.setFileSystem(fsId); } query.getQueryRequestChoice().add(queryParam); iStream=_vnxFileInputRequestBuilder.getQueryParamPacket(queryParam,false); } catch ( JAXBException jaxbException) { throw new VNXFilePluginException("Exception occurred while generating input xml for fileSystem info",jaxbException.getCause()); } return iStream; }
Create Quota Tree information input XML request and returns stream after marshalling.
public void testGetRandomColorByLevel(){ try { for ( String level : MaterialPalettes.NON_ACCENT_COLOR_LEVELS) { List<Integer> colorList=MaterialPalettes.getColorsByLevel(level); Integer randomColor=MaterialPalettes.getRandomColorByLevel(level); assertTrue(colorList.contains(randomColor)); } } catch ( IllegalAccessException iae) { fail(); } }
Ensures the color returned has the appropriate level.
private VCardParameters parseParameters(Element element){ VCardParameters parameters=new VCardParameters(); List<Element> roots=XmlUtils.toElementList(element.getElementsByTagNameNS(PARAMETERS.getNamespaceURI(),PARAMETERS.getLocalPart())); for ( Element root : roots) { List<Element> parameterElements=XmlUtils.toElementList(root.getChildNodes()); for ( Element parameterElement : parameterElements) { String name=parameterElement.getLocalName().toUpperCase(); List<Element> valueElements=XmlUtils.toElementList(parameterElement.getChildNodes()); for ( Element valueElement : valueElements) { String value=valueElement.getTextContent(); parameters.put(name,value); } } } return parameters; }
Parses the property parameters.
public static void salsaCore(int rounds,int[] input,int[] x){ if (input.length != 16) { throw new IllegalArgumentException(); } if (x.length != 16) { throw new IllegalArgumentException(); } if (rounds % 2 != 0) { throw new IllegalArgumentException("Number of rounds must be even"); } int x00=input[0]; int x01=input[1]; int x02=input[2]; int x03=input[3]; int x04=input[4]; int x05=input[5]; int x06=input[6]; int x07=input[7]; int x08=input[8]; int x09=input[9]; int x10=input[10]; int x11=input[11]; int x12=input[12]; int x13=input[13]; int x14=input[14]; int x15=input[15]; for (int i=rounds; i > 0; i-=2) { x04^=rotl(x00 + x12,7); x08^=rotl(x04 + x00,9); x12^=rotl(x08 + x04,13); x00^=rotl(x12 + x08,18); x09^=rotl(x05 + x01,7); x13^=rotl(x09 + x05,9); x01^=rotl(x13 + x09,13); x05^=rotl(x01 + x13,18); x14^=rotl(x10 + x06,7); x02^=rotl(x14 + x10,9); x06^=rotl(x02 + x14,13); x10^=rotl(x06 + x02,18); x03^=rotl(x15 + x11,7); x07^=rotl(x03 + x15,9); x11^=rotl(x07 + x03,13); x15^=rotl(x11 + x07,18); x01^=rotl(x00 + x03,7); x02^=rotl(x01 + x00,9); x03^=rotl(x02 + x01,13); x00^=rotl(x03 + x02,18); x06^=rotl(x05 + x04,7); x07^=rotl(x06 + x05,9); x04^=rotl(x07 + x06,13); x05^=rotl(x04 + x07,18); x11^=rotl(x10 + x09,7); x08^=rotl(x11 + x10,9); x09^=rotl(x08 + x11,13); x10^=rotl(x09 + x08,18); x12^=rotl(x15 + x14,7); x13^=rotl(x12 + x15,9); x14^=rotl(x13 + x12,13); x15^=rotl(x14 + x13,18); } x[0]=x00 + input[0]; x[1]=x01 + input[1]; x[2]=x02 + input[2]; x[3]=x03 + input[3]; x[4]=x04 + input[4]; x[5]=x05 + input[5]; x[6]=x06 + input[6]; x[7]=x07 + input[7]; x[8]=x08 + input[8]; x[9]=x09 + input[9]; x[10]=x10 + input[10]; x[11]=x11 + input[11]; x[12]=x12 + input[12]; x[13]=x13 + input[13]; x[14]=x14 + input[14]; x[15]=x15 + input[15]; }
Salsa20 function
@Override public boolean equals(Object obj){ if (obj == this) { return true; } if (!(obj instanceof XYDifferenceRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYDifferenceRenderer that=(XYDifferenceRenderer)obj; if (!PaintUtilities.equal(this.positivePaint,that.positivePaint)) { return false; } if (!PaintUtilities.equal(this.negativePaint,that.negativePaint)) { return false; } if (this.shapesVisible != that.shapesVisible) { return false; } if (!ShapeUtilities.equal(this.legendLine,that.legendLine)) { return false; } if (this.roundXCoordinates != that.roundXCoordinates) { return false; } return true; }
Tests this renderer for equality with an arbitrary object.
public void registerNode(String oidString,SnmpMibNode node) throws IllegalAccessException { SnmpOid oid=new SnmpOid(oidString); registerNode(oid.longValue(),0,node); }
Registers a specific node in the tree.
public void finishTransition(){ if (mViewToHide != null) { removeView(mViewToHide); } getLayoutParams().height=ViewGroup.LayoutParams.WRAP_CONTENT; requestLayout(); mViewToHide=null; mViewToShow=null; mInfoBar.setControlsEnabled(true); }
Called when the animation is done. At this point, we can get rid of the View that used to represent the InfoBar and re-enable controls.
static StringBuilder newStringBuilderForCollection(int size){ checkNonnegative(size,"size"); return new StringBuilder((int)Math.min(size * 8L,Ints.MAX_POWER_OF_TWO)); }
Returns best-effort-sized StringBuilder based on the given collection size.
public void focusLost(FocusEvent e){ log.fine("focusLost"); try { String text=getText(); fireVetoableChange(m_columnName,text,null); } catch ( PropertyVetoException pve) { } }
Data Binding to MTable (via GridController)
public void removeHexEditorListener(HexEditorListener l){ listenerList.remove(HexEditorListener.class,l); }
Removes the specified hex editor listener from this editor.
public void populateDAO(Object value,int row,int column){ final TradelogDetail element=getData().getTradelogDetail().get(row); switch (column) { case 1: { element.setOpen((String)value); break; } case 2: { element.setSymbol((String)value); break; } case 3: { element.setLongShort(((Side)value).getCode()); break; } case 4: { element.setTier(((Tier)value).getCode()); break; } case 5: { element.setMarketBias(((MarketBar)value).getCode()); break; } case 6: { element.setMarketBar(((MarketBar)value).getCode()); break; } case 7: { element.setName((String)value); break; } case 8: { element.setStatus(((TradestrategyStatus)value).getCode()); break; } case 9: { element.setSide(((Side)value).getCode()); break; } case 10: { element.setAction(((Action)value).getCode()); break; } case 11: { element.setStopPrice(((Money)value).getBigDecimalValue()); break; } case 12: { element.setOrderStatus(((OrderStatus)value).getCode()); break; } case 13: { element.setFilledDate(((Date)value).getZonedDateTime()); break; } case 14: { element.setQuantity(((Quantity)value).getIntegerValue()); break; } case 15: { element.setAverageFilledPrice(((Decimal)value).getBigDecimalValue()); break; } case 16: { element.setCommission(((Money)value).getBigDecimalValue()); break; } case 17: { element.setProfitLoss(((Money)value).getBigDecimalValue()); break; } default : { } } }
getData() -
public void testEOF() throws Exception { String JSON="{ \"key\": [ { \"a\" : { \"name\": \"foo\", \"type\": 1\n" + "}, \"type\": 3, \"url\": \"http://www.google.com\" } ],\n" + "\"name\": \"xyz\", \"type\": 1, \"url\" : null }\n "; JsonFactory jf=new JsonFactory(); ObjectMapper mapper=new ObjectMapper(); JsonParser jp=jf.createJsonParser(new StringReader(JSON)); JsonNode result=mapper.readTree(jp); assertTrue(result.isObject()); assertEquals(4,result.size()); assertNull(mapper.readTree(jp)); }
Type mappers should be able to gracefully deal with end of input.
public XMLString concat(String str){ return new XMLStringDefault(m_str.concat(str)); }
Concatenates the specified string to the end of this string.
public N4JSDocletParser(){ super(new TagDictionary<>(N4JS_LINE_TAGS),DESCRIPTION_DICT); }
Creates N4JSDoclet parser with default N4JS line tags.
public void shutdown(){ for ( Topic topic : _topics.values()) { if (topic.getConsumerConnector() != null) { topic.getConsumerConnector().shutdown(); } topic.getStreamExecutorService().shutdownNow(); try { topic.getStreamExecutorService().awaitTermination(60,TimeUnit.SECONDS); } catch ( InterruptedException e) { _logger.warn("Stream executor service was interrupted while awaiting termination. This should never happen."); } } _logger.debug("Pushing unflushed messages back to Kafka."); Producer producer=new Producer(_configuration); for ( Map.Entry<String,Topic> entry : _topics.entrySet()) { String topicName=entry.getKey(); Topic topic=entry.getValue(); List<String> unflushedMessages=new ArrayList<String>(); if (!topic.getMessages().isEmpty()) { topic.getMessages().drainTo(unflushedMessages); producer.enqueue(topicName,unflushedMessages); } _logger.debug("{} messages for topic {} enqueued on Kafka queue",unflushedMessages.size(),topicName); } producer.shutdown(); }
Enqueue un-flushed messages back on to Kafka.
public Unit createUnit(){ UnitImpl unit=new UnitImpl(); return unit; }
<!-- begin-user-doc --> <!-- end-user-doc -->
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:20.237 -0500",hash_original_method="A7026FD3DE10525F382BCFDA63577851",hash_generated_method="D83D82C75D0C85838D7CC6E60BE8AA26") public void drawPoints(float[] pts,int offset,int count,Paint paint){ addTaint(pts[0]); addTaint(offset); addTaint(count); addTaint(paint.getTaint()); }
Draw a series of points. Each point is centered at the coordinate specified by pts[], and its diameter is specified by the paint's stroke width (as transformed by the canvas' CTM), with special treatment for a stroke width of 0, which always draws exactly 1 pixel (or at most 4 if antialiasing is enabled). The shape of the point is controlled by the paint's Cap type. The shape is a square, unless the cap type is Round, in which case the shape is a circle.
private boolean zzRefill(){ return zzCurrentPos >= s.offset + s.count; }
Refills the input buffer.
public synchronized String count(String nonce){ Integer count=nonces.get(nonce); if (count == null) { count=Integer.valueOf(1); } else { count=Integer.valueOf(count.intValue() + 1); } nonces.put(nonce,count); return String.format("%08x",count.intValue()); }
Count returns a hexadecimal string counting the number of times nonce has been seen. The first value returned for a nonce is 00000001.
void prepareEnterRecentsAnimation(){ }
Prepares this task view for the enter-recents animations. This is called earlier in the first layout because the actual animation into recents may take a long time.
protected static String normalizeUrlEnding(String link){ if (link.indexOf("#") > -1) link=link.substring(0,link.indexOf("#")); if (link.endsWith("?")) link=link.substring(0,link.length() - 1); if (link.endsWith("/")) link=link.substring(0,link.length() - 1); return link; }
Normalizes a URL string by removing anchor part and trailing slash
public void onResume(){ hasSavedState=false; unlock(); }
Call this method from your Activity or Fragment's onResume method
@DSSink({DSSinkKind.SENSITIVE_UNCATEGORIZED}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:28:38.324 -0500",hash_original_method="D0996D4DFB9F5585E3927B19545BE3E4",hash_generated_method="BA24E7C3A8B18A175AD4E4B71A2B86FC") public static void dumpCurrentRow(Cursor cursor,PrintStream stream){ String[] cols=cursor.getColumnNames(); stream.println("" + cursor.getPosition() + " {"); int length=cols.length; for (int i=0; i < length; i++) { String value; try { value=cursor.getString(i); } catch ( SQLiteException e) { value="<unprintable>"; } stream.println(" " + cols[i] + '='+ value); } stream.println("}"); }
Prints the contents of a Cursor's current row to a PrintSteam.
public synchronized void internalRemoveAllRelationships(){ for (Iterator<Relationship> iterator=allRelationships(); iterator.hasNext(); ) { this.network.removeRelationship(iterator.next()); } getRelationships().clear(); if (this.allRelationships != null) { this.allRelationships.clear(); } }
Remove all relationships.
private ResourceCommand loadEppResourceCommand(String filename) throws Exception { EppInput eppInput=new EppLoader(this,filename).getEpp(); return ((ResourceCommandWrapper)eppInput.getCommandWrapper().getCommand()).getResourceCommand(); }
Loads the EppInput from the given filename and returns its ResourceCommand element.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case N4JSPackage.EXPORTED_VARIABLE_STATEMENT__ANNOTATION_LIST: return getAnnotationList(); case N4JSPackage.EXPORTED_VARIABLE_STATEMENT__DECLARED_MODIFIERS: return getDeclaredModifiers(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public DecoderResult decode(boolean[][] image) throws FormatException, ChecksumException { int dimension=image.length; BitMatrix bits=new BitMatrix(dimension); for (int i=0; i < dimension; i++) { for (int j=0; j < dimension; j++) { if (image[i][j]) { bits.set(j,i); } } } return decode(bits); }
<p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans. "true" is taken to mean a black module.</p>
public static String classNameFor(Connection connection){ return "connection-" + connection.getOutputSocket().getSocketHint().getIdentifier() + "-to-"+ connection.getInputSocket().getSocketHint().getIdentifier(); }
Return the CSS class name for a connection. To use as a css selector then prepend the string with a '.'.
public final void addAllConstraints(@NonNull final Collection<Constraint<CharSequence>> constraints){ ensureNotNull(constraints,"The collection may not be null"); for ( Constraint<CharSequence> constraint : constraints) { addConstraint(constraint); } }
Adds all constraints, which are contained by a specific collection.
public long create_time_to_sample_atom(MP4DataStream bitstream) throws IOException { log.trace("Time to sample atom"); create_full_atom(bitstream); timeToSamplesRecords=new Vector<TimeSampleRecord>(); entryCount=(int)bitstream.readBytes(4); log.trace("Time to sample entries: {}",entryCount); readed+=4; for (int i=0; i < entryCount; i++) { int sampleCount=(int)bitstream.readBytes(4); int sampleDuration=(int)bitstream.readBytes(4); timeToSamplesRecords.addElement(new TimeSampleRecord(sampleCount,sampleDuration)); readed+=8; } return readed; }
Loads MP4TimeToSampleAtom atom from the input bitstream.
protected void createODataUri(String serviceRoot){ odataUri=TestUtils.createODataUri(serviceRoot); }
Create a test OData URI specifying only the service root.
public static void LDC(int x){ if (ignoreCallback) return; ignoreCallback=true; vm.countCallback(); try { for ( IVM listener : vm.listeners) listener.LDC(x); } catch ( Throwable t) { handleException(t); } ignoreCallback=false; }
http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2. doc8. html#ldc
public AbstractGraphics2D(AbstractGraphics2D g){ this.gc=(GraphicContext)g.gc.clone(); this.gc.validateTransformStack(); this.textAsShapes=g.textAsShapes; }
Creates a new AbstractGraphics2D from an existing instance.
public BufferObject unitSquareBuffer(){ if (this.unitSquareBuffer != null) { return this.unitSquareBuffer; } float[] points=new float[]{0,1,0,0,1,1,1,0}; int size=points.length * 4; FloatBuffer buffer=ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()).asFloatBuffer(); buffer.put(points).rewind(); BufferObject bufferObject=new BufferObject(GLES20.GL_ARRAY_BUFFER,size,buffer); return (this.unitSquareBuffer=bufferObject); }
Returns an OpenGL buffer object containing a unit square expressed as four vertices at (0, 1), (0, 0), (1, 1) and (1, 0). Each vertex is stored as two 32-bit floating point coordinates. The four vertices are in the order required by a triangle strip. <p/> The OpenGL buffer object is created on first use and cached. Subsequent calls to this method return the cached buffer object.
public JsonArrayRequest(String url,Listener<JSONArray> listener,ErrorListener errorListener){ super(Method.GET,url,null,listener,errorListener); }
Creates a new request.
private boolean isChangePwdOnLogin(){ StringBuffer contextPath=getRequest().getRequestURL(); return contextPath.indexOf("public/pwd.jsf") != -1; }
Check if the password change occurs on login.
public List<JetstreamEvent> readEvents() throws OffsetOutOfRangeException { List<JetstreamEvent> events=new ArrayList<JetstreamEvent>(); if (m_nextBatchSizeBytes < 0) m_nextBatchSizeBytes=m_config.getBatchSizeBytes(); if (m_nextBatchSizeBytes == 0) { m_nextBatchSizeBytes=m_config.getBatchSizeBytes(); return events; } for (int i=0; i < 2; i++) { for (int j=0; j < m_retries; j++) { FetchRequest req=new FetchRequestBuilder().clientId(m_clientId).addFetch(m_topic,m_partition,m_readOffset,m_nextBatchSizeBytes).build(); FetchResponse fetchResponse=null; try { fetchResponse=m_consumer.fetch(req); } catch ( Exception e) { LOGGER.error("Error occurs when fetching.",e); continue; } if (fetchResponse == null) continue; if (fetchResponse.hasError()) { short code=fetchResponse.errorCode(m_topic,m_partition); if (code == ErrorMapping.OffsetOutOfRangeCode()) { long smallest=-1L, largest=-1L; try { smallest=fetchResetOffset(SmallestTimeString()); largest=fetchResetOffset(LargestTimeString()); } catch ( Exception e) { } throw new OffsetOutOfRangeException(m_clientId + ": readOffset=" + m_readOffset+ " smallest="+ smallest+ " largest="+ largest); } else continue; } else { ByteBufferMessageSet messageSet=fetchResponse.messageSet(m_topic,m_partition); boolean hasMessage=messageSet.iterator().hasNext(); if (!hasMessage && !readToTheEnd()) { m_nextBatchSizeBytes=Math.min(m_nextBatchSizeBytes * 2,m_config.getMaxBatchSizeBytes()); continue; } for ( MessageAndOffset messageAndOffset : messageSet) { long currentOffset=messageAndOffset.offset(); if (currentOffset < m_readOffset) { continue; } m_readOffset=messageAndOffset.nextOffset(); Message message=messageAndOffset.message(); ByteBuffer k=message.key(); ByteBuffer p=message.payload(); byte[] key=null; if (k != null) { key=new byte[k.limit()]; k.get(key); } byte[] payload=new byte[p.limit()]; p.get(payload); JetstreamEvent event=m_serializer.decode(key,payload); EventKafkaMetadata meta=new EventKafkaMetadata(m_topic,m_partition,currentOffset); event.put(kmKey,meta.encode()); events.add(event); } m_nextBatchSizeBytes=m_config.getBatchSizeBytes(); return events; } } reinit(); } throw new RuntimeException("Fail to read events from " + m_clientId + " with offset "+ m_readOffset); }
consumer events from kafka by one FetchRequest
public Attributes(Attributes attr){ map=new HashMap<>(attr); }
Constructs a new Attributes object with the same attribute name-value mappings as in the specified Attributes.
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public void remove() throws InterruptedException { List peekedIds=(List)HARegionQueue.peekedEventsContext.get(); if (peekedIds == null) { if (logger.isDebugEnabled()) { logger.debug("Remove() called before peek(), nothing to remove."); } return; } if (!this.checkPrevAcks()) { return; } Map groupedThreadIDs=new HashMap(); for (Iterator iter=peekedIds.iterator(); iter.hasNext(); ) { Long counter=(Long)iter.next(); Conflatable event=(Conflatable)this.region.get(counter); if (event != null) { EventID eventid=event.getEventId(); long sequenceId=eventid.getSequenceID(); ThreadIdentifier threadid=getThreadIdentifier(eventid); if (!checkEventForRemoval(counter,threadid,sequenceId)) { continue; } Object key=null; String r=null; if (shouldBeConflated(event)) { key=event.getKeyToConflate(); r=event.getRegionToConflate(); } RemovedEventInfo info=new RemovedEventInfo(counter,r,key); List countersList; if ((countersList=(List)groupedThreadIDs.get(threadid)) != null) { countersList.add(info); countersList.set(0,Long.valueOf(sequenceId)); } else { countersList=new ArrayList(); countersList.add(Long.valueOf(sequenceId)); countersList.add(info); groupedThreadIDs.put(threadid,countersList); } event=null; info=null; } else { HARegionQueue.this.stats.incNumVoidRemovals(); } } for (Iterator iter=groupedThreadIDs.entrySet().iterator(); iter.hasNext(); ) { Map.Entry element=(Map.Entry)iter.next(); ThreadIdentifier tid=(ThreadIdentifier)element.getKey(); List removedEvents=(List)element.getValue(); long lastDispatchedId=((Long)removedEvents.remove(0)).longValue(); DispatchedAndCurrentEvents dace=(DispatchedAndCurrentEvents)this.eventsMap.get(tid); if (dace != null && dace.lastDispatchedSequenceId < lastDispatchedId) { try { dace.setLastDispatchedIDAndRemoveEvents(removedEvents,lastDispatchedId); } catch ( CacheException e) { logger.error(LocalizedMessage.create(LocalizedStrings.HARegionQueue_EXCEPTION_OCCURED_WHILE_TRYING_TO_SET_THE_LAST_DISPATCHED_ID),e); } } } groupedThreadIDs=null; setPeekedEvents(); }
Removes the events that were peeked by this thread. The events are destroyed from the queue and conflation map and DispatchedAndCurrentEvents are updated accordingly.
public BoundedHashMap(int capacity){ this(capacity,false); }
Creates a BoundedHashMap with a specified maximum capacity, in insertion order mode.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
private synchronized int decreaseRefCount(){ ensureValid(); Preconditions.checkArgument(mRefCount > 0); mRefCount--; return mRefCount; }
Decrements reference count for the shared reference. Returns value of mRefCount after decrementing
public DeregisterRequest(String registrationID){ Validate.notNull(registrationID); this.registrationID=registrationID; }
Creates a request for removing the registration information from the LWM2M Server.
public static long readQwordLittleEndian(final byte[] data,final int offset){ return ((data[offset + 7] & 0xFFL) * 0x100 * 0x100* 0x100* 0x100* 0x100* 0x100* 0x100) + ((data[offset + 6] & 0xFFL) * 0x100 * 0x100* 0x100* 0x100* 0x100* 0x100) + ((data[offset + 5] & 0xFFL) * 0x100 * 0x100* 0x100* 0x100* 0x100)+ ((data[offset + 4] & 0xFFL) * 0x100 * 0x100* 0x100* 0x100)+ ((data[offset + 3] & 0xFFL) * 0x100 * 0x100* 0x100)+ ((data[offset + 2] & 0xFFL) * 0x100 * 0x100)+ ((data[offset + 1] & 0xFFL) * 0x100)+ (data[offset + 0] & 0xFFL); }
Reads a Little Endian QWORD value from a byte array.
public void initialize(UISearchResult sr){ super.initialize(sr); RESULT=sr; _mediaType=NamedMediaType.getFromExtension(getExtension()); addedOn=sr.getCreationTime() > 0 ? new Date(sr.getCreationTime()) : null; actionsHolder=new SearchResultActionsHolder(sr); name=new SearchResultNameHolder(sr); seeds=RESULT.getSeeds() <= 0 || !(RESULT instanceof TorrentUISearchResult) ? "" : String.valueOf(RESULT.getSeeds()); icon=getIcon(); size=new SizeHolder(getSize()); source=new SourceHolder(RESULT); }
Initializes this line with the specified search result.
public Object nextMeta() throws JSONException { char c; char q; do { c=next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped meta tag"); case '<': return XML.LT; case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; case '"': case '\'': q=c; for (; ; ) { c=next(); if (c == 0) { throw syntaxError("Unterminated string"); } if (c == q) { return Boolean.TRUE; } } default : for (; ; ) { c=next(); if (Character.isWhitespace(c)) { return Boolean.TRUE; } switch (c) { case 0: case '<': case '>': case '/': case '=': case '!': case '?': case '"': case '\'': back(); return Boolean.TRUE; } } } }
Returns the next XML meta token. This is used for skipping over <!...> and <?...?> structures.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public int write(Connection conn,String outputFileName,String sql,String charset) throws SQLException { Statement stat=conn.createStatement(); ResultSet rs=stat.executeQuery(sql); int rows=write(outputFileName,rs,charset); stat.close(); return rows; }
Writes the result set of a query to a file in the CSV format.
private void depthInc(int index){ depths[index]++; depthCalc(); }
increment the depth at index and calc the new depthSum
public void declareStartOfScopeVariable(Identifier id){ Scope s=getClosestDeclarationContainer(); s.addStartOfScopeStatement((Statement)substV("var @id;","id",id)); }
Add a variable declaration to the start of the closest enclosing true scope.
public byte[] remove(QueueEvent event) throws KeeperException, InterruptedException { TimerContext time=stats.time(dir + "_remove_event"); try { String path=event.getId(); String responsePath=dir + "/" + response_prefix+ path.substring(path.lastIndexOf("-") + 1); if (zookeeper.exists(responsePath,true)) { zookeeper.setData(responsePath,event.getBytes(),true); } byte[] data=zookeeper.getData(path,null,null,true); zookeeper.delete(path,-1,true); return data; } finally { time.stop(); } }
Remove the event and save the response into the other path.
public void createTables(DatabaseSession session,JPAMSchemaManager schemaManager,boolean build){ createTables(session,schemaManager,build,true,true,true); }
This creates the tables on the database. If the table already exists this will fail.
@DSSink({DSSinkKind.SENSITIVE_UNCATEGORIZED}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:36.520 -0500",hash_original_method="0DA9D5A0C7EE7D2AFD4BCC53AD3802F3",hash_generated_method="72956D90BC7B32B0D39A00538E67E3E0") @Deprecated public void putIBinder(String key,IBinder value){ unparcel(); mMap.put(key,value); }
Inserts an IBinder value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null.
@SuppressWarnings("unchecked") public SimpleIoProcessorPool(Class<? extends IoProcessor<S>> processorType,Executor executor,int size,SelectorProvider selectorProvider){ if (processorType == null) { throw new IllegalArgumentException("processorType"); } if (size <= 0) { throw new IllegalArgumentException("size: " + size + " (expected: positive integer)"); } createdExecutor=(executor == null); if (createdExecutor) { this.executor=Executors.newCachedThreadPool(); ((ThreadPoolExecutor)this.executor).setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); } else { this.executor=executor; } pool=new IoProcessor[size]; boolean success=false; Constructor<? extends IoProcessor<S>> processorConstructor=null; boolean usesExecutorArg=true; try { try { try { processorConstructor=processorType.getConstructor(ExecutorService.class); pool[0]=processorConstructor.newInstance(this.executor); } catch ( NoSuchMethodException e1) { try { if (selectorProvider == null) { processorConstructor=processorType.getConstructor(Executor.class); pool[0]=processorConstructor.newInstance(this.executor); } else { processorConstructor=processorType.getConstructor(Executor.class,SelectorProvider.class); pool[0]=processorConstructor.newInstance(this.executor,selectorProvider); } } catch ( NoSuchMethodException e2) { try { processorConstructor=processorType.getConstructor(); usesExecutorArg=false; pool[0]=processorConstructor.newInstance(); } catch ( NoSuchMethodException e3) { } } } } catch ( RuntimeException re) { LOGGER.error("Cannot create an IoProcessor :{}",re.getMessage()); throw re; } catch ( Exception e) { String msg="Failed to create a new instance of " + processorType.getName() + ":"+ e.getMessage(); LOGGER.error(msg,e); throw new RuntimeIoException(msg,e); } if (processorConstructor == null) { String msg=String.valueOf(processorType) + " must have a public constructor with one " + ExecutorService.class.getSimpleName()+ " parameter, a public constructor with one "+ Executor.class.getSimpleName()+ " parameter or a public default constructor."; LOGGER.error(msg); throw new IllegalArgumentException(msg); } for (int i=1; i < pool.length; i++) { try { if (usesExecutorArg) { if (selectorProvider == null) { pool[i]=processorConstructor.newInstance(this.executor); } else { pool[i]=processorConstructor.newInstance(this.executor,selectorProvider); } } else { pool[i]=processorConstructor.newInstance(); } } catch ( Exception e) { } } success=true; } finally { if (!success) { dispose(); } } }
Creates a new instance of SimpleIoProcessorPool with an executor
public void add(String string,Image image){ checkWidget(); if (string == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); TableItem newItem=new TableItem(this.table,SWT.NONE); newItem.setText(string); if (image != null) newItem.setImage(image); }
Adds the argument to the end of the receiver's list.
public void onDamaged(final Entity attacker,final int damage){ resolution=Resolution.HIT; combatIconTime=System.currentTimeMillis(); boolean showAttackInfoForPlayer=(this.isUser() || attacker.isUser()); showAttackInfoForPlayer=showAttackInfoForPlayer & (!stendhal.FILTER_ATTACK_MESSAGES); if (stendhal.SHOW_EVERYONE_ATTACK_INFO || showAttackInfoForPlayer) { ClientSingletonRepository.getUserInterface().addEventLine(new HeaderLessEventLine(getTitle() + " suffers " + Grammar.quantityplnoun(damage,"point")+ " of damage from "+ attacker.getTitle(),NotificationType.NEGATIVE)); } }
Called when this entity is damaged by attacker with damage amount.
public String buildQuery(String[] projectionIn,String selection,String groupBy,String having,String sortOrder,String limit){ String[] projection=computeProjection(projectionIn); StringBuilder where=new StringBuilder(); boolean hasBaseWhereClause=mWhereClause != null && mWhereClause.length() > 0; if (hasBaseWhereClause) { where.append(mWhereClause.toString()); where.append(')'); } if (selection != null && selection.length() > 0) { if (hasBaseWhereClause) { where.append(" AND "); } where.append('('); where.append(selection); where.append(')'); } return buildQueryString(mDistinct,mTables,projection,where.toString(),groupBy,having,sortOrder,limit); }
Construct a SELECT statement suitable for use in a group of SELECT statements that will be joined through UNION operators in buildUnionQuery.
public static final GCodeFlavor tasteFlavor(Resources res,int resId) throws IOException, NotFoundException { BufferedInputStream buffer=new BufferedInputStream(res.openRawResource(resId)); GCodeFlavor ret=tasteFlavor(buffer); buffer.close(); return ret; }
Determine the content generator (i.e. Slic3r, Skeinforge) for the given resource.
public static void devicePermissions(Context context,String accessToken,String identifier,AsyncHttpResponseHandler responseHandler){ List<Header> headerList=new ArrayList<Header>(); headerList.add(new BasicHeader(ApiKey.HeadKey.ACCESS_TOKEN,accessToken)); get(context,String.format(getApiServerUrl() + DEVICE_PERMISSION_LIST,identifier),headerList,null,responseHandler); }
get all authorized devices information(/v1/devices/{identifier}/permissions) <p>Method: get</p>
public Object parse() throws XMLException { try { this.builder.startBuilding(this.reader.getSystemID(),this.reader.getLineNr()); this.scanData(); return this.builder.getResult(); } catch ( XMLException e) { throw e; } catch ( Exception e) { XMLException error=new XMLException(e); error.initCause(e); throw error; } }
Parses the data and lets the builder create the logical data structure.
public void onRetry(R result,Throwable failure,ExecutionContext context){ }
Called before an execution is retried.
public void pressed(){ state=STATE_PRESSED; repaint(); }
Invoked to change the state of the button to the pressed state
private static List<AclEntry> decode(long address,int n){ ArrayList<AclEntry> acl=new ArrayList<>(n); for (int i=0; i < n; i++) { long offset=address + i * SIZEOF_ACE_T; int uid=unsafe.getInt(offset + OFFSETOF_UID); int mask=unsafe.getInt(offset + OFFSETOF_MASK); int flags=(int)unsafe.getShort(offset + OFFSETOF_FLAGS); int type=(int)unsafe.getShort(offset + OFFSETOF_TYPE); UnixUserPrincipals.User who=null; if ((flags & ACE_OWNER) > 0) { who=UnixUserPrincipals.SPECIAL_OWNER; } else if ((flags & ACE_GROUP) > 0) { who=UnixUserPrincipals.SPECIAL_GROUP; } else if ((flags & ACE_EVERYONE) > 0) { who=UnixUserPrincipals.SPECIAL_EVERYONE; } else if ((flags & ACE_IDENTIFIER_GROUP) > 0) { who=UnixUserPrincipals.fromGid(uid); } else { who=UnixUserPrincipals.fromUid(uid); } AclEntryType aceType=null; switch (type) { case ACE_ACCESS_ALLOWED_ACE_TYPE: aceType=AclEntryType.ALLOW; break; case ACE_ACCESS_DENIED_ACE_TYPE: aceType=AclEntryType.DENY; break; case ACE_SYSTEM_AUDIT_ACE_TYPE: aceType=AclEntryType.AUDIT; break; case ACE_SYSTEM_ALARM_ACE_TYPE: aceType=AclEntryType.ALARM; break; default : assert false; } Set<AclEntryPermission> aceMask=EnumSet.noneOf(AclEntryPermission.class); if ((mask & ACE_READ_DATA) > 0) aceMask.add(AclEntryPermission.READ_DATA); if ((mask & ACE_WRITE_DATA) > 0) aceMask.add(AclEntryPermission.WRITE_DATA); if ((mask & ACE_APPEND_DATA) > 0) aceMask.add(AclEntryPermission.APPEND_DATA); if ((mask & ACE_READ_NAMED_ATTRS) > 0) aceMask.add(AclEntryPermission.READ_NAMED_ATTRS); if ((mask & ACE_WRITE_NAMED_ATTRS) > 0) aceMask.add(AclEntryPermission.WRITE_NAMED_ATTRS); if ((mask & ACE_EXECUTE) > 0) aceMask.add(AclEntryPermission.EXECUTE); if ((mask & ACE_DELETE_CHILD) > 0) aceMask.add(AclEntryPermission.DELETE_CHILD); if ((mask & ACE_READ_ATTRIBUTES) > 0) aceMask.add(AclEntryPermission.READ_ATTRIBUTES); if ((mask & ACE_WRITE_ATTRIBUTES) > 0) aceMask.add(AclEntryPermission.WRITE_ATTRIBUTES); if ((mask & ACE_DELETE) > 0) aceMask.add(AclEntryPermission.DELETE); if ((mask & ACE_READ_ACL) > 0) aceMask.add(AclEntryPermission.READ_ACL); if ((mask & ACE_WRITE_ACL) > 0) aceMask.add(AclEntryPermission.WRITE_ACL); if ((mask & ACE_WRITE_OWNER) > 0) aceMask.add(AclEntryPermission.WRITE_OWNER); if ((mask & ACE_SYNCHRONIZE) > 0) aceMask.add(AclEntryPermission.SYNCHRONIZE); Set<AclEntryFlag> aceFlags=EnumSet.noneOf(AclEntryFlag.class); if ((flags & ACE_FILE_INHERIT_ACE) > 0) aceFlags.add(AclEntryFlag.FILE_INHERIT); if ((flags & ACE_DIRECTORY_INHERIT_ACE) > 0) aceFlags.add(AclEntryFlag.DIRECTORY_INHERIT); if ((flags & ACE_NO_PROPAGATE_INHERIT_ACE) > 0) aceFlags.add(AclEntryFlag.NO_PROPAGATE_INHERIT); if ((flags & ACE_INHERIT_ONLY_ACE) > 0) aceFlags.add(AclEntryFlag.INHERIT_ONLY); AclEntry ace=AclEntry.newBuilder().setType(aceType).setPrincipal(who).setPermissions(aceMask).setFlags(aceFlags).build(); acl.add(ace); } return acl; }
Decode the buffer, returning an ACL
@Override public int eDerivedStructuralFeatureID(int baseFeatureID,Class<?> baseClass){ if (baseClass == TypableElement.class) { switch (baseFeatureID) { default : return -1; } } if (baseClass == TypeDefiningElement.class) { switch (baseFeatureID) { case N4JSPackage.TYPE_DEFINING_ELEMENT__DEFINED_TYPE: return N4JSPackage.NAMESPACE_IMPORT_SPECIFIER__DEFINED_TYPE; default : return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID,baseClass); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private void putResize(long key,V value){ if (key == 0) { zeroValue=value; hasZeroValue=true; return; } int index1=(int)(key & mask); long key1=keyTable[index1]; if (key1 == EMPTY) { keyTable[index1]=key; valueTable[index1]=value; if (size++ >= threshold) resize(capacity << 1); return; } int index2=hash2(key); long key2=keyTable[index2]; if (key2 == EMPTY) { keyTable[index2]=key; valueTable[index2]=value; if (size++ >= threshold) resize(capacity << 1); return; } int index3=hash3(key); long key3=keyTable[index3]; if (key3 == EMPTY) { keyTable[index3]=key; valueTable[index3]=value; if (size++ >= threshold) resize(capacity << 1); return; } push(key,value,index1,key1,index2,key2,index3,key3); }
Skips checks for existing keys.
private void updateHoveringState(final MouseEvent e){ int hoveringProcessIndex=model.getHoveringProcessIndex(); if (model.getHoveringProcessIndex() != -1) { int relativeX=(int)model.getMousePositionRelativeToProcess().getX(); int relativeY=(int)model.getMousePositionRelativeToProcess().getY(); OutputPort connectionSourceUnderMouse=controller.getPortForConnectorNear(model.getMousePositionRelativeToProcess(),model.getProcess(hoveringProcessIndex)); if (connectionSourceUnderMouse != model.getHoveringConnectionSource()) { model.setHoveringConnectionSource(connectionSourceUnderMouse); model.fireMiscChanged(); e.consume(); } if (controller.checkPortUnder(model.getProcess(hoveringProcessIndex).getInnerSinks(),relativeX,relativeY) || controller.checkPortUnder(model.getProcess(hoveringProcessIndex).getInnerSources(),relativeX,relativeY)) { e.consume(); return; } List<Operator> operators=model.getProcess(hoveringProcessIndex).getOperators(); ListIterator<Operator> iterator=operators.listIterator(operators.size()); while (iterator.hasPrevious()) { Operator op=iterator.previous(); if (controller.checkPortUnder(op.getInputPorts(),relativeX,relativeY) || controller.checkPortUnder(op.getOutputPorts(),relativeX,relativeY)) { e.consume(); return; } Rectangle2D rect=model.getOperatorRect(op); if (rect == null) { continue; } if (rect.contains(new Point2D.Double(relativeX,relativeY))) { if (model.getHoveringOperator() != op) { model.setHoveringPort(null); view.setHoveringOperator(op); if (model.getHoveringOperator() instanceof OperatorChain) { controller.showStatus(I18N.getGUILabel("processRenderer.displayChain.hover")); } else { controller.showStatus(I18N.getGUILabel("processRenderer.operator.hover")); } } e.consume(); return; } } } if (model.getHoveringOperator() != null) { view.setHoveringOperator(null); } if (model.getHoveringPort() != null) { model.setHoveringPort(null); view.updateCursor(); model.fireMiscChanged(); } if (model.getHoveringConnectionSource() != null) { controller.showStatus(I18N.getGUILabel("processRenderer.connection.hover")); } else { controller.clearStatus(); } }
Updates the currently hovered element
public void testNegNegFirstShorter(){ byte aBytes[]={-2,-3,-4,-4,5,14,23,39,48,57,66,5,14,23}; byte bBytes[]={-128,9,56,100,-2,-76,89,45,91,3,-15,35,26,-117,23,87,-25,-75}; int aSign=-1; int bSign=-1; byte rBytes[]={-1,1,75,-89,-45,-2,-3,-18,-36,-17,-10,-3,-6,-7,-21}; BigInteger aNumber=new BigInteger(aSign,aBytes); BigInteger bNumber=new BigInteger(bSign,bBytes); BigInteger result=aNumber.or(bNumber); byte resBytes[]=new byte[rBytes.length]; resBytes=result.toByteArray(); for (int i=0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign",-1,result.signum()); }
Or for two negative numbers; the first is shorter
public final CC gapAfter(String boundsSize){ hor.setGapAfter(ConstraintParser.parseBoundSize(boundsSize,true,true)); return this; }
Sets the horizontal gap after the component. <p> Note! This is currently same as gapRight(). This might change in 4.x.
public static Lattice<String> plfStringToLattice(String plfString,boolean predictPinchPoints){ final Pattern nodePattern=Pattern.compile("(.+?)\\((\\(.+?\\),)\\)(.*)"); final Pattern arcPattern=Pattern.compile("\\('(.+?)',(-?\\d+.?\\d*),(\\d+)\\),(.*)"); Matcher nodeMatcher=nodePattern.matcher(plfString); final Lattice<String> lattice=new Lattice<String>(); int nodeID=Lattice.ROOT_ID; int edgeId=0; int maxPinchPoint=-1; while (nodeMatcher.matches()) { String nodeData=nodeMatcher.group(2); String remainingData=nodeMatcher.group(3); ++nodeID; Node<String> currentNode=lattice.getNode(nodeID,true); if (nodeID == 1) { currentNode.addInEdge(new Edge<String>("",lattice.identity(),edgeId++,lattice.getRoot())); if (predictPinchPoints) { lattice.getRoot().setPinchPoint(true); currentNode.setPinchPoint(true); maxPinchPoint=nodeID; } } Matcher arcMatcher=arcPattern.matcher(nodeData); while (arcMatcher.matches()) { final String arcLabel=arcMatcher.group(1); final double arcWeight=Math.abs(Double.valueOf(arcMatcher.group(2))); final int destinationNodeID=nodeID + Integer.valueOf(arcMatcher.group(3)); maxPinchPoint=(destinationNodeID > maxPinchPoint) ? destinationNodeID : maxPinchPoint; String remainingArcs=arcMatcher.group(4); arcMatcher=arcPattern.matcher(remainingArcs); Node<String> destinationNode=lattice.getNode(destinationNodeID,true); Edge<String> edge=new Edge<String>(arcLabel,arcWeight,edgeId++,currentNode); destinationNode.addInEdge(edge); } if (predictPinchPoints) lattice.getNode(maxPinchPoint).setPinchPoint(true); nodeMatcher=nodePattern.matcher(remainingData); } Node<String> lastNode=lattice.nodeList.get(lattice.nodeList.size() - 1); Node<String> goalNode=lattice.getNode(lattice.nodeList.size(),true); goalNode.addInEdge(new Edge<String>("",lattice.identity(),edgeId++,lastNode)); if (predictPinchPoints) { lastNode.setPinchPoint(true); goalNode.setPinchPoint(true); } return lattice; }
Constructs a lattice from a lattice encoded in PLF. NOTE: For the predictPinchPoints functionality to work, cdec (or whichever lattice generator) must include the unsegmented tokens in the output lattice. TODO: This language can be recognized with a PDA. We really should just have a lexer that returns lists of tuples. Right now I'm using some regexes bootlegged from Joshua: http://github.com/joshua-decoder/joshua/blob/master/src/joshua/lattice/Lattice.java
@Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); if (savedInstanceState != null) { Log.d(TAG,"onCreate(): activity re-created"); } else { Log.d(TAG,"onCreate(): activity created anew"); } }
Hook method called when a new instance of Activity is created. One time initialization code should go here e.g. UI layout, some class scope variable initialization. if finish() is called from onCreate no other lifecycle callbacks are called except for onDestroy().
public Metaphone(){ super(); }
Creates an instance of the Metaphone encoder
public ColorTintFilter(Color mixColor,float mixValue){ if (mixColor == null) { throw new IllegalArgumentException("mixColor cannot be null"); } this.mixColor=mixColor; if (mixValue < 0.0f) { mixValue=0.0f; } else if (mixValue > 1.0f) { mixValue=1.0f; } this.mixValue=mixValue; int mix_r=(int)(mixColor.getRed() * mixValue); int mix_g=(int)(mixColor.getGreen() * mixValue); int mix_b=(int)(mixColor.getBlue() * mixValue); float factor=1.0f - mixValue; preMultipliedRed=new int[256]; preMultipliedGreen=new int[256]; preMultipliedBlue=new int[256]; for (int i=0; i < 256; i++) { int value=(int)(i * factor); preMultipliedRed[i]=value + mix_r; preMultipliedGreen[i]=value + mix_g; preMultipliedBlue[i]=value + mix_b; } }
<p>Creates a new color mixer filter. The specified color will be used to tint the source image, with a mixing strength defined by <code>mixValue</code>.</p>
public static ZTauElement partModReduction(BigInteger k,int m,byte a,BigInteger[] s,byte mu,byte c){ BigInteger d0; if (mu == 1) { d0=s[0].add(s[1]); } else { d0=s[0].subtract(s[1]); } BigInteger[] v=getLucas(mu,m,true); BigInteger vm=v[1]; SimpleBigDecimal lambda0=approximateDivisionByN(k,s[0],vm,a,m,c); SimpleBigDecimal lambda1=approximateDivisionByN(k,s[1],vm,a,m,c); ZTauElement q=round(lambda0,lambda1,mu); BigInteger r0=k.subtract(d0.multiply(q.u)).subtract(BigInteger.valueOf(2).multiply(s[1]).multiply(q.v)); BigInteger r1=s[1].multiply(q.u).subtract(s[0].multiply(q.v)); return new ZTauElement(r0,r1); }
Partial modular reduction modulo <code>(&tau;<sup>m</sup> - 1)/(&tau; - 1)</code>.
private Collection<GraphNode> buildSingleSet(GraphNode inputNode){ Collection<GraphNode> input=Sets.newHashSet(); input.add(inputNode); return input; }
Creates a new input set including the given node.