code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static long deinterleave(long b){
b&=MAGIC[0];
b=(b ^ (b >>> SHIFT[0])) & MAGIC[1];
b=(b ^ (b >>> SHIFT[1])) & MAGIC[2];
b=(b ^ (b >>> SHIFT[2])) & MAGIC[3];
b=(b ^ (b >>> SHIFT[3])) & MAGIC[4];
b=(b ^ (b >>> SHIFT[4])) & MAGIC[5];
return b;
}
| Deinterleaves long value back to two concatenated 32bit values |
public void deleteFilesFromContainer(String applicationName,String containerId,String path) throws ServiceException {
try {
final String command="rm -rf " + path;
dockerService.execCommand(containerId,command);
}
catch ( FatalDockerJSONException e) {
throw new ServiceException("Cannot delete files " + path + " for "+ containerId,e);
}
}
| File Explorer Feature <p> Delete all resources (files and folders) for an application + container + path. |
public BackpropTrainer(Trainable network,List<List<Neuron>> layers){
super(network);
this.layers=layers;
errorMap=new HashMap<Neuron,Double>();
weightDeltaMap=new HashMap<Synapse,Double>();
biasDeltaMap=new HashMap<Neuron,Double>();
this.setIteration(0);
mse=0;
}
| Construct the backprop trainer. |
final int submit(T item){
int stat;
if ((stat=offer(item)) == 0) {
putItem=item;
timeout=0L;
putStat=0;
ForkJoinPool.helpAsyncBlocker(executor,this);
if ((stat=putStat) == 0) {
try {
ForkJoinPool.managedBlock(this);
}
catch ( InterruptedException ie) {
timeout=INTERRUPTED;
}
stat=putStat;
}
if (timeout < 0L) Thread.currentThread().interrupt();
}
return stat;
}
| Spins/helps/blocks while offer returns 0. Called only if initial offer return 0. |
public static <T>Set<T> toSet(T obj1,T obj2){
Set<T> theSet=new LinkedHashSet<T>();
theSet.add(obj1);
theSet.add(obj2);
return theSet;
}
| Create a Set from passed objX parameters |
protected LayerDrawable drawable_button_extended(){
return drawble_pad_button();
}
| maded for extension: please write your own extension in here |
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
lock.lock();
try {
q=new PriorityQueue<E>(Math.max(size,1),comparator);
q.addAll(this);
s.defaultWriteObject();
}
finally {
q=null;
lock.unlock();
}
}
| Saves this queue to a stream (that is, serializes it). For compatibility with previous version of this class, elements are first copied to a java.util.PriorityQueue, which is then serialized. |
private List<Runnable> drainQueue(){
BlockingQueue<Runnable> q=workQueue;
ArrayList<Runnable> taskList=new ArrayList<Runnable>();
q.drainTo(taskList);
if (!q.isEmpty()) {
for ( Runnable r : q.toArray(new Runnable[0])) {
if (q.remove(r)) taskList.add(r);
}
}
return taskList;
}
| Drains the task queue into a new list, normally using drainTo. But if the queue is a DelayQueue or any other kind of queue for which poll or drainTo may fail to remove some elements, it deletes them one by one. |
protected void forwardMessage(AbstractMRListener client,AbstractMRMessage m){
((CanListener)client).message((CanMessage)m);
}
| Forward a CanMessage to all registered CanInterface listeners. |
public T caseScope(Scope object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Scope</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
private PostgreSQLRawModuleFunctions(){
}
| Do not instantiate this class. |
private void readGlyphNames(int base){
if (base == 0) {
glyphnames=new int[229];
for (int i=0; i < glyphnames.length; i++) {
glyphnames[i]=i;
}
return;
}
else if (base == 1) {
glyphnames=FontSupport.type1CExpertCharset;
return;
}
else if (base == 2) {
glyphnames=FontSupport.type1CExpertSubCharset;
return;
}
glyphnames=new int[nglyphs];
glyphnames[0]=0;
pos=base;
int t=readByte();
if (t == 0) {
for (int i=1; i < nglyphs; i++) {
glyphnames[i]=readInt(2);
}
}
else if (t == 1) {
int n=1;
while (n < nglyphs) {
int sid=readInt(2);
int range=readByte() + 1;
for (int i=0; i < range; i++) {
glyphnames[n++]=sid++;
}
}
}
else if (t == 2) {
int n=1;
while (n < nglyphs) {
int sid=readInt(2);
int range=readInt(2) + 1;
for (int i=0; i < range; i++) {
glyphnames[n++]=sid++;
}
}
}
}
| read the names of the glyphs. |
public static <T>T loadSpringBean(String springXmlPath,String beanName) throws IgniteCheckedException {
A.notNull(springXmlPath,"springXmlPath");
A.notNull(beanName,"beanName");
URL url=U.resolveSpringUrl(springXmlPath);
assert url != null;
return loadSpringBean(url,beanName);
}
| Loads spring bean by name. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:31:44.744 -0500",hash_original_method="3E96BAE0A73C07217EE9E69C0532B078",hash_generated_method="2365E22F3A38CEC7407569DAB2E8C5E7") public void show(){
if (localLOGV) Log.v(TAG,"SHOW: " + this);
mHandler.post(mShow);
}
| schedule handleShow into the right thread |
public static ContextFreeGrammar load(Reader reader) throws IOException {
StreamTokenizer tokenizer=new StreamTokenizer(reader);
tokenizer.resetSyntax();
tokenizer.wordChars('a','z');
tokenizer.wordChars('A','Z');
tokenizer.wordChars('0','9');
tokenizer.wordChars('<','<');
tokenizer.wordChars('>','>');
tokenizer.wordChars('_','_');
tokenizer.wordChars('-','-');
tokenizer.wordChars('.','.');
tokenizer.wordChars(128 + 32,255);
tokenizer.whitespaceChars(0,' ');
tokenizer.quoteChar('"');
tokenizer.quoteChar('\'');
tokenizer.eolIsSignificant(true);
tokenizer.slashSlashComments(true);
tokenizer.slashStarComments(true);
ContextFreeGrammar grammar=new ContextFreeGrammar();
Rule rule=null;
Production production=null;
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if ((tokenizer.ttype == ':') || (tokenizer.ttype == '=')) {
do {
tokenizer.nextToken();
}
while ((tokenizer.ttype == ':') || (tokenizer.ttype == '='));
if ((rule == null) || (production != null)) {
throw new GrammarException("unexpected rule separator",tokenizer.lineno());
}
tokenizer.pushBack();
}
else if (tokenizer.ttype == '|') {
if ((rule != null) && (production == null)) {
throw new GrammarException("rule must contain at least one production",tokenizer.lineno());
}
production=null;
}
else if (tokenizer.ttype == StreamTokenizer.TT_EOL) {
if ((rule != null) && (production == null)) {
throw new GrammarException("rule must contain at least one production",tokenizer.lineno());
}
rule=null;
production=null;
}
else {
String string=null;
if ((tokenizer.ttype == StreamTokenizer.TT_WORD) || (tokenizer.ttype == '\'') || (tokenizer.ttype == '\"')) {
string=tokenizer.sval;
}
else if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
string=Double.toString(tokenizer.nval);
}
else {
string=Character.toString((char)tokenizer.ttype);
}
if (string.startsWith("<") && string.endsWith(">")) {
string=string.substring(1,string.length() - 1);
if (string.isEmpty()) {
throw new GrammarException("invalid symbol",tokenizer.lineno());
}
if (rule == null) {
rule=new Rule(new Symbol(string,false));
grammar.add(rule);
}
else if (production == null) {
production=new Production();
production.add(new Symbol(string,false));
rule.add(production);
}
else {
production.add(new Symbol(string,false));
}
}
else {
if (rule == null) {
throw new GrammarException("rule must start with non-terminal",tokenizer.lineno());
}
else if (production == null) {
production=new Production();
production.add(new Symbol(string,true));
rule.add(production);
}
else {
production.add(new Symbol(string,true));
}
}
}
}
if ((rule != null) && (production == null)) {
throw new GrammarException("rule must contain at least one production",tokenizer.lineno());
}
return grammar;
}
| Parses the context-free grammar. |
public static BufferedImage toCompatibleImage(BufferedImage image){
if (image.getColorModel().equals(getGraphicsConfiguration().getColorModel())) {
return image;
}
BufferedImage compatibleImage=getGraphicsConfiguration().createCompatibleImage(image.getWidth(),image.getHeight(),image.getTransparency());
Graphics g=compatibleImage.getGraphics();
g.drawImage(image,0,0,null);
g.dispose();
return compatibleImage;
}
| <p>Return a new compatible image that contains a copy of the specified image. This method ensures an image is compatible with the hardware, and therefore optimized for fast blitting operations.</p> |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-24 16:07:23.775 -0400",hash_original_method="DE754C83318E762068C769E079ADB7A1",hash_generated_method="2CA859495FCE04BE30AB7E12B34FD3ED") private void onDeviceDisconnectRequested(String deviceObjectPath){
String address=mBluetoothService.getAddressFromObjectPath(deviceObjectPath);
if (address == null) {
Log.e(TAG,"onDeviceDisconnectRequested: Address of the remote device in null");
return;
}
Intent intent=new Intent(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE,mAdapter.getRemoteDevice(address));
mContext.sendBroadcast(intent,BLUETOOTH_PERM);
}
| Called by native code on a DisconnectRequested signal from org.bluez.Device. |
ConcurrentSkipListSet(ConcurrentNavigableMap<E,Object> m){
this.m=m;
}
| For use by submaps |
public void computeAuxiliaryData(EvolutionState state,Individual[] inds){
double[][] distances=calculateDistances(state,inds);
for (int y=0; y < inds.length; y++) {
int myStrength=0;
for (int z=0; z < inds.length; z++) if (((SPEA2MultiObjectiveFitness)inds[y].fitness).paretoDominates((MultiObjectiveFitness)inds[z].fitness)) myStrength++;
((SPEA2MultiObjectiveFitness)inds[y].fitness).strength=myStrength;
}
int kTH=(int)Math.sqrt(inds.length);
for (int y=0; y < inds.length; y++) {
double fitness=0;
for (int z=0; z < inds.length; z++) {
if (((SPEA2MultiObjectiveFitness)inds[z].fitness).paretoDominates((MultiObjectiveFitness)inds[y].fitness)) {
fitness+=((SPEA2MultiObjectiveFitness)inds[z].fitness).strength;
}
}
SPEA2MultiObjectiveFitness indYFitness=((SPEA2MultiObjectiveFitness)inds[y].fitness);
double kthDistance=Math.sqrt(orderStatistics(distances[y],kTH,state.random[0]));
indYFitness.kthNNDistance=1.0 / (2 + kthDistance);
indYFitness.fitness=fitness + indYFitness.kthNNDistance;
}
}
| Computes the strength of individuals, then the raw fitness (wimpiness) and kth-closest sparsity measure. Finally, computes the final fitness of the individuals. |
public static void resetAccessedStatus(){
ACCESSED_FLAGS.clear();
DEFAULT_FLAGS.reset();
sFlags=DEFAULT_FLAGS;
}
| Unsets list of flags which have been accessed/set. If your test is failing due to another test using a global flag, find THAT test and put a call to this into the tear down method. |
private static DeclaredType parameterisedType(Types typeUtils,TypeMirror rawType,List<TypeMirror> paramTypes){
Preconditions.checkArgument(rawType.getKind() == TypeKind.DECLARED && ((DeclaredType)rawType).getTypeArguments().isEmpty(),"Expected raw type, got '%s'",rawType);
TypeElement genericType=(TypeElement)typeUtils.asElement(rawType);
Preconditions.checkArgument(genericType.getTypeParameters().size() == paramTypes.size(),"Incorrect number of arguments for %s (expected %s, got %s)",genericType,genericType.getTypeParameters().size(),paramTypes.size());
DeclaredType declaredType=typeUtils.getDeclaredType(genericType,paramTypes.toArray(new TypeMirror[paramTypes.size()]));
return declaredType;
}
| Returns a parameterised generic type. |
private static int dimensionality(Relation<ParameterizationFunction> relation){
return relation.get(relation.iterDBIDs()).getDimensionality();
}
| Get the dimensionality of a vector field. |
public ScriptedProblem(String script,String name) throws ScriptException {
this(new StringReader(script),name);
}
| Constructs a new problem implemented in a scripting language. |
void handleException(Exception e) throws IOException {
handleException(e,true);
}
| Handle an exception. This method is called by top level exception handlers (in read(), write()) to make sure we always shutdown the connection correctly and do not pass runtime exception to the application. |
public static DefineShape createShapeForImage(DefineBits tag,BitmapGraphicNode node){
double width=node.width;
double height=node.height;
boolean repeat=node.repeat;
FillMode fillMode=node.fillMode;
FXGVersion fileVersion=node.getFileVersion();
if (Double.isNaN(width)) width=tag.width;
if (Double.isNaN(height)) height=tag.height;
Matrix matrix=new Matrix();
matrix.scaleX=(int)(SwfConstants.TWIPS_PER_PIXEL * SwfConstants.FIXED_POINT_MULTIPLE);
matrix.scaleY=(int)(SwfConstants.TWIPS_PER_PIXEL * SwfConstants.FIXED_POINT_MULTIPLE);
matrix.hasScale=true;
FillStyle fs=null;
if (fileVersion.equalTo(FXGVersion.v1_0)) {
if (repeat) fs=new FillStyle(FillStyle.FILL_BITS,matrix,tag);
else fs=new FillStyle(FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP,matrix,tag);
}
else {
if (fillMode.equals(FillMode.REPEAT)) {
fs=new FillStyle(FillStyle.FILL_BITS,matrix,tag);
}
else if (fillMode.equals(FillMode.CLIP)) {
fs=new FillStyle(FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP,matrix,tag);
}
else if (fillMode.equals(FillMode.SCALE)) {
matrix.scaleX=(int)StrictMath.rint((width * SwfConstants.TWIPS_PER_PIXEL * SwfConstants.FIXED_POINT_MULTIPLE) / (double)tag.width);
matrix.scaleY=(int)StrictMath.rint((height * SwfConstants.TWIPS_PER_PIXEL * SwfConstants.FIXED_POINT_MULTIPLE) / (double)tag.height);
fs=new FillStyle(FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP,matrix,tag);
}
}
ShapeWithStyle sws=new ShapeWithStyle();
sws.fillstyles=new ArrayList<FillStyle>(1);
sws.fillstyles.add(fs);
List<ShapeRecord> shapeRecords=ShapeHelper.rectangle(width,height);
ShapeHelper.setStyles(shapeRecords,0,1,0);
sws.shapeRecords=shapeRecords;
DefineShape defineShape=new DefineShape(Tag.stagDefineShape4);
defineShape.bounds=TypeHelper.rect(width,height);
defineShape.edgeBounds=defineShape.bounds;
defineShape.shapeWithStyle=sws;
return defineShape;
}
| Creates a rectangle for the given width and height as a DefineShape. The shape is painted with a bitmap FillStyle with the given DefineBits tag. |
public void reply(Object... args){
reply(ArgArrayBuilder.buildArgumentsArray(stateController.clientConfig().objectMapper(),args),null);
}
| Send a normal response to the request.<br> This version of the function will use Jacksons object mapping capabilities to transform the argument objects in a JSON argument array which will be sent as the positional arguments of the call. If keyword arguments are needed then this function can not be used.<br> If this is called more than once then the following invocations will have no effect. Respones will be only sent once. |
public static boolean isLength(double[] M,int n){
if (M.length != n) return false;
return true;
}
| Same as checkLength but returns a boolean value rather than throwing an exception. |
public void rollbackCreateMirrors(URI vplexURI,List<URI> vplexMirrorURIs,String executeStepId,String stepId) throws WorkflowException {
try {
List<VolumeInfo> rollbackData=(List<VolumeInfo>)_workflowService.loadStepData(executeStepId);
if (rollbackData != null) {
WorkflowStepCompleter.stepExecuting(stepId);
StorageSystem vplex=getDataObject(StorageSystem.class,vplexURI,_dbClient);
VPlexApiClient client=getVPlexAPIClient(_vplexApiFactory,vplex,_dbClient);
for ( VolumeInfo rollbackInfo : rollbackData) {
client.deleteLocalDevice(rollbackInfo);
}
}
}
catch ( Exception ex) {
_log.error("Exception rolling back: " + ex.getLocalizedMessage());
}
finally {
for ( URI uri : vplexMirrorURIs) {
VplexMirror vplexMirror=_dbClient.queryObject(VplexMirror.class,uri);
if (vplexMirror != null) {
Volume sourceVplexVolume=_dbClient.queryObject(Volume.class,vplexMirror.getSource());
sourceVplexVolume.getMirrors().remove(vplexMirror.getId().toString());
_dbClient.updateObject(sourceVplexVolume);
_dbClient.markForDeletion(vplexMirror);
}
}
WorkflowStepCompleter.stepSucceded(stepId);
}
}
| Rollback any mirror device previously created. |
private void restoreSelection(){
if (m_selectedGame == null) {
return;
}
for (int i=0; i < getModel().getRowCount(); i++) {
final GUID current=(GUID)getModel().getValueAt(i,LobbyGameTableModel.Column.GUID.ordinal());
if (current.equals(m_selectedGame)) {
getSelectionModel().setSelectionInterval(i,i);
break;
}
}
}
| Restore the selection to the marked value |
public boolean isExportXMLBackup(){
Object oo=get_Value(COLUMNNAME_IsExportXMLBackup);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Export XML Backup. |
@Override public void eUnset(int featureID){
switch (featureID) {
case UmplePackage.ANONYMOUS_MORE_GUARDS_1__CODE_LANG_1:
getCodeLang_1().clear();
return;
case UmplePackage.ANONYMOUS_MORE_GUARDS_1__CODE_LANGS_1:
getCodeLangs_1().clear();
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private void addToken(int start,int end,int tokenType){
int so=start + offsetShift;
addToken(zzBuffer,start,end,tokenType,so);
}
| Adds the token specified to the current linked list of tokens. |
protected Position determineRangeLabelPosition(Position center,Angle centerAzimuth,Angle leftAzimuth,Angle rightAzimuth,double radiusRadians){
leftAzimuth=(leftAzimuth != null) ? leftAzimuth : centerAzimuth;
rightAzimuth=(rightAzimuth != null) ? rightAzimuth : centerAzimuth;
double deltaLeft=Math.abs(centerAzimuth.subtract(leftAzimuth).degrees);
double deltaRight=Math.abs(centerAzimuth.subtract(rightAzimuth).degrees);
Angle labelAzimuth=(deltaLeft > deltaRight) ? leftAzimuth : rightAzimuth;
labelAzimuth=labelAzimuth.add(centerAzimuth).divide(2.0);
LatLon ll=LatLon.greatCircleEndPosition(center,labelAzimuth.radians,radiusRadians);
return new Position(ll,0);
}
| Determine the position of a range label for a ring in the range fan. The method finds a point to either the left or right of the center line, depending on which has more space for the label. |
public static final double dsigma(double a){
double s=sigma(a);
return s * (1. - s);
}
| Derivative of the sigmoid function applied to scalar |
public TemplateTestSuite(){
try {
Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,FILE_RESOURCE_LOADER_PATH);
Velocity.setProperty(Velocity.RUNTIME_LOG_ERROR_STACKTRACE,"true");
Velocity.setProperty(Velocity.RUNTIME_LOG_WARN_STACKTRACE,"true");
Velocity.setProperty(Velocity.RUNTIME_LOG_INFO_STACKTRACE,"true");
Velocity.init();
testProperties=new Properties();
testProperties.load(new FileInputStream(TEST_CASE_PROPERTIES));
}
catch ( Exception e) {
System.err.println("Cannot setup TemplateTestSuite!");
e.printStackTrace();
System.exit(1);
}
addTemplateTestCases();
}
| Creates an instace of the Apache Velocity test suite. |
void load(Data buff,FileStore file,UndoLog log){
int min=Constants.FILE_BLOCK_SIZE;
log.seek(filePos);
buff.reset();
file.readFully(buff.getBytes(),0,min);
int len=buff.readInt() * Constants.FILE_BLOCK_SIZE;
buff.checkCapacity(len);
if (len - min > 0) {
file.readFully(buff.getBytes(),min,len - min);
}
int oldOp=operation;
load(buff,log);
if (SysProperties.CHECK) {
if (operation != oldOp) {
DbException.throwInternalError("operation=" + operation + " op="+ oldOp);
}
}
}
| Load an undo log record row using a buffer. |
public final String yytext(){
return new String(zzBuffer,zzStartRead,zzMarkedPos - zzStartRead);
}
| Returns the text matched by the current regular expression. |
public static final ColorTheme instance(){
if (inst == null) inst=new ColorTheme();
return inst;
}
| Get singleton instance. |
public static Date parseDate(final String str,final String... parsePatterns) throws ParseException {
return parseDate(str,null,parsePatterns);
}
| <p>Parses a string representing a date by trying a variety of different parsers.</p> <p>The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.</p> The parser will be lenient toward the parsed date. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:47.115 -0500",hash_original_method="BBD9B5CD65A55FC3201E30C2D0E96E71",hash_generated_method="614F8DFFF6E32ED9966CA19F2DF68C62") public static String snippetize(String content,String displayName,String query,char snippetStartMatch,char snippetEndMatch,String snippetEllipsis,int snippetMaxTokens){
String lowerQuery=query != null ? query.toLowerCase() : null;
if (TextUtils.isEmpty(content) || TextUtils.isEmpty(query) || TextUtils.isEmpty(displayName)|| !content.toLowerCase().contains(lowerQuery)) {
return null;
}
String lowerDisplayName=displayName != null ? displayName.toLowerCase() : "";
List<String> nameTokens=new ArrayList<String>();
List<Integer> nameTokenOffsets=new ArrayList<Integer>();
split(lowerDisplayName.trim(),nameTokens,nameTokenOffsets);
for ( String nameToken : nameTokens) {
if (nameToken.startsWith(lowerQuery)) {
return null;
}
}
String[] contentLines=content.split("\n");
for ( String contentLine : contentLines) {
if (contentLine.toLowerCase().contains(lowerQuery)) {
List<String> lineTokens=new ArrayList<String>();
List<Integer> tokenOffsets=new ArrayList<Integer>();
split(contentLine.trim(),lineTokens,tokenOffsets);
List<String> markedTokens=new ArrayList<String>();
int firstToken=-1;
int lastToken=-1;
for (int i=0; i < lineTokens.size(); i++) {
String token=lineTokens.get(i);
String lowerToken=token.toLowerCase();
if (lowerToken.startsWith(lowerQuery)) {
markedTokens.add(snippetStartMatch + token + snippetEndMatch);
if (firstToken == -1) {
firstToken=Math.max(0,i - (int)Math.floor(Math.abs(snippetMaxTokens) / 2.0));
lastToken=Math.min(lineTokens.size(),firstToken + Math.abs(snippetMaxTokens));
}
}
else {
markedTokens.add(token);
}
}
if (firstToken > -1) {
StringBuilder sb=new StringBuilder();
if (firstToken > 0) {
sb.append(snippetEllipsis);
}
for (int i=firstToken; i < lastToken; i++) {
String markedToken=markedTokens.get(i);
String originalToken=lineTokens.get(i);
sb.append(markedToken);
if (i < lastToken - 1) {
sb.append(contentLine.substring(tokenOffsets.get(i) + originalToken.length(),tokenOffsets.get(i + 1)));
}
}
if (lastToken < lineTokens.size()) {
sb.append(snippetEllipsis);
}
return sb.toString();
}
}
}
return null;
}
| Creates a snippet out of the given content that matches the given query. |
public static boolean scrub(final Intent intent){
return null != intent && scrub(intent.getExtras());
}
| Scrubs Intents for private serializable subclasses in the Intent extras. If the Intent's extras contain a private serializable subclass, the Bundle is cleared. The Bundle will not be set to null. If the Bundle is null, has no extras, or the extras do not contain a private serializable subclass, the Bundle is not mutated. |
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. |
@Deprecated public String[] removeTitleRow(){
String[] titles=getStringRow(0);
removeRow(0);
setColumnTitles(titles);
return titles;
}
| Remove the first row from the data set, and use it as the column titles. Use loadTable("table.csv", "header") instead. |
private Node<E> findPredecessor(Comparable<? super E> key){
if (key == null) throw new NullPointerException();
for (; ; ) {
Index<E> q=head;
Index<E> r=q.right;
for (; ; ) {
if (r != null) {
Node<E> n=r.node;
E k=n.key;
if (n.value == null) {
if (!q.unlink(r)) break;
r=q.right;
continue;
}
if (key.compareTo(k) >= 0) {
q=r;
r=r.right;
continue;
}
}
Index<E> d=q.down;
if (d != null) {
q=d;
r=d.right;
}
else return q.node;
}
}
}
| Returns a base-level node with key strictly less than given key, or the base-level header if there is no such node. Also unlinks indexes to deleted nodes found along the way. Callers rely on this side-effect of clearing indices to deleted nodes. |
private int rChild(int i){
return (i << 1) + 2;
}
| Returns the index of the right child of the element at index <code>i</code> of the heap. |
public synchronized Vertex findByName(String name){
if (name == null) {
return null;
}
for ( Vertex vertex : findAll()) {
if (name.equals(vertex.getName())) {
return vertex;
}
}
return null;
}
| Return the vertex with the given name. |
public void addCommand(int commandOffset,int commandLength,String commandText,IDocumentListener commandOwner) throws BadLocationException {
final Command command=new Command(commandOffset,commandLength,commandText,commandOwner);
if (intersects(command)) throw new BadLocationException();
final int index=Collections.binarySearch(fCommands,command);
if (index >= 0) throw new BadLocationException();
final int insertionIndex=-(index + 1);
if (insertionIndex != fCommands.size() && intersects((Command)fCommands.get(insertionIndex),command)) throw new BadLocationException();
if (insertionIndex != 0 && intersects((Command)fCommands.get(insertionIndex - 1),command)) throw new BadLocationException();
fCommands.add(insertionIndex,command);
}
| Adds an additional replace command. The added replace command must not overlap with existing ones. If the document command owner is not <code>null</code>, it will not get document change notifications for the particular command. |
public static RaptorWorkerState plan(Request req,Response res) throws IOException {
ProfileRequest request=JsonUtilities.objectMapper.readValue(req.body(),ProfileRequest.class);
TransportNetwork network=request.scenario.modifications.isEmpty() ? RaptorDebugger.network : scenarioCache.get(request.scenario.id);
InstrumentedRaptorWorker worker=new InstrumentedRaptorWorker(network.transitLayer,null,request);
long initialStopStartTime=System.currentTimeMillis();
StreetRouter streetRouter=new StreetRouter(network.streetLayer);
EnumSet<LegMode> modes=request.accessModes;
if (modes.contains(LegMode.CAR)) {
streetRouter.streetMode=StreetMode.CAR;
streetRouter.distanceLimitMeters=100_000;
}
else if (modes.contains(LegMode.BICYCLE)) {
streetRouter.streetMode=StreetMode.BICYCLE;
streetRouter.distanceLimitMeters=(int)(request.maxBikeTime * request.bikeSpeed * 60);
}
else {
streetRouter.streetMode=StreetMode.WALK;
streetRouter.distanceLimitMeters=Math.min((int)(request.maxWalkTime * request.walkSpeed * 60),TransitLayer.DISTANCE_TABLE_SIZE_METERS);
}
streetRouter.profileRequest=request;
streetRouter.setOrigin(request.fromLat,request.fromLon);
streetRouter.dominanceVariable=StreetRouter.State.RoutingVariable.DURATION_SECONDS;
streetRouter.route();
TIntIntMap transitStopAccessTimes=streetRouter.getReachedStops();
worker.runRaptorAsync(transitStopAccessTimes,null,new TaskStatistics());
String workerId=UUID.randomUUID().toString();
String oldWorkerId=req.session().attribute("workerId");
if (oldWorkerId != null) workersForSession.remove(oldWorkerId);
req.session().attribute("workerId",workerId);
workersForSession.put(workerId,worker);
return worker.workerState;
}
| Start a new request |
public boolean isPollable(){
return pollable;
}
| Checks if is pollable. |
@Override protected boolean shouldComposeCreationImage(){
return true;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
void afterWriting(){
if (conn != null) {
conn.afterWriting();
}
}
| Called after each write operation. |
public VersionException(Throwable cause){
super(cause);
}
| Constructs a <code>VersionException</code> with a cause |
public QueryStringDecoderUtil(String uri,Charset charset){
this(uri,charset,true);
}
| Creates a new decoder that decodes the specified URI encoded in the specified charset. |
private static CloseableHttpClient createTMDBHttpClient(){
CloseableHttpClient httpClient=HttpClients.createDefault();
return httpClient;
}
| Creates HTTP Client |
public ColumnInfo(String name,int position,String mysqlType){
this.name=name;
this.position=position;
this.columnDataType=ColumnDataType.valueOf(mysqlType.toUpperCase()).initialize();
}
| Column Info creation. |
public int keyAt(int index){
return mKeys[index];
}
| Given an index in the range <code>0...size()-1</code>, returns the key from the <code>index</code>th key-value mapping that this SparseDoubleArray stores. |
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. |
protected void tearDown() throws Exception {
verbosePrint("tearDown beginning");
fTransformers=null;
super.tearDown();
}
| Sets the manager and transformers to null so that setUp needs to update. |
public void testSingleThreaded() throws Exception {
AtomicCounter c=new AtomicCounter(0);
c.waitSeqnoGreaterEqual(0);
c.waitSeqnoGreaterEqual(-1);
c.waitSeqnoLessEqual(0);
c.waitSeqnoLessEqual(1);
assertEquals("New counter is 0",0,c.getSeqno());
long v1=c.incrAndGetSeqno();
assertEquals("Incremented counter is 1",1,v1);
assertEquals("Returned value matches increment value",v1,c.getSeqno());
long v2=c.decrAndGetSeqno();
assertEquals("Decremented counter is 0",0,v2);
assertEquals("Returned value matches increment value",v2,c.getSeqno());
c.setSeqno(99);
assertEquals("Returned value matches set value",99,c.getSeqno());
}
| Show that single-threaded operations work as expected when waiting for great and lesser values. |
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public DefaultHttpClient(final ClientConnectionManager conman,final HttpParams params){
super(conman,params);
}
| Creates a new HTTP client from parameters and a connection manager. |
public static <T>List<T> synchronizedList(List<T> list){
if (list == null) {
throw new NullPointerException("list == null");
}
if (list instanceof RandomAccess) {
return new SynchronizedRandomAccessList<T>(list);
}
return new SynchronizedList<T>(list);
}
| Returns a wrapper on the specified List which synchronizes all access to the List. |
public static void backup(File file) throws IOException {
FileUtilSupport.getDefault().backup(file);
}
| Backup a file. The backup is in the same location as the original file, has the extension <code>.bak</code> appended to the file name, and up to four revisions are retained. The lowest numbered revision is the most recent. |
public static String XMLEnc(String s){
return XMLOrHTMLEnc(s,true,true,XML_APOS);
}
| XML Encoding. Replaces all '>' '<' '&', "'" and '"' with entity reference |
private boolean sendUpdatesTable(int AD_Table_ID,String TableName,int AD_ReplicationTable_ID) throws Exception {
RemoteUpdateVO data=new RemoteUpdateVO();
data.Test=m_test;
data.TableName=TableName;
StringBuffer sql=new StringBuffer("SELECT * FROM ").append(TableName).append(" WHERE AD_Client_ID=").append(m_replication.getRemote_Client_ID());
if (m_replication.getRemote_Org_ID() != 0) sql.append(" AND AD_Org_ID IN (0,").append(m_replication.getRemote_Org_ID()).append(")");
if (m_replication.getDateLastRun() != null) sql.append(" AND Updated >= ").append(DB.TO_DATE(m_replication.getDateLastRun(),false));
sql.append(" ORDER BY ");
data.KeyColumns=getKeyColumns(AD_Table_ID);
if (data.KeyColumns == null || data.KeyColumns.length == 0) {
log.log(Level.SEVERE,"sendUpdatesTable - No KeyColumns for " + TableName);
m_replicated=false;
return false;
}
for (int i=0; i < data.KeyColumns.length; i++) {
if (i > 0) sql.append(",");
sql.append(data.KeyColumns[i]);
}
data.Sql=sql.toString();
data.CentralData=getRowSet(data.Sql,null);
if (data.CentralData == null) {
log.fine("sendUpdatesTable - Null - " + TableName);
m_replicated=false;
return false;
}
int rows=0;
try {
if (data.CentralData.last()) rows=data.CentralData.getRow();
data.CentralData.beforeFirst();
}
catch ( SQLException ex) {
log.fine("RowCheck " + ex);
m_replicated=false;
return false;
}
if (rows == 0) {
log.fine("No Rows - " + TableName);
return true;
}
else log.fine(TableName + " #" + rows);
ProcessInfo pi=new ProcessInfo("SendUpdates",0);
pi.setClassName(REMOTE);
pi.setSerializableObject(data);
pi=m_serverRemote.process(new Properties(),pi);
log.info("sendUpdatesTable - " + pi);
ProcessInfoLog[] logs=pi.getLogs();
String msg="> ";
if (logs != null && logs.length > 0) msg+=logs[0].getP_Msg();
MReplicationLog rLog=new MReplicationLog(getCtx(),m_replicationRun.getAD_Replication_Run_ID(),AD_ReplicationTable_ID,msg,get_TrxName());
if (pi.isError()) m_replicated=false;
rLog.setIsReplicated(!pi.isError());
rLog.saveEx();
return !pi.isError();
}
| Send UPdates to Remote |
public String trueCase(String input,int inputId){
Sequence<IString> source=IStrings.tokenize(input);
RichTranslation<IString,String> translation=inferer.translate(source,inputId,null,new UnconstrainedOutputSpace<IString,String>(),null);
return translation.translation.toString();
}
| Apply casing to the input. |
public static int translateNameToCWE(String category){
switch (category) {
case "Command Injection":
return 78;
case "Cross-Site Scripting":
return 79;
case "LDAP Injection":
return 90;
case "Insecure Cookie":
return 614;
case "Path Traversal":
return 22;
case "Weak Encryption Algorithm":
return 327;
case "Weak Hash Algorithm":
return 328;
case "Weak Random Number":
return 330;
case "SQL Injection":
return 89;
case "Hibernate Injection":
return 564;
case "Trust Boundary Violation":
return 501;
case "XPath Injection":
return 643;
default :
System.out.println("Error: Category: " + category + " not supported.");
return -1;
}
}
| This method translates vulnerability names, e.g., Cross-Site Scripting, to their CWE number. |
public static AC parseColumnConstraints(String s){
return parseAxisConstraint(s,true);
}
| Parses the column or rows constraints. They normally looks something like <code>"[min:pref]rel[10px][]"</code>. |
public int readInt(){
return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF);
}
| Reads the next four bytes as a signed value. |
@Override public final void write(final String filename){
new FacilitiesWriterV1(coordinateTransformation,facilities).write(filename);
}
| Writes the activity facilities in the current default format (currently facilities_v1.dtd). |
public RelationPair(String source,String target){
this.source=source;
this.target=target;
}
| Instantiates a new relation pair. |
@Override public int eDerivedOperationID(int baseOperationID,Class<?> baseClass){
if (baseClass == AnnotableElement.class) {
switch (baseOperationID) {
case N4JSPackage.ANNOTABLE_ELEMENT___GET_ANNOTATIONS:
return N4JSPackage.N4_TYPE_DECLARATION___GET_ANNOTATIONS;
default :
return super.eDerivedOperationID(baseOperationID,baseClass);
}
}
if (baseClass == N4TypeDefinition.class) {
switch (baseOperationID) {
case N4JSPackage.N4_TYPE_DEFINITION___IS_EXTERNAL:
return N4JSPackage.N4_TYPE_DECLARATION___IS_EXTERNAL;
default :
return super.eDerivedOperationID(baseOperationID,baseClass);
}
}
if (baseClass == ScriptElement.class) {
switch (baseOperationID) {
default :
return -1;
}
}
if (baseClass == AnnotableScriptElement.class) {
switch (baseOperationID) {
case N4JSPackage.ANNOTABLE_SCRIPT_ELEMENT___GET_ANNOTATIONS:
return N4JSPackage.N4_TYPE_DECLARATION___GET_ANNOTATIONS;
default :
return -1;
}
}
if (baseClass == ModifiableElement.class) {
switch (baseOperationID) {
default :
return -1;
}
}
if (baseClass == ExportableElement.class) {
switch (baseOperationID) {
case N4JSPackage.EXPORTABLE_ELEMENT___IS_EXPORTED:
return N4JSPackage.N4_TYPE_DECLARATION___IS_EXPORTED;
case N4JSPackage.EXPORTABLE_ELEMENT___IS_EXPORTED_AS_DEFAULT:
return N4JSPackage.N4_TYPE_DECLARATION___IS_EXPORTED_AS_DEFAULT;
case N4JSPackage.EXPORTABLE_ELEMENT___GET_EXPORTED_NAME:
return N4JSPackage.N4_TYPE_DECLARATION___GET_EXPORTED_NAME;
case N4JSPackage.EXPORTABLE_ELEMENT___IS_TOPLEVEL:
return N4JSPackage.N4_TYPE_DECLARATION___IS_TOPLEVEL;
default :
return -1;
}
}
if (baseClass == NamedElement.class) {
switch (baseOperationID) {
case N4JSPackage.NAMED_ELEMENT___GET_NAME:
return N4JSPackage.N4_TYPE_DECLARATION___GET_NAME;
default :
return -1;
}
}
return super.eDerivedOperationID(baseOperationID,baseClass);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void addObject(SimpleBeanObject object){
beans.put(new Long(object.getId()),object);
String customGraphicClassName=object.getCustomGraphicClassName();
OMGraphic graphic=null;
if (customGraphicClassName == null) {
ImageIcon icon=new ImageIcon(object.getGraphicImage());
int width=icon.getIconWidth();
int height=icon.getIconHeight();
graphic=new OMRaster(object.getLatitude(),object.getLongitude(),-width / 2,-height / 2,icon);
((OMRaster)graphic).setRotationAngle(Math.toRadians(object.getBearingInDeg()));
graphic.setRenderType(OMGraphicConstants.RENDERTYPE_OFFSET);
graphic.putAttribute(OMGraphic.APP_OBJECT,new Long(object.getId()));
}
else {
try {
Class graphicClass=Class.forName(customGraphicClassName);
Class parentClass=graphicClass;
while (parentClass != null) {
if (parentClass == CustomGraphic.class) {
break;
}
else parentClass=parentClass.getSuperclass();
}
if (parentClass != null) {
Constructor constructor=graphicClass.getConstructor(new Class[]{SimpleBeanObject.class});
graphic=(CustomGraphic)constructor.newInstance(new Object[]{object});
}
}
catch ( Exception e) {
e.printStackTrace();
}
}
if (graphic != null) {
graphic.setNeedToRegenerate(true);
graphics.put(new Long(object.getId()),graphic);
if (projection != null) graphic.generate(projection);
repaint();
}
}
| Adds a bean to this layer. |
public void delete(int id){
final ProviderIdentifier providerIdentifier=mPlaylist.getProvider();
try {
ProviderConnection connection=PluginsLookup.getDefault().getProvider(providerIdentifier);
if (connection != null) {
IMusicProvider binder=connection.getBinder();
if (binder != null) {
binder.deleteSongFromPlaylist(id,mPlaylist.getRef());
}
}
mSongs.remove(id);
mIds.remove(id);
mVisible.remove(id);
resetIds();
}
catch ( RemoteException e) {
Log.e(TAG,"Error: " + e.getMessage());
}
}
| Removes the provided item from the playlist on the view and from the playlist on the provider |
private XMLBuilder.Node showQuery(final HttpServletRequest req,final HttpServletResponse resp,final Writer w,XMLBuilder.Node current,final IRunningQuery q,final RunningQuery acceptedQuery,final boolean showQueryDetails,final int maxBopLength) throws IOException {
final UUID queryId=q.getQueryId();
final IRunningQuery[] children=((AbstractRunningQuery)q).getChildren();
final long elapsedMillis=q.getElapsed();
current.node("h1","Query");
{
current=current.node("FORM").attr("method","POST").attr("action","");
final String detailsURL=req.getRequestURL().append("?").append(SHOW_QUERIES).append("=").append(DETAILS).append("&").append(QUERY_ID).append("=").append(queryId.toString()).toString();
final BOpStats stats=q.getStats().get(q.getQuery().getId());
final String solutionsOut=stats == null ? NA : Long.toString(stats.unitsOut.get());
final String chunksOut=stats == null ? NA : Long.toString(stats.chunksOut.get());
current.node("p").text("solutions=").node("span").attr("class","solutions").text("" + solutionsOut).close().text(", chunks=").node("span").attr("class","chunks").text("" + chunksOut).close().text(", children=").node("span").attr("class","children").text("" + children.length).close().text(", elapsed=").node("span").attr("class","elapsed").text("" + elapsedMillis).close().text("ms, ").node("a").attr("href",detailsURL).attr("class","details-url").text("details").close().close();
current=current.node("p");
current.node("INPUT").attr("type","hidden").attr("name","queryId").attr("value",queryId).close();
current.node("INPUT").attr("type","submit").attr("name",CANCEL_QUERY).attr("value","Cancel").close();
current=current.close();
current=current.close();
}
final String queryString;
if (acceptedQuery != null) {
final ASTContainer astContainer=acceptedQuery.queryTask.astContainer;
queryString=astContainer.getQueryString();
if (queryString != null) {
current.node("h2","SPARQL");
current.node("p").attr("class","query-string").text(queryString).close();
}
if (showQueryDetails) {
final SimpleNode parseTree=((SimpleNode)astContainer.getParseTree());
if (parseTree != null) {
current.node("h2","Parse Tree");
current.node("p").attr("class","parse-tree").text(parseTree.dump("")).close();
}
final QueryRoot originalAST=astContainer.getOriginalAST();
if (originalAST != null) {
current.node("h2","Original AST");
current.node("p").attr("class","original-ast").text(originalAST.toString()).close();
}
final QueryRoot optimizedAST=astContainer.getOptimizedAST();
if (optimizedAST != null) {
current.node("h2","Optimized AST");
current.node("p").attr("class","optimized-ast").text(optimizedAST.toString()).close();
}
final PipelineOp queryPlan=astContainer.getQueryPlan();
if (queryPlan != null) {
current.node("h2","Query Plan");
current.node("p").attr("class","query-plan").text(BOpUtility.toString(queryPlan)).close();
}
}
}
else {
queryString="N/A";
}
if (showQueryDetails) {
current.node("h2","Query Evaluation Statistics");
final boolean clusterStats=q.getFederation() != null;
final boolean detailedStats=false;
final boolean mutationStats=false;
QueryLog.getTableXHTML(queryString,q,children,w,!showQueryDetails,maxBopLength,clusterStats,detailedStats,mutationStats);
}
return current;
}
| Paint a single query. |
public void define(HGHandle handle,HGHandle type,Object instance,int flags){
graph.define(handle,type,instance,flags);
add(handle);
}
| Define in global graph and mark as member of this subgraph. |
String paramToString(){
return parameterization.toString();
}
| For debugging. |
public static ColorWithEnum newInstance(int colorWithEnumAsInt){
ColorWithEnum colorWithEnum=new ColorWithEnum();
colorWithEnum.colorWithEnumAsInt=colorWithEnumAsInt;
return colorWithEnum;
}
| Create a new instance of ColorWithEnum with value set as a integer. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 15:01:21.249 -0400",hash_original_method="7361C97DE18BBD90CCD2423C0E727D3D",hash_generated_method="7361C97DE18BBD90CCD2423C0E727D3D") Index(Node<K,V> node,Index<K,V> down,Index<K,V> right){
this.node=node;
this.down=down;
this.right=right;
}
| Creates index node with given values. |
public static boolean urlEqualsHostIgnoreCase(String endpointUrl,String url){
try {
return urlEqualsHostIgnoreCase(new URI(endpointUrl),new URI(url));
}
catch ( URISyntaxException e) {
return false;
}
}
| Check if the endpointUrl matches the url, except for the hostname part. |
private boolean isPeriod(String period){
return period.contains(RANGE_SEP);
}
| Return true if the days expression is a period For example 'Sa-Su' is a period, 'Tu' is not. |
public void fixupVariables(java.util.Vector vars,int globalsSize){
super.fixupVariables(vars,globalsSize);
if (null != m_arg1) m_arg1.fixupVariables(vars,globalsSize);
}
| This function is used to fixup variables from QNames to stack frame indexes at stylesheet build time. |
public StageActivityTypesImpl(final String type){
this(Collections.singleton(type));
}
| Initializes an instance with a single type |
public TMemberEntry(String name,boolean _static){
this.name=name;
this._static=_static;
}
| Creates a new entry for a member with given name and static modifier. The actual members are to be added via the add methods. |
public SummaryPanel(final SynapseGroup sg){
setGroup(sg);
incomingGroupLabel.setText("Source Group: ");
outgoingGroupLabel.setText("Target Group: ");
fillFieldValues();
initializeLayout();
}
| Constructs the summary panel based on a synapse group. Names the incoming and outgoing labels appropriately (Source Group/Target Group). |
public int advanceToNextRow(){
int bytesNextRow;
if (deinterlacer == null) {
bytesNextRow=getRown() >= imgInfo.rows - 1 ? 0 : imgInfo.bytesPerRow + 1;
}
else {
boolean more=deinterlacer.nextRow();
bytesNextRow=more ? deinterlacer.getBytesToRead() + 1 : 0;
}
if (!isCallbackMode()) {
prepareForNextRow(bytesNextRow);
}
return bytesNextRow;
}
| Signals that we are done with the previous row, begin reading the next one. <p> In polled mode, calls setNextRowLen() <p> Warning: after calling this, the unfilterRow is invalid! |
public static int findNextWordStartNTE(String s,int startIndex){
int i=startIndex;
for (; i < s.length(); i++) {
char currChar=s.charAt(i);
if (Character.isLetterOrDigit(currChar) || getNteChars(currChar) != null) {
return i;
}
}
return i;
}
| Given a String and a start index, returns the next index where there is a alpha or numeric character indicating the start of a word -- including the current string position |
protected void moveLocation(ControlPointMarker controlPoint,Position terrainPosition,List<LatLon> locations){
Vec4 delta=this.computeControlPointDelta(this.getPreviousPosition(),terrainPosition);
Vec4 markerPoint=getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(new Position(controlPoint.getPosition(),0));
Position markerPosition=getWwd().getModel().getGlobe().computePositionFromEllipsoidalPoint(markerPoint.add3(delta));
locations.set(controlPoint.getId(),markerPosition);
}
| Moves a control point location. |
public Object[] patch_apply(LinkedList<Patch> patches,String text){
if (patches.isEmpty()) {
return new Object[]{text,new boolean[0]};
}
patches=patch_deepCopy(patches);
String nullPadding=patch_addPadding(patches);
text=nullPadding + text + nullPadding;
patch_splitMax(patches);
int x=0;
int delta=0;
boolean[] results=new boolean[patches.size()];
for ( Patch aPatch : patches) {
int expected_loc=aPatch.start2 + delta;
String text1=diff_text1(aPatch.diffs);
int start_loc;
int end_loc=-1;
if (text1.length() > this.Match_MaxBits) {
start_loc=match_main(text,text1.substring(0,this.Match_MaxBits),expected_loc);
if (start_loc != -1) {
end_loc=match_main(text,text1.substring(text1.length() - this.Match_MaxBits),expected_loc + text1.length() - this.Match_MaxBits);
if (end_loc == -1 || start_loc >= end_loc) {
start_loc=-1;
}
}
}
else {
start_loc=match_main(text,text1,expected_loc);
}
if (start_loc == -1) {
results[x]=false;
delta-=aPatch.length2 - aPatch.length1;
}
else {
results[x]=true;
delta=start_loc - expected_loc;
String text2;
if (end_loc == -1) {
text2=text.substring(start_loc,Math.min(start_loc + text1.length(),text.length()));
}
else {
text2=text.substring(start_loc,Math.min(end_loc + this.Match_MaxBits,text.length()));
}
if (text1.equals(text2)) {
text=text.substring(0,start_loc) + diff_text2(aPatch.diffs) + text.substring(start_loc + text1.length());
}
else {
LinkedList<Diff> diffs=diff_main(text1,text2,false);
if (text1.length() > this.Match_MaxBits && diff_levenshtein(diffs) / (float)text1.length() > this.Patch_DeleteThreshold) {
results[x]=false;
}
else {
diff_cleanupSemanticLossless(diffs);
int index1=0;
for ( Diff aDiff : aPatch.diffs) {
if (aDiff.operation != Operation.EQUAL) {
int index2=diff_xIndex(diffs,index1);
if (aDiff.operation == Operation.INSERT) {
text=text.substring(0,start_loc + index2) + aDiff.text + text.substring(start_loc + index2);
}
else if (aDiff.operation == Operation.DELETE) {
text=text.substring(0,start_loc + index2) + text.substring(start_loc + diff_xIndex(diffs,index1 + aDiff.text.length()));
}
}
if (aDiff.operation != Operation.DELETE) {
index1+=aDiff.text.length();
}
}
}
}
}
x++;
}
text=text.substring(nullPadding.length(),text.length() - nullPadding.length());
return new Object[]{text,results};
}
| Merge a set of patches onto the text. Return a patched text, as well as an array of true/false values indicating which patches were applied. |
public BigInteger calculateSecret(BigInteger serverB) throws CryptoException {
this.B=SRP6Util.validatePublicValue(N,serverB);
this.u=SRP6Util.calculateU(digest,N,A,B);
this.S=calculateS();
return S;
}
| Generates the secret S given the server's credentials |
public WAppsAction(String action,String accelerator) throws IOException {
this(action,accelerator,null);
}
| Application Action |
public void closeNetwork(){
}
| Close model Network. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-25 15:47:16.629 -0400",hash_original_method="618D7845515FD0AE91AC232728DBE8EB",hash_generated_method="10A12555120830F4CD4383CA872BA8B8") public void pair(BluetoothAdapter adapter,BluetoothDevice device,int passkey,byte[] pin){
pairOrAcceptPair(adapter,device,passkey,pin,true);
}
| Initiates a pairing with a remote device and checks to make sure that the devices are paired and that the correct actions were broadcast. |
private SelectResults evaluateOrJunction(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
SelectResults[] grpResults=new SelectResults[1];
List finalList=context.getCurrentIterators();
RuntimeIterator[][] itrsForResultFields=new RuntimeIterator[1][];
CompiledValue gj=null;
Iterator junctionItr=this.abstractGroupOrRangeJunctions.iterator();
List grpItrs=null;
RuntimeIterator tempItr=null;
SelectResults intermediateResults=null;
while (junctionItr.hasNext()) {
List expansionList=new LinkedList(finalList);
gj=(CompiledValue)junctionItr.next();
grpResults[0]=((Filter)gj).filterEvaluate(context,null);
grpItrs=(gj instanceof CompositeGroupJunction) ? QueryUtils.getDependentItrChainForIndpndntItrs(((CompositeGroupJunction)gj).getIndependentIteratorsOfCJ(),context) : context.getCurrScopeDpndntItrsBasedOnSingleIndpndntItr(((AbstractGroupOrRangeJunction)gj).getIndependentIteratorForGroup()[0]);
itrsForResultFields[0]=new RuntimeIterator[grpItrs.size()];
Iterator grpItr=grpItrs.iterator();
int k=0;
while (grpItr.hasNext()) {
tempItr=(RuntimeIterator)grpItr.next();
itrsForResultFields[0][k++]=tempItr;
expansionList.remove(tempItr);
}
SelectResults expandedResult=QueryUtils.cartesian(grpResults,itrsForResultFields,expansionList,finalList,context,null);
intermediateResults=(intermediateResults == null) ? expandedResult : QueryUtils.union(expandedResult,intermediateResults,context);
}
return intermediateResults;
}
| Evaluates the individual GroupJunctions and CompositeGroupJunctions and expands the individual results so obtained to the query from clause iterator level ( i.e top level iterators). The expanded results so obtained are then merged (union) to get the ORed results.The evaluated result of an AllGroupJunction will always be of the query from clause iterator level (top level) which can be ORed or ANDd with filter evaluable subtree CompiledJunction. |
public ReplDBMSFilteredEvent(Long firstFilteredSeqno,Short firstFilteredFragno,Long lastFilteredSeqno,Short lastFilteredFragno,boolean lastFrag,String eventId,String sourceId,Timestamp timestamp,long epochNumber){
super(firstFilteredSeqno,new DBMSEvent(eventId,null,timestamp));
this.seqnoEnd=lastFilteredSeqno;
this.fragno=firstFilteredFragno;
this.fragnoEnd=lastFilteredFragno;
this.lastFrag=lastFrag;
this.sourceId=sourceId;
this.extractedTstamp=timestamp;
this.epochNumber=epochNumber;
}
| Method to instantiate a filtered event from header data of the first event in the sequence plus the end seqno and fragno of the last event. |
public boolean isCommandList(){
return commandList;
}
| Indicates that the list should be treated as a list of commands, if the user "clicks" a command from the list its action performed method is invoked. |
private void handleChannelInfoResultError(String stream,RequestType type,int responseCode){
if (type == RequestType.CHANNEL) {
if (responseCode == 404) {
resultListener.receivedChannelInfo(stream,null,RequestResult.NOT_FOUND);
}
else {
resultListener.receivedChannelInfo(stream,null,RequestResult.FAILED);
}
}
else {
if (responseCode == 404) {
resultListener.putChannelInfoResult(RequestResult.NOT_FOUND);
}
else if (responseCode == 401 || responseCode == 403) {
LOGGER.warning("Error setting channel info: Access denied");
resultListener.putChannelInfoResult(RequestResult.ACCESS_DENIED);
accessDenied();
}
else if (responseCode == 422) {
LOGGER.warning("Error setting channel info: Probably invalid title");
resultListener.putChannelInfoResult(RequestResult.INVALID_STREAM_STATUS);
}
else {
LOGGER.warning("Error setting channel info: Unknown error (" + responseCode + ")");
resultListener.putChannelInfoResult(RequestResult.FAILED);
}
}
}
| Handle the error of a ChannelInfo request result, this can be from changing the channel info as well. Handle by logging the error as well as informing the client who can inform the user on the GUI. |
@SuppressWarnings({"unchecked","rawtypes"}) @Override public void endWindow(){
if (!mins.isEmpty()) {
for ( Map.Entry<K,V> e : mins.entrySet()) {
min.emit(new KeyValPair(e.getKey(),e.getValue()));
}
mins.clear();
}
}
| Emits all key,min value pairs. Clears internal data. Node only works in windowed mode. |
public String prepareIt(){
if (!isValidAction(ACTION_Prepare)) return m_status;
if (m_document != null) {
m_status=m_document.prepareIt();
m_document.setDocStatus(m_status);
}
return m_status;
}
| Process Document. Status is set by process |
public void testBasics() throws IOException {
Analyzer a=new IndonesianAnalyzer();
checkOneTerm(a,"peledakan","ledak");
checkOneTerm(a,"pembunuhan","bunuh");
assertAnalyzesTo(a,"bahwa",new String[]{});
a.close();
}
| test stopwords and stemming |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.