code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public BusyPeerException(final Throwable cause){
super(cause);
}
| Creates a new exception. |
public static JsonObject loadCustomConfig(InputStream customConfig){
final Reader reader=new InputStreamReader(customConfig);
return new JsonParser().parse(reader).getAsJsonObject();
}
| Loads a custom configuration from the input stream specified. |
public ManagerFactory(String databaseUrl,ManagerPool pool,long pollPeriod,TimeUnit unit,ConnectionMode mode){
this.databaseUrl=databaseUrl;
this.pool=pool;
this.pollMs=unit.toMillis(pollPeriod);
this.mode=mode;
tryCreateTables();
}
| Creates Managers connected to databaseUrl. |
public static void writeFileList(XMLOutput xmlOutput,String tagName,Iterator<File> listValueIterator) throws IOException {
while (listValueIterator.hasNext()) {
xmlOutput.openTag(tagName);
xmlOutput.writeText(listValueIterator.next().getPath());
xmlOutput.closeTag(tagName);
}
}
| Write a list of Strings to document as elements with given tag name. |
void halt(boolean wait){
synchronized (sigLock) {
halted.set(true);
if (paused) {
sigLock.notifyAll();
}
else {
signalSchedulingChange(0);
}
}
if (wait) {
boolean interrupted=false;
try {
while (true) {
try {
join();
break;
}
catch ( InterruptedException _) {
interrupted=true;
}
}
}
finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
}
| <p> Signals the main processing loop to pause at the next possible point. </p> |
public static Normal serializableInstance(){
return new Normal(0,1);
}
| Generates a simple exemplar of this class to test serialization. |
static void openTag(String name){
openTag(name,true);
}
| Open a simple XML entity. |
public void reset(){
offset=0;
}
| Reset the buffer (clears the offset of the next byte to be written to zero). |
public static boolean intersectRayCircle(Vector2fc origin,Vector2fc dir,Vector2fc center,float radiusSquared,Vector2f result){
return intersectRayCircle(origin.x(),origin.y(),dir.x(),dir.y(),center.x(),center.y(),radiusSquared,result);
}
| Test whether the ray with the given <code>origin</code> and direction <code>dir</code> intersects the circle with the given <code>center</code> and square radius <code>radiusSquared</code>, and store the values of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> for both points (near and far) of intersections into the given <code>result</code> vector. <p> This method returns <code>true</code> for a ray whose origin lies inside the circle. <p> Reference: <a href="http://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection">http://www.scratchapixel.com/</a> |
public RecentFilesHandler(String propsFile,int maxCount,M menu){
super(propsFile,maxCount,menu);
}
| Initializes the handler. |
public static InetAddress applyMask(String ip,String mask){
byte[] rawIP=null;
byte[] rawMask=null;
try {
rawIP=InetAddress.getByName(ip).getAddress();
rawMask=InetAddress.getByName(mask).getAddress();
if (rawIP.length != rawMask.length) {
logger.error("IP " + ip + " and mask "+ mask+ " use different formats");
return null;
}
byte[] maskedAddressBytes=new byte[rawIP.length];
for (int i=0; i < rawIP.length; i++) {
byte currentAddressByte=rawIP[i];
byte currentMaskByte=rawMask[i];
maskedAddressBytes[i]=(byte)(currentAddressByte & currentMaskByte);
}
return InetAddress.getByAddress(maskedAddressBytes);
}
catch ( UnknownHostException uhe) {
logger.debug("Caught UnknownHostException while applying mask " + mask + " to IP "+ ip,uhe);
return null;
}
}
| Applies the given mask to the given IP |
public MutableInterval copy(){
return (MutableInterval)clone();
}
| Clone this object without having to cast the returned object. |
public static void main(String[] args){
long startMsec=System.currentTimeMillis();
FullOrderTest t=new FullOrderTest();
t.setUpBase();
t.setUp();
t.testOrderVectorIndexAscEmptyNoRewriteMR();
t.tearDown();
long elapsedMsec=System.currentTimeMillis() - startMsec;
System.err.printf("Finished in %1.3f sec\n",elapsedMsec / 1000.0);
}
| Main method for running one test at a time. |
public void traceInstructions(boolean enable){
return;
}
| Turns the output of debug information for instructions on or off. |
public final void testHandlingSpeed(){
SpellCheckedMetadata result;
long start=System.currentTimeMillis();
for (int i=0; i < NUM_ITERATIONS; i++) {
SpellCheckedMetadata scmd=constructSpellCheckedMetadata();
result=writeRead(scmd);
}
System.out.println(NUM_ITERATIONS + " spellchecked metadata I/O time:" + (System.currentTimeMillis() - start)+ "ms.");
}
| IO Test method, usable only when you plan to do changes in metadata to measure relative performance impact. |
public void reset(){
startTime_ns=System.nanoTime();
totalPktCnt=0;
totalProcTimeNs=0;
avgTotalProcTimeNs=0;
sumSquaredProcTimeNs2=0;
maxTotalProcTimeNs=Long.MIN_VALUE;
minTotalProcTimeNs=Long.MAX_VALUE;
sigmaTotalProcTimeNs=0;
for ( OneComponentTime oct : compStats.values()) {
oct.resetAllCounters();
}
}
| Resets all counters and counters for each component time |
public synchronized String toString(){
StringBuffer sb=new StringBuffer();
sb.append(this.getClass().getSimpleName()).append(": ");
sb.append("name=").append(file.getName());
sb.append(" mode=").append(mode);
if (dataInput != null) {
sb.append(" open=y size=").append(file.length());
sb.append(" offset=").append(dataInput.getOffset());
}
else if (dataOutput != null) {
sb.append(" open=y size=").append(file.length());
try {
sb.append(" offset=").append(dataOutput.getOffset());
}
catch ( IOException e) {
sb.append(" [unable to get offset due to i/o error]");
}
}
else {
sb.append(" open=n");
}
return sb.toString();
}
| Returns a nicely formatting description of the file. |
private void updateTabText(ViewPagerAdapter pagerAdapter){
Typeface font=FontCache.get("Roboto-Regular.ttf",context);
for (int i=0; i < pagerAdapter.getCount(); i++) {
TextView tv=(TextView)(((LinearLayout)((LinearLayout)tabLayout.getChildAt(0)).getChildAt(i)).getChildAt(0));
tv.setAllCaps(false);
tv.setTypeface(font);
}
}
| Programmatically take away all caps for tab bar titles. |
public ExceptionBuilder moreInfo(String moreInfo){
body.setMoreInfo(moreInfo);
return this;
}
| Sets the "more info" field |
private static void addComponent(final JPanel panel,final Component component,final String description,final String hint){
final JPanel settingPanel=new JPanel(new BorderLayout());
settingPanel.setBorder(STANDARD_EMPTY_BORDER);
settingPanel.add(new JLabel(description),BorderLayout.CENTER);
final JPanel innerPanel=new JPanel(new BorderLayout());
innerPanel.add(component,BorderLayout.CENTER);
final JHintIcon hintPopup=new JHintIcon(hint);
hintPopup.setBorder(new EmptyBorder(0,3,0,0));
innerPanel.add(hintPopup,BorderLayout.EAST);
settingPanel.add(innerPanel,BorderLayout.EAST);
panel.add(settingPanel);
}
| Adds a component that is used to configure a setting. |
public Query parseUnaryTerm(ODataTokenList tokens) throws IllegalArgumentException {
ODataToken left;
ODataToken right;
ODataToken verb;
if (tokens.lookToken().getKind().equals(ODataToken.ODataTokenKind.SIMPLE_TYPE)) {
left=tokens.next();
}
else {
throw new IllegalArgumentException("Term mismatch");
}
if (tokens.lookToken().getKind().equals(ODataToken.ODataTokenKind.BINARY_COMPARISON)) {
verb=tokens.next();
}
else {
throw new IllegalArgumentException("Term mismatch");
}
if (tokens.lookToken().getKind().equals(ODataToken.ODataTokenKind.SIMPLE_TYPE)) {
right=tokens.next();
}
else {
throw new IllegalArgumentException("Term mismatch");
}
return visitBinaryComparator(left.getUriLiteral(),stringToVerb(verb.getUriLiteral()),right.getUriLiteral());
}
| Parse a single term; |
public static double variance(double shape,double scale){
if (shape > 2) {
return scale * scale / ((shape - 1) * (scale - 1) * (scale - 2));
}
return Double.POSITIVE_INFINITY;
}
| variance of the Gamma distribution. |
private void writeAttribute(java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
| Util method to write an attribute without the ns prefix |
private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, javax.xml.transform.TransformerException {
try {
stream.defaultReadObject();
m_clones=new IteratorPool(this);
}
catch ( ClassNotFoundException cnfe) {
throw new javax.xml.transform.TransformerException(cnfe);
}
}
| Read the object from a serialization stream. |
@Override public boolean equals(Object obj){
return getMonitoredObject().equals(getMonitoredObject(obj));
}
| When this is called on the proxy object it is the same as calling proxyObject1.equals(proxyObject2) is the same as calling originalObject1.equals(originalObject2) |
@OnClose public void onClose(Session session){
openSessions.remove(session.getId());
callInternal("onClose",session,null);
}
| On close handler |
private String buildBookmarksPath(AppContext ctx,String path){
String fullPath;
if (path == null || path.equals("")) {
String myPath=Bookmark.SEPARATOR + Bookmark.Folder.USER + Bookmark.SEPARATOR+ ctx.getUser().getOid();
fullPath=myPath;
}
else {
fullPath=path;
}
return fullPath;
}
| Build a decoded path. |
private static boolean merge(final ClassWriter cw,int t,final int[] types,final int index){
int u=types[index];
if (u == t) {
return false;
}
if ((t & ~DIM) == NULL) {
if (u == NULL) {
return false;
}
t=NULL;
}
if (u == 0) {
types[index]=t;
return true;
}
int v;
if ((u & BASE_KIND) == OBJECT || (u & DIM) != 0) {
if (t == NULL) {
return false;
}
else if ((t & (DIM | BASE_KIND)) == (u & (DIM | BASE_KIND))) {
if ((u & BASE_KIND) == OBJECT) {
v=(t & DIM) | OBJECT | cw.getMergedType(t & BASE_VALUE,u & BASE_VALUE);
}
else {
int vdim=ELEMENT_OF + (u & DIM);
v=vdim | OBJECT | cw.addType("java/lang/Object");
}
}
else if ((t & BASE_KIND) == OBJECT || (t & DIM) != 0) {
int tdim=(((t & DIM) == 0 || (t & BASE_KIND) == OBJECT) ? 0 : ELEMENT_OF) + (t & DIM);
int udim=(((u & DIM) == 0 || (u & BASE_KIND) == OBJECT) ? 0 : ELEMENT_OF) + (u & DIM);
v=Math.min(tdim,udim) | OBJECT | cw.addType("java/lang/Object");
}
else {
v=TOP;
}
}
else if (u == NULL) {
v=(t & BASE_KIND) == OBJECT || (t & DIM) != 0 ? t : TOP;
}
else {
v=TOP;
}
if (u != v) {
types[index]=v;
return true;
}
return false;
}
| Merges the type at the given index in the given type array with the given type. Returns <tt>true</tt> if the type array has been modified by this operation. |
public boolean hasMoreWords(){
return !this.words.isEmpty();
}
| True if there are more words remaining. |
private void initializeDefault(){
int[] defh={10,10,10,10};
int[] defw={3,3,3,3};
int[] defk={2,2,2,2};
KeyGenerationParameters kgp=new GMSSKeyGenerationParameters(new SecureRandom(),new GMSSParameters(defh.length,defh,defw,defk));
this.initialize(kgp);
}
| This method is called by generateKeyPair() in case that no other initialization method has been called by the user |
public DOMPGPData(Element pdElem) throws MarshalException {
byte[] keyId=null;
byte[] keyPacket=null;
NodeList nl=pdElem.getChildNodes();
int length=nl.getLength();
List<XMLStructure> other=new ArrayList<XMLStructure>(length);
for (int x=0; x < length; x++) {
Node n=nl.item(x);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element childElem=(Element)n;
String localName=childElem.getLocalName();
try {
if (localName.equals("PGPKeyID")) {
keyId=Base64.decode(childElem);
}
else if (localName.equals("PGPKeyPacket")) {
keyPacket=Base64.decode(childElem);
}
else {
other.add(new javax.xml.crypto.dom.DOMStructure(childElem));
}
}
catch ( Base64DecodingException bde) {
throw new MarshalException(bde);
}
}
}
this.keyId=keyId;
this.keyPacket=keyPacket;
this.externalElements=Collections.unmodifiableList(other);
}
| Creates a <code>DOMPGPData</code> from an element. |
public static byte[] encodeBitmapAsPNG(Bitmap bitmap,boolean color,int numColors,boolean allowTransparent){
int bits;
if (!color && numColors != 2) throw new IllegalArgumentException("must have 2 colors for black and white");
if (numColors < 2) throw new IllegalArgumentException("minimum 2 colors");
else if (numColors == 2) bits=1;
else if (numColors <= 4) bits=2;
else if (numColors <= 16) bits=4;
else if (numColors <= 64) bits=8;
else throw new IllegalArgumentException("maximum 64 colors");
SimpleImageEncoder encoder=new SimpleImageEncoder();
int[] pixels=new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(pixels,0,bitmap.getWidth(),0,0,bitmap.getWidth(),bitmap.getHeight());
encoder.optimizePalette(pixels,numColors,allowTransparent);
return encoder.encodeIndexedPNG(pixels,bitmap.getWidth(),bitmap.getHeight(),color,bits);
}
| Encode an Android bitmap as an indexed PNG using Pebble Time colors. param: bitmap param: color Whether the image is color (true) or black-and-white param: numColors Should be 2, 4, 16, or 64. Using 16 colors is typically the best tradeoff. Must be 2 if B&W. param: allowTransparent Allow fully transparent pixels return: Array of bytes in PNG format |
@Interruptible public static void initializeHeader(BootImageInterface bootImage,Address ref,TIB tib,int size,boolean isScalar){
byte status=Selected.Plan.get().setBuildTimeGCByte(ref,ObjectReference.fromObject(tib),size);
JavaHeader.writeAvailableByte(bootImage,ref,status);
}
| Override the boot-time initialization method here, so that the core MMTk code doesn't need to know about the BootImageInterface type. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
private static Version readVersion(BitMatrix bitMatrix) throws FormatException {
int numRows=bitMatrix.getHeight();
int numColumns=bitMatrix.getWidth();
return Version.getVersionForDimensions(numRows,numColumns);
}
| <p>Creates the version object based on the dimension of the original bit matrix from the datamatrix code.</p> <p>See ISO 16022:2006 Table 7 - ECC 200 symbol attributes</p> |
public boolean forwardIfCurrent(char first,char second){
int start=pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn=forwardIfCurrent(second);
if (!rtn) pos=start;
return rtn;
}
| Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second, wenn ja wird der Zeiger um die Laenge der uebereinstimmung nach vorne gestellt. |
public static <E>ImmutableList<E> of(E e1,E e2,E e3,E e4,E e5,E e6,E e7,E e8,E e9){
return construct(e1,e2,e3,e4,e5,e6,e7,e8,e9);
}
| Returns an immutable list containing the given elements, in order. |
public static double sum(double[] v){
int m=v.length;
double s=0;
for (int i=0; i < m; i++) s+=v[i];
return s;
}
| Calculate the sum of the values in an array |
public synchronized void clear(){
listeners=emptyArray;
}
| Removes all listeners from this list. |
public void add(char ch){
if (i == b.length) {
char[] new_b=new char[i + INC];
for (int c=0; c < i; c++) new_b[c]=b[c];
b=new_b;
}
b[i++]=ch;
}
| Add a character to the word being stemmed. When you are finished adding characters, you can call stem(void) to stem the word. |
public static Mosaic createMosaic(final int id,final long quantity){
return new Mosaic(createMosaicId(id),Quantity.fromValue(quantity));
}
| Creates a mosaic that conforms to a certain pattern. |
public void addItemLabel(final JLabel label,final JComponent item){
GridBagConstraints labelConstraints=new GridBagConstraints();
labelConstraints.gridx=0;
labelConstraints.gridy=myNextItemRow;
labelConstraints.insets=new Insets(10,10,0,0);
labelConstraints.anchor=GridBagConstraints.NORTHEAST;
labelConstraints.fill=GridBagConstraints.NONE;
add(label,labelConstraints);
GridBagConstraints itemConstraints=new GridBagConstraints();
itemConstraints.gridx=1;
itemConstraints.gridy=myNextItemRow;
itemConstraints.insets=new Insets(10,10,0,10);
itemConstraints.weightx=1.0;
itemConstraints.anchor=GridBagConstraints.WEST;
itemConstraints.fill=GridBagConstraints.HORIZONTAL;
add(item,itemConstraints);
myNextItemRow++;
}
| Modification of addItem which takes a label, rather than text, as an argument. |
public WorldMapLayer(String iconFilePath){
this.setOpacity(0.6);
this.setIconFilePath(iconFilePath);
}
| Displays a world map overlay with a current position crosshair in a screen corner |
private void log(LogLevel eventLevel,String message,Object param){
switch (eventLevel) {
case TRACE:
logger.trace(message,param);
return;
case DEBUG:
logger.debug(message,param);
return;
case INFO:
logger.info(message,param);
return;
case WARN:
logger.warn(message,param);
return;
case ERROR:
logger.error(message,param);
return;
default :
return;
}
}
| Log if the logger and the current event log level are compatible. We log a formated message and its parameters. |
public void invokeAndBlock(Runnable r){
invokeAndBlock(r,false);
}
| Invokes runnable and blocks the current thread, if the current thread is the EDT it will still be blocked in a way that doesn't break event dispatch . <b>Important:</b> calling this method spawns a new thread that shouldn't access the UI!<br /> See <a href="https://www.codenameone.com/manual/edt.html#_invoke_and_block"> this section</a> in the developer guide for further information. |
public OperandExpression(final INaviOperandTreeNode node){
m_node=Preconditions.checkNotNull(node,"Error: Node argument can't be null");
for ( final IReference reference : m_node.getReferences()) {
m_references.add(new Reference(reference));
}
m_node.addListener(m_internalListener);
}
| Creates a new operand expression object. |
public boolean isHighlighted(){
return isHighlighted;
}
| Get whether the <code>Annotation</code> is highlighted and should be drawn bigger - see setHighlightScale(). |
public SgmExcepcion(String message){
this(message,null);
}
| Construye un objeto de la clase. |
public BufferedInputStream(InputStream in,int size){
this(in,size,"unnamed");
}
| Creates a <code>BufferedInputStream</code> with the specified buffer size, and saves its argument, the input stream <code>in</code>, for later use. An internal buffer array of length <code>size</code> is created and stored in <code>buf</code>. |
private void upgradeTenantDB(){
final Flyway flyway=new Flyway();
flyway.setDataSource(tenantDataSource);
flyway.setLocations("sql/migrations/list_db");
flyway.setOutOfOrder(true);
flyway.migrate();
tenantDataSourcePortFixService.fixUpTenantsSchemaServerPort();
}
| Initializes, and if required upgrades (using Flyway) the Tenant DB itself. |
public ModelMBeanNotificationInfo(ModelMBeanNotificationInfo inInfo){
this(inInfo.getNotifTypes(),inInfo.getName(),inInfo.getDescription(),inInfo.getDescriptor());
}
| Constructs a new ModelMBeanNotificationInfo object from this ModelMBeanNotfication Object. |
@SuppressWarnings("unchecked") @Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case UmplePackage.POSITION___ASSOCIATION_POSITION_1:
getAssociationPosition_1().clear();
getAssociationPosition_1().addAll((Collection<? extends AssociationPosition_>)newValue);
return;
case UmplePackage.POSITION___ELEMENT_POSITION_1:
getElementPosition_1().clear();
getElementPosition_1().addAll((Collection<? extends ElementPosition_>)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void test_insertElementAtLjava_lang_ObjectI(){
Vector v=vectorClone(tVector);
String prevElement=(String)v.elementAt(99);
v.insertElementAt("Inserted Element",99);
assertEquals("Element not inserted","Inserted Element",((String)v.elementAt(99)));
assertTrue("Elements shifted incorrectly",((String)v.elementAt(100)).equals(prevElement));
v.insertElementAt(null,20);
assertNull("null not inserted",v.elementAt(20));
try {
tVector.insertElementAt(null,-5);
fail("ArrayIndexOutOfBoundsException expected");
}
catch ( ArrayIndexOutOfBoundsException e) {
}
try {
tVector.insertElementAt(null,tVector.size() + 1);
fail("ArrayIndexOutOfBoundsException expected");
}
catch ( ArrayIndexOutOfBoundsException e) {
}
}
| java.util.Vector#insertElementAt(java.lang.Object, int) |
public boolean isSetVersion(){
return EncodingUtils.testBit(__isset_bitfield,__VERSION_ISSET_ID);
}
| Returns true if field version is set (has been assigned a value) and false otherwise |
@Override public void remove(ZombieStatus status,StatusList statusList){
statusList.removeInternal(status);
RPEntity entity=statusList.getEntity();
if (entity == null) {
return;
}
Status nextStatus=statusList.getFirstStatusByClass(ZombieStatus.class);
entity.setBaseSpeed(originalSpeed);
if (nextStatus != null) {
TurnNotifier.get().notifyInSeconds(60,new StatusRemover(statusList,nextStatus));
}
else {
entity.sendPrivateText(NotificationType.SCENE_SETTING,"You are no longer zombified.");
entity.remove("status_" + status.getName());
}
}
| removes a status |
@Override public void printStackTrace(){
super.printStackTrace();
if (nested != null) {
nested.printStackTrace();
}
}
| Prints the composite message to System.err. |
protected AbstractExtension(XmlNamespace namespace,String localName){
this.namespace=namespace;
this.localName=localName;
}
| Constructs an extension bound to a specific XML representation. Note: this is here for backwards compatibility and may be removed at some point in the future. |
public ProcessingUnit(CompilerConfiguration configuration,GroovyClassLoader classLoader,ErrorCollector er){
this.phase=Phases.INITIALIZATION;
this.configuration=configuration;
this.setClassLoader(classLoader);
configure((configuration == null ? new CompilerConfiguration() : configuration));
if (er == null) er=new ErrorCollector(getConfiguration());
this.errorCollector=er;
}
| Initialize the ProcessingUnit to the empty state. |
public boolean checkSlotsAndSizes(@Nonnull IInventory inv,@Nonnull IMultiItemStacks[] filter,int[] from){
assert filter.length == from.length;
for (int i=0; i < filter.length; ++i) {
if (!checkSlotAndSize(inv,filter[i],from[i])) return false;
}
return true;
}
| Checks a slice of slots for the given items |
public ContentModel(int type,ContentModel content){
this(type,content,null);
}
| Create a content model of a particular type. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
@Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case MappingPackage.FAULT_SOURCE__PROPERTY:
setProperty((Property)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private String discoverTagName(RSyntaxDocument doc,int dot){
Stack stack=new Stack();
Element root=doc.getDefaultRootElement();
int curLine=root.getElementIndex(dot);
for (int i=0; i <= curLine; i++) {
Token t=doc.getTokenListForLine(i);
while (t != null && t.isPaintable()) {
if (t.type == Token.MARKUP_TAG_DELIMITER) {
if (t.isSingleChar('<') || t.isSingleChar('[')) {
t=t.getNextToken();
while (t != null && t.isPaintable()) {
if (t.type == Token.MARKUP_TAG_NAME || t.type == Token.MARKUP_TAG_ATTRIBUTE) {
stack.push(t.getLexeme());
break;
}
t=t.getNextToken();
}
}
else if (t.textCount == 2 && t.text[t.textOffset] == '/' && (t.text[t.textOffset + 1] == '>' || t.text[t.textOffset + 1] == ']')) {
if (!stack.isEmpty()) {
stack.pop();
}
}
else if (t.textCount == 2 && (t.text[t.textOffset] == '<' || t.text[t.textOffset] == '[') && t.text[t.textOffset + 1] == '/') {
String tagName=null;
if (!stack.isEmpty()) {
tagName=(String)stack.pop();
}
if (t.offset + t.textCount >= dot) {
return tagName;
}
}
}
t=t.getNextToken();
}
}
return null;
}
| Discovers the name of the tag being closed. Assumes standard SGML-style markup tags. |
public VarNode tVarLeft(){
return (VarNode)super.getRequiredProperty(Annotations.TRANSITIVITY_VAR_LEFT);
}
| Return the left transitivity var. |
public boolean removeAll(Collection<?> c){
Objects.requireNonNull(c);
boolean modified=false;
if (size() > c.size()) {
for (Iterator<?> i=c.iterator(); i.hasNext(); ) modified|=remove(i.next());
}
else {
for (Iterator<?> i=iterator(); i.hasNext(); ) {
if (c.contains(i.next())) {
i.remove();
modified=true;
}
}
}
return modified;
}
| Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the <i>asymmetric set difference</i> of the two sets. <p>This implementation determines which is the smaller of this set and the specified collection, by invoking the <tt>size</tt> method on each. If this set has fewer elements, then the implementation iterates over this set, checking each element returned by the iterator in turn to see if it is contained in the specified collection. If it is so contained, it is removed from this set with the iterator's <tt>remove</tt> method. If the specified collection has fewer elements, then the implementation iterates over the specified collection, removing from this set each element returned by the iterator, using this set's <tt>remove</tt> method. <p>Note that this implementation will throw an <tt>UnsupportedOperationException</tt> if the iterator returned by the <tt>iterator</tt> method does not implement the <tt>remove</tt> method. |
private void saveVolatiles(Instruction inst){
PhysicalRegisterSet phys=ir.regpool.getPhysicalRegisterSet().asPPC();
Register FP=phys.getFP();
int i=0;
for (Enumeration<Register> e=phys.enumerateVolatileGPRs(); e.hasMoreElements(); i++) {
Register r=e.nextElement();
int location=saveVolatileGPRLocation[i];
inst.insertBefore(MIR_Store.create(PPC_STAddr,A(r),A(FP),IC(location)));
}
i=0;
for (Enumeration<Register> e=phys.enumerateVolatileFPRs(); e.hasMoreElements(); i++) {
Register r=e.nextElement();
int location=saveVolatileFPRLocation[i];
inst.insertBefore(MIR_Store.create(PPC_STFD,D(r),A(FP),IC(location)));
}
Register temp=phys.getTemp();
inst.insertBefore(MIR_Move.create(PPC_MFSPR,I(temp),I(phys.getXER())));
inst.insertBefore(MIR_Store.create(PPC_STW,I(temp),A(FP),IC(saveXERLocation)));
inst.insertBefore(MIR_Move.create(PPC_MFSPR,A(temp),A(phys.getCTR())));
inst.insertBefore(MIR_Store.create(PPC_STAddr,A(temp),A(FP),IC(saveCTRLocation)));
}
| Insert code in the prologue to save the volatile registers. |
public void add(final ConversationStates[] states,final String trigger,final ChatCondition condition,final ConversationStates nextState,final String reply,final ChatAction action){
for ( final ConversationStates state : states) {
add(state,trigger,condition,nextState,reply,action);
}
}
| Adds a new set of transitions to the FSM. |
public void clear(String className){
rawCFGs.remove(className);
actualCFGs.remove(className);
controlDependencies.remove(className);
}
| <p> clear </p> |
public ApplicationUtil(String token) throws LoginException {
api=new JDAImpl(false,false,false);
api.verifyToken(token);
}
| Creates a new instance of the ApplicationUtil class. This requires login-information of the person owning the application(s). <b>Do not use login-information of a account you use as bot here.</b> |
public String toJson(){
Gson gson=new Gson();
return gson.toJson(payload);
}
| To json string. |
public CareerLevel careerLevel(){
return careerLevel;
}
| Returns the user's career level. <br><i>Non-mandatory field if creating new company.</i> |
@Override public Dimension minimumLayoutSize(Container parent){
synchronized (parent.getTreeLock()) {
Insets insets=parent.getInsets();
int ncomponents=parent.getComponentCount();
int nrows=rows;
int ncols=cols;
if (nrows > 0) {
ncols=(ncomponents + nrows - 1) / nrows;
}
else {
nrows=(ncomponents + ncols - 1) / ncols;
}
int w=0;
int h=0;
for (int i=0; i < ncomponents; i++) {
Component comp=parent.getComponent(i);
Dimension d=comp.getMinimumSize();
if (w < d.width) {
w=d.width;
}
if (h < d.height) {
h=d.height;
}
}
return new Dimension(insets.left + insets.right + ncols * w + (ncols - 1) * hgap,insets.top + insets.bottom + nrows * h + (nrows - 1) * vgap);
}
}
| Determines the minimum size of the container argument using this grid layout. <p> The minimum width of a grid layout is the largest minimum width of any of the components in the container times the number of columns, plus the horizontal padding times the number of columns plus one, plus the left and right insets of the target container. <p> The minimum height of a grid layout is the largest minimum height of any of the components in the container times the number of rows, plus the vertical padding times the number of rows plus one, plus the top and bottom insets of the target container. |
public void refresh(){
validate();
repaint();
}
| validates and repaints the frame |
public static double standardError(int size,double variance){
return Math.sqrt(variance / size);
}
| Returns the standard error of a data sequence. That is <tt>Math.sqrt(variance/size)</tt>. |
private int readFromResponse(State state,InnerState innerState,byte[] data,InputStream entityStream) throws StopRequest {
try {
return entityStream.read(data);
}
catch ( IOException ex) {
logNetworkState();
mInfo.mCurrentBytes=innerState.mBytesSoFar;
mDB.updateDownload(mInfo);
if (cannotResume(innerState)) {
String message="while reading response: " + ex.toString() + ", can't resume interrupted download with no ETag";
throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,message,ex);
}
else {
throw new StopRequest(getFinalStatusForHttpError(state),"while reading response: " + ex.toString(),ex);
}
}
}
| Read some data from the HTTP response stream, handling I/O errors. |
public void cleanUp(){
cleanUpStatics(this.sender);
}
| This method does the cleanup of any threads, sockets, connection that are held up by the queue. Note that this cleanup doesn't clean the data held by the queue. |
public int awaitAdvance(int phase){
final Phaser root=this.root;
long s=(root == this) ? state : reconcileState();
int p=(int)(s >>> PHASE_SHIFT);
if (phase < 0) return phase;
if (p == phase) return root.internalAwaitAdvance(phase,null);
return p;
}
| Awaits the phase of this phaser to advance from the given phase value, returning immediately if the current phase is not equal to the given phase value or this phaser is terminated. |
protected ReferenceType mergeReferenceTypes(ReferenceType aRef,ReferenceType bRef) throws DataflowAnalysisException {
if (aRef.equals(bRef)) {
return aRef;
}
byte aType=aRef.getType();
byte bType=bRef.getType();
try {
if (isObjectType(aType) && isObjectType(bType) && ((aType == T_EXCEPTION || isThrowable(aRef)) && (bType == T_EXCEPTION || isThrowable(bRef)))) {
ExceptionSet union=exceptionSetFactory.createExceptionSet();
if (aType == T_OBJECT && "Ljava/lang/Throwable;".equals(aRef.getSignature())) {
return aRef;
}
if (bType == T_OBJECT && "Ljava/lang/Throwable;".equals(bRef.getSignature())) {
return bRef;
}
updateExceptionSet(union,(ObjectType)aRef);
updateExceptionSet(union,(ObjectType)bRef);
Type t=ExceptionObjectType.fromExceptionSet(union);
if (t instanceof ReferenceType) {
return (ReferenceType)t;
}
}
if (aRef instanceof GenericObjectType && bRef instanceof GenericObjectType && aRef.getSignature().equals(bRef.getSignature())) {
GenericObjectType aG=(GenericObjectType)aRef;
GenericObjectType bG=(GenericObjectType)bRef;
if (aG.getTypeCategory() == bG.getTypeCategory()) {
switch (aG.getTypeCategory()) {
case PARAMETERIZED:
List<? extends ReferenceType> aP=aG.getParameters();
List<? extends ReferenceType> bP=bG.getParameters();
assert aP != null;
assert bP != null;
if (aP.size() != bP.size()) {
break;
}
ArrayList<ReferenceType> result=new ArrayList<ReferenceType>(aP.size());
for (int i=0; i < aP.size(); i++) {
result.add(mergeReferenceTypes(aP.get(i),bP.get(i)));
}
GenericObjectType rOT=GenericUtilities.getType(aG.getClassName(),result);
return rOT;
}
}
}
if (aRef instanceof GenericObjectType) {
aRef=((GenericObjectType)aRef).getObjectType();
}
if (bRef instanceof GenericObjectType) {
bRef=((GenericObjectType)bRef).getObjectType();
}
if (Subtypes2.ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES) {
return AnalysisContext.currentAnalysisContext().getSubtypes2().getFirstCommonSuperclass(aRef,bRef);
}
else {
return aRef.getFirstCommonSuperclass(bRef);
}
}
catch (ClassNotFoundException e) {
lookupFailureCallback.reportMissingClass(e);
return Type.OBJECT;
}
}
| Default implementation of merging reference types. This just returns the first common superclass, which is compliant with the JVM Spec. Subclasses may override this method in order to implement extended type rules. |
@DSSource({DSSourceKind.SENSITIVE_UNCATEGORIZED}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:07.242 -0500",hash_original_method="CA4CA07B31DF6CB609C05636F40DB22F",hash_generated_method="F1656D64C351B2C62FC72407CC65AFFB") public RSeqHeader createRSeqHeader(long sequenceNumber) throws InvalidArgumentException {
if (sequenceNumber < 0) throw new InvalidArgumentException("invalid sequenceNumber arg " + sequenceNumber);
RSeq rseq=new RSeq();
rseq.setSeqNumber(sequenceNumber);
return rseq;
}
| Creates a new RSeqHeader based on the newly supplied sequenceNumber value. |
public static long readDwordLittleEndian(final byte[] data,final int offset){
return ((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 DWORD value from a byte array. |
protected void captureSnapshot(final String messagePrefix){
ScreenshotUtil.captureSnapshot(messagePrefix);
}
| Captures snapshot of the current browser window, and prefix the file name with the assigned string. |
public boolean isFailFast(){
return failFast;
}
| Returns true (the default) to indicate that the first statement to fail starting will fail the complete module deployment, or set to false to indicate that the operation should attempt to start all statements regardless of any failures. |
public void triggerUpdateOnStartup(){
mTriggerUpdate=true;
}
| Trigger update programmtically |
public String join(String separator) throws JSONException {
int len=this.length();
StringBuffer sb=new StringBuffer();
for (int i=0; i < len; i+=1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
| Make a string from the contents of this JSONArray. The <code>separator</code> string is inserted between each element. Warning: This method assumes that the data structure is acyclical. |
protected final void startNamespaceMapping() throws SAXException {
int count=fNamespaceContext.getDeclaredPrefixCount();
if (count > 0) {
String prefix=null;
String uri=null;
for (int i=0; i < count; i++) {
prefix=fNamespaceContext.getDeclaredPrefixAt(i);
uri=fNamespaceContext.getURI(prefix);
fContentHandler.startPrefixMapping(prefix,(uri == null) ? "" : uri);
}
}
}
| Send startPrefixMapping events |
public static GoogleAnalytics initialiseGoogleAnalytics(Context context,String trackerId,final ExceptionParser callback){
mAnalytics=GoogleAnalytics.getInstance(context);
mAnalytics.setLocalDispatchPeriod(1800);
mTracker=mAnalytics.newTracker(trackerId);
mTracker.enableExceptionReporting(true);
mTracker.enableAutoActivityTracking(true);
Thread.UncaughtExceptionHandler handler=Thread.getDefaultUncaughtExceptionHandler();
if (handler != null && handler instanceof ExceptionReporter) {
ExceptionReporter exceptionReporter=(ExceptionReporter)handler;
exceptionReporter.setExceptionParser(callback);
Thread.setDefaultUncaughtExceptionHandler(exceptionReporter);
Log.d(LOG_TAG,"Analytics active.");
}
else {
Log.e(LOG_TAG,"Cannot set custom exception parser.");
}
return mAnalytics;
}
| Initialise Google Analytics immediately so it will catch all sorts of errors prior to EasyTracker onStart. Also makes sensible exception stack traces if you want. |
protected void drawCheckboxes(DrawContext dc,Iterable<NodeLayout> nodes){
GL2 gl=dc.getGL().getGL2();
Dimension symbolSize;
if (!dc.isPickingMode()) {
this.drawFilledCheckboxes(dc,nodes);
this.drawCheckmarks(dc,nodes);
symbolSize=this.getSelectedSymbolSize();
}
else {
symbolSize=new Dimension(this.getSelectedSymbolSize().width + this.getActiveAttributes().getIconSpace(),this.lineHeight + this.getActiveAttributes().getRowSpacing());
}
if (dc.isPickingMode()) {
gl.glBegin(GL2.GL_QUADS);
}
try {
for ( NodeLayout layout : nodes) {
int vertAdjust=layout.bounds.height - symbolSize.height - (this.lineHeight - symbolSize.height) / 2;
int x=layout.drawPoint.x;
int y=layout.drawPoint.y + vertAdjust;
int width=symbolSize.width;
if (!dc.isPickingMode()) {
gl.glBegin(GL2.GL_LINE_LOOP);
try {
gl.glVertex2f(x + width,y + symbolSize.height + 0.5f);
gl.glVertex2f(x,y + symbolSize.height + 0.5f);
gl.glVertex2f(x,y);
gl.glVertex2f(x + width,y + 0.5f);
}
finally {
gl.glEnd();
}
}
else {
Color color=dc.getUniquePickColor();
int colorCode=color.getRGB();
this.pickSupport.addPickableObject(colorCode,this.createSelectControl(layout.node));
gl.glColor3ub((byte)color.getRed(),(byte)color.getGreen(),(byte)color.getBlue());
if (layout.node.isLeaf() || !this.isDrawNodeStateSymbol()) {
width=x - this.screenLocation.x + symbolSize.width;
x=this.screenLocation.x;
}
gl.glVertex2f(x + width,y + symbolSize.height);
gl.glVertex2f(x,y + symbolSize.height);
gl.glVertex2f(x,y);
gl.glVertex2f(x + width,y);
}
layout.drawPoint.x+=symbolSize.width + this.getActiveAttributes().getIconSpace();
}
}
finally {
if (dc.isPickingMode()) {
gl.glEnd();
}
}
}
| Draw check boxes. Each box includes a check mark is the node is selected, or is filled with a gradient if the node is partially selected. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public boolean isPrefixOf(Path anotherPath){
if (device == null) {
if (anotherPath.getDevice() != null) {
return false;
}
}
else {
if (!device.equalsIgnoreCase(anotherPath.getDevice())) {
return false;
}
}
if (isEmpty() || (isRoot() && anotherPath.isAbsolute())) {
return true;
}
int len=segments.length;
if (len > anotherPath.segmentCount()) {
return false;
}
for (int i=0; i < len; i++) {
if (!segments[i].equals(anotherPath.segment(i))) return false;
}
return true;
}
| Returns whether this path is a prefix of the given path. To be a prefix, this path's segments must appear in the argument path in the same order, and their device ids must match. <p> An empty path is a prefix of all paths with the same device; a root path is a prefix of all absolute paths with the same device. </p> |
public ParseACL(ParseUser owner){
this();
setReadAccess(owner,true);
setWriteAccess(owner,true);
}
| Creates an ACL where only the provided user has access. |
public boolean isZoomYEnabled(){
return mZoomYEnabled;
}
| Returns the enabled state of the zoom on Y axis. |
public Template(String id,String name,String description,String contextTypeId,String pattern,boolean isAutoInsertable){
this.id=id;
Assert.isNotNull(description);
fDescription=description;
fName=name;
Assert.isNotNull(contextTypeId);
fContextTypeId=contextTypeId;
fPattern=pattern;
fIsAutoInsertable=isAutoInsertable;
}
| Creates a template. |
COMMarkerSegment(JPEGBuffer buffer) throws IOException {
super(buffer);
loadData(buffer);
}
| Constructs a marker segment from the given buffer, which contains data from an <code>ImageInputStream</code>. This is used when reading metadata from a stream. |
public static _Fields findByName(String name){
return byName.get(name);
}
| Find the _Fields constant that matches name, or null if its not found. |
public boolean startsWith(String prefix,int toffset){
return m_str.startsWith(prefix,toffset);
}
| Tests if this string starts with the specified prefix beginning a specified index. |
public Flag registerRequired(final char nameChar,final String name,final Class<?> type,final String usage,final String description){
return registerRequired(Character.valueOf(nameChar),name,type,usage,description);
}
| Registers a required flag. This flag requires a parameter of a specified type. |
public int hashCode(){
return id.hashCode();
}
| Returns a hash code value for this object. |
public void newMethod(String methodName){
assert (currentMethod == null) || currentMethod.getCode().isEmpty();
assert currentMethodVars.isEmpty();
currentScope=TestScope.METHOD;
currentMethod=new MethodDef(methodName);
}
| <p> newMethod </p> |
public void addIterator(DTMIterator expr){
if (null == m_iterators) {
m_iterators=new DTMIterator[1];
m_iterators[0]=expr;
}
else {
DTMIterator[] exprs=m_iterators;
int len=m_iterators.length;
m_iterators=new DTMIterator[len + 1];
System.arraycopy(exprs,0,m_iterators,0,len);
m_iterators[len]=expr;
}
expr.nextNode();
if (expr instanceof Expression) ((Expression)expr).exprSetParent(this);
}
| Add an iterator to the union list. |
private BufferedImageHelper(){
}
| This class has only static methods, so there is no need to construct anything. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.