code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public void test_setBooleanLjava_lang_ObjectIZ(){
boolean[] x={false};
boolean thrown=false;
try {
Array.setBoolean(x,0,true);
}
catch ( Exception e) {
fail("Exception during get test : " + e.getMessage());
}
assertTrue("Failed to set correct value",Array.getBoolean(x,0));
try {
Array.setBoolean(new Object(),0,false);
}
catch ( IllegalArgumentException e) {
thrown=true;
}
if (!thrown) {
fail("Passing non-array failed to throw exception");
}
thrown=false;
try {
Array.setBoolean(x,4,false);
}
catch ( ArrayIndexOutOfBoundsException e) {
thrown=true;
}
if (!thrown) {
fail("Invalid index failed to throw exception");
}
thrown=false;
try {
Array.setBoolean(null,0,true);
}
catch ( NullPointerException e) {
thrown=true;
}
if (!thrown) {
fail("Null argument failed to throw NPE");
}
}
| java.lang.reflect.Array#setBoolean(java.lang.Object, int, boolean) |
public static boolean isConnectedWifi(Context context){
NetworkInfo info=Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
| Check if there is any connectivity to a Wifi network |
private void checkValid(Position pos,Move move){
assertTrue(move != null);
MoveGen.MoveList moveList=new MoveGen().pseudoLegalMoves(pos);
MoveGen.removeIllegal(pos,moveList);
boolean contains=false;
for (int mi=0; mi < moveList.size; mi++) if (moveList.m[mi].equals(move)) {
contains=true;
break;
}
assertTrue(contains);
}
| Check that move is a legal move in position pos. |
protected void appendDetail(StringBuffer buffer,String fieldName,byte value){
buffer.append(value);
}
| <p>Append to the <code>toString</code> a <code>byte</code> value.</p> |
public void onGoogleLoginError(final Exception error){
Logger.e(TAG,"GOOGLE LOGIN ERROR");
}
| Method called when there is an error while google login |
public boolean isOpposed(ECMInfo other){
return (owner == null) || (other.getOwner() == null) || owner.isEnemyOf(other.getOwner());
}
| Returns true if the supplied ECMInfo is opposed to this one. |
private String neededPermissionForFeature(String feature){
String neededPermission=null;
if (FEATURE_KEY_PREF_CONTACTS.equals(feature)) {
neededPermission=Manifest.permission.READ_CONTACTS;
}
else if (FEATURE_KEY_PREF_DIALER.equals(feature)) {
neededPermission=Manifest.permission.WRITE_CALL_LOG;
}
return neededPermission;
}
| Provides the permission associated to a feature |
public boolean booleanPrimitiveValueOfParameterNamed(final String parameterName){
final Boolean value=this.fromApiJsonHelper.extractBooleanNamed(parameterName,this.parsedQuery);
return (Boolean)ObjectUtils.defaultIfNull(value,Boolean.FALSE);
}
| always returns true or false |
public static void v(String tag,String msg){
if (sLevel > LEVEL_VERBOSE) {
return;
}
Log.v(tag,msg);
}
| Send a VERBOSE log message. |
public static ImageRequestBuilder newBuilderWithSource(Uri uri){
return new ImageRequestBuilder().setSource(uri);
}
| Creates a new request builder instance. The setting will be done according to the source type. |
private int decodeGaincData(){
int ret;
for (int chNum=0; chNum < numChannels; chNum++) {
for (int i=0; i < ATRAC3P_SUBBANDS; i++) {
ctx.channels[chNum].gainData[i].clear();
}
if (br.readBool()) {
int codedSubbands=br.read(4) + 1;
if (br.readBool()) {
ctx.channels[chNum].numGainSubbands=br.read(4) + 1;
}
else {
ctx.channels[chNum].numGainSubbands=codedSubbands;
}
ret=decodeGaincNPoints(chNum,codedSubbands);
if (ret < 0) {
return ret;
}
ret=decodeGaincLevels(chNum,codedSubbands);
if (ret < 0) {
return ret;
}
ret=decodeGaincLocCodes(chNum,codedSubbands);
if (ret < 0) {
return ret;
}
if (codedSubbands > 0) {
for (int sb=codedSubbands; sb < ctx.channels[chNum].numGainSubbands; sb++) {
ctx.channels[chNum].gainData[sb].copy(ctx.channels[chNum].gainData[sb - 1]);
}
}
}
else {
ctx.channels[chNum].numGainSubbands=0;
}
}
return 0;
}
| Decode gain control data for all channels. |
static public void qsort(double[] array){
qsort_h(array,0,array.length - 1);
}
| Non-Recursive QuickSort |
public boolean isEmpty(){
return bits == 0;
}
| Return whether or not the set of non-null parameters is empty. |
public MutableLeafData(final int branchingFactor,final ILeafData src){
keys=new MutableKeyBuffer(branchingFactor + 1,src.getKeys());
vals=new MutableValueBuffer(branchingFactor + 1,src.getValues());
versionTimestamps=(src.hasVersionTimestamps() ? new long[branchingFactor + 1] : null);
deleteMarkers=(src.hasDeleteMarkers() ? new boolean[branchingFactor + 1] : null);
rawRecords=(src.hasRawRecords() ? new boolean[branchingFactor + 1] : null);
final int nkeys=keys.size();
if (versionTimestamps != null) {
for (int i=0; i < nkeys; i++) {
versionTimestamps[i]=src.getVersionTimestamp(i);
}
minimumVersionTimestamp=src.getMinimumVersionTimestamp();
maximumVersionTimestamp=src.getMaximumVersionTimestamp();
}
else {
minimumVersionTimestamp=Long.MAX_VALUE;
maximumVersionTimestamp=Long.MIN_VALUE;
}
if (deleteMarkers != null) {
for (int i=0; i < nkeys; i++) {
deleteMarkers[i]=src.getDeleteMarker(i);
}
}
if (rawRecords != null) {
for (int i=0; i < nkeys; i++) {
rawRecords[i]=src.getRawRecord(i) != IRawStore.NULL;
}
}
}
| Copy ctor. |
public boolean isI_IsImported(){
Object oo=get_Value(COLUMNNAME_I_IsImported);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Imported. |
public static int nextPowerOfTwo(int x){
if (x == 0) return 1;
x--;
x|=x >> 1;
x|=x >> 2;
x|=x >> 4;
x|=x >> 8;
return (x | x >> 16) + 1;
}
| Return the least power of two greater than or equal to the specified value. <p>Note that this function will return 1 when the argument is 0. |
public static ObjectAnimator ofFloat(Object target,String propertyName,float... values){
ObjectAnimator anim=new ObjectAnimator(target,propertyName);
anim.setFloatValues(values);
return anim;
}
| Constructs and returns an ObjectAnimator that animates between float values. A single value implies that that value is the one being animated to. Two values imply a starting and ending values. More than two values imply a starting value, values to animate through along the way, and an ending value (these values will be distributed evenly across the duration of the animation). |
public static int calculateReward(Player player){
int moneys=0;
int kills=0;
for (int i=0; i < RAT_TYPES.size(); i++) {
try {
final String killed=player.getQuest(QUEST_SLOT,i + 1);
if (killed != null) {
kills=Integer.decode(killed);
}
}
catch ( NumberFormatException nfe) {
}
moneys=moneys + kills * RAT_REWARDS.get(i);
}
return (moneys);
}
| function for calculating reward's moneys for player |
public void copyContent(){
StringSelection selection;
Clipboard clipboard;
selection=getTable().getStringSelection();
if (selection == null) {
return;
}
clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection,selection);
}
| copies the content of the selection to the clipboard |
public AngularObject add(String name,Object o,String noteId,String paragraphId,boolean emit){
AngularObject ao=createNewAngularObject(name,o,noteId,paragraphId);
synchronized (registry) {
Map<String,AngularObject> noteLocalRegistry=getRegistryForKey(noteId,paragraphId);
noteLocalRegistry.put(name,ao);
if (listener != null && emit) {
listener.onAdd(interpreterId,ao);
}
}
return ao;
}
| Add object into registry Paragraph scope when noteId and paragraphId both not null Notebook scope when paragraphId is null Global scope when noteId and paragraphId both null |
public DisqusClient(ApiConfig config,Context context){
super(config);
mcontent=context;
if (instance_am == null) {
instance_am=createAuthenticationManager(context);
}
}
| THe content |
public FunctionDeclaration(ImportStack importStack,Context context,String signature,Object object,Method method,List<ArgumentConverter> argumentConverters){
this.importStack=importStack;
this.context=context;
this.signature=signature;
this.object=object;
this.method=method;
this.argumentConverters=argumentConverters;
}
| Create a new function declaration. |
public List<RawProperty> removeExperimentalProperties(String name){
List<RawProperty> all=getExperimentalProperties();
List<RawProperty> toRemove=new ArrayList<RawProperty>();
for ( RawProperty property : all) {
if (property.getName().equalsIgnoreCase(name)) {
toRemove.add(property);
}
}
all.removeAll(toRemove);
return Collections.unmodifiableList(toRemove);
}
| Removes all experimental properties that have the given name. |
public int typicalIndsProduced(){
return (tossSecondParent ? 1 : INDS_PRODUCED);
}
| Returns 2 (unless tossing the second sibling, in which case it returns 1) |
public static String asUrl(File file){
return PROTOCOL + file.getAbsolutePath();
}
| Prefixes `file://` to the file's absolute path. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-08-13 13:14:13.410 -0400",hash_original_method="25736550470809040A3F8C62976339C4",hash_generated_method="B61E8F76A04C239FB09D418D5B87F38F") public Method element(){
return element;
}
| Returns the method object for the invalid type. |
int read(byte[] buffer,int offset,int length) throws IOException {
throw new UnsupportedOperationException();
}
| Reads bytes from the underlying stream. |
private String replacePlaceholders(String query,Map<String,String> replacements){
String resultQuery=query;
for ( Map.Entry<String,String> entry : replacements.entrySet()) {
resultQuery=resultQuery.replace(entry.getKey(),entry.getValue());
}
return resultQuery;
}
| Replaces the placeholders with concrete values |
public static void annotateSupers(List<AnnotatedDeclaredType> supertypes,TypeElement subtypeElement){
SuperTypeApplier.annotateSupers(supertypes,subtypeElement);
}
| Annotate the list of supertypes using the annotations on the TypeElement representing a class or interface |
public void close() throws java.io.IOException {
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(PREFIX);
out.writeBytes(NEWLINE);
out.flush();
out.close();
}
| Closes the stream. <br /> <br /> <b>NOTE:</b> This method <b>MUST</b> be called to finalize the multipart stream. |
private void processMethods(final Object component,final Context context,final ContextDestroyer contextDestroyer){
Class<?> componentClass=component.getClass();
while (componentClass != null && !componentClass.equals(Object.class)) {
final Method[] methods=ClassReflection.getDeclaredMethods(componentClass);
if (methods != null && methods.length > 0) {
processMethods(component,methods,context,contextDestroyer);
}
componentClass=componentClass.getSuperclass();
}
}
| Scans class tree of component to process all its methods. |
@Override public void run(){
amIActive=true;
String inputFilesString=null;
String[] pointFiles;
String outputHeader=null;
int row, col;
int nrows, ncols;
double x, y, z;
int i;
int progress=0;
int numPoints=0;
int lineNum=0;
int nlines=0;
double maxDist=Double.POSITIVE_INFINITY;
double minX=Double.POSITIVE_INFINITY;
double maxX=Double.NEGATIVE_INFINITY;
double minY=Double.POSITIVE_INFINITY;
double maxY=Double.NEGATIVE_INFINITY;
double north, south, east, west;
double resolution=1;
String delimiter=" ";
boolean firstLineHeader=false;
String str1=null;
FileWriter fw=null;
BufferedWriter bw=null;
PrintWriter out=null;
List<KdTree.Entry<Double>> results;
double noData=-32768;
double northing, easting;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
inputFilesString=args[0];
firstLineHeader=Boolean.parseBoolean(args[1]);
outputHeader=args[2];
resolution=Double.parseDouble(args[3]);
if (!args[4].equalsIgnoreCase("not specified")) {
maxDist=Double.parseDouble(args[4]);
}
if ((inputFilesString.length() <= 0) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
pointFiles=inputFilesString.split(";");
int numPointFiles=pointFiles.length;
if (maxDist < Double.POSITIVE_INFINITY) {
maxDist=maxDist * maxDist;
}
updateProgress("Counting the number of points:",0);
numPoints=0;
for (i=0; i < numPointFiles; i++) {
nlines=countLinesInFile(pointFiles[i]);
if (firstLineHeader) {
numPoints+=nlines - 1;
}
else {
numPoints+=nlines;
}
}
KdTree<Double> pointsTree=new KdTree.SqrEuclid<Double>(2,new Integer(numPoints));
nlines=0;
for (i=0; i < numPointFiles; i++) {
DataInputStream in=null;
BufferedReader br=null;
try {
FileInputStream fstream=new FileInputStream(pointFiles[i]);
in=new DataInputStream(fstream);
br=new BufferedReader(new InputStreamReader(in));
String line;
String[] str;
lineNum=1;
while ((line=br.readLine()) != null) {
str=line.split(delimiter);
if (str.length <= 1) {
delimiter="\t";
str=line.split(delimiter);
if (str.length <= 1) {
delimiter=" ";
str=line.split(delimiter);
if (str.length <= 1) {
delimiter=",";
str=line.split(delimiter);
}
}
}
if ((lineNum > 1 || !firstLineHeader) && (str.length >= 3)) {
x=Double.parseDouble(str[0]);
y=Double.parseDouble(str[1]);
z=Double.parseDouble(str[2]);
double[] entry={y,x};
pointsTree.addPoint(entry,z);
if (x < minX) {
minX=x;
}
if (x > maxX) {
maxX=x;
}
if (y < minY) {
minY=y;
}
if (y > maxY) {
maxY=y;
}
}
lineNum++;
nlines++;
progress=(int)(100d * nlines / numPoints);
updateProgress("Reading point data:",progress);
}
in.close();
br.close();
}
catch ( java.io.IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
try {
if (in != null || br != null) {
in.close();
br.close();
}
}
catch ( java.io.IOException ex) {
}
}
}
west=minX - 0.5 * resolution;
north=maxY + 0.5 * resolution;
nrows=(int)(Math.ceil((north - minY) / resolution));
ncols=(int)(Math.ceil((maxX - west) / resolution));
south=north - nrows * resolution;
east=west + ncols * resolution;
fw=new FileWriter(outputHeader,false);
bw=new BufferedWriter(fw);
out=new PrintWriter(bw,true);
str1="Min:\t" + Double.toString(Integer.MAX_VALUE);
out.println(str1);
str1="Max:\t" + Double.toString(Integer.MIN_VALUE);
out.println(str1);
str1="North:\t" + Double.toString(north);
out.println(str1);
str1="South:\t" + Double.toString(south);
out.println(str1);
str1="East:\t" + Double.toString(east);
out.println(str1);
str1="West:\t" + Double.toString(west);
out.println(str1);
str1="Cols:\t" + Integer.toString(ncols);
out.println(str1);
str1="Rows:\t" + Integer.toString(nrows);
out.println(str1);
str1="Data Type:\t" + "float";
out.println(str1);
str1="Z Units:\t" + "not specified";
out.println(str1);
str1="XY Units:\t" + "not specified";
out.println(str1);
str1="Projection:\t" + "not specified";
out.println(str1);
str1="Data Scale:\tcontinuous";
out.println(str1);
str1="Preferred Palette:\t" + "spectrum.pal";
out.println(str1);
str1="NoData:\t" + noData;
out.println(str1);
if (java.nio.ByteOrder.nativeOrder() == java.nio.ByteOrder.LITTLE_ENDIAN) {
str1="Byte Order:\t" + "LITTLE_ENDIAN";
}
else {
str1="Byte Order:\t" + "BIG_ENDIAN";
}
out.println(str1);
out.close();
WhiteboxRaster image=new WhiteboxRaster(outputHeader,"rw");
double halfResolution=resolution / 2;
for (row=0; row < nrows; row++) {
for (col=0; col < ncols; col++) {
easting=(col * resolution) + (west + halfResolution);
northing=(north - halfResolution) - (row * resolution);
double[] entry={northing,easting};
results=pointsTree.nearestNeighbor(entry,1,true);
if (results.get(0).distance < maxDist) {
image.setValue(row,col,results.get(0).value);
}
else {
image.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(100f * row / (nrows - 1));
updateProgress("Interpolating point data:",progress);
}
image.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
image.addMetadataEntry("Created on " + new Date());
image.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public RotateFilter(float angle){
this(angle,true);
}
| Construct a RotateFilter. |
@Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case DomPackage.VARIABLE_REFERENCE__VARIABLE_NAME:
setVariableName((String)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static void writeStaticField(final Class<?> cls,final String fieldName,final Object value) throws IllegalAccessException {
FieldUtils.writeStaticField(cls,fieldName,value,false);
}
| Write a named public static Field. Superclasses will be considered. |
static Object newInstance(String className,ClassLoader cl,boolean doFallback) throws ConfigurationError {
try {
Class providerClass=findProviderClass(className,cl,doFallback);
Object instance=providerClass.newInstance();
debugPrintln("created new instance of " + providerClass + " using ClassLoader: "+ cl);
return instance;
}
catch ( ClassNotFoundException x) {
throw new ConfigurationError("Provider " + className + " not found",x);
}
catch ( Exception x) {
throw new ConfigurationError("Provider " + className + " could not be instantiated: "+ x,x);
}
}
| Create an instance of a class using the specified ClassLoader |
public void calcMajorTick(){
majorTick=10;
majorTickCount=(int)Math.round(log10(maxTick / minTick)) + 1;
}
| Calculate the optimum major tick distance. |
protected void finalize() throws Throwable {
this.systemID=null;
this.encapsulatedException=null;
super.finalize();
}
| Cleans up the object when it's destroyed. |
public TFSFolder(final ExtendedItem extendedItem){
this(extendedItem,null);
}
| Creates a new TFSFolder using the given AExtendedItem. |
public NGramTokenizer(int n,Tokenizer base,boolean allSubN){
if (n <= 0) throw new IllegalArgumentException("Number of n-grams must be positive, not " + n);
this.n=n;
this.base=base;
this.allSubN=allSubN;
}
| Creates a new n-gramer |
protected boolean accept(XSLTVisitor visitor){
return visitor.visitInstruction(this);
}
| Accept a visitor and call the appropriate method for this class. |
public void query(String query){
}
| Filters the DbfTableModel given a SQL like string |
public void push(final int a){
if (pointer >= stack.length) {
final int[] newStack=new int[(int)(stack.length * 1.5)];
System.arraycopy(stack,0,newStack,0,stack.length);
stack=newStack;
}
stack[pointer]=a;
pointer++;
}
| Adds an item to the top of the stack, expanding the stack if needed |
private HttpEntity paramsToEntity(RequestParams params,ResponseHandlerInterface responseHandler){
HttpEntity entity=null;
try {
if (params != null) {
entity=params.getEntity(responseHandler);
}
}
catch ( IOException e) {
if (responseHandler != null) {
responseHandler.sendFailureMessage(0,null,null,e);
}
else {
e.printStackTrace();
}
}
return entity;
}
| Returns HttpEntity containing data from RequestParams included with request declaration. Allows also passing progress from upload via provided ResponseHandler |
public void shuffle(){
Random random=new Random();
for (int i=size() - 1; i > 0; i--) {
int j=random.nextInt(i);
swapCards(i,j);
}
}
| Randomly permute the cards. |
public void readCommandLine(String[] args){
String key=null;
String value="";
for (int i=0; i < args.length; i++) {
if (args[i].startsWith("-")) {
if (key != null) {
put(key,value);
}
key=args[i].substring(1);
int ik=key.indexOf('=');
if (ik >= 0) {
value=key.substring(ik + 1);
key=key.substring(0,ik).toLowerCase();
}
else {
key=key.toLowerCase();
value=NULL;
}
}
else {
if (value == NULL) {
value=args[i];
}
else {
value+=(" " + args[i]);
}
}
}
if (key != null) {
put(key,value);
}
}
| Removes any - or -- prepends as it populates properties. |
public CubeHash224(){
}
| Create the engine. |
public void swap(int original,int newPosition){
Song temp=mSongs.get(original);
Song newSong=mSongs.get(newPosition);
mSongs.set(original,newSong);
mSongs.set(newPosition,temp);
int tempVis=mVisible.get(original);
mVisible.set(original,mVisible.get(newPosition));
mVisible.set(newPosition,tempVis);
int tempId=mIds.get(original);
mIds.set(original,mIds.get(newPosition));
mIds.set(newPosition,tempId);
super.notifyDataSetChanged();
}
| Swaps two elements and their properties |
public SignificantTermsBuilder field(String field){
this.field=field;
return this;
}
| Set the field to fetch significant terms from. |
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 BubbleTransition(int duration,String componentName){
this(duration);
this.componentName=componentName;
}
| Creates a Bubble Transition |
public Object clone(){
OVector clone=null;
try {
clone=(OVector)super.clone();
}
catch ( Exception e) {
System.err.println("Error cloning " + getClass().getName() + ":");
e.printStackTrace();
System.exit(1);
}
clone.vector=(Object[])vector.clone();
return clone;
}
| Returns a shallow clone of this vector; the vector itself is cloned, but the element objects aren't. |
void remove(String filename){
if (debug) {
System.err.println("Removing " + filename);
}
new File(filename).delete();
if (new File(filename).exists()) {
throw new RuntimeException("Error deleting " + filename);
}
}
| Helper, removes a file |
@Override public int eBaseStructuralFeatureID(int derivedFeatureID,Class<?> baseClass){
if (baseClass == ReferencingElement_IM.class) {
switch (derivedFeatureID) {
case ImPackage.PARAMETERIZED_PROPERTY_ACCESS_EXPRESSION_IM__REWIRED_TARGET:
return ImPackage.REFERENCING_ELEMENT_IM__REWIRED_TARGET;
default :
return -1;
}
}
if (baseClass == ReferencingElementExpression_IM.class) {
switch (derivedFeatureID) {
default :
return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID,baseClass);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private DefaultJavaType createType(TypeDef typeDef,int dimensions){
if (typeDef == null) {
return null;
}
return TypeAssembler.createUnresolved(typeDef,dimensions,classStack.isEmpty() ? source : classStack.getFirst());
}
| this one is specific for those cases where dimensions can be part of both the type and identifier i.e. private String[] matrix[]; //field public abstract String[] getMatrix[](); //method |
public ConfigureXmlEntityExpansionDialog_NB(XmlEntityExpansion xmlEntityExpansion){
this.xmlEntityExpansion=xmlEntityExpansion;
initComponents();
final IterateModel numberOfEntitiesIterator=xmlEntityExpansion.getNumberOfEntitiesIterator();
configureNumberOfEntities.setStartAt(String.valueOf(numberOfEntitiesIterator.getStartAt()));
configureNumberOfEntities.setStopAt(String.valueOf(numberOfEntitiesIterator.getStopAt()));
configureNumberOfEntities.setIncrement(String.valueOf(numberOfEntitiesIterator.getIncrement()));
configureNumberOfEntities.setIterateStrategie(numberOfEntitiesIterator.getIterateStrategie());
final IterateModel numberOfTagsIterator=xmlEntityExpansion.getNumberOfEntityElementsIterator();
configureNumberOfTags.setStartAt(String.valueOf(numberOfTagsIterator.getStartAt()));
configureNumberOfTags.setStopAt(String.valueOf(numberOfTagsIterator.getStopAt()));
configureNumberOfTags.setIncrement(String.valueOf(numberOfTagsIterator.getIncrement()));
configureNumberOfTags.setIterateStrategie(numberOfTagsIterator.getIterateStrategie());
}
| Creates new form ConfigureCoerceiveParsingDialog_NB |
static public short unpackShort(final InputStream is) throws IOException {
short b=(short)readByte(is);
short v;
if ((b & 0x80) != 0) {
v=(short)((b & 0x7f) << 8);
b=readByte(is);
v|=(b & 0xff);
}
else {
v=b;
}
return (short)v;
}
| Unpack a non-negative short value from the input stream. |
private void action_loadTree(){
KeyNamePair tree=treeField.getSelectedItem().toKeyNamePair();
log.info("Tree=" + tree);
if (tree.getKey() <= 0) {
SimpleListModel tmp=new SimpleListModel();
centerList.setItemRenderer(tmp);
centerList.setModel(tmp);
return;
}
m_tree=new MTree(Env.getCtx(),tree.getKey(),null);
cbAllNodes.setSelected(m_tree.isAllNodes());
bAddAll.setEnabled(!m_tree.isAllNodes());
bAdd.setEnabled(!m_tree.isAllNodes());
bDelete.setEnabled(!m_tree.isAllNodes());
bDeleteAll.setEnabled(!m_tree.isAllNodes());
String fromClause=m_tree.getSourceTableName(false);
String columnNameX=m_tree.getSourceTableName(true);
String actionColor=m_tree.getActionColorName();
SimpleListModel model=new SimpleListModel();
ArrayList<ListItem> items=getTreeItemData();
for ( ListItem item : items) model.addElement(item);
log.config("#" + model.getSize());
centerList.setItemRenderer(model);
centerList.setModel(model);
try {
centerTree.setModel(null);
}
catch ( Exception e) {
}
if (centerTree.getTreecols() != null) centerTree.getTreecols().detach();
if (centerTree.getTreefoot() != null) centerTree.getTreefoot().detach();
if (centerTree.getTreechildren() != null) centerTree.getTreechildren().detach();
SimpleTreeModel.initADTree(centerTree,m_tree.getAD_Tree_ID(),m_WindowNo);
}
| Action: Fill Tree with all nodes |
public void testPeek(){
LinkedBlockingQueue q=populatedQueue(SIZE);
for (int i=0; i < SIZE; ++i) {
assertEquals(i,q.peek());
assertEquals(i,q.poll());
assertTrue(q.peek() == null || !q.peek().equals(i));
}
assertNull(q.peek());
}
| peek returns next element, or null if empty |
public boolean isInitializing(){
return getState().isInitializing();
}
| Returns true for the initializing state. |
public PMElement elementAt(int i){
return gr.elementAt(i);
}
| Returns element at specific index. |
public void emitMessage(String emitType,JSONObject jsonObject){
if (mSocket != null) mSocket.emit(emitType,jsonObject);
}
| emit message to socket |
void allocPaddle(){
BasicAlignedRect rect=new BasicAlignedRect();
rect.setScale(DEFAULT_PADDLE_WIDTH * mPaddleSizeMultiplier,ARENA_HEIGHT * PADDLE_HEIGHT_PERC);
rect.setColor(1.0f,1.0f,1.0f);
rect.setPosition(ARENA_WIDTH / 2.0f,ARENA_HEIGHT * PADDLE_VERTICAL_PERC);
mPaddle=rect;
}
| Creates the paddle. |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
@SuppressWarnings("unchecked") @Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case DatatypePackage.TYPE__NAME:
setName((String)newValue);
return;
case DatatypePackage.TYPE__NAMESPACE:
setNamespace((String)newValue);
return;
case DatatypePackage.TYPE__VERSION:
setVersion((String)newValue);
return;
case DatatypePackage.TYPE__REFERENCES:
getReferences().clear();
getReferences().addAll((Collection<? extends ModelReference>)newValue);
return;
case DatatypePackage.TYPE__DESCRIPTION:
setDescription((String)newValue);
return;
case DatatypePackage.TYPE__DISPLAYNAME:
setDisplayname((String)newValue);
return;
case DatatypePackage.TYPE__CATEGORY:
setCategory((String)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public boolean isAttribute(){
return false;
}
| This method is used to determine if the parameter represents an attribute. This is used to style the name so that elements are styled as elements and attributes are styled as required. |
void loadMethodIds() throws IOException {
int count=mHeaderItem.methodIdsSize;
mMethodIds=new MethodIdItem[count];
seek(mHeaderItem.methodIdsOff);
for (int i=0; i < count; i++) {
mMethodIds[i]=new MethodIdItem();
mMethodIds[i].classIdx=readShort() & 0xffff;
mMethodIds[i].protoIdx=readShort() & 0xffff;
mMethodIds[i].nameIdx=readInt();
}
}
| Loads the method ID list. |
public long next(){
moveToNextIndex();
return _hash._set[_index];
}
| Advances the iterator to the next element in the underlying collection and returns it. |
public static void checkState(boolean expression,@Nullable Object errorMessage){
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
| Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method. |
public boolean requiresFreshAST(){
return fRequiresFreshAST;
}
| Tells whether a fresh AST, containing all the changes from previous clean ups, will be needed. |
public BigdataValueSerializer(final ValueFactory valueFactory){
if (valueFactory == null) throw new IllegalArgumentException();
this.valueFactory=valueFactory;
this.uc=new UnicodeHelper(new NoCompressor());
}
| Create an instance that will materialize objects using the caller's factory. |
public final void referencesMustNotBeFrozen(){
if (referencesFrozen) {
throw new CompilerError("referencesMustNotBeFrozen " + this);
}
}
| assertion check |
protected void onPrepareRequest(HttpUriRequest request) throws IOException {
}
| Called before the request is executed using the underlying HttpClient. <p>Overwrite in subclasses to augment the request.</p> |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
public Builder addListenUrl(String url){
if (UrlUtil.isUrl(url)) {
if (mListenUrls == null) {
mListenUrls=new HashSet<String>();
}
mListenUrls.add(url);
}
return this;
}
| add the url for listening |
public String toString(){
StringBuffer buffer=new StringBuffer();
buffer.append("UasDaoLdapUserRecA[");
buffer.append("m_id = ").append(m_id);
buffer.append(", m_ldapGuid = ").append(m_ldapGuid);
buffer.append(", m_ldapFullName = ").append(m_ldapFullName);
buffer.append("]");
return buffer.toString();
}
| toString methode: creates a String representation of the object |
public static <T>void ifPresent(T primary,Consumer<? super T> consumer){
if (primary != null) {
consumer.accept(primary);
}
}
| If primary is non-null, invoke the specified consumer with the value, otherwise do nothing. |
private int mapNSTokens(String pat,int startSubstring,int posOfNSSep,int posOfScan) throws javax.xml.transform.TransformerException {
String prefix="";
if ((startSubstring >= 0) && (posOfNSSep >= 0)) {
prefix=pat.substring(startSubstring,posOfNSSep);
}
String uName;
if ((null != m_namespaceContext) && !prefix.equals("*") && !prefix.equals("xmlns")) {
try {
if (prefix.length() > 0) uName=((PrefixResolver)m_namespaceContext).getNamespaceForPrefix(prefix);
else {
if (false) {
addToTokenQueue(":");
String s=pat.substring(posOfNSSep + 1,posOfScan);
if (s.length() > 0) addToTokenQueue(s);
return -1;
}
else {
uName=((PrefixResolver)m_namespaceContext).getNamespaceForPrefix(prefix);
}
}
}
catch ( ClassCastException cce) {
uName=m_namespaceContext.getNamespaceForPrefix(prefix);
}
}
else {
uName=prefix;
}
if ((null != uName) && (uName.length() > 0)) {
addToTokenQueue(uName);
addToTokenQueue(":");
String s=pat.substring(posOfNSSep + 1,posOfScan);
if (s.length() > 0) addToTokenQueue(s);
}
else {
m_processor.errorForDOM3(XPATHErrorResources.ER_PREFIX_MUST_RESOLVE,new String[]{prefix});
}
return -1;
}
| When a seperator token is found, see if there's a element name or the like to map. |
public void testOneNodeSubmitQueryWithLinearizableConsistency() throws Throwable {
testSubmitQuery(1,Query.ConsistencyLevel.LINEARIZABLE);
}
| Tests submitting a query. |
public LongMap(){
this(32,0.8f);
}
| Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the backing table. |
protected void handleMouseReleased(MouseEvent e){
Object obj=e.getSource();
MapBean map=(MapBean)theMap;
Point firstPoint=this.point1;
Point secondPoint=this.point2;
if (!(obj == map) || !autoZoom || firstPoint == null || secondPoint == null) {
return;
}
Projection projection=map.getProjection();
Proj p=(Proj)projection;
synchronized (this) {
point2=getRatioPoint((MapBean)e.getSource(),firstPoint,e.getPoint());
secondPoint=point2;
int dx=Math.abs(secondPoint.x - firstPoint.x);
int dy=Math.abs(secondPoint.y - firstPoint.y);
if ((dx < 5) || (dy < 5)) {
if ((dx < 5) && (dy < 5)) {
Point2D llp=map.getCoordinates(e);
boolean shift=e.isShiftDown();
boolean control=e.isControlDown();
if (control) {
if (shift) {
p.setScale(p.getScale() * 2.0f);
}
else {
p.setScale(p.getScale() / 2.0f);
}
}
cleanUp();
p.setCenter(llp);
map.setProjection(p);
}
else {
cleanUp();
map.repaint();
}
return;
}
float newScale=com.bbn.openmap.proj.ProjMath.getScale(firstPoint,secondPoint,projection);
int centerx=Math.min(firstPoint.x,secondPoint.x) + dx / 2;
int centery=Math.min(firstPoint.y,secondPoint.y) + dy / 2;
Point2D center=map.inverse(centerx,centery,null);
p.setScale(newScale);
p.setCenter(center);
cleanUp();
map.setProjection(p);
}
}
| Override this method to change what happens when the mouse is released. |
public static String toUpperCase(String src){
if (src == null) {
return null;
}
else {
return src.toUpperCase();
}
}
| Safely convert the string to uppercase. |
public void visitTypeArgument(){
}
| Visits an unbounded type argument of the last visited class or inner class type. |
public boolean isGroupOwner(){
return (groupCapability & GROUP_CAPAB_GROUP_OWNER) != 0;
}
| Returns true if the device is a group owner |
private void processBackwardBranch(int index,int branchtarget){
BasicBlock existingBB, currentBB, newBB;
int newBlockNum, i, newBlockEnd;
existingBB=basicBlocks[byteToBlockMap[branchtarget]];
if (existingBB.getStart() != branchtarget) {
newBB=bbf.newBlock(existingBB.getStart());
addBasicBlock(newBB);
newBlockNum=newBB.getBlockNumber();
existingBB.setStart(branchtarget);
for (i=branchtarget - 1; byteToBlockMap[i] == BasicBlock.NOTBLOCK; i--) {
}
newBlockEnd=i;
newBB.setEnd(i);
for (i=newBB.getStart(); i <= newBlockEnd; i++) {
if (byteToBlockMap[i] != BasicBlock.NOTBLOCK) {
byteToBlockMap[i]=(short)newBlockNum;
}
}
BasicBlock.transferPredecessors(existingBB,newBB);
existingBB.addPredecessor(newBB);
}
else {
}
currentBB=basicBlocks[byteToBlockMap[index]];
existingBB.addPredecessor(currentBB);
}
| A backwards branch has been found from the byte code at location "index" to a target location of "branchtarget". Need to make sure that the branchtarget location is the start of a block (and if not, then split the existing block into two) Need to register the block that ends at "index" as a predecessor of the block that starts at branchtarget. |
public static final String createMessage(String msgKey,Object args[]){
return createMsg(XSLTBundle,msgKey,args);
}
| Creates a message from the specified key and replacement arguments, localized to the given locale. |
@Override public void doSave(IProgressMonitor monitor){
if (!isDirty()) {
return;
}
try {
saveInProgress=true;
monitor.beginTask("Save changes...",1);
try {
monitor.subTask("Save '" + getPartName() + "' changes...");
SaveJob saveJob=new SaveJob();
saveJob.schedule();
Display display=Display.getCurrent();
while (saveJob.finished == null) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.update();
if (!saveJob.finished) {
monitor.setCanceled(true);
return;
}
}
finally {
monitor.done();
}
firePropertyChange(IEditorPart.PROP_DIRTY);
}
finally {
saveInProgress=false;
}
}
| Saves data in all nested editors |
public Object nextEntity(char ampersand) throws JSONException {
StringBuilder sb=new StringBuilder();
for (; ; ) {
char c=next();
if (Character.isLetterOrDigit(c) || c == '#') {
sb.append(Character.toLowerCase(c));
}
else if (c == ';') {
break;
}
else {
throw syntaxError("Missing ';' in XML entity: &" + sb);
}
}
String string=sb.toString();
Object object=entity.get(string);
return object != null ? object : ampersand + string + ";";
}
| Return the next entity. These entities are translated to Characters: <code>& ' > < "</code>. |
public String retryTime(){
if (code == 7100) return retryTime;
return null;
}
| If this does not return <code>null</code>, you need to wait at least until the time returned by this method. |
public static void check(String answer,String path) throws IOException {
String ans=trimTrailingSlashes(answer);
if (path.length() == 0) return;
if (checked.get(path) != null) {
System.err.println("DUP " + path);
return;
}
checked.put(path,path);
String cpath;
try {
File f=new File(path);
cpath=f.getCanonicalPath();
if (f.exists() && f.isFile() && f.canRead()) {
InputStream in=new FileInputStream(path);
in.close();
RandomAccessFile raf=new RandomAccessFile(path,"r");
raf.close();
}
}
catch ( IOException x) {
System.err.println(ans + " <-- " + path+ " ==> "+ x);
if (debug) return;
else throw x;
}
if (cpath.equals(ans)) {
System.err.println(ans + " <== " + path);
}
else {
System.err.println(ans + " <-- " + path+ " ==> "+ cpath+ " MISMATCH");
if (!debug) {
throw new RuntimeException("Mismatch: " + path + " ==> "+ cpath+ ", should be "+ ans);
}
}
}
| Check the given pathname. Its canonical pathname should be the given answer. If the path names a file that exists and is readable, then FileInputStream and RandomAccessFile should both be able to open it. |
int entryCountMod(){
int result=0;
Iterator it=this.entryMods.values().iterator();
while (it.hasNext()) {
TXEntryState es=(TXEntryState)it.next();
result+=es.entryCountMod();
}
return result;
}
| Returns the total number of modifications made by this transaction to this region's entry count. The result will have a +1 for every create and a -1 for every destroy. |
private void processJournal() throws IOException {
deleteIfExists(journalFileTmp);
for (final Iterator<Entry> i=lruEntries.values().iterator(); i.hasNext(); ) {
final Entry entry=i.next();
if (entry.currentEditor == null) {
for (int t=0; t < valueCount; t++) {
size+=entry.lengths[t];
}
}
else {
entry.currentEditor=null;
for (int t=0; t < valueCount; t++) {
deleteIfExists(entry.getCleanFile(t));
deleteIfExists(entry.getDirtyFile(t));
}
i.remove();
}
}
}
| Computes the initial size and collects garbage as a part of opening the cache. Dirty entries are assumed to be inconsistent and will be deleted. |
public Vector minus(Vector v){
Vector result=new Vector(size());
for (int i=0; i < size(); i++) {
result.setValue(i,getValue(i) - v.getValue(i));
}
return result;
}
| Returns the result of vector subtraction. |
@Override public void emitErrorMessage(String pMessage){
if (mMessageCollectionEnabled) {
mMessages.add(pMessage);
}
else {
super.emitErrorMessage(pMessage);
}
}
| Collects an error message or passes the error message to <code> super.emitErrorMessage(...)</code>. <p/> The actual behaviour depends on whether collecting error messages has been enabled or not. |
public static int read(FileDescriptor fd,byte[] bytes,int byteOffset,int byteCount) throws IOException {
Arrays.checkOffsetAndCount(bytes.length,byteOffset,byteCount);
if (byteCount == 0) {
return 0;
}
try {
int readCount=Libcore.os.read(fd,bytes,byteOffset,byteCount);
if (readCount == 0) {
return -1;
}
return readCount;
}
catch ( ErrnoException errnoException) {
if (errnoException.errno == EAGAIN) {
return 0;
}
throw errnoException.rethrowAsIOException();
}
}
| java.io thinks that a read at EOF is an error and should return -1, contrary to traditional Unix practice where you'd read until you got 0 bytes (and any future read would return -1). |
public WallForce(float x1,float y1,float x2,float y2){
this(DEFAULT_GRAV_CONSTANT,x1,y1,x2,y2);
}
| Create a new WallForce with default gravitational constant. |
public Buffer maxDistance(String maxDistance){
this.maxDistance=maxDistance;
return this;
}
| Sets the max allowed distance. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:38:09.153 -0500",hash_original_method="52B4DCA52CE9008BF4F1F47D8B6558D0",hash_generated_method="A1DE28B462D206CC85DA36A53CF4B23D") public int body(String messageId) throws IOException {
return sendCommand(NNTPCommand.BODY,messageId);
}
| A convenience method to send the NNTP BODY command to the server, receive the initial reply, and return the reply code. <p> |
public V put(K key,V value){
m_keys.add(key);
m_values.add(value);
return null;
}
| Put Key & Value |
public static Boolean isTopActivity(Context context,String packageName){
if (context == null || StringUtils.isEmpty(packageName)) {
return null;
}
ActivityManager activityManager=(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasksInfo=activityManager.getRunningTasks(1);
if (ListUtils.isEmpty(tasksInfo)) {
return null;
}
try {
return packageName.equals(tasksInfo.get(0).topActivity.getPackageName());
}
catch ( Exception e) {
e.printStackTrace();
return false;
}
}
| whether the app whost package's name is packageName is on the top of the stack <ul> <strong>Attentions:</strong> <li>You should add <strong>android.permission.GET_TASKS</strong> in manifest</li> </ul> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.