code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static MethodAnnotation fromMethodDescriptor(MethodDescriptor methodDescriptor){
return fromForeignMethod(methodDescriptor.getSlashedClassName(),methodDescriptor.getName(),methodDescriptor.getSignature(),methodDescriptor.isStatic());
}
| Create a MethodAnnotation from a MethodDescriptor. |
public long optLong(int index){
return this.optLong(index,0);
}
| Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if the value is not a number and cannot be converted to a number. |
public static Tiling singleTile(String name){
Tiling ret=new Tiling(1,1);
ret.setAt(0,0,name);
return ret;
}
| Convenience factory method for tests |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:29:10.765 -0500",hash_original_method="1E17DF4D2E642F9316AB5D83170D1374",hash_generated_method="781E6B54E01322E06173924A59BC3BEB") static public MotionEvent obtain(long downTime,long eventTime,int action,float x,float y,float pressure,float size,int metaState,float xPrecision,float yPrecision,int deviceId,int edgeFlags){
MotionEvent ev=obtain();
synchronized (gSharedTempLock) {
ensureSharedTempPointerCapacity(1);
final PointerProperties[] pp=gSharedTempPointerProperties;
pp[0].clear();
pp[0].id=0;
final PointerCoords pc[]=gSharedTempPointerCoords;
pc[0].clear();
pc[0].x=x;
pc[0].y=y;
pc[0].pressure=pressure;
pc[0].size=size;
ev.mNativePtr=nativeInitialize(ev.mNativePtr,deviceId,InputDevice.SOURCE_UNKNOWN,action,0,edgeFlags,metaState,0,0,0,xPrecision,yPrecision,downTime * NS_PER_MS,eventTime * NS_PER_MS,1,pp,pc);
return ev;
}
}
| Create a new MotionEvent, filling in all of the basic values that define the motion. |
public int hash(char[] buffer,int offset,int length){
int code=0;
for (int i=0; i < length; i++) {
code=code * 37 + buffer[offset + i];
}
return code & 0x7FFFFFF;
}
| Returns a hashcode value for the specified symbol information. The value returned by this method must be identical to the value returned by the <code>hash(String)</code> method when called with the string object created from the symbol information. |
public boolean isShowGridX(){
return mShowGridX;
}
| Returns if the X axis grid should be visible. |
public WebSocket flush(){
synchronized (mStateManager) {
WebSocketState state=mStateManager.getState();
if (state != OPEN && state != CLOSING) {
return this;
}
}
WritingThread wt=mWritingThread;
if (wt != null) {
wt.queueFlush();
}
return this;
}
| Flush frames to the server. Flush is performed asynchronously. |
@Override public void inc(ScoreMap<E> map){
if (map == null) return;
for ( E entry : map) {
int count=map.get(entry);
if (count > 0) this.inc(entry,count);
}
}
| apply all E/int mappings from an external ScoreMap to this ScoreMap |
public ByteVector putLong(final long l){
int length=this.length;
if (length + 8 > data.length) {
enlarge(8);
}
byte[] data=this.data;
int i=(int)(l >>> 32);
data[length++]=(byte)(i >>> 24);
data[length++]=(byte)(i >>> 16);
data[length++]=(byte)(i >>> 8);
data[length++]=(byte)i;
i=(int)l;
data[length++]=(byte)(i >>> 24);
data[length++]=(byte)(i >>> 16);
data[length++]=(byte)(i >>> 8);
data[length++]=(byte)i;
this.length=length;
return this;
}
| Puts a long into this byte vector. The byte vector is automatically enlarged if necessary. |
private UIComponent newInstance(TreeNode n) throws FacesException {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST,"FaceletFullStateManagementStrategy.newInstance",n.componentType);
}
try {
Class<?> t=((classMap != null) ? classMap.get(n.componentType) : null);
if (t == null) {
t=Util.loadClass(n.componentType,n);
if (t != null && classMap != null) {
classMap.put(n.componentType,t);
}
else {
if (!isDevelopmentMode) {
throw new NullPointerException();
}
}
}
assert (t != null);
UIComponent c=(UIComponent)t.newInstance();
c.setId(n.id);
return c;
}
catch ( ClassNotFoundException|NullPointerException|InstantiationException|IllegalAccessException e) {
throw new FacesException(e);
}
}
| Create a new component instance. |
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 final void testValidateSucceeds(){
IPv4AddressValidator iPv4AddressValidator=new IPv4AddressValidator("foo");
assertTrue(iPv4AddressValidator.validate(""));
assertTrue(iPv4AddressValidator.validate("1.1.1.1"));
assertTrue(iPv4AddressValidator.validate("255.255.255.255"));
assertTrue(iPv4AddressValidator.validate("192.168.1.1"));
assertTrue(iPv4AddressValidator.validate("10.10.1.1"));
assertTrue(iPv4AddressValidator.validate("132.254.111.10"));
assertTrue(iPv4AddressValidator.validate("26.10.2.10"));
assertTrue(iPv4AddressValidator.validate("127.0.0.1"));
}
| Tests the functionality of the validate-method, if it succeeds. |
public boolean isEmpty(){
return warnings.isEmpty();
}
| Determines whether there are any validation warnings. |
public static String escape(String s){
return JSONValue.escape(s);
}
| Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). It's the same as JSONValue.escape() only for compatibility here. |
public Sound(File file,SoundType type) throws IOException {
super(file,type);
}
| Creates a sound property. |
private XPathFactory loadFromServicesFile(String uri,String resourceName,InputStream in){
if (debug) debugPrintln("Reading " + resourceName);
BufferedReader rd;
try {
rd=new BufferedReader(new InputStreamReader(in,"UTF-8"),DEFAULT_LINE_LENGTH);
}
catch ( java.io.UnsupportedEncodingException e) {
rd=new BufferedReader(new InputStreamReader(in),DEFAULT_LINE_LENGTH);
}
String factoryClassName;
XPathFactory resultFactory=null;
while (true) {
try {
factoryClassName=rd.readLine();
}
catch ( IOException x) {
break;
}
if (factoryClassName != null) {
int hashIndex=factoryClassName.indexOf('#');
if (hashIndex != -1) {
factoryClassName=factoryClassName.substring(0,hashIndex);
}
factoryClassName=factoryClassName.trim();
if (factoryClassName.length() == 0) {
continue;
}
try {
XPathFactory foundFactory=createInstance(factoryClassName);
if (foundFactory.isObjectModelSupported(uri)) {
resultFactory=foundFactory;
break;
}
}
catch ( Exception ignored) {
}
}
else {
break;
}
}
IoUtils.closeQuietly(rd);
return resultFactory;
}
| Searches for a XPathFactory for a given uri in a META-INF/services file. |
private boolean hasAccess(StorageOSUser storageOSUser,StringSetMap acls){
if (acls == null || acls.isEmpty()) {
log.debug("acls is empty, pass");
return true;
}
List<ACLEntry> aclEntries=_permissionsHelper.convertToACLEntries(acls);
String username=storageOSUser.getName();
for ( ACLEntry entry : aclEntries) {
if (entry.getSubjectId() != null && entry.getSubjectId().equalsIgnoreCase(username)) {
log.debug("has acls contain subjectId for current user: " + username);
return true;
}
else if (entry.getGroup() != null) {
for ( String group : storageOSUser.getGroups()) {
if (group.equalsIgnoreCase(entry.getGroup())) {
log.debug("has acls contain group for current user: " + entry.getGroup());
return true;
}
}
}
else {
continue;
}
}
log.debug("has acls, but current user is not in them: " + username);
return false;
}
| check if specified acls permission user to access |
public boolean isReplaceHtmlLinefeeds(){
return replaceHtmlLinefeeds;
}
| Returns replaceHtmlLinefeeds |
@LargeTest public void testThumbnailWithCorruptedVideoPart() throws Exception {
final String videoItemFilename=INPUT_FILE_PATH + "corrupted_H264_BP_640x480_12.5fps_256kbps_AACLC_16khz_24kbps_s_0_26.mp4";
final int renderingMode=MediaItem.RENDERING_MODE_BLACK_BORDER;
boolean flagForException=false;
try {
final MediaVideoItem mediaVideoItem=mVideoEditorHelper.createMediaItem(mVideoEditor,"m1",videoItemFilename,renderingMode);
final int outWidth=mediaVideoItem.getWidth();
final int outHeight=mediaVideoItem.getHeight() * 2;
final Bitmap thumbNailBmp=mediaVideoItem.getThumbnail(outWidth,outHeight,mediaVideoItem.getDuration() / 2);
}
catch ( IllegalArgumentException e) {
flagForException=true;
}
assertTrue("Corrupted File cannot be read",flagForException);
}
| To test ThumbnailList for file which has video part corrupted |
public String prepareIt(){
log.info(toString());
m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_PREPARE);
if (m_processMsg != null) return DocAction.STATUS_Invalid;
MDocType dt=MDocType.get(getCtx(),getC_DocType_ID());
if (!MPeriod.isOpen(getCtx(),getDateOrdered(),dt.getDocBaseType(),getAD_Org_ID())) {
m_processMsg="@PeriodClosed@";
return DocAction.STATUS_Invalid;
}
MDDOrderLine[] lines=getLines(true,"M_Product_ID");
if (lines.length == 0) {
m_processMsg="@NoLines@";
return DocAction.STATUS_Invalid;
}
if (getDeliveryRule() != null && getDeliveryRule().equals(MDDOrder.DELIVERYRULE_CompleteOrder)) {
for (int i=0; i < lines.length; i++) {
MDDOrderLine line=lines[i];
MProduct product=line.getProduct();
if (product != null && product.isExcludeAutoDelivery()) {
m_processMsg="@M_Product_ID@ " + product.getValue() + " @IsExcludeAutoDelivery@";
return DocAction.STATUS_Invalid;
}
}
}
String mandatoryType="='Y'";
String sql="SELECT COUNT(*) " + "FROM DD_OrderLine ol" + " INNER JOIN M_Product p ON (ol.M_Product_ID=p.M_Product_ID)"+ " INNER JOIN M_AttributeSet pas ON (p.M_AttributeSet_ID=pas.M_AttributeSet_ID) "+ "WHERE pas.MandatoryType" + mandatoryType + " AND ol.M_AttributeSetInstance_ID IS NULL"+ " AND ol.DD_Order_ID=?";
int no=DB.getSQLValue(get_TrxName(),sql,getDD_Order_ID());
if (no != 0) {
m_processMsg="@LinesWithoutProductAttribute@ (" + no + ")";
return DocAction.STATUS_Invalid;
}
reserveStock(lines);
m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_PREPARE);
if (m_processMsg != null) return DocAction.STATUS_Invalid;
m_justPrepared=true;
return DocAction.STATUS_InProgress;
}
| Prepare Document |
protected JBZipEntry(String name,JBZipFile file){
this.name=name;
myFile=file;
}
| Creates a new zip entry with the specified name. |
private void bol(){
column=0;
collectingIndent=(maxIndent != 0);
indent=0;
}
| Indicates that output is at the beginning of a line. |
public void addImplicit(ObjectType type){
add(type,false);
}
| Add an implicit exception. |
public Slf4jLogger(){
impl=LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
}
| Creates new logger. |
public static void directOutput(String filename,boolean append,boolean alsoToOutStream){
try {
directOutput(new FileOutputStream(filename,append),alsoToOutStream);
}
catch ( IOException ioe) {
notifyOut=true;
out=System.out;
error("Debug: can't set up <" + filename + "> for log file! \n"+ ioe);
return;
}
}
| Provide a file to log output. This can be in conjunction with the output stream, or instead of it. |
protected boolean haveSharedCellsRaw(ObjectMatrix1D other){
if (other instanceof SelectedSparseObjectMatrix1D) {
SelectedSparseObjectMatrix1D otherMatrix=(SelectedSparseObjectMatrix1D)other;
return this.elements == otherMatrix.elements;
}
else if (other instanceof SparseObjectMatrix1D) {
SparseObjectMatrix1D otherMatrix=(SparseObjectMatrix1D)other;
return this.elements == otherMatrix.elements;
}
return false;
}
| Returns <tt>true</tt> if both matrices share at least one identical cell. |
@Override public void flush() throws IOException {
super.flush();
}
| Flushes this stream to ensure all pending data is sent out to the target stream. This implementation then also flushes the target stream. |
public Object jjtAccept(SyntaxTreeBuilderVisitor visitor,Object data) throws VisitorException {
return visitor.visit(this,data);
}
| Accept the visitor. |
public static String addVisibleNewLineChars(String string){
return string.replaceAll("\r",CARRIAGE_RETURN_SYMBOL + "\r").replaceAll("\n",LINE_FEED_SYMBOL + "\n");
}
| Returns a string with visible new line characters, shown along the invisible ones. |
private void readCode(final MethodVisitor mv,final Context context,int u){
byte[] b=this.b;
char[] c=context.buffer;
int maxStack=readUnsignedShort(u);
int maxLocals=readUnsignedShort(u + 2);
int codeLength=readInt(u + 4);
u+=8;
int codeStart=u;
int codeEnd=u + codeLength;
Label[] labels=context.labels=new Label[codeLength + 2];
readLabel(codeLength + 1,labels);
while (u < codeEnd) {
int offset=u - codeStart;
int opcode=b[u] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
case ClassWriter.IMPLVAR_INSN:
u+=1;
break;
case ClassWriter.LABEL_INSN:
readLabel(offset + readShort(u + 1),labels);
u+=3;
break;
case ClassWriter.LABELW_INSN:
readLabel(offset + readInt(u + 1),labels);
u+=5;
break;
case ClassWriter.WIDE_INSN:
opcode=b[u + 1] & 0xFF;
if (opcode == Opcodes.IINC) {
u+=6;
}
else {
u+=4;
}
break;
case ClassWriter.TABL_INSN:
u=u + 4 - (offset & 3);
readLabel(offset + readInt(u),labels);
for (int i=readInt(u + 8) - readInt(u + 4) + 1; i > 0; --i) {
readLabel(offset + readInt(u + 12),labels);
u+=4;
}
u+=12;
break;
case ClassWriter.LOOK_INSN:
u=u + 4 - (offset & 3);
readLabel(offset + readInt(u),labels);
for (int i=readInt(u + 4); i > 0; --i) {
readLabel(offset + readInt(u + 12),labels);
u+=8;
}
u+=8;
break;
case ClassWriter.VAR_INSN:
case ClassWriter.SBYTE_INSN:
case ClassWriter.LDC_INSN:
u+=2;
break;
case ClassWriter.SHORT_INSN:
case ClassWriter.LDCW_INSN:
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.TYPE_INSN:
case ClassWriter.IINC_INSN:
u+=3;
break;
case ClassWriter.ITFMETH_INSN:
case ClassWriter.INDYMETH_INSN:
u+=5;
break;
default :
u+=4;
break;
}
}
for (int i=readUnsignedShort(u); i > 0; --i) {
Label start=readLabel(readUnsignedShort(u + 2),labels);
Label end=readLabel(readUnsignedShort(u + 4),labels);
Label handler=readLabel(readUnsignedShort(u + 6),labels);
String type=readUTF8(items[readUnsignedShort(u + 8)],c);
mv.visitTryCatchBlock(start,end,handler,type);
u+=8;
}
u+=2;
int[] tanns=null;
int[] itanns=null;
int tann=0;
int itann=0;
int ntoff=-1;
int nitoff=-1;
int varTable=0;
int varTypeTable=0;
boolean zip=true;
boolean unzip=(context.flags & EXPAND_FRAMES) != 0;
int stackMap=0;
int stackMapSize=0;
int frameCount=0;
Context frame=null;
Attribute attributes=null;
for (int i=readUnsignedShort(u); i > 0; --i) {
String attrName=readUTF8(u + 2,c);
if ("LocalVariableTable".equals(attrName)) {
if ((context.flags & SKIP_DEBUG) == 0) {
varTable=u + 8;
for (int j=readUnsignedShort(u + 8), v=u; j > 0; --j) {
int label=readUnsignedShort(v + 10);
if (labels[label] == null) {
readLabel(label,labels).status|=Label.DEBUG;
}
label+=readUnsignedShort(v + 12);
if (labels[label] == null) {
readLabel(label,labels).status|=Label.DEBUG;
}
v+=10;
}
}
}
else if ("LocalVariableTypeTable".equals(attrName)) {
varTypeTable=u + 8;
}
else if ("LineNumberTable".equals(attrName)) {
if ((context.flags & SKIP_DEBUG) == 0) {
for (int j=readUnsignedShort(u + 8), v=u; j > 0; --j) {
int label=readUnsignedShort(v + 10);
if (labels[label] == null) {
readLabel(label,labels).status|=Label.DEBUG;
}
Label l=labels[label];
while (l.line > 0) {
if (l.next == null) {
l.next=new Label();
}
l=l.next;
}
l.line=readUnsignedShort(v + 12);
v+=4;
}
}
}
else if (ANNOTATIONS && "RuntimeVisibleTypeAnnotations".equals(attrName)) {
tanns=readTypeAnnotations(mv,context,u + 8,true);
ntoff=tanns.length == 0 || readByte(tanns[0]) < 0x43 ? -1 : readUnsignedShort(tanns[0] + 1);
}
else if (ANNOTATIONS && "RuntimeInvisibleTypeAnnotations".equals(attrName)) {
itanns=readTypeAnnotations(mv,context,u + 8,false);
nitoff=itanns.length == 0 || readByte(itanns[0]) < 0x43 ? -1 : readUnsignedShort(itanns[0] + 1);
}
else if (FRAMES && "StackMapTable".equals(attrName)) {
if ((context.flags & SKIP_FRAMES) == 0) {
stackMap=u + 10;
stackMapSize=readInt(u + 4);
frameCount=readUnsignedShort(u + 8);
}
}
else if (FRAMES && "StackMap".equals(attrName)) {
if ((context.flags & SKIP_FRAMES) == 0) {
zip=false;
stackMap=u + 10;
stackMapSize=readInt(u + 4);
frameCount=readUnsignedShort(u + 8);
}
}
else {
for (int j=0; j < context.attrs.length; ++j) {
if (context.attrs[j].type.equals(attrName)) {
Attribute attr=context.attrs[j].read(this,u + 8,readInt(u + 4),c,codeStart - 8,labels);
if (attr != null) {
attr.next=attributes;
attributes=attr;
}
}
}
}
u+=6 + readInt(u + 4);
}
u+=2;
if (FRAMES && stackMap != 0) {
frame=context;
frame.offset=-1;
frame.mode=0;
frame.localCount=0;
frame.localDiff=0;
frame.stackCount=0;
frame.local=new Object[maxLocals];
frame.stack=new Object[maxStack];
if (unzip) {
getImplicitFrame(context);
}
for (int i=stackMap; i < stackMap + stackMapSize - 2; ++i) {
if (b[i] == 8) {
int v=readUnsignedShort(i + 1);
if (v >= 0 && v < codeLength) {
if ((b[codeStart + v] & 0xFF) == Opcodes.NEW) {
readLabel(v,labels);
}
}
}
}
}
u=codeStart;
while (u < codeEnd) {
int offset=u - codeStart;
Label l=labels[offset];
if (l != null) {
Label next=l.next;
l.next=null;
mv.visitLabel(l);
if ((context.flags & SKIP_DEBUG) == 0 && l.line > 0) {
mv.visitLineNumber(l.line,l);
while (next != null) {
mv.visitLineNumber(next.line,l);
next=next.next;
}
}
}
while (FRAMES && frame != null && (frame.offset == offset || frame.offset == -1)) {
if (frame.offset != -1) {
if (!zip || unzip) {
mv.visitFrame(Opcodes.F_NEW,frame.localCount,frame.local,frame.stackCount,frame.stack);
}
else {
mv.visitFrame(frame.mode,frame.localDiff,frame.local,frame.stackCount,frame.stack);
}
}
if (frameCount > 0) {
stackMap=readFrame(stackMap,zip,unzip,frame);
--frameCount;
}
else {
frame=null;
}
}
int opcode=b[u] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
mv.visitInsn(opcode);
u+=1;
break;
case ClassWriter.IMPLVAR_INSN:
if (opcode > Opcodes.ISTORE) {
opcode-=59;
mv.visitVarInsn(Opcodes.ISTORE + (opcode >> 2),opcode & 0x3);
}
else {
opcode-=26;
mv.visitVarInsn(Opcodes.ILOAD + (opcode >> 2),opcode & 0x3);
}
u+=1;
break;
case ClassWriter.LABEL_INSN:
mv.visitJumpInsn(opcode,labels[offset + readShort(u + 1)]);
u+=3;
break;
case ClassWriter.LABELW_INSN:
mv.visitJumpInsn(opcode - 33,labels[offset + readInt(u + 1)]);
u+=5;
break;
case ClassWriter.WIDE_INSN:
opcode=b[u + 1] & 0xFF;
if (opcode == Opcodes.IINC) {
mv.visitIincInsn(readUnsignedShort(u + 2),readShort(u + 4));
u+=6;
}
else {
mv.visitVarInsn(opcode,readUnsignedShort(u + 2));
u+=4;
}
break;
case ClassWriter.TABL_INSN:
{
u=u + 4 - (offset & 3);
int label=offset + readInt(u);
int min=readInt(u + 4);
int max=readInt(u + 8);
Label[] table=new Label[max - min + 1];
u+=12;
for (int i=0; i < table.length; ++i) {
table[i]=labels[offset + readInt(u)];
u+=4;
}
mv.visitTableSwitchInsn(min,max,labels[label],table);
break;
}
case ClassWriter.LOOK_INSN:
{
u=u + 4 - (offset & 3);
int label=offset + readInt(u);
int len=readInt(u + 4);
int[] keys=new int[len];
Label[] values=new Label[len];
u+=8;
for (int i=0; i < len; ++i) {
keys[i]=readInt(u);
values[i]=labels[offset + readInt(u + 4)];
u+=8;
}
mv.visitLookupSwitchInsn(labels[label],keys,values);
break;
}
case ClassWriter.VAR_INSN:
mv.visitVarInsn(opcode,b[u + 1] & 0xFF);
u+=2;
break;
case ClassWriter.SBYTE_INSN:
mv.visitIntInsn(opcode,b[u + 1]);
u+=2;
break;
case ClassWriter.SHORT_INSN:
mv.visitIntInsn(opcode,readShort(u + 1));
u+=3;
break;
case ClassWriter.LDC_INSN:
mv.visitLdcInsn(readConst(b[u + 1] & 0xFF,c));
u+=2;
break;
case ClassWriter.LDCW_INSN:
mv.visitLdcInsn(readConst(readUnsignedShort(u + 1),c));
u+=3;
break;
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.ITFMETH_INSN:
{
int cpIndex=items[readUnsignedShort(u + 1)];
boolean itf=b[cpIndex - 1] == ClassWriter.IMETH;
String iowner=readClass(cpIndex,c);
cpIndex=items[readUnsignedShort(cpIndex + 2)];
String iname=readUTF8(cpIndex,c);
String idesc=readUTF8(cpIndex + 2,c);
if (opcode < Opcodes.INVOKEVIRTUAL) {
mv.visitFieldInsn(opcode,iowner,iname,idesc);
}
else {
mv.visitMethodInsn(opcode,iowner,iname,idesc,itf);
}
if (opcode == Opcodes.INVOKEINTERFACE) {
u+=5;
}
else {
u+=3;
}
break;
}
case ClassWriter.INDYMETH_INSN:
{
int cpIndex=items[readUnsignedShort(u + 1)];
int bsmIndex=context.bootstrapMethods[readUnsignedShort(cpIndex)];
Handle bsm=(Handle)readConst(readUnsignedShort(bsmIndex),c);
int bsmArgCount=readUnsignedShort(bsmIndex + 2);
Object[] bsmArgs=new Object[bsmArgCount];
bsmIndex+=4;
for (int i=0; i < bsmArgCount; i++) {
bsmArgs[i]=readConst(readUnsignedShort(bsmIndex),c);
bsmIndex+=2;
}
cpIndex=items[readUnsignedShort(cpIndex + 2)];
String iname=readUTF8(cpIndex,c);
String idesc=readUTF8(cpIndex + 2,c);
mv.visitInvokeDynamicInsn(iname,idesc,bsm,bsmArgs);
u+=5;
break;
}
case ClassWriter.TYPE_INSN:
mv.visitTypeInsn(opcode,readClass(u + 1,c));
u+=3;
break;
case ClassWriter.IINC_INSN:
mv.visitIincInsn(b[u + 1] & 0xFF,b[u + 2]);
u+=3;
break;
default :
mv.visitMultiANewArrayInsn(readClass(u + 1,c),b[u + 3] & 0xFF);
u+=4;
break;
}
while (tanns != null && tann < tanns.length && ntoff <= offset) {
if (ntoff == offset) {
int v=readAnnotationTarget(context,tanns[tann]);
readAnnotationValues(v + 2,c,true,mv.visitInsnAnnotation(context.typeRef,context.typePath,readUTF8(v,c),true));
}
ntoff=++tann >= tanns.length || readByte(tanns[tann]) < 0x43 ? -1 : readUnsignedShort(tanns[tann] + 1);
}
while (itanns != null && itann < itanns.length && nitoff <= offset) {
if (nitoff == offset) {
int v=readAnnotationTarget(context,itanns[itann]);
readAnnotationValues(v + 2,c,true,mv.visitInsnAnnotation(context.typeRef,context.typePath,readUTF8(v,c),false));
}
nitoff=++itann >= itanns.length || readByte(itanns[itann]) < 0x43 ? -1 : readUnsignedShort(itanns[itann] + 1);
}
}
if (labels[codeLength] != null) {
mv.visitLabel(labels[codeLength]);
}
if ((context.flags & SKIP_DEBUG) == 0 && varTable != 0) {
int[] typeTable=null;
if (varTypeTable != 0) {
u=varTypeTable + 2;
typeTable=new int[readUnsignedShort(varTypeTable) * 3];
for (int i=typeTable.length; i > 0; ) {
typeTable[--i]=u + 6;
typeTable[--i]=readUnsignedShort(u + 8);
typeTable[--i]=readUnsignedShort(u);
u+=10;
}
}
u=varTable + 2;
for (int i=readUnsignedShort(varTable); i > 0; --i) {
int start=readUnsignedShort(u);
int length=readUnsignedShort(u + 2);
int index=readUnsignedShort(u + 8);
String vsignature=null;
if (typeTable != null) {
for (int j=0; j < typeTable.length; j+=3) {
if (typeTable[j] == start && typeTable[j + 1] == index) {
vsignature=readUTF8(typeTable[j + 2],c);
break;
}
}
}
mv.visitLocalVariable(readUTF8(u + 4,c),readUTF8(u + 6,c),vsignature,labels[start],labels[start + length],index);
u+=10;
}
}
if (tanns != null) {
for (int i=0; i < tanns.length; ++i) {
if ((readByte(tanns[i]) >> 1) == (0x40 >> 1)) {
int v=readAnnotationTarget(context,tanns[i]);
v=readAnnotationValues(v + 2,c,true,mv.visitLocalVariableAnnotation(context.typeRef,context.typePath,context.start,context.end,context.index,readUTF8(v,c),true));
}
}
}
if (itanns != null) {
for (int i=0; i < itanns.length; ++i) {
if ((readByte(itanns[i]) >> 1) == (0x40 >> 1)) {
int v=readAnnotationTarget(context,itanns[i]);
v=readAnnotationValues(v + 2,c,true,mv.visitLocalVariableAnnotation(context.typeRef,context.typePath,context.start,context.end,context.index,readUTF8(v,c),false));
}
}
}
while (attributes != null) {
Attribute attr=attributes.next;
attributes.next=null;
mv.visitAttribute(attributes);
attributes=attr;
}
mv.visitMaxs(maxStack,maxLocals);
}
| Reads the bytecode of a method and makes the given visitor visit it. |
public void testTwoStatements() throws IOException {
final InputStream stream=this.getStream(R.raw.two_statements);
List<String> commands=SqlParser.parse(stream);
assertEquals(2,commands.size());
assertEquals(sql1,commands.get(0));
assertEquals(sql2,commands.get(1));
}
| Should be able to parse a script with two multi-line statments, even if the last statement is not terminated by a semicolon. |
public void scrollTo(WebView view,int x,int y){
view.getEngine().executeScript("window.scrollTo(" + x + ", "+ y+ ")");
}
| Scrolls to the specified position. |
@Override public Request<Workspace> create(Workspace workspaceReference){
checkNotNull(workspaceReference);
final Invocation request=getWebTarget().request().accept(APPLICATION_JSON).buildPost(json(workspaceReference));
return new SimpleRequest<Workspace>(request,DefaultWorkspace.class,getAuthenticationManager());
}
| Creates the given workspace. |
private static URL fixEmbeddedParams(URL base,String target) throws MalformedURLException {
if (target.indexOf(';') >= 0 || base.toString().indexOf(';') == -1) {
return new URL(base,target);
}
String baseURL=base.toString();
int startParams=baseURL.indexOf(';');
String params=baseURL.substring(startParams);
int startQS=target.indexOf('?');
if (startQS >= 0) {
target=target.substring(0,startQS) + params + target.substring(startQS);
}
else {
target+=params;
}
return new URL(base,target);
}
| Handles cases where the url param information is encoded into the base url as opposed to the target. <p> If the taget contains params (i.e. ';xxxx') information then the target params information is assumed to be correct and any base params information is ignored. If the base contains params information but the tareget does not, then the params information is moved to the target allowing it to be correctly determined by the java.net.URL class. |
private byte[] lookupClassData(String className) throws ClassNotFoundException {
byte[] data=null;
for ( String path : pathItems) {
String fileName=className.replace('.','/') + ".class";
if (isJar(path)) data=loadJarData(path,fileName);
else data=loadFileData(path,fileName);
if (data != null) return data;
}
throw new ClassNotFoundException();
}
| Search for a class file, and return class data if found. |
public void dropTable(Database database,Table table,StringBuilder ddl){
for (int idx=database.getTableCount() - 1; idx >= 0; idx--) {
Table otherTable=database.getTable(idx);
ForeignKey[] fks=otherTable.getForeignKeys();
for (int fkIdx=0; (fks != null) && (fkIdx < fks.length); fkIdx++) {
if (fks[fkIdx].getForeignTable().equals(table)) {
writeExternalForeignKeyDropStmt(otherTable,fks[fkIdx],ddl);
}
}
}
dropExternalForeignKeys(table,ddl);
writeTableComment(table,ddl);
dropTable(table,ddl,false,false);
}
| Outputs the DDL required to drop the given table. This method also drops foreign keys to the table. |
public Integer limit(){
return limit;
}
| Gets the limit. |
public void undo(){
EditItem edit=mEditHistory.getPrevious();
if (edit == null) {
return;
}
Editable text=mEditText.getEditableText();
int start=edit.mmStart;
int end=start + (edit.mmAfter != null ? edit.mmAfter.length() : 0);
mIsUndoOrRedo=true;
text.replace(start,end,edit.mmBefore);
mIsUndoOrRedo=false;
for ( Object o : text.getSpans(0,text.length(),UnderlineSpan.class)) {
text.removeSpan(o);
}
Selection.setSelection(text,edit.mmBefore == null ? start : (start + edit.mmBefore.length()));
}
| Perform undo. |
public void moveToPrevious(){
checkWidget();
final int index=this.selection - 1;
if (index < 0) {
return;
}
changeSelectionTo(index);
}
| Move selection to the previous control |
public static ContigField parseContigLine(String line){
return new ContigField(line);
}
| Convert <code>contig</code> line into <code>ContigField</code> object |
protected String parseGameEvents(String inboundMessage){
containedStyle12=false;
if (inboundMessage.length() > MAX_GAME_MESSAGE) {
return inboundMessage;
}
else {
if (LOG.isDebugEnabled()) {
LOG.debug("Raw message in " + connector.getContext().getShortName() + ": "+ inboundMessage);
}
boolean trimAtEnd=false;
StringBuilder result=new StringBuilder(inboundMessage.length());
RaptorStringTokenizer tok=new RaptorStringTokenizer(inboundMessage,"\n");
while (tok.hasMoreTokens()) {
String line=tok.nextToken();
if (LOG.isDebugEnabled()) {
LOG.debug("Processing raw line " + connector.getContext().getShortName() + ": "+ line);
}
G1Message g1Message=g1Parser.parse(line);
if (g1Message != null) {
process(g1Message,connector.getGameService());
trimAtEnd=true;
continue;
}
Style12Message style12Message=style12Parser.parse(line);
if (style12Message != null) {
process(style12Message,connector.getGameService(),inboundMessage);
containedStyle12=true;
continue;
}
B1Message b1Message=b1Parser.parse(line);
if (b1Message != null) {
process(b1Message,connector.getGameService());
continue;
}
GameEndMessage gameEndMessage=gameEndParser.parse(line);
if (gameEndMessage != null) {
process(gameEndMessage,connector.getGameService());
result.append(line).append(tok.hasMoreTokens() ? "\n" : "");
trimAtEnd=true;
continue;
}
IllegalMoveMessage illegalMoveMessage=illegalMoveParser.parse(line);
if (illegalMoveMessage != null) {
process(illegalMoveMessage,connector.getGameService());
result.append(line).append(tok.hasMoreTokens() ? "\n" : "");
continue;
}
RemovingObsGameMessage removingObsGameMessage=removingObsGameParser.parse(line);
if (removingObsGameMessage != null) {
process(removingObsGameMessage,inboundMessage,connector.getGameService());
result.append(line).append(tok.hasMoreTokens() ? "\n" : "");
continue;
}
if (processPendInfo(line)) {
trimAtEnd=true;
continue;
}
NoLongerExaminingGameMessage noLongerExaminingGameMessage=noLongerExaminingParser.parse(line);
if (noLongerExaminingGameMessage != null) {
process(noLongerExaminingGameMessage,connector.getGameService());
result.append(line).append(tok.hasMoreTokens() ? "\n" : "");
continue;
}
takebackParser.parse(line);
ChatEvent followingEvent=followingParser.parse(line);
if (followingEvent != null && followingEvent.getType() == ChatType.FOLLOWING) {
connector.setUserFollowing(followingEvent.getSource());
}
if (line.startsWith("Entering setup mode.") && !inboundMessage.contains("<12>")) {
processExaminedGameBecameSetup();
}
else if (line.startsWith("Game ") && line.endsWith("enters setup mode.") && !inboundMessage.contains("<12>")) {
processExaminedGameBecameSetup();
}
result.append(line).append(tok.hasMoreTokens() ? "\n" : "");
}
return trimAtEnd ? result.toString().trim() : result.toString();
}
}
| Parses and removes all of the game events from inboundEvent. Adjusts the games in service. Returns a String with the game events removed. |
private double[] averageStackValues(double[] stack1,double[] stack2){
double[] result=new double[2];
result[0]=(stack1[0] + stack2[0]) / 2.0;
result[1]=(stack1[1] + stack2[1]) / 2.0;
return result;
}
| Returns a pair of "stack" values calculated as the mean of the two specified stack value pairs. |
@Override public void receive(Event[] events){
String policyName=context.getPolicyDefinition().getName();
CompositePolicyHandler handler=((PolicyGroupEvaluatorImpl)context.getPolicyEvaluator()).getPolicyHandler(policyName);
if (LOG.isDebugEnabled()) {
LOG.debug("Generated {} alerts from policy '{}' in {}, index of definiton {} ",events.length,policyName,context.getPolicyEvaluatorId(),currentIndex);
}
for ( Event e : events) {
AlertStreamEvent event=new AlertStreamEvent();
event.setTimestamp(e.getTimestamp());
event.setData(e.getData());
event.setStreamId(outputStream);
event.setPolicyId(context.getPolicyDefinition().getName());
if (this.context.getPolicyEvaluator() != null) {
event.setCreatedBy(context.getPolicyEvaluator().getName());
}
event.setCreatedTime(System.currentTimeMillis());
event.setSchema(definition);
if (LOG.isDebugEnabled()) {
LOG.debug("Generate new alert event: {}",event);
}
try {
if (handler == null) {
if (LOG.isDebugEnabled()) {
LOG.debug(" handler not found when callback received event, directly emit. policy removed? ");
}
collector.emit(event);
}
else {
handler.send(event,currentIndex + 1);
}
}
catch ( Exception ex) {
LOG.error(String.format("send event %s to index %d failed with exception. ",event,currentIndex),ex);
}
}
context.getPolicyCounter().scope(String.format("%s.%s",this.context.getPolicyDefinition().getName(),"alert_count")).incrBy(events.length);
}
| Possibly more than one event will be triggered for alerting. |
public void memoryReallocate(long memPtr,int cap){
enter();
try {
PlatformCallbackUtils.memoryReallocate(envPtr,memPtr,cap);
}
finally {
leave();
}
}
| Re-allocate external memory chunk. |
@SuppressWarnings("rawtypes") public static Task createDummy(){
return new Task(TaskTypes.DUMMY);
}
| Creates a dummy task without data. |
protected int entityIndex(Entity entity){
return Arrays.binarySearch(entities,entity);
}
| Check whether the device contains the specified entity |
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. |
public static String makeValidFileName(String fileName){
return fileName.replaceAll("[^a-zA-Z0-9_\\-\\.]","-");
}
| Replace all invalid file characters with valid ones. example: himom(*).txt becomes himom---.txt Note some characters that will be replaced wouldn't really be invalid (' ' for example) but a conservative approach is taken. |
public void writeTo(ChannelBuffer data){
super.writeTo(data);
data.writeByte(tableIndex);
data.writeByte(pad1);
data.writeByte(pad2);
data.writeByte(pad3);
data.writeInt(netMask);
}
| Write the vendor data to the channel buffer |
public static Object[] toArray(List<?> list){
Iterator<?> it=list.iterator();
Class clazz=null;
while (it.hasNext()) {
Object v=it.next();
if (v == null) continue;
if (clazz == null) clazz=v.getClass();
else if (clazz != v.getClass()) return list.toArray();
}
if (clazz == Object.class || clazz == null) return list.toArray();
Object arr=java.lang.reflect.Array.newInstance(clazz,list.size());
return list.toArray((Object[])arr);
}
| creates a native array out of the input list, if all values are from the same type, this type is used for the array, otherwise object |
public int size(){
if (tail == null) {
return 1;
}
return 1 + tail.size();
}
| Retuns the size of this IntList |
private <N extends Oplet<P,P>>ExecutableVertex<N,P,P> newInternalVertex(N op,int nInputs,int nOutputs){
ExecutableVertex<N,P,P> vertex=graph().insert(op,nInputs,nOutputs);
for ( EtiaoConnector<P> connector : vertex.getConnectors()) {
connector.state=state;
}
return vertex;
}
| Create a new vertex for internal use (with shared connector state) |
public Bits(){
this(false);
}
| Construct an initially empty set. |
public DateMidnight minus(long duration){
return withDurationAdded(duration,-1);
}
| Returns a copy of this date with the specified duration taken away. <p> If the amount is zero or null, then <code>this</code> is returned. |
@Override public void run(){
while (!mDie) {
synchronized (mJobSync) {
if (hasJob()) {
final Runnable job=mJob;
try {
job.run();
}
catch ( final Throwable t) {
Diagnostic.error(ErrorType.SLIM_ERROR);
Diagnostic.userLog(t);
}
synchronized (mCompleteNotify) {
setJob(null);
mCompleteNotify.notifyAll();
}
}
}
synchronized (mSleepSync) {
try {
if (!hasJob() && !mDie) {
mSleepSync.wait(SLEEP_TIME);
}
}
catch ( final InterruptedException e) {
}
}
}
}
| Runs jobs in the job queue |
public static List<List<String>> chunkRelativePaths(List<String> files){
ArrayList<List<String>> rc=new ArrayList<List<String>>();
int start=0;
int size=0;
int i=0;
for (; i < files.size(); i++) {
String p=files.get(i);
if (size + p.length() > FILE_PATH_LIMIT) {
if (start == i) {
rc.add(files.subList(i,i + 1));
start=i + 1;
}
else {
rc.add(files.subList(start,i));
start=i;
}
size=0;
}
else {
size+=p.length();
}
}
if (start != files.size()) {
rc.add(files.subList(start,i));
}
return rc;
}
| Chunk paths on the command line |
public final void alignSwitch(){
if (VM.VerifyAssertions) {
VM._assert(opcode == JBC_tableswitch || opcode == JBC_lookupswitch);
}
int align=bcIndex & 3;
if (align != 0) bcIndex+=4 - align;
}
| Skips the padding of a switch instruction.<p> Used for tableswitch, lookupswitch |
public static _Fields findByName(String name){
return byName.get(name);
}
| Find the _Fields constant that matches name, or null if its not found. |
public static PGPPublicKey readPublicKey(InputStream instr) throws PGPException {
PGPPublicKeyRingCollection pgpPub;
try {
instr=org.bouncycastle.openpgp.PGPUtil.getDecoderStream(instr);
pgpPub=new PGPPublicKeyRingCollection(instr,new JcaKeyFingerprintCalculator());
}
catch ( IOException|PGPException ex) {
throw new PGPException("Failed to init public key ring",ex);
}
Iterator keyRingIter=pgpPub.getKeyRings();
while (keyRingIter.hasNext()) {
PGPPublicKeyRing keyRing=(PGPPublicKeyRing)keyRingIter.next();
Iterator keyIter=keyRing.getPublicKeys();
while (keyIter.hasNext()) {
PGPPublicKey key=(PGPPublicKey)keyIter.next();
if (key.isEncryptionKey()) {
return key;
}
}
}
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
| ***************************************** A simple routine that opens a key ring file and loads the first available key suitable for encryption. |
private void executeCreate(String[] args) throws IOException, MalformedURLException, ServiceException, DocumentListException {
if (args.length == 3) {
printDocumentEntry(documentList.createNew(args[2],args[1]));
}
else {
printMessage(COMMAND_HELP_CREATE);
}
}
| Executes the "create" command. |
public Value createClob(Reader x,long length){
if (x == null) {
return ValueNull.INSTANCE;
}
if (length <= 0) {
length=-1;
}
Value v=session.getDataHandler().getLobStorage().createClob(x,length);
session.addTemporaryLob(v);
return v;
}
| Create a Clob value from this reader. |
public void testStringUnion(){
List<BytesRef> strings=new ArrayList<>();
for (int i=RandomNumbers.randomIntBetween(random(),0,1000); --i >= 0; ) {
strings.add(new BytesRef(TestUtil.randomUnicodeString(random())));
}
Collections.sort(strings);
Automaton union=Automata.makeStringUnion(strings);
assertTrue(union.isDeterministic());
assertFalse(Operations.hasDeadStatesFromInitial(union));
Automaton naiveUnion=naiveUnion(strings);
assertTrue(naiveUnion.isDeterministic());
assertFalse(Operations.hasDeadStatesFromInitial(naiveUnion));
assertTrue(Operations.sameLanguage(union,naiveUnion));
}
| Test string union. |
public AutoDeskewTransform(){
this(true,defaultList);
}
| Creates a new AutoDeskew transform |
public boolean isContent(){
return state.equals(CONTENT);
}
| Check if content is shown |
public boolean isAccessibleChildSelected(int i){
if (i == 0) {
Object[] rootPath=new Object[1];
rootPath[0]=treeModel.getRoot();
if (rootPath[0] == null) return false;
TreePath childPath=new TreePath(rootPath);
return JTree.this.isPathSelected(childPath);
}
else {
return false;
}
}
| Returns true if the current child of this object is selected. |
private static void generateNewData(){
for (int i=0; i < categoryNames.length; i++) {
newList[i]=new int[10];
}
storeNewData();
if (newListCount[BMP][categoryNames.length - 1] != 1) {
System.err.println("This should not happen. Unicode data which belongs to an undefined category exists");
System.exit(1);
}
}
| Makes CategoryMap in newer format which is used by JDK 1.5.0. |
public T caseCoordinate_(Coordinate_ object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Coordinate </em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
private List<AnnotatedTypeMirror> arrayAllComponents(AnnotatedArrayType atype){
LinkedList<AnnotatedTypeMirror> arrays=new LinkedList<AnnotatedTypeMirror>();
AnnotatedTypeMirror type=atype;
while (type.getKind() == TypeKind.ARRAY) {
arrays.addFirst(type);
type=((AnnotatedArrayType)type).getComponentType();
}
arrays.add(type);
return arrays;
}
| List of all array component types. Example input: int[][] Example output: int, int[], int[][] |
private void processMenuKeyEvent(MenuKeyEvent e){
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
fireMenuKeyPressed(e);
break;
case KeyEvent.KEY_RELEASED:
fireMenuKeyReleased(e);
break;
case KeyEvent.KEY_TYPED:
fireMenuKeyTyped(e);
break;
default :
break;
}
}
| Handles a keystroke in a menu. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:30:01.362 -0500",hash_original_method="757FC08885175457E85C9AB1294F9204",hash_generated_method="60EC476456FAA597E0E3D6EF5D2BCBF4") public DrmInputStream(DrmRights rights){
isClosed=false;
offset=0;
b=new byte[1];
}
| Construct a DrmInputStream instance. |
static String add_escapes(String str){
StringBuffer retval=new StringBuffer();
char ch;
for (int i=0; i < str.length(); i++) {
switch (str.charAt(i)) {
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default :
if ((ch=str.charAt(i)) < 0x20 || ch > 0x7e) {
String s="0000" + Integer.toString(ch,16);
retval.append("\\u" + s.substring(s.length() - 4,s.length()));
}
else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
| Used to convert raw characters to their escaped version when these raw version cannot be used as part of an ASCII string literal. |
@SuppressWarnings("unchecked") public ManagedArray(final T[] array){
if (array == null) throw new IllegalArgumentException();
this.elementClass=(Class<? extends T>)array.getClass().getComponentType();
this.buf=array;
}
| Create a view wrapping the entire array. <p> Note: the caller's reference will be used until and unless the array is grown, at which point the caller's reference will be replaced by a larger array having the same data. |
public void actionPerformed(ActionEvent e){
if (e.getSource() == bImport) cmd_import();
else if (e.getSource() == bExport) cmd_export();
else if (e.getActionCommand().equals(ConfirmPanel.A_OK)) {
m_text=editorPane.getText();
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) dispose();
}
| Action Listener |
private boolean split(Register r1,Register r2){
for (Enumeration<RegisterOperand> e=DefUse.defs(r1); e.hasMoreElements(); ) {
RegisterOperand def=e.nextElement();
Instruction s=def.instruction;
if (s.operator() == SPLIT) {
Operand rhs=Unary.getVal(s);
if (rhs.similar(def)) return true;
}
}
for (Enumeration<RegisterOperand> e=DefUse.defs(r2); e.hasMoreElements(); ) {
RegisterOperand def=e.nextElement();
Instruction s=def.instruction;
if (s.operator() == SPLIT) {
Operand rhs=Unary.getVal(s);
if (rhs.similar(def)) return true;
}
}
return false;
}
| Is there an instruction r1 = split r2 or r2 = split r1?? |
public static void main(String[] args) throws Exception {
Http http=new Http();
http.setConf(NutchConfiguration.create());
main(http,args);
}
| Main method. |
public JSONException syntaxError(String message){
return new JSONException(message + this.toString());
}
| Make a JSONException to signal a syntax error. |
protected void sequence_AnnotatedExportableElement_AsyncNoTrailingLineBreak_FunctionBody_FunctionHeader_FunctionImpl_StrictFormalParameters_TypeVariables(ISerializationContext context,FunctionDeclaration semanticObject){
genericSequencer.createSequence(context,semanticObject);
}
| Contexts: AnnotatedExportableElement<Yield> returns FunctionDeclaration AnnotatedExportableElement returns FunctionDeclaration Constraint: ( annotationList=AnnotatedExportableElement_FunctionDeclaration_1_0_0 declaredModifiers+=N4Modifier* declaredAsync?='async'? generator?='*'? (typeVars+=TypeVariable typeVars+=TypeVariable*)? name=BindingIdentifier? (fpars+=FormalParameter fpars+=FormalParameter*)? returnTypeRef=TypeRef? body=Block? ) |
public static boolean isSupplemental(int c){
return (c >= 0x10000 && c <= 0x10FFFF);
}
| Returns true if the specified character is a supplemental character. |
@Override public void run(){
amIActive=true;
if (args.length < 2) {
showFeedback("Plugin parameters have not been set properly.");
return;
}
String inputHeader=args[0];
String outputHeader=args[1];
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
int row, col;
double z;
int progress, oldProgress=-1;
double[] data;
WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r");
int rows=inputFile.getNumberRows();
int cols=inputFile.getNumberColumns();
double noData=inputFile.getNoDataValue();
double multiplier=Math.PI / 180;
if (inputFile.getZUnits().toLowerCase().contains("rad")) {
multiplier=1;
}
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
outputFile.setPreferredPalette(inputFile.getPreferredPalette());
for (row=0; row < rows; row++) {
data=inputFile.getRowValues(row);
for (col=0; col < cols; col++) {
z=data[col];
if (z != noData) {
outputFile.setValue(row,col,Math.cosh(z * multiplier));
}
}
progress=(int)(100f * row / (rows - 1));
if (progress != oldProgress) {
oldProgress=progress;
updateProgress((int)progress);
if (cancelOp) {
cancelOperation();
return;
}
}
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile.close();
outputFile.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
private int find(int k){
if (offsets != null) {
int lo=0;
int hi=size - 1;
while (lo <= hi) {
int i=(lo + hi) / 2;
int m=offsets[i];
if (k > m) lo=i + 1;
else if (k < m) hi=i - 1;
else return i;
}
return -(lo + 1);
}
else {
return k;
}
}
| perform a binary search to find the requested offset. |
public boolean hasValue(){
return super.hasTextValue();
}
| Returns whether it has the value. |
public static Object distArchiveEvent(String sessionID,String eventId,ScrDistreg scrDistReg,String entidad) throws DistributionException, SessionException, ValidationException {
Object result=null;
if (log.isDebugEnabled()) {
log.debug("distributionEx eventId [" + eventId + "]");
}
Validator.validate_String_NotNull_LengthMayorZero(sessionID,ValidationException.ATTRIBUTE_SESSION);
try {
CacheBag cacheBag=CacheFactory.getCacheInterface().getCacheEntry(sessionID);
AuthenticationUser user=(AuthenticationUser)cacheBag.get(HIBERNATE_Iuseruserhdr);
ScrOfic scrofic=(ScrOfic)cacheBag.get(HIBERNATE_ScrOfic);
RuleContext ruleCtx=new RuleContext();
ruleCtx=new RuleContext();
ruleCtx.setUsuario(user.getId().toString());
ruleCtx.setSessionId(sessionID);
ruleCtx.setEventId(eventId);
ruleCtx.setLibro(new Integer(scrDistReg.getIdArch()));
ruleCtx.setRegistro(new Integer(scrDistReg.getIdFdr()));
if (scrofic != null) {
ruleCtx.setOficina(scrofic.getId());
}
ruleCtx.setEntidad(entidad);
result=EventsFactory.getCurrentEvent(ruleCtx.getEventId()).execute(ruleCtx);
}
catch ( EventException ee) {
log.error("Se ha producido un error durante la ejecucion del evento de archivo de la distribucion [" + scrDistReg.getId() + "]");
throw ee;
}
catch ( SessionException e) {
throw e;
}
catch ( Exception e) {
log.error("Impossible to launch event for externe distribution for the session [" + sessionID + "]",e);
throw new DistributionException(DistributionException.ERROR_CANNOT_ACCEPT_DISTRIBUTION);
}
return result;
}
| Llamada al evento que se lanza cuando un registro distribuido pasa al estado archivado |
private static boolean haveSetCompressedSize(){
checkSCS();
return setCompressedSizeMethod != null;
}
| Are we running JDK 1.2 or higher? |
public RandomDecisionTree(int numFeatures){
setRandomFeatureCount(numFeatures);
}
| Creates a new Random Decision Tree |
public void test_restart() throws Exception {
final boolean doYouWantMeToBreak=true;
final URI SYSTAP=new URIImpl("http://bigdata.com/elm#a479c37c-407e-4f4a-be30-5a643a54561f");
final URI ORGANIZATION=new URIImpl("http://bigdata.com/domain#Organization");
final URI ENTITY=new URIImpl("http://bigdata.com/system#Entity");
final String query="construct {" + "?s <" + RDF.TYPE + "> <"+ ENTITY+ "> ."+ " } "+ "where { "+ " ?s <"+ RDF.TYPE+ "> <"+ ENTITY+ "> ."+ " ?s ?p ?lit ."+ " ?lit <"+ BDS.SEARCH+ "> \"systap\" ."+ " ?lit <"+ BDS.MIN_RELEVANCE+ "> \"0.0\"^^<http://www.w3.org/2001/XMLSchema#double> ."+ " }";
final Graph test_restart_1=new LinkedHashModel();
{
test_restart_1.add(new StatementImpl(ORGANIZATION,RDFS.SUBCLASSOF,ENTITY));
}
final Graph test_restart_2=new LinkedHashModel();
{
test_restart_2.add(new StatementImpl(SYSTAP,RDF.TYPE,ENTITY));
test_restart_2.add(new StatementImpl(SYSTAP,RDFS.LABEL,new LiteralImpl("SYSTAP")));
}
final File file;
{
try {
file=File.createTempFile(getName(),".tmp");
if (log.isInfoEnabled()) log.info("file=" + file);
}
catch ( IOException ex) {
throw new RuntimeException(ex);
}
}
final Properties properties=super.getProperties();
properties.setProperty(Options.BUFFER_MODE,BufferMode.Disk.toString());
properties.setProperty(Options.CREATE_TEMP_FILE,"false");
properties.setProperty(Options.FILE,file.toString());
BigdataSail sail=getSail(properties);
try {
{
final BigdataSailRepository repo=new BigdataSailRepository(sail);
repo.initialize();
{
boolean ok=false;
final RepositoryConnection cxn=repo.getConnection();
try {
cxn.setAutoCommit(false);
log.info("loading ontology");
cxn.add(test_restart_1);
if (!doYouWantMeToBreak) {
log.info("loading entity data");
cxn.add(test_restart_2);
}
cxn.commit();
ok=true;
}
finally {
if (!ok) cxn.rollback();
cxn.close();
}
}
if (doYouWantMeToBreak) {
boolean ok=false;
final RepositoryConnection cxn=repo.getConnection();
try {
cxn.setAutoCommit(false);
log.info("loading entity data");
cxn.add(test_restart_2);
cxn.commit();
ok=true;
}
finally {
if (!ok) cxn.rollback();
cxn.close();
}
}
{
final RepositoryConnection cxn=repo.getConnection();
try {
final Set<Statement> results=new LinkedHashSet<Statement>();
final GraphQuery graphQuery=cxn.prepareGraphQuery(QueryLanguage.SPARQL,query);
graphQuery.evaluate(new StatementCollector(results));
for ( Statement stmt : results) {
if (log.isInfoEnabled()) log.info(stmt);
}
assertTrue(results.contains(new StatementImpl(SYSTAP,RDF.TYPE,ENTITY)));
}
finally {
cxn.close();
}
}
repo.shutDown();
}
sail=reopenSail(sail);
{
final BigdataSailRepository repo=new BigdataSailRepository(sail);
repo.initialize();
{
final RepositoryConnection cxn=repo.getConnection();
try {
final Set<Statement> results=new LinkedHashSet<Statement>();
final GraphQuery graphQuery=cxn.prepareGraphQuery(QueryLanguage.SPARQL,query);
graphQuery.evaluate(new StatementCollector(results));
for ( Statement stmt : results) {
if (log.isInfoEnabled()) log.info(stmt);
}
assertTrue("Lost commit?",results.contains(new StatementImpl(SYSTAP,RDF.TYPE,ENTITY)));
}
finally {
cxn.close();
}
}
}
}
finally {
sail.__tearDownUnitTest();
}
}
| Unit test used to track down a commit problem. |
public BitOutputStream(OutputStream out){
this.out=out;
}
| Use an OutputStream to produce a BitWriter. The BitWriter will send its bits to the OutputStream as each byte is filled. |
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix,namespace);
xmlWriter.setPrefix(prefix,namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
| Util method to write an attribute with the ns prefix |
public static void addDependency(Dependency depend,ClassLoader loader){
for (; loader != null; loader=loader.getParent()) {
if (loader instanceof EnvironmentClassLoader) {
((EnvironmentClassLoader)loader).addDependency(depend);
return;
}
}
}
| Adds a dependency to the current environment. |
public script addElement(String hashcode,String element){
addElementToRegistry(hashcode,element);
return (this);
}
| Adds an Element to the element. |
public void addHeaderView(View v){
addHeaderView(v,null,true);
}
| Add a fixed view to appear at the top of the list. If addHeaderView is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want. <p/> NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that will also account for header and footer views. |
public static <T>ArrayList<T> arrayList(int initialCapacity){
return new ArrayList<T>(initialCapacity);
}
| Create a new ArrayList. |
public static InputStream toInputStream(final CharSequence input,final String encoding) throws IOException {
return IOUtils.toInputStream(input,Charsets.toCharset(encoding));
}
| Convert the specified CharSequence to an input stream, encoded as bytes using the specified character encoding. <p> Character encoding names can be found at <a href="http://www.iana.org/assignments/character-sets">IANA</a>. |
public String objectToString(final Object productSkuObject){
return String.valueOf(((ProductSku)productSkuObject).getSkuId());
}
| Object to string conversion. |
public NBTTagCompound loadFile(File saveDirectory,String filename){
return loadFile(new File(saveDirectory,filename + ".dat"));
}
| Reads NBT data from the world folder. |
@Override public boolean equals(Object obj){
if (this == obj) {
return true;
}
if (obj instanceof YearMonth) {
YearMonth other=(YearMonth)obj;
return year == other.year && month == other.month;
}
return false;
}
| Checks if this year-month is equal to another year-month. <p> The comparison is based on the time-line position of the year-months. |
static long toLong(String v){
String buildPart="1";
long buildType=700;
if (v.endsWith("-SNAPSHOT")) {
buildPart="";
v=v.substring(0,v.indexOf("-SNAPSHOT"));
buildType=0;
}
else if (v.contains("-alpha-")) {
buildPart=v.substring(v.lastIndexOf('-') + 1);
v=v.substring(0,v.indexOf("-alpha-"));
buildType=100;
}
else if (v.contains("-beta-")) {
buildPart=v.substring(v.lastIndexOf('-') + 1);
v=v.substring(0,v.indexOf("-beta-"));
buildType=300;
}
else if (v.contains("-rc-")) {
buildPart=v.substring(v.lastIndexOf('-') + 1);
v=v.substring(0,v.indexOf("-rc-"));
buildType=500;
}
String[] parts=v.split("\\.");
if (parts.length > 3) {
throw new IllegalArgumentException("Illegal version number: " + v);
}
long major=parts.length > 0 ? Long.parseLong(parts[0]) : 0;
long minor=parts.length > 1 ? Long.parseLong(parts[1]) : 0;
long rev=parts.length > 2 ? Long.parseLong(parts[2]) : 0;
long build=buildPart.isEmpty() ? 0 : Long.parseLong(buildPart);
long result=(((major * 1000 + minor) * 1000 + rev) * 1000) + build + buildType;
return result;
}
| Converts a version string on the form x.y.z into an integer which can be compared to other versions converted into integers. |
private String token(final String code) throws IOException {
return new JdkRequest(new Href(this.gauth).path("o").path("oauth2").path("token").toString()).body().formParam("client_id",this.app).formParam("redirect_uri",this.redir).formParam("client_secret",this.key).formParam("grant_type","authorization_code").formParam(PsGoogle.CODE,code).back().header("Content-Type","application/x-www-form-urlencoded").method(com.jcabi.http.Request.POST).fetch().as(RestResponse.class).assertStatus(HttpURLConnection.HTTP_OK).as(JsonResponse.class).json().readObject().getString(PsGoogle.ACCESS_TOKEN);
}
| Retrieve Google access token. |
public void addStateValueAsDouble(String name,double doubleValue){
addStateValueAsDouble(null,name,doubleValue);
}
| Adds a new StateObject with the specified <code>name</code> and Double <code>value</code>. The new StateObject is placed beneath the document root. If a StateObject with this name already exists, a new one is still created. |
@Override public void run(){
amIActive=true;
String streamsHeader=null;
String pointerHeader=null;
String outputHeader=null;
WhiteboxRaster output;
int[] dX=new int[]{1,1,1,0,-1,-1,-1,0};
int[] dY=new int[]{-1,0,1,1,1,0,-1,-1};
final double LnOf2=0.693147180559945;
int row, col, x, y;
float progress=0;
double slope;
double z;
int i, c;
double[] inflowingVals=new double[]{16,32,64,128,1,2,4,8};
boolean flag=false;
double flowDir=0;
double outletID=0;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
streamsHeader=args[0];
pointerHeader=args[1];
outputHeader=args[2];
if ((streamsHeader == null) || (pointerHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster streams=new WhiteboxRaster(streamsHeader,"r");
int rows=streams.getNumberRows();
int cols=streams.getNumberColumns();
WhiteboxRaster pntr=new WhiteboxRaster(pointerHeader,"r");
double noData=pntr.getNoDataValue();
if (pntr.getNumberRows() != rows || pntr.getNumberColumns() != cols) {
showFeedback("The input images must be of the same dimensions.");
return;
}
output=new WhiteboxRaster(outputHeader,"rw",streamsHeader,WhiteboxRaster.DataType.INTEGER,0);
output.setNoDataValue(noData);
output.setPreferredPalette("qual.pal");
output.setDataScale(WhiteboxRaster.DataScale.CATEGORICAL);
byte numNeighbouringStreamCells=0;
double currentID=0;
double currentValue=0;
double streamsID=0;
updateProgress("Loop 1 of 4:",0);
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
if (streams.getValue(row,col) > 0) {
numNeighbouringStreamCells=0;
for (c=0; c < 8; c++) {
x=col + dX[c];
y=row + dY[c];
if (streams.getValue(y,x) > 0 && pntr.getValue(y,x) == inflowingVals[c]) {
numNeighbouringStreamCells++;
}
}
if (numNeighbouringStreamCells == 0) {
x=col;
y=row;
currentID++;
output.setValue(y,x,currentID);
flag=true;
do {
flowDir=pntr.getValue(y,x);
if (flowDir > 0) {
c=(int)(Math.log(flowDir) / LnOf2);
if (c > 7) {
showFeedback("An unexpected value has " + "been identified in the pointer " + "image. This tool requires a "+ "pointer grid that has been "+ "created using either the D8 "+ "or Rho8 tools.");
return;
}
x+=dX[c];
y+=dY[c];
if (streams.getValue(y,x) <= 0) {
flag=false;
}
else {
currentValue=output.getValue(y,x);
if (currentValue > 0) {
flag=false;
break;
}
numNeighbouringStreamCells=0;
int x2, y2;
for (int d=0; d < 8; d++) {
x2=x + dX[d];
y2=y + dY[d];
if (streams.getValue(y2,x2) > 0 && pntr.getValue(y2,x2) == inflowingVals[d]) {
numNeighbouringStreamCells++;
}
}
if (numNeighbouringStreamCells >= 2) {
currentID++;
}
output.setValue(y,x,currentID);
}
}
else {
if (streams.getValue(y,x) > 0) {
output.setValue(y,x,currentID);
}
flag=false;
}
}
while (flag);
}
}
else {
output.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress("Loop 1 of 4:",(int)progress);
}
updateProgress("Loop 2 of 4:",0);
byte numStreamNeighbours=0;
double startingStreamHeadID=currentID + 1;
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
if (streams.getValue(row,col) > 0) {
numStreamNeighbours=0;
for (c=0; c < 8; c++) {
if (streams.getValue(row + dY[c],col + dX[c]) > 0 && pntr.getValue(row + dY[c],col + dX[c]) == inflowingVals[c]) {
numStreamNeighbours++;
}
}
if (numStreamNeighbours == 0) {
currentID++;
output.setValue(row,col,currentID);
}
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress("Loop 2 of 4:",(int)progress);
}
int d;
boolean state=false;
int currentMaxID=(int)currentID;
double[][] sideVals=new double[4][currentMaxID + 1];
for (i=1; i <= currentMaxID; i++) {
sideVals[0][i]=i;
currentID++;
sideVals[1][i]=currentID;
}
for (i=1; i <= currentMaxID; i++) {
currentID++;
sideVals[2][i]=currentID;
}
for (i=1; i <= currentMaxID; i++) {
currentID++;
sideVals[3][i]=currentID;
}
updateProgress("Loop 3 of 4:",0);
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
if (streams.getValue(row,col) > 0) {
currentID=output.getValue(row,col);
flowDir=pntr.getValue(row,col);
if (flowDir > 0) {
c=(int)(Math.log(flowDir) / LnOf2);
flag=false;
d=c;
state=false;
do {
d++;
if (d > 7) {
d=0;
}
if (d < 0) {
d=7;
}
x=col + dX[d];
y=row + dY[d];
z=streams.getValue(y,x);
if (z <= 0 && z != noData) {
state=true;
if (pntr.getValue(y,x) == inflowingVals[d]) {
output.setValue(y,x,sideVals[0][(int)currentID]);
}
}
else {
if (state) {
flag=true;
}
}
}
while (!flag);
flag=false;
d=c;
state=false;
int k=0;
double val=sideVals[1][(int)currentID];
int j=1;
do {
d--;
if (d > 7) {
d=0;
}
if (d < 0) {
d=7;
}
x=col + dX[d];
y=row + dY[d];
z=streams.getValue(y,x);
if (z <= 0 && z != noData) {
if (!state) {
val=sideVals[j][(int)currentID];
j++;
state=true;
}
if (pntr.getValue(y,x) == inflowingVals[d] && output.getValue(y,x) <= 0) {
output.setValue(y,x,val);
}
}
k++;
if (k == 7) {
flag=true;
}
}
while (!flag);
}
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress("Loop 3 of 4:",(int)progress);
}
updateProgress("Loop 4 of 4:",0);
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
if (output.getValue(row,col) == noData && pntr.getValue(row,col) != noData) {
flag=false;
x=col;
y=row;
do {
flowDir=pntr.getValue(y,x);
if (flowDir > 0) {
c=(int)(Math.log(flowDir) / LnOf2);
x+=dX[c];
y+=dY[c];
z=output.getValue(y,x);
if (z != noData) {
streamsID=z;
flag=true;
}
}
else {
streamsID=noData;
flag=true;
}
}
while (!flag);
flag=false;
x=col;
y=row;
output.setValue(y,x,streamsID);
do {
flowDir=pntr.getValue(y,x);
if (flowDir > 0) {
c=(int)(Math.log(flowDir) / LnOf2);
x+=dX[c];
y+=dY[c];
z=output.getValue(y,x);
if (z != noData) {
flag=true;
}
}
else {
flag=true;
}
output.setValue(y,x,streamsID);
}
while (!flag);
}
else if (pntr.getValue(row,col) == noData) {
output.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress("Loop 4 of 4:",(int)progress);
}
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
if (streams.getValue(row,col) > 0) {
output.setValue(row,col,0);
}
}
if (cancelOp) {
cancelOperation();
return;
}
}
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
pntr.close();
streams.close();
output.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
protected void paintTrack(SynthContext context,Graphics g,Rectangle trackBounds){
int orientation=slider.getOrientation();
SynthLookAndFeel.updateSubregion(context,g,trackBounds);
context.getPainter().paintSliderTrackBackground(context,g,trackBounds.x,trackBounds.y,trackBounds.width,trackBounds.height,orientation);
context.getPainter().paintSliderTrackBorder(context,g,trackBounds.x,trackBounds.y,trackBounds.width,trackBounds.height,orientation);
}
| Paints the slider track. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.