code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int row, col, x, y;
double z;
float progress=0;
int a;
int filterSizeX=3;
int filterSizeY=3;
double n;
double sum;
double sumOfTheSquares;
double average;
double stdDev;
int dX[];
int dY[];
int midPointX;
int midPointY;
int numPixelsInFilter;
boolean filterRounded=false;
double[] filterShape;
boolean reflectAtBorders=false;
double threshold=0;
double centreValue=0;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (int i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
else if (i == 2) {
filterSizeX=Integer.parseInt(args[i]);
}
else if (i == 3) {
filterSizeY=Integer.parseInt(args[i]);
}
else if (i == 4) {
threshold=Double.parseDouble(args[i]);
}
else if (i == 5) {
filterRounded=Boolean.parseBoolean(args[i]);
}
else if (i == 6) {
reflectAtBorders=Boolean.parseBoolean(args[i]);
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r");
inputFile.isReflectedAtEdges=reflectAtBorders;
int rows=inputFile.getNumberRows();
int cols=inputFile.getNumberColumns();
double noData=inputFile.getNoDataValue();
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
outputFile.setPreferredPalette(inputFile.getPreferredPalette());
if (Math.floor(filterSizeX / 2d) == (filterSizeX / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter x-dimension" + " has been modified.");
filterSizeX++;
}
if (Math.floor(filterSizeY / 2d) == (filterSizeY / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter y-dimension" + " has been modified.");
filterSizeY++;
}
numPixelsInFilter=filterSizeX * filterSizeY;
dX=new int[numPixelsInFilter];
dY=new int[numPixelsInFilter];
filterShape=new double[numPixelsInFilter];
midPointX=(int)Math.floor(filterSizeX / 2);
midPointY=(int)Math.floor(filterSizeY / 2);
if (!filterRounded) {
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
filterShape[a]=1;
a++;
}
}
}
else {
double aSqr=midPointX * midPointX;
double bSqr=midPointY * midPointY;
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
z=(dX[a] * dX[a]) / aSqr + (dY[a] * dY[a]) / bSqr;
if (z > 1) {
filterShape[a]=0;
}
else {
filterShape[a]=1;
}
a++;
}
}
}
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
centreValue=inputFile.getValue(row,col);
if (centreValue != noData) {
n=0;
sum=0;
sumOfTheSquares=0;
for (a=0; a < numPixelsInFilter; a++) {
x=col + dX[a];
y=row + dY[a];
if ((x != midPointX) && (y != midPointY)) {
z=inputFile.getValue(y,x);
if (z != noData) {
n+=filterShape[a];
sum+=z * filterShape[a];
sumOfTheSquares+=(z * filterShape[a]) * z;
}
}
}
if (n > 2) {
average=sum / n;
stdDev=(sumOfTheSquares / n) - (average * average);
if (stdDev > 0) {
stdDev=Math.sqrt(stdDev);
}
if (Math.abs((centreValue - average) / stdDev) > threshold) {
outputFile.setValue(row,col,average);
}
else {
outputFile.setValue(row,col,centreValue);
}
}
}
else {
outputFile.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress((int)progress);
}
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. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-24 16:05:57.216 -0400",hash_original_method="29CF94A8D78D7A07450933C1FA54D781",hash_generated_method="456E4A0190C28AE89497DA7AB99F64EE") public void deactivateGLEnvironment(){
GLEnvironment glEnv=mContext.getGLEnvironment();
if (glEnv != null) {
mContext.getGLEnvironment().deactivate();
}
else {
throw new NullPointerException("No GLEnvironment in place to deactivate!");
}
}
| Deactivate the GL environment from use in the current thread. A GL environment must have been previously set or created using setGLEnvironment() or createGLEnvironment()! Call this before running GL filters in another thread. |
public static Field makeFieldModifiable(String field,Class clazz) throws NoSuchFieldException, IllegalAccessException {
try {
Field fieldInstance=getField(field,clazz);
fieldInstance.setAccessible(true);
int modifiers=fieldInstance.getModifiers();
Field modifierField=fieldInstance.getClass().getDeclaredField("modifiers");
modifiers=modifiers & ~Modifier.FINAL;
modifierField.setAccessible(true);
modifierField.setInt(fieldInstance,modifiers);
return fieldInstance;
}
catch ( NoSuchFieldException|IllegalAccessException e) {
LOGGER.error("Could not access field or set value to it",e);
throw e;
}
}
| Makes the field of the given class modifiable |
private String createString(String f){
StringBuilder sb=new StringBuilder();
sb.append("format=" + cudaResourceViewFormat.stringFor(format) + f);
sb.append("width=" + width + f);
sb.append("height=" + height + f);
sb.append("depth=" + depth + f);
sb.append("firstMipmapLevel=" + firstMipmapLevel + f);
sb.append("lastMipmapLevel=" + lastMipmapLevel + f);
sb.append("firstLayer=" + firstLayer + f);
sb.append("lastLayer=" + lastLayer + f);
return sb.toString();
}
| Creates and returns a string representation of this object, using the given separator for the fields |
public static String readFileContents(IPath path) throws IOException {
File file=new File(path.toOSString());
return readFileContents(file);
}
| Reads the contents of a file. |
public Crop withWidth(int width){
cropIntent.putExtra(Extra.MAX_WIDTH,width);
return this;
}
| Set maximum crop size |
public static Map<String,Object> curryDelegateAndGetContent(Closure<?> c,Object o){
JsonDelegate delegate=new JsonDelegate();
Closure<?> curried=c.curry(o);
curried.setDelegate(delegate);
curried.setResolveStrategy(Closure.DELEGATE_FIRST);
curried.call();
return delegate.getContent();
}
| Factory method for creating <code>JsonDelegate</code>s from closures currying an object argument. |
@Override public void onClick(AjaxRequestTarget aTarget){
editor.reset(aTarget);
List<SourceDocument> listOfSourceDocuements=getListOfDocs();
int currentDocumentIndex=listOfSourceDocuements.indexOf(bModel.getDocument());
if (currentDocumentIndex == 0) {
aTarget.appendJavaScript("alert('This is the first document!')");
return;
}
bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex - 1).getName());
bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1));
loadDocumentAction(aTarget);
}
| Get the current beginning sentence address and add on it the size of the display window |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:12.192 -0500",hash_original_method="B19BAB1EEF674556A3A9CC47CD14FB0B",hash_generated_method="A4A93DB84096F87B82DB777B3CD75A12") private void updateVisitedHistory(String url,boolean isReload){
mCallbackProxy.doUpdateVisitedHistory(url,isReload);
}
| Tell the activity to update its global history. |
public void addParameter(DoubleParameter param,Distribution dist){
if (param == null) throw new IllegalArgumentException("null not allowed for parameter");
searchParams.add(param);
searchValues.add(dist.clone());
}
| Adds a new double parameter to be altered for the model being tuned. |
public static int abs(final int x){
final int i=x >>> 31;
return (x ^ (~i + 1)) + i;
}
| Absolute value. |
public void arrange(ArrayList<Integer> A){
int N=A.size();
for (int i=0; i < N; i++) {
int num=A.get(i);
int B=num;
int C=A.get(num);
if (C >= N) {
C=A.get(num) % N;
}
int encode=B + C * N;
A.set(i,encode);
}
for (int i=0; i < N; i++) {
A.set(i,A.get(i) / N);
}
}
| Store two numbers in one index using tricks. A = B + C * N; <=> B = A % N, C = A / N; |
public long duration(){
return (endTime - startTime) / 1000;
}
| Which duration the data in this stats covers. This is not necessarily the whole duration that was worked with (e.g. if the stream went offline at the end, that data may not be included). This is the range between the first and last valid data point. |
private Graphics2D createSVGGraphics2D(int w,int h){
try {
Class<?> svgGraphics2d=Class.forName("org.jfree.graphics2d.svg.SVGGraphics2D");
Constructor<?> ctor=svgGraphics2d.getConstructor(int.class,int.class);
return (Graphics2D)ctor.newInstance(w,h);
}
catch ( ClassNotFoundException ex) {
return null;
}
catch ( NoSuchMethodException ex) {
return null;
}
catch ( SecurityException ex) {
return null;
}
catch ( InstantiationException ex) {
return null;
}
catch ( IllegalAccessException ex) {
return null;
}
catch ( IllegalArgumentException ex) {
return null;
}
catch ( InvocationTargetException ex) {
return null;
}
}
| This is copied from JFreeChart's ChartPanel class (version 1.0.19). |
private static Method findMethod(Object instance,String name,Class<?>... parameterTypes) throws NoSuchMethodException {
for (Class<?> clazz=instance.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
try {
Method method=clazz.getDeclaredMethod(name,parameterTypes);
if (!method.isAccessible()) {
method.setAccessible(true);
}
return method;
}
catch ( NoSuchMethodException e) {
}
}
throw new NoSuchMethodException("Method " + name + " with parameters "+ Arrays.asList(parameterTypes)+ " not found in "+ instance.getClass());
}
| Locates a given method anywhere in the class inheritance hierarchy. |
void update(final byte[] input){
md5.update(input);
}
| Update by adding a complete array |
private void updateProgress(String progressLabel,int progress){
if (myHost != null) {
myHost.updateProgress(progressLabel,progress);
}
else {
System.out.println(progressLabel + " " + progress+ "%");
}
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
void registerAnimatedInternal(Animation cmp){
if (internalAnimatableComponents == null) {
internalAnimatableComponents=new ArrayList<Animation>();
}
if (!internalAnimatableComponents.contains(cmp)) {
internalAnimatableComponents.add(cmp);
}
Display.getInstance().notifyDisplay();
}
| Identical to the none-internal version, the difference between the internal/none-internal is that it references a different vector that is unaffected by the user actions. That is why we can dynamically register/deregister without interfering with user interaction. |
private void initRasterProgram(){
glUseProgram(rasterProgram);
viewMatrixUniform=glGetUniformLocation(rasterProgram,"viewMatrix");
projectionMatrixUniform=glGetUniformLocation(rasterProgram,"projectionMatrix");
glUseProgram(0);
}
| Initialize the raster program. |
int chunkSize(){
return mChunkSize;
}
| Get the chunk size. Should only be used for testing. |
@Override public String toString(){
return ("epanechnikov(s=" + sigma + ",d="+ degree+ ")");
}
| Output as String |
public static byte[] toBytes(int data){
return new byte[]{(byte)((data >> 24) & 0xff),(byte)((data >> 16) & 0xff),(byte)((data >> 8) & 0xff),(byte)((data >> 0) & 0xff)};
}
| Converts an int to a byte array with 4 elements. Used to put ints into a byte[] payload in a convenient and fast way by shifting without using streams (which is kind of slow). <br/> Taken from http://www.daniweb.com/code/snippet216874.html |
public void released(){
released(-1,-1);
}
| Invoked to change the state of the button to the released state |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
private void removeGCTrace(){
int index=getSelectedRow();
if (index > -1) {
assert 0 <= index && index < gcTraceSet.size();
GCTrace gcTrace=gcTraceSet.findGCTrace(index);
gcTraceSet.remove(gcTrace.getName());
if (gcTraceSet.size() > 0) {
if (index < gcTraceSet.size()) {
setSelectedRow(index);
}
else {
assert index == gcTraceSet.size();
setSelectedRow(index - 1);
}
}
}
}
| It removes the currently selected GC trace. |
public String completeState(){
StringBuilder builder=new StringBuilder();
args.asMap().forEach(null);
return builder.toString();
}
| Writes out the entire state of this argsbuilder to a string. This can be used to determine if the arguments have changed at all, to aid in staleness checking. If you extend EclipseArgsBuilder and add any kinds of new state (e.g. EclipseAntArgsBuilder), then you *must* override this method and embed all internal state within it. |
private static void validateFieldName(String fieldName){
if (fieldName == null) {
throw new NullPointerException("fieldName is null");
}
if (fieldName.length() == 0) {
throw new IllegalArgumentException("fieldName is empty");
}
}
| Ensures that a given field name is valid. Used as a helper for methods that have that precondition. |
final public MutableString insert(final int index,final double d){
return insert(index,String.valueOf(d));
}
| Inserts a double in this mutable string, starting from index <code>index</code>. |
private static int intValue(String key,Map<String,Object> params,int dfltVal) throws IgniteCheckedException {
assert key != null;
String val=(String)params.get(key);
try {
return val == null ? dfltVal : Integer.parseInt(val);
}
catch ( NumberFormatException ignore) {
throw new IgniteCheckedException("Failed to parse parameter of Integer type [" + key + "="+ val+ "]");
}
}
| Retrieves int value from parameters map. |
public void test4(){
final JPanel panel=new JPanel(new GridLayoutManager(3,1,new Insets(0,0,0,0),0,7));
final JButton btn1=new JButton();
btn1.setPreferredSize(new Dimension(100,20));
final JButton btn2=new JButton();
btn2.setPreferredSize(new Dimension(100,20));
panel.add(btn1,new GridConstraints(0,0,1,1,GridConstraints.ANCHOR_CENTER,GridConstraints.FILL_HORIZONTAL,GridConstraints.SIZEPOLICY_CAN_GROW,GridConstraints.SIZEPOLICY_FIXED,null,null,null,0));
panel.add(btn2,new GridConstraints(2,0,1,1,GridConstraints.ANCHOR_CENTER,GridConstraints.FILL_HORIZONTAL,GridConstraints.SIZEPOLICY_CAN_GROW,GridConstraints.SIZEPOLICY_FIXED,null,null,null,0));
final Dimension preferredSize=panel.getPreferredSize();
if (SystemInfo.isMac) {
assertEquals(65,preferredSize.height);
}
else {
assertEquals(47,preferredSize.height);
}
panel.setSize(panel.getPreferredSize());
panel.doLayout();
}
| btn1 ----- empty ---- btn2 |
public static Integer[] transformIntArray(int[] source){
Integer[] destin=new Integer[source.length];
for (int i=0; i < source.length; i++) {
destin[i]=source[i];
}
return destin;
}
| convert int array to Integer array |
@JsonCreator public ClockEntry(@JsonProperty("nodeId") short nodeId,@JsonProperty("version") long version){
if (nodeId < 0) throw new IllegalArgumentException("Node id " + nodeId + " is not in the range (0, "+ Short.MAX_VALUE+ ").");
if (version < 1) throw new IllegalArgumentException("Version " + version + " is not in the range (1, "+ Short.MAX_VALUE+ ").");
this.nodeId=nodeId;
this.version=version;
}
| Create a new Version from constituate parts |
public Boolean isCloseOnPowerOffOrSuspend(){
return closeOnPowerOffOrSuspend;
}
| Gets the value of the closeOnPowerOffOrSuspend property. |
public static void main(String[] args){
if (args.length != 9) {
throw new RuntimeException("Must provide 9 field arguments: filename, startLine, outputfolder and the field locations for VehId, Time, Long, Lat, Status and Speed.");
}
log.info("=================================================================");
log.info(" Splitting the DigiCore data file into seperate vehicle files.");
log.info("=================================================================");
DigicoreFileSplitter dfs=new DigicoreFileSplitter(args[0],args[1],Long.parseLong(args[2]));
dfs.split(Integer.parseInt(args[3]),Integer.parseInt(args[4]),Integer.parseInt(args[5]),Integer.parseInt(args[6]),Integer.parseInt(args[7]),Integer.parseInt(args[8]));
GregorianCalendar first=new GregorianCalendar(TimeZone.getTimeZone("GMT+02"),Locale.ENGLISH);
first.setTimeInMillis(dfs.getEarliestTimestamp() * 1000);
GregorianCalendar last=new GregorianCalendar(TimeZone.getTimeZone("GMT+02"),Locale.ENGLISH);
last.setTimeInMillis(dfs.getLatestTimestamp() * 1000);
log.info("-----------------------------------------------------------------");
log.info(" Process complete.");
log.info("-----------------------------------------------------------------");
log.info(" Earliest date parsed: " + dfs.calendarToString(first));
log.info(" Latest date parsed: " + dfs.calendarToString(last));
log.info("=================================================================");
}
| This class processes a single file provided by DigiCore holdings, <code>Poslog_Research_Data.txt</code>, and split it into separate files, one for each vehicle. The main method creates a file splitter, and splits the entire file. <h4> Process </h4> <p>A single line is read from the input file (comma delimited), and die vehicle ID is determined. The associated vehicle file is opened (with amending privileges), and the line is added (again comma delimited) to the vehicle file. In an attempt to save time, I've implemented the reading such that the next line is also read. If the new line relates to the same vehicle, the vehicle file is kept open. Otherwise, the file is closed, and the new vehicle file is opened.</p> <br>Since the process runs over multiple days, and interruptions during the process can lead to lost time, a <i>safety mechanism</i> has been employed: after every line read, the total number of lines read (and processed) is written to a text file named <code>logRecordsRead_*.txt</code> where <code>`*'</code> denotes the time stamp (in seconds) when the process started. This gives the user flexibility in terms of which line of the input files should be processed first. An interrupted job can then be easily <i>continued</i> by just checking what the last line was that was processed in the terminated run. |
public static Complex ComplexFromPolar(double r,double phi){
return new Complex(r * Math.cos(phi),r * Math.sin(phi));
}
| Instantiates a new complex number object from polar representation parameters. |
@After public void cleanEnv() throws IOException {
try {
FileUtils.deleteDirectory(localTempPath.toFile());
S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto=s3DaoTestHelper.getTestS3FileTransferRequestParamsDto();
s3FileTransferRequestParamsDto.setS3KeyPrefix(testS3KeyPrefix);
s3Dao.deleteDirectory(s3FileTransferRequestParamsDto);
}
catch ( Exception ex) {
LOGGER.warn("Unable to cleanup environment.",ex);
}
}
| Cleans up the local temp directory and S3 test path that we are using. |
public void query(String structuredQuery) throws IOException, ServiceException {
RecordQuery query=new RecordQuery(recordsFeedUrl);
query.setSpreadsheetQuery(structuredQuery);
RecordFeed feed=service.query(query,RecordFeed.class);
out.println("Results for [" + structuredQuery + "]");
for ( RecordEntry entry : feed.getEntries()) {
printAndCacheEntry(entry);
}
}
| Performs a full database-like query on the records. |
public EaseOut(){
}
| Easing equation function for a cubic (t^3) easing out: decelerating from zero velocity. |
public void engineSetProperty(String key,String value){
if (properties == null) {
properties=new HashMap<String,String>();
}
properties.put(key,value);
}
| Method engineSetProperty |
public static Boolean evaluate(boolean defaultValue,List<Pair<StringPatternSet,Boolean>> patterns,String literal){
boolean result=defaultValue;
for ( Pair<StringPatternSet,Boolean> item : patterns) {
if (result) {
if (!item.getSecond()) {
boolean testResult=item.getFirst().match(literal);
if (testResult) {
result=false;
}
}
}
else {
if (item.getSecond()) {
boolean testResult=item.getFirst().match(literal);
if (testResult) {
result=true;
}
}
}
}
return result;
}
| Executes a seriers of include/exclude patterns against a match string, returning the last pattern match result as boolean in/out. |
public Distribution(double[] values){
addAll(values);
}
| Creates a distribution containing the values of <tt>values</tt>. |
public void testDurableTopicRollbackMarksMessageRedelivered() throws JMSException {
connection.setClientID(getName());
connection.start();
Session session=connection.createSession(true,Session.CLIENT_ACKNOWLEDGE);
Topic topic=session.createTopic("topic-" + getName());
MessageConsumer consumer=session.createDurableSubscriber(topic,"sub1");
MessageProducer producer=createProducer(session,topic);
producer.send(createTextMessage(session));
session.commit();
Message msg=consumer.receive(1000);
assertNotNull(msg);
assertFalse("Message should not be redelivered.",msg.getJMSRedelivered());
session.rollback();
msg=consumer.receive(2000);
assertNotNull(msg);
assertTrue("Message should be redelivered.",msg.getJMSRedelivered());
session.commit();
session.close();
}
| Tests rollback message to be marked as redelivered. Session uses client acknowledgement and the destination is a topic. |
private void newline(Writer out) throws IOException {
out.write(lineSeparator);
}
| This will print a new line only if the newlines flag was set to true. |
private boolean puedeSerEnviada(PrevisionVO prevision){
boolean puedeSerEnviada=false;
if (prevision.getEstado() == EstadoPrevision.ABIERTA.getIdentificador()) {
if (prevision.isDetallada()) {
if (numeroDetallesPrevision(prevision.getId()) > 0) puedeSerEnviada=true;
else errorCode=ArchivoErrorCodes.PREVISION_DETALLADA_SIN_DETALLES;
}
else puedeSerEnviada=true;
}
else errorCode=ArchivoErrorCodes.PREVISION_NO_ABIERTA;
return puedeSerEnviada;
}
| Comprueba si una prevision puede ser enviada |
private void updateCrc(Buffer buffer,long offset,long byteCount){
Segment s=buffer.head;
for (; offset >= (s.limit - s.pos); s=s.next) {
offset-=(s.limit - s.pos);
}
for (; byteCount > 0; s=s.next) {
int pos=(int)(s.pos + offset);
int toUpdate=(int)Math.min(s.limit - pos,byteCount);
crc.update(s.data,pos,toUpdate);
byteCount-=toUpdate;
offset=0;
}
}
| Updates the CRC with the given bytes. |
public static List<String> parseArguments(String functionCall) throws FBSQLParseException {
functionCall=functionCall.trim();
checkSyntax(functionCall);
final int parenthesisStart=functionCall.indexOf('(');
if (parenthesisStart == -1) {
return Collections.emptyList();
}
final String paramsString=functionCall.substring(parenthesisStart + 1,functionCall.length() - 1);
final List<String> params=new ArrayList<String>();
final StringBuilder sb=new StringBuilder();
boolean inQuotes=false;
boolean inDoubleQuotes=false;
boolean coalesceSpace=true;
int nestedParentheses=0;
for (int i=0, n=paramsString.length(); i < n; i++) {
char currentChar=paramsString.charAt(i);
if (Character.isWhitespace(currentChar)) {
if (inQuotes || inDoubleQuotes) {
sb.append(currentChar);
}
else if (!coalesceSpace) {
sb.append(' ');
coalesceSpace=true;
}
continue;
}
switch (currentChar) {
case '\'':
sb.append(currentChar);
if (!inDoubleQuotes) inQuotes=!inQuotes;
coalesceSpace=false;
break;
case '"':
sb.append(currentChar);
if (!inQuotes) inDoubleQuotes=!inDoubleQuotes;
coalesceSpace=false;
break;
case '(':
if (!(inQuotes || inDoubleQuotes)) {
nestedParentheses++;
}
sb.append('(');
coalesceSpace=false;
break;
case ')':
if (!(inQuotes || inDoubleQuotes)) {
nestedParentheses--;
if (nestedParentheses < 0) {
throw new FBSQLParseException("Unbalanced parentheses in parameters at position " + i);
}
}
sb.append(')');
coalesceSpace=false;
break;
case ',':
if (inQuotes || inDoubleQuotes || nestedParentheses > 0) {
sb.append(currentChar);
}
else {
params.add(sb.toString());
sb.setLength(0);
coalesceSpace=true;
}
break;
default :
sb.append(currentChar);
coalesceSpace=false;
}
}
if (sb.length() > 0) params.add(sb.toString());
if (inQuotes || inDoubleQuotes) {
throw new FBSQLParseException("String literal is not properly closed.");
}
if (nestedParentheses != 0) {
throw new FBSQLParseException("Unbalanced parentheses in parameters.");
}
return params;
}
| Extract function arguments from the function call. This method parses escaped function call string and extracts function parameters from it. |
public static void validateExperimentalMode(){
if (System.getProperty("EXPERIMENTAL") == null) throw new UnsupportedOperationException("Work in progress");
}
| This method to validate whether code is being run in experimental mode or not |
public static Test suite(){
return (new TestSuite(ConverterTagTestCase.class));
}
| Return the tests include |
private boolean putSource(int swfIndex,int moduleId,int bitmap,String name,String text,int isolateId){
Map<Integer,DModule> source=getIsolateState(isolateId).m_source;
synchronized (source) {
if (!source.containsKey(moduleId)) {
DModule s=new DModule(this,moduleId,bitmap,name,text,isolateId);
source.put(moduleId,s);
DSwfInfo swf;
if (swfIndex == -1) swf=getActiveSwfInfo(isolateId);
else swf=getOrCreateSwfInfo(swfIndex,isolateId);
swf.addSource(moduleId,s);
return true;
}
return false;
}
}
| Record a new source file. |
public static Geometry combine(Collection geoms){
GeometryCombiner combiner=new GeometryCombiner(geoms);
return combiner.combine();
}
| Combines a collection of geometries. |
public static void UF7(double[] x,double[] f,int nx){
int count1=0;
int count2=0;
double sum1=0.0;
double sum2=0.0;
double yj;
for (int j=2; j <= nx; j++) {
yj=x[j - 1] - Math.sin(6.0 * PI * x[0] + j * PI / nx);
if (j % 2 == 0) {
sum2+=yj * yj;
count2++;
}
else {
sum1+=yj * yj;
count1++;
}
}
yj=Math.pow(x[0],0.2);
f[0]=yj + 2.0 * sum1 / (double)count1;
f[1]=1.0 - yj + 2.0 * sum2 / (double)count2;
}
| Evaluates the UF7 problem. |
CopticDate(int prolepticYear,int month,int dayOfMonth){
CopticChronology.MOY_RANGE.checkValidValue(month,MONTH_OF_YEAR);
ValueRange range;
if (month == 13) {
range=CopticChronology.INSTANCE.isLeapYear(prolepticYear) ? CopticChronology.DOM_RANGE_LEAP : CopticChronology.DOM_RANGE_NONLEAP;
}
else {
range=CopticChronology.DOM_RANGE;
}
range.checkValidValue(dayOfMonth,DAY_OF_MONTH);
this.prolepticYear=prolepticYear;
this.month=(short)month;
this.day=(short)dayOfMonth;
}
| Creates an instance. |
Item newItfMethod(final String ownerItf,final String name,final String desc){
key3.set(IMETH,ownerItf,name,desc);
Item result=get(key3);
if (result == null) {
put122(IMETH,newClass(ownerItf).index,newNameType(name,desc).index);
result=new Item(index++,key3);
put(result);
}
return result;
}
| Adds an interface method reference to the constant pool of the class being build. Does nothing if the constant pool already contains a similar item. |
public void putString(String key,String value){
map.put(key,value);
}
| Inserts a String value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. |
public final synchronized void newGame(GameMode gameMode,TimeControlData tcData){
boolean updateGui=abortSearch();
if (updateGui) updateGUI();
this.gameMode=gameMode;
if (computerPlayer == null) {
computerPlayer=new DroidComputerPlayer(gui.getContext(),listener);
computerPlayer.setBookOptions(bookOptions);
computerPlayer.setEngineOptions(engineOptions);
}
computerPlayer.queueStartEngine(searchId,engine);
searchId++;
game=new Game(gameTextListener,tcData);
computerPlayer.uciNewGame();
setPlayerNames(game);
updateGameMode();
}
| Start a new game. |
public void loadLocal(final int local,final Type type){
setLocalType(local,type);
loadInsn(type,local);
}
| Generates the instruction to load the given local variable on the stack. |
public AboutDialog(){
initComponents();
}
| Creates new form ConvertDialog |
public FrameworkException(String message,Throwable cause){
super(message,cause);
}
| Constructs a new framework exception with the specified message and cause. |
private Map<Double,Map<Id<Link>,Double>> convertMapToDoubleValues(Map<Double,Map<Id<Link>,Integer>> time2Counts1){
Map<Double,Map<Id<Link>,Double>> mapOfDoubleValues=new HashMap<>();
for ( Double endOfTimeInterval : time2Counts1.keySet()) {
Map<Id<Link>,Integer> linkId2Value=time2Counts1.get(endOfTimeInterval);
Map<Id<Link>,Double> linkId2DoubleValue=new HashMap<>();
for ( Id<Link> linkId : linkId2Value.keySet()) {
int intValue=linkId2Value.get(linkId);
double doubleValue=intValue;
double linkLength_km=this.scenario.getNetwork().getLinks().get(linkId).getLength() / 1000.;
double vehicleKm=doubleValue * linkLength_km;
linkId2DoubleValue.put(linkId,vehicleKm);
}
mapOfDoubleValues.put(endOfTimeInterval,linkId2DoubleValue);
}
return mapOfDoubleValues;
}
| Is this really necessary?! AN |
public boolean hasSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException {
Set<ClassDescriptor> subtypes=getDirectSubtypes(classDescriptor);
if (DEBUG) {
System.out.println("Direct subtypes of " + classDescriptor + " are "+ subtypes);
}
return !subtypes.isEmpty();
}
| Determine whether or not the given class has any known subtypes. |
public static <T>String[] toStringArray(Sequence<T> sequence){
String[] tokens=new String[sequence.size()];
for (int i=0, sz=sequence.size(); i < sz; ++i) tokens[i]=sequence.get(i).toString();
return tokens;
}
| Convert a sequence to an array of Strings. |
public static double sqrt(long n){
long lastGuess=1;
long nextGuess=(lastGuess + n / lastGuess) / 2;
while (nextGuess - lastGuess > 0.0001) {
lastGuess=nextGuess;
nextGuess=(lastGuess + n / lastGuess) / 2;
}
lastGuess=nextGuess;
return nextGuess=(lastGuess + n / lastGuess) / 2;
}
| Method squrt approximates the square root of n |
public void addProperty(String property,Character value){
add(property,createJsonElement(value));
}
| Convenience method to add a char member. The specified value is converted to a JsonPrimitive of Character. |
protected void callChildVisitors(XSLTVisitor visitor,boolean callAttrs){
if (callAttrs) m_selectExpression.getExpression().callVisitors(m_selectExpression,visitor);
super.callChildVisitors(visitor,callAttrs);
}
| Call the children visitors. |
public BadLocationException(String message){
super(message);
}
| Creates a new bad location exception. |
public Action chooseAction(Map<Direction,Occupant> neighbors){
List<Direction> empties=getNeighborsOfType(neighbors,"empty");
if (empties.size() == 1) {
Direction moveDir=empties.get(0);
return new Action(Action.ActionType.MOVE,moveDir);
}
if (empties.size() > 1) {
if (HugLifeUtils.random() < moveProbability) {
Direction moveDir=HugLifeUtils.randomEntry(empties);
return new Action(Action.ActionType.MOVE,moveDir);
}
}
return new Action(Action.ActionType.STAY);
}
| Sample Creatures take actions according to the following rules about NEIGHBORS: 1. If surrounded on three sides, move into the empty space. 2. Otherwise, if there are any empty spaces, move into one of them with probabiltiy given by moveProbability. 3. Otherwise, stay. Returns the action selected. |
public static final Criterion bodyContains(String value){
return new TextCriterion(value,Scope.BODY);
}
| Creates a filter matching messages which contains the given text within the body. Implementations may choose to ignore mime parts which cannot be decoded to text. All to-compared Strings MUST BE converted to uppercase before doing so (this also include the search value) |
public void disconnected(){
m_isHalted=false;
m_isConnected=false;
m_manager.disconnected();
}
| Issued when the socket connection to the player is cut |
public static void addNewMapping(final Class<?> type,final String property,final String mapping){
if (allowedColmns.get(type) == null) {
allowedColmns.put(type,new HashMap<String,String>());
}
allowedColmns.get(type).put(property,mapping);
}
| Add new mapping - property name and alias. |
public static void severe(final String message,final Object... objects){
NaviLogger.severe(message,objects);
}
| Logs a string at log level SEVERE. |
private static List<SiteVerificationWebResourceResource> listOwnedSites(SiteVerification siteVerification) throws IOException {
SiteVerification.WebResource.List listRequest=siteVerification.webResource().list();
SiteVerificationWebResourceListResponse listResponse=listRequest.execute();
return listResponse.getItems();
}
| This method demonstrates an example of a <a href= 'https://code.google.com/apis/siteverification/v1/reference.html#method_siteVerification_webResource_list'>List</a> call. |
public static List<? extends SearchResult> crawlTorrent(SearchPerformer performer,TorrentCrawlableSearchResult sr,byte[] data,boolean detectAlbums){
List<TorrentCrawledSearchResult> list=new LinkedList<TorrentCrawledSearchResult>();
if (data == null) {
return list;
}
TorrentInfo ti=null;
try {
ti=TorrentInfo.bdecode(data);
}
catch ( Throwable t) {
LOG.error("Can't bdecode:\n" + new String(data) + "\n\n");
throw t;
}
int numFiles=ti.numFiles();
FileStorage fs=ti.files();
for (int i=0; !performer.isStopped() && i < numFiles; i++) {
if (fs.padFileAt(i)) {
continue;
}
list.add(new TorrentCrawledSearchResult(sr,ti,i,fs.filePath(i),fs.fileSize(i)));
}
if (detectAlbums) {
List<SearchResult> temp=new LinkedList<SearchResult>();
temp.addAll(list);
temp.addAll(new AlbumCluster().detect(sr,list));
return temp;
}
else {
return list;
}
}
| This method is only public allow reuse inside the package search, consider it a private API |
private void initUnconfirmedTab(){
if (m_modelUnconfirmed != null) return;
Vector<String> columnNames=new Vector<String>();
columnNames.add(Msg.translate(Env.getCtx(),m_C_BPartner_ID == 0 ? "C_BPartner_ID" : "M_Product_ID"));
columnNames.add(Msg.translate(Env.getCtx(),"MovementQty"));
columnNames.add(Msg.translate(Env.getCtx(),"MovementDate"));
columnNames.add(Msg.translate(Env.getCtx(),"IsSOTrx"));
columnNames.add(Msg.translate(Env.getCtx(),"DocumentNo"));
columnNames.add(Msg.translate(Env.getCtx(),"M_Warehouse_ID"));
String sql=null;
int parameter=0;
if (m_C_BPartner_ID == 0) {
sql="SELECT bp.Name," + " CASE WHEN io.IsSOTrx='Y' THEN iol.MovementQty*-1 ELSE iol.MovementQty END AS MovementQty," + " io.MovementDate,io.IsSOTrx,"+ " dt.PrintName || ' ' || io.DocumentNo As DocumentNo,"+ " w.Name "+ "FROM M_InOutLine iol"+ " INNER JOIN M_InOut io ON (iol.M_InOut_ID=io.M_InOut_ID)"+ " INNER JOIN C_BPartner bp ON (io.C_BPartner_ID=bp.C_BPartner_ID)"+ " INNER JOIN C_DocType dt ON (io.C_DocType_ID=dt.C_DocType_ID)"+ " INNER JOIN M_Warehouse w ON (io.M_Warehouse_ID=w.M_Warehouse_ID)"+ " INNER JOIN M_InOutLineConfirm lc ON (iol.M_InOutLine_ID=lc.M_InOutLine_ID) "+ "WHERE iol.M_Product_ID=?"+ " AND lc.Processed='N' "+ "ORDER BY io.MovementDate,io.IsSOTrx";
parameter=m_M_Product_ID;
}
else {
sql="SELECT p.Name," + " CASE WHEN io.IsSOTrx='Y' THEN iol.MovementQty*-1 ELSE iol.MovementQty END AS MovementQty," + " io.MovementDate,io.IsSOTrx,"+ " dt.PrintName || ' ' || io.DocumentNo As DocumentNo,"+ " w.Name "+ "FROM M_InOutLine iol"+ " INNER JOIN M_InOut io ON (iol.M_InOut_ID=io.M_InOut_ID)"+ " INNER JOIN M_Product p ON (iol.M_Product_ID=p.M_Product_ID)"+ " INNER JOIN C_DocType dt ON (io.C_DocType_ID=dt.C_DocType_ID)"+ " INNER JOIN M_Warehouse w ON (io.M_Warehouse_ID=w.M_Warehouse_ID)"+ " INNER JOIN M_InOutLineConfirm lc ON (iol.M_InOutLine_ID=lc.M_InOutLine_ID) "+ "WHERE io.C_BPartner_ID=?"+ " AND lc.Processed='N' "+ "ORDER BY io.MovementDate,io.IsSOTrx";
parameter=m_C_BPartner_ID;
}
Vector<Vector<Object>> data=new Vector<Vector<Object>>();
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
pstmt=DB.prepareStatement(sql,null);
pstmt.setInt(1,parameter);
rs=pstmt.executeQuery();
while (rs.next()) {
Vector<Object> line=new Vector<Object>(6);
line.add(rs.getString(1));
line.add(new Double(rs.getDouble(2)));
line.add(rs.getTimestamp(3));
line.add(new Boolean("Y".equals(rs.getString(4))));
line.add(rs.getString(5));
line.add(rs.getString(6));
data.add(line);
}
}
catch ( SQLException e) {
log.log(Level.SEVERE,sql,e);
}
finally {
DB.close(rs,pstmt);
rs=null;
pstmt=null;
}
log.fine("#" + data.size());
m_modelUnconfirmed=new ListModelTable(data);
m_tableUnconfirmed.setData(m_modelUnconfirmed,columnNames);
m_tableUnconfirmed.setColumnClass(0,String.class,true);
m_tableUnconfirmed.setColumnClass(1,Double.class,true);
m_tableUnconfirmed.setColumnClass(2,Timestamp.class,true);
m_tableUnconfirmed.setColumnClass(3,Boolean.class,true);
m_tableUnconfirmed.setColumnClass(4,String.class,true);
m_tableUnconfirmed.autoSize();
}
| Query Unconfirmed |
@Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAddButton=(ImageButton)findViewById(R.id.addButton);
mContactAddressMapper=new ContactAddressMapper(this);
}
| Hook method called when a new instance of Activity is created. One time initialization code goes here, e.g., UI layout. |
public FilteredExperienceDelayHandler(final Scenario scenario,final int noOfTimeBins,final String userGroup,final PersonFilter personFilter){
this(scenario,noOfTimeBins,userGroup,personFilter,null);
LOGGER.info("Usergroup filtering is used, result will include all links but persons from given user group only.");
}
| User group filtering will be used, result will include all links but persons from given user group only. |
public void scheduleCommitWithin(long commitMaxTime){
_scheduleCommitWithin(commitMaxTime);
}
| schedule individual commits |
private int findAppIndex(String appName){
int index=-1;
for (int i=0; i < appUsages.size(); i++) {
if (appUsages.get(i).getAppName().equals(appName)) {
index=i;
}
}
return index;
}
| Given the app name, find the index of the app in the uasages list If not there, return -1 |
public void createPictScenario09() throws Exception {
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-02-28 00:00:00"));
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-01 00:00:00"));
String supplierAdminId="Pict09Supplier";
VOOrganization supplier=orgSetup.createOrganization(basicSetup.getPlatformOperatorUserKey(),supplierAdminId,"Pict09SupplierOrg",TestOrganizationSetup.ORGANIZATION_DOMICILE_DE,OrganizationRoleType.TECHNOLOGY_PROVIDER,OrganizationRoleType.SUPPLIER);
VOUser supplierAdmin=orgSetup.getUser(supplierAdminId,true);
VOMarketplace supplMarketplace=orgSetup.createMarketplace("Pict09Supplier_MP",false,supplier);
paymentSetup.createPaymentForSupplier(basicSetup.getPlatformOperatorUserKey(),supplierAdmin.getKey(),supplier);
container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER,ROLE_TECHNOLOGY_MANAGER);
serviceSetup.importTechnicalServices(BaseAdmUmTest.TECHNICAL_SERVICE_EXAMPLE2_ASYNC_XML);
VOTechnicalService example2TechService=serviceSetup.getTechnicalService(VOTechServiceFactory.TECH_SERVICE_EXAMPLE2_ASYNC_ID);
setCutOffDay(supplierAdmin.getKey(),1);
String customerAdminId="PIC09Customer";
VOOrganization customer=orgSetup.registerCustomer("PIC09CustomerOrg",TestOrganizationSetup.ORGANIZATION_DOMICILE_UK,customerAdminId,supplMarketplace.getMarketplaceId(),supplier.getOrganizationId());
VOUser customerAdmin=orgSetup.getUser(customerAdminId,true);
orgSetup.createMarketingPermission(supplierAdmin.getKey(),supplier.getOrganizationId(),example2TechService);
VOServiceDetails unitServTemplate=serviceSetup.createAndPublishMarketableService(supplierAdmin.getKey(),"PICT09_PERUNIT_SERVICE",TestService.EXAMPLE2_ASYNC,TestPriceModel.EXAMPLE_PICT09_UNIT_HOUR,example2TechService,supplierMarketplace);
VOServiceDetails freeTemplate=serviceSetup.createAndPublishMarketableService(supplierAdmin.getKey(),"PICT09_FREE",TestService.EXAMPLE2_ASYNC,TestPriceModel.FREE,example2TechService,supplierMarketplace);
unitServTemplate=serviceSetup.registerCompatibleServices(supplierAdmin.getKey(),unitServTemplate,freeTemplate);
freeTemplate=serviceSetup.registerCompatibleServices(supplierAdmin.getKey(),freeTemplate,unitServTemplate);
VOServiceDetails serviceDetails=serviceSetup.activateMarketableService(unitServTemplate);
VOServiceDetails serviceFreeDetails=serviceSetup.activateMarketableService(freeTemplate);
VORoleDefinition role=VOServiceFactory.getRole(serviceDetails,"ADMIN");
container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN);
VOSubscriptionDetails subDetails=subscrSetup.subscribeToService("PICT_TEST_09",serviceDetails,customerAdmin,role);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-01 00:00:00"));
subDetails=subscrSetup.completeAsyncSubscription(supplierAdmin.getKey(),customerAdmin,subDetails);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-10 13:00:00"));
container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN);
VOSubscriptionDetails upgradedSubDetailsOld=subDetails;
subDetails.setSubscriptionId("PICT_TEST_09" + "_SubID2");
subDetails=subscrSetup.modifySubscription(subDetails,null);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-10 14:00:00"));
subDetails=subscrSetup.completeAsyncModifySubscription(supplierAdmin.getKey(),customerAdmin,upgradedSubDetailsOld);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-22 14:10:00"));
container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER,ROLE_TECHNOLOGY_MANAGER);
paymentSetup.deleteCustomerPaymentTypes(customer);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-22 14:20:00"));
paymentSetup.reassignCustomerPaymentTypes(customer);
subDetails=subscrSetup.getSubscriptionDetails(customerAdmin.getKey(),subDetails.getSubscriptionId());
container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-22 14:30:00"));
subscrSetup.revokeUser(customerAdmin,subDetails.getSubscriptionId());
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-22 14:40:00"));
role=VOServiceFactory.getRole(serviceDetails,"ADMIN");
subDetails=subscrSetup.addUser(customerAdmin,role,subDetails.getSubscriptionId());
container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER,ROLE_TECHNOLOGY_MANAGER);
subscrSetup.recordEventForSubscription(subDetails,DateTimeHandling.calculateMillis("2013-03-22 14:41:00"),"FILE_DOWNLOAD",100);
subscrSetup.recordEventForSubscription(subDetails,DateTimeHandling.calculateMillis("2013-03-22 14:42:00"),"FILE_UPLOAD",100);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-31 11:59:58"));
container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN);
VOSubscriptionDetails upgradedSubDetails=subscrSetup.upgradeSubscription(subDetails,serviceFreeDetails);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-31 11:59:59"));
upgradedSubDetails=subscrSetup.completeAsyncUpgradeSubscription(supplierAdmin.getKey(),customerAdmin,upgradedSubDetails);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-31 14:00:00"));
container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN);
VOSubscriptionDetails upgradedSubDetails2=subscrSetup.upgradeSubscription(upgradedSubDetails,serviceDetails);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-31 15:00:00"));
upgradedSubDetails2=subscrSetup.completeAsyncUpgradeSubscription(supplierAdmin.getKey(),customerAdmin,upgradedSubDetails2);
container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER,ROLE_TECHNOLOGY_MANAGER);
subscrSetup.recordEventForSubscription(upgradedSubDetails2,DateTimeHandling.calculateMillis("2013-03-31 15:05:00"),"FILE_DOWNLOAD",100);
subscrSetup.recordEventForSubscription(upgradedSubDetails2,DateTimeHandling.calculateMillis("2013-03-31 15:06:00"),"FILE_UPLOAD",100);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-03-31 16:00:00"));
container.login(supplierAdmin.getKey(),ROLE_SERVICE_MANAGER);
serviceSetup.deleteMarketableService(serviceDetails);
container.login(customerAdmin.getKey(),ROLE_ORGANIZATION_ADMIN);
BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-04-10 10:00:00"));
subscrSetup.unsubscribeToService(upgradedSubDetails2.getSubscriptionId());
resetCutOffDay(supplierAdmin.getKey());
BillingIntegrationTestBase.updateSubscriptionListForTests("PICT_TEST_09",subDetails);
BillingIntegrationTestBase.updateSubscriptionListForTests("PICT_TEST_09",upgradedSubDetails);
BillingIntegrationTestBase.updateSubscriptionListForTests("PICT_TEST_09",upgradedSubDetails2);
BillingIntegrationTestBase.updateCustomerListForTests("PICT_TEST_09",customer);
}
| See testcase #9 of BESBillingFactorCombinations.xlsx |
protected int[] colorInscribedDataCircleFromYuvImage(ImageProxy img,int subsample){
Rect defaultCrop=new Rect(0,0,img.getWidth(),img.getHeight());
return colorInscribedDataCircleFromYuvImage(img,defaultCrop,subsample);
}
| Converts an Android Image to a inscribed circle bitmap of ARGB_8888 in a super-optimized loop unroll. Guarantees only one subsampled pass over the YUV data. This version of the function should be used in production and also feathers the edges with 50% alpha on its edges. <br> NOTE: To get the size of the resultant bitmap, you need to call inscribedCircleRadius(w, h) outside of this function. Runs in ~10-15ms for 4K image with a subsample of 13. <br> <p> <b>Crop Treatment: </b>Since this class does a lot of memory offset calculation, it is critical that it doesn't poke strange memory locations on strange crop values. Crop is always applied before any rotation. Out-of-bound crop boundaries are accepted, but treated mathematically as intersection with the Image rectangle. If this intersection is null, the result is minimal 2x2 images. <p> <b>Known Image Artifacts</b> Since this class produces bitmaps that are transient on the screen, the implementation is geared toward efficiency rather than image quality. The image created is a straight, dumb integer subsample of the YUV space with an acceptable color conversion, but w/o any sort of re-sampling. So, expect the usual aliasing noise. Furthermore, when a subsample factor of n is chosen, the resultant UV pixels will have the same subsampling, even though the RGBA artifact produces could produce an effective resample of (n/2) in the U,V color space. For cases where subsample is odd-valued, there will be pixel-to-pixel color bleeding, which may be apparent in sharp color edges. But since our eyes are pretty bad at color edges anyway, it may be an acceptable trade-off for run-time efficiency on an image artifact that has a short lifetime on the screen. </p> TODO: Implement horizontal alpha feathering of the edge of the image. |
public synchronized boolean add(Object obj){
throw new UnsupportedOperationException("add(Object) not supported, try add(Object key, Object obj) instead");
}
| Unsupported, we do not use HashIndexSet as a general all purpose set |
private void actionRead(boolean binary) throws PageException {
if (variable == null) throw new ApplicationException("attribute variable is not defined for tag file");
checkFile(pageContext,securityManager,file,serverPassword,false,false,true,false);
boolean hasCached=cachedWithin != null;
if (StringUtil.isEmpty(cachedWithin)) {
Object tmp=((PageContextImpl)pageContext).getCachedWithin(ConfigWeb.CACHEDWITHIN_HTTP);
if (tmp != null) setCachedwithin(tmp);
}
if (hasCached) {
CacheHandler ch=pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_FILE,null).getInstanceMatchingObject(cachedWithin,null);
CacheItem ci=ch != null ? ch.get(pageContext,createId(binary)) : null;
if (ci instanceof FileCacheItem) {
pageContext.setVariable(variable,((FileCacheItem)ci).getData());
return;
}
}
try {
long start=System.nanoTime();
Object data=binary ? IOUtil.toBytes(file) : IOUtil.toString(file,CharsetUtil.toCharset(charset));
pageContext.setVariable(variable,data);
if (cachedWithin != null) {
String id=createId(binary);
CacheHandler ch=pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_FILE,null).getInstanceMatchingObject(cachedWithin,null);
if (ch != null) ch.set(pageContext,id,cachedWithin,FileCacheItem.getInstance(file.getAbsolutePath(),data,System.nanoTime() - start));
}
}
catch ( IOException e) {
throw new ApplicationException("can't read file [" + file.toString() + "]",e.getMessage());
}
}
| read source file |
public NettyWSTransport(URI remoteLocation,NettyTransportOptions options){
this(null,remoteLocation,options);
}
| Create a new transport instance |
public base addElement(Element element){
addElementToRegistry(element);
return (this);
}
| Adds an Element to the element. |
protected static boolean id_char(int ch){
return id_start_char(ch) || (ch >= '0' && ch <= '9');
}
| Determine if a character is ok for the middle of an id. |
public void deactivate(URI id){
doDeactivate(id);
}
| Deactivates the given virtual array by ID. <p> API Call: <tt>POST /vdc/varrays/{id}/deactivate</tt> |
public BigDecimalPolynomial mult(BigIntPolynomial poly2){
return mult(new BigDecimalPolynomial(poly2));
}
| Multiplies the polynomial by another. Does not change this polynomial but returns the result as a new polynomial. |
static Object createObject(String factoryId,String fallbackClassName) throws ConfigurationError {
return createObject(factoryId,null,fallbackClassName);
}
| Finds the implementation Class object in the specified order. The specified order is the following: <ol> <li>query the system property using <code>System.getProperty</code> <li>read <code>META-INF/services/<i>factoryId</i></code> file <li>use fallback classname </ol> |
public XMLDocument(double version,boolean standalone){
prolog=new Vector<Object>(2);
StringBuffer versionStr=new StringBuffer();
versionStr.append("<?xml version=\"");
versionStr.append(version);
versionStr.append("\" standalone=\"");
if (standalone) versionStr.append("yes\"?>");
else versionStr.append("no\"?>\n");
this.versionDecl=versionStr.toString();
}
| This sets the document up. Since an XML document can be pretty much anything, all this does is create the XML Instruction with the version specified, and identifies the document as standalone if set |
public void rollback(URI taskId){
client.postURI(String.class,client.uriBuilder(getIdUrl() + "/rollback").build(taskId));
}
| Rollback a task |
public ConditionIn(Database database,Expression left,ArrayList<Expression> values){
this.database=database;
this.left=left;
this.valueList=values;
}
| Create a new IN(..) condition. |
public Builder withTerm(long term){
response.term=Assert.argNot(term,term < 0,"term cannot be negative");
return this;
}
| Sets the response term. |
private static void rotate(int first,int middle,int last,Swapper swapper){
if (middle != first && middle != last) {
reverse(first,middle,swapper);
reverse(middle,last,swapper);
reverse(first,last,swapper);
}
}
| Rotate a range in place: <code>array[middle]</code> is put in <code>array[first]</code>, <code>array[middle+1]</code> is put in <code>array[first+1]</code>, etc. Generally, the element in position <code>i</code> is put into position <code>(i + (last-middle)) % (last-first)</code>. |
private void parseSecondaryDevicePar(Node node){
}
| Parse the secondary device parameter |
@PatchMethod public static <T>void add(List array,T value){
}
| Patch add method. |
public Matrix4x3f rotateXYZ(Vector3f angles){
return rotateXYZ(angles.x,angles.y,angles.z);
}
| Apply rotation of <code>angles.x</code> radians about the X axis, followed by a rotation of <code>angles.y</code> radians about the Y axis and followed by a rotation of <code>angles.z</code> radians about the Z axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>M * R</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first! <p> This method is equivalent to calling: <tt>rotateX(angles.x).rotateY(angles.y).rotateZ(angles.z)</tt> |
@Override protected void textLineImpl(char buffer[],int start,int stop,float x,float y){
if (textMode == MODEL) {
textTex=getFontTexture(textFont);
if (textTex == null || textTex.contextIsOutdated()) {
textTex=new FontTexture(this,textFont,is3D());
setFontTexture(textFont,textTex);
}
textTex.begin();
int savedTextureMode=textureMode;
boolean savedStroke=stroke;
float savedNormalX=normalX;
float savedNormalY=normalY;
float savedNormalZ=normalZ;
boolean savedTint=tint;
int savedTintColor=tintColor;
int savedBlendMode=blendMode;
textureMode=NORMAL;
stroke=false;
normalX=0;
normalY=0;
normalZ=1;
tint=true;
tintColor=fillColor;
blendMode(BLEND);
super.textLineImpl(buffer,start,stop,x,y);
textureMode=savedTextureMode;
stroke=savedStroke;
normalX=savedNormalX;
normalY=savedNormalY;
normalZ=savedNormalZ;
tint=savedTint;
tintColor=savedTintColor;
blendMode(savedBlendMode);
textTex.end();
}
else if (textMode == SHAPE) {
super.textLineImpl(buffer,start,stop,x,y);
}
}
| Implementation of actual drawing for a line of text. |
private URI buildLogoutRequestURI(ClientID clientID,ClientIDToken idToken,URI postLogoutURI) throws AuthException, URISyntaxException, UnsupportedEncodingException {
try {
return replaceIdTokenWithPlaceholder(oidcClient.getOidcClient(clientID).buildLogoutRequestURI(postLogoutURI,idToken,new State(LOGOUT_STATE)));
}
catch ( OIDCClientException e) {
throw new AuthException("Failed to build logout URI",e);
}
}
| Build logout request URI for the given client. The client is expected to have exactly one post-logout URI. |
@Override public int texturesLength(){
return mTextures.size();
}
| texture methods |
public void printOptions(){
System.err.println("Current value of GC options");
Option o=getFirst();
while (o != null) {
if (o.getType() == Option.BOOLEAN_OPTION) {
String key=o.getKey();
System.err.print("\t");
System.err.print(key);
for (int c=key.length(); c < 31; c++) {
System.err.print(" ");
}
System.err.print(" = ");
logValue(o,false);
System.err.println();
}
o=o.getNext();
}
o=getFirst();
while (o != null) {
if (o.getType() != Option.BOOLEAN_OPTION && o.getType() != Option.ENUM_OPTION) {
String key=o.getKey();
System.err.print("\t");
System.err.print(key);
for (int c=key.length(); c < 31; c++) {
System.err.print(" ");
}
System.err.print(" = ");
logValue(o,false);
System.err.println();
}
o=o.getNext();
}
o=getFirst();
while (o != null) {
if (o.getType() == Option.ENUM_OPTION) {
String key=o.getKey();
System.err.print("\t");
System.err.print(key);
for (int c=key.length(); c < 31; c++) {
System.err.print(" ");
}
System.err.print(" = ");
logValue(o,false);
System.err.println();
}
o=o.getNext();
}
}
| Print out the option values |
protected void mutate(Node node,Rules rules){
if (!node.isFixed() && (PRNG.nextDouble() <= probability)) {
List<Node> mutations=rules.listAvailableMutations(node);
if (!mutations.isEmpty()) {
Node mutation=PRNG.nextItem(mutations).copyNode();
Node parent=node.getParent();
for (int i=0; i < parent.getNumberOfArguments(); i++) {
if (parent.getArgument(i) == node) {
parent.setArgument(i,mutation);
break;
}
}
for (int i=0; i < node.getNumberOfArguments(); i++) {
mutation.setArgument(i,node.getArgument(i));
}
node=mutation;
}
}
for (int i=0; i < node.getNumberOfArguments(); i++) {
mutate(node.getArgument(i),rules);
}
}
| Applies point mutation to the specified node. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.