code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public ComputeElementRestRep rediscover(URI id){
return client.post(ComputeElementRestRep.class,getIdUrl() + "/discover",id);
}
| Rediscover a compute element. <p> API Call: <tt>POST /vdc/compute-elements/{id}/discover</tt> |
public Iterator<E> iterator(){
return new Itr();
}
| Returns an iterator over the elements in this queue in proper sequence. The elements will be returned in order from first (head) to last (tail). <p>The returned iterator is <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
public int addAggregate(AggregateFunctionExpression aggregate){
int position=groupBy.size() + aggregates.size();
aggregates.add(aggregate);
options.add(aggregate.getOption());
return position;
}
| Add a new aggregate and return its position. |
public static void main(String args[]) throws Exception {
Security.setProperty("jdk.tls.disabledAlgorithms","");
setupBasePort();
RmiBootstrapTest manager=new RmiBootstrapTest();
try {
manager.run(args);
}
catch ( RuntimeException r) {
System.out.println("Test Failed: " + r.getMessage());
System.exit(1);
}
catch ( Throwable t) {
System.out.println("Test Failed: " + t);
t.printStackTrace();
System.exit(2);
}
System.out.println("**** Test RmiBootstrap Passed ****");
}
| Calls run(args[]). exit(1) if the test fails. |
@Override protected void drawXLabels(List<Double> xLabels,Double[] xTextLabelLocations,Canvas canvas,Paint paint,int left,int top,int bottom,double xPixelsPerUnit,double minX,double maxX){
int length=xLabels.size();
if (length > 0) {
boolean showLabels=mRenderer.isShowLabels();
boolean showGridY=mRenderer.isShowGridY();
boolean showTickMarks=mRenderer.isShowTickMarks();
DateFormat format=getDateFormat(xLabels.get(0),xLabels.get(length - 1));
for (int i=0; i < length; i++) {
long label=Math.round(xLabels.get(i));
float xLabel=(float)(left + xPixelsPerUnit * (label - minX));
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
if (showTickMarks) {
canvas.drawLine(xLabel,bottom,xLabel,bottom + mRenderer.getLabelsTextSize() / 3,paint);
}
drawText(canvas,format.format(new Date(label)),xLabel,bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding(),paint,mRenderer.getXLabelsAngle());
}
if (showGridY) {
paint.setColor(mRenderer.getGridColor(0));
canvas.drawLine(xLabel,bottom,xLabel,top,paint);
}
}
}
drawXTextLabels(xTextLabelLocations,canvas,paint,true,left,top,bottom,xPixelsPerUnit,minX,maxX);
}
| The graphical representation of the labels on the X axis. |
public List<EvaluationStatistics> retrieve(MultiLabelClassifier classifier,Instances dataset){
List<EvaluationStatistics> result;
String cls;
String rel;
result=new ArrayList<>();
cls=Utils.toCommandLine(classifier);
rel=dataset.relationName();
for ( EvaluationStatistics stat : m_Statistics) {
if (stat.getCommandLine().equals(cls) && stat.getRelation().equals(rel)) result.add(stat);
}
return result;
}
| Retrieves the statis for the specified combination of classifier and dataset. |
public static boolean isLeapYear(int year){
return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
}
| Determines if a year is a leap year. |
public void updateGeoDescription(Context context,String fallbackNumber){
String number=TextUtils.isEmpty(phoneNumber) ? fallbackNumber : phoneNumber;
geoDescription=getGeoDescription(context,number);
}
| Updates this CallerInfo's geoDescription field, based on the raw phone number in the phoneNumber field. (Note that the various getCallerInfo() methods do *not* set the geoDescription automatically; you need to call this method explicitly to get it.) |
synchronized SignatureData createSignatureData(String signature,int signerIndex){
return new SignatureData(signature,hashChainResult,hashChains != null ? hashChains[signerIndex] : null);
}
| Returns the signature data for a given signer -- either normal signature or batch signature with corresponding hash chain and hash chain result. |
public SimpleScheduleBuilder withIntervalInMinutes(int intervalInMinutes){
this.interval=intervalInMinutes * DateBuilder.MILLISECONDS_IN_MINUTE;
return this;
}
| Specify a repeat interval in minutes - which will then be multiplied by 60 * 1000 to produce milliseconds. |
public CShowOptionsDialogAction(final JFrame parent,final DebugTargetSettings debugTarget,final IDebugger debugger){
super("Show Options");
Preconditions.checkNotNull(parent,"IE01471: Parent argument can not be null");
Preconditions.checkNotNull(debugTarget,"IE01472: Debug target argument can not be null");
Preconditions.checkNotNull(debugger,"IE01473: Options argument can not be null");
m_parent=parent;
m_debugTarget=debugTarget;
m_debugger=debugger;
}
| Creates a new action object. |
public synchronized OMGraphicList prepare(){
Projection projection=getProjection();
if (projection == null) {
Debug.error("DTED Layer needs to be added to the MapBean before it can draw images!");
return new OMGraphicList();
}
DTEDCacheManager cache=getCache();
if (!(projection instanceof EqualArc)) {
}
Debug.message("basic",getName() + "|DTEDLayer.prepare(): doing it");
if (Debug.debugging("dted")) {
Debug.output(getName() + "|DTEDLayer.prepare(): " + "calling getRectangle "+ " with projection: "+ projection+ " ul = "+ projection.getUpperLeft()+ " lr = "+ projection.getLowerRight());
}
OMGraphicList omGraphicList;
if (projection.getScale() < maxScale) {
omGraphicList=cache.getRectangle(projection);
}
else {
fireRequestInfoLine(" The scale is too small for DTED viewing.");
Debug.error("DTEDLayer: scale (1:" + projection.getScale() + ") is smaller than minimum (1:"+ maxScale+ ") allowed.");
omGraphicList=new OMGraphicList();
}
int size=0;
if (omGraphicList != null) {
size=omGraphicList.size();
Debug.message("basic",getName() + "|DTEDLayer.prepare(): finished with " + size+ " graphics");
}
else {
Debug.message("basic",getName() + "|DTEDLayer.prepare(): finished with null graphics list");
}
return omGraphicList;
}
| Prepares the graphics for the layer. This is where the getRectangle() method call is made on the dted. <p> Occasionally it is necessary to abort a prepare call. When this happens, the map will set the cancel bit in the LayerThread, (the thread that is running the prepare). If this Layer needs to do any cleanups during the abort, it should do so, but return out of the prepare asap. |
Circle2D(){
this(0,0,1);
}
| Create a default Circle2D with (0,0) for (x,y) and 1 for radius |
public Graph search(){
lookupArrows=new ConcurrentHashMap<>();
final List<Node> nodes=new ArrayList<>(variables);
this.effectEdgesGraph=getEffectEdges(nodes);
if (adjacencies != null) {
adjacencies=GraphUtils.replaceNodes(adjacencies,nodes);
}
Graph graph;
if (initialGraph == null) {
graph=new EdgeListGraphSingleConnections(getVariables());
}
else {
graph=new EdgeListGraphSingleConnections(initialGraph);
for ( Edge edge : initialGraph.getEdges()) {
if (!effectEdgesGraph.isAdjacentTo(edge.getNode1(),edge.getNode2())) {
effectEdgesGraph.addUndirectedEdge(edge.getNode1(),edge.getNode2());
}
}
}
addRequiredEdges(graph);
topGraphs.clear();
storeGraph(graph);
long start=System.currentTimeMillis();
score=0.0;
fes(graph);
bes(graph);
long endTime=System.currentTimeMillis();
this.elapsedTime=endTime - start;
this.logger.log("graph","\nReturning this graph: " + graph);
this.logger.log("info","Elapsed time = " + (elapsedTime) / 1000. + " s");
this.logger.flush();
return graph;
}
| Greedy equivalence search: Start from the empty graph, add edges till model is significant. Then start deleting edges till a minimum is achieved. |
private static void write(CharSequence from,File to,Charset charset,boolean append) throws IOException {
asCharSink(to,charset,modes(append)).write(from);
}
| Private helper method. Writes a character sequence to a file, optionally appending. |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:13.011 -0500",hash_original_method="64392856CD4BE8946E6224874D95C0C3",hash_generated_method="BCF93A278DC9D95CE64E1A5A048773E7") private int socksGetServerPort(){
InetSocketAddress addr=(InetSocketAddress)proxy.address();
return addr.getPort();
}
| Gets the SOCKS proxy server port. |
private void writeMajorStatisticsString(BufferedWriter output,SAZone zone) throws IOException {
output.write(zone.getName());
output.write(delimiter);
output.write(String.valueOf(zone.getMajorActivityCount()));
output.write(delimiter);
for (int i=0; i < 24; i++) {
output.write(String.valueOf(zone.getMajorActivityCountDetail(i)));
output.write(delimiter);
}
for (int i=0; i < 23; i++) {
output.write(String.valueOf(zone.getMajorActivityDurationDetail(i)));
output.write(delimiter);
}
output.write(String.valueOf(zone.getMajorActivityDurationDetail(23)));
output.newLine();
}
| Method to create a statistics string for 'major' activities. |
public MockHttpSession(ServletContext servletContext,String id){
this.servletContext=(servletContext != null ? servletContext : new MockServletContext());
this.id=(id != null ? id : Integer.toString(nextId++));
}
| Create a new MockHttpSession. |
private EditVariableDialog(final Window parent,final String title,final String variableName){
super(parent,title,ModalityType.APPLICATION_MODAL);
this.parent=parent;
setLayout(new BorderLayout());
new CDialogEscaper(this);
nameField.setText(variableName);
nameField.setSelectionStart(0);
nameField.setSelectionEnd(Integer.MAX_VALUE);
final JPanel upperPanel=new JPanel(new BorderLayout());
upperPanel.add(nameField,BorderLayout.NORTH);
upperPanel.setBorder(new TitledBorder(""));
final CPanelTwoButtons panel=new CPanelTwoButtons(new InternalActionListener(),"OK","Cancel");
add(upperPanel,BorderLayout.NORTH);
add(panel,BorderLayout.SOUTH);
setSize(300,100);
setResizable(false);
final InputMap windowImap=getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
windowImap.put(HotKeys.APPLY_HK.getKeyStroke(),"APPLY");
getRootPane().getActionMap().put("APPLY",CActionProxy.proxy(new ApplyAction()));
GuiHelper.centerChildToParent(parent,this,true);
}
| Creates a new dialog to rename a variable. |
public static void addGzipHeader(HttpServletResponse response) throws GzipResponseHeadersNotModifiableException {
response.setHeader("Content-Encoding","gzip");
boolean containsEncoding=response.containsHeader("Content-Encoding");
if (!containsEncoding) {
throw new GzipResponseHeadersNotModifiableException("Failure when attempting to set " + "Content-Encoding: gzip");
}
}
| Adds the gzip HTTP header to the response. <p/> <p> This is need when a gzipped body is returned so that browsers can properly decompress it. </p> |
public void store(Word value,Offset offset){
}
| Stores the word value in the memory location pointed to by the current instance. |
public static MemcacheClientBuilder<String> newStringClient(Charset charset){
return new MemcacheClientBuilder<>(new StringTranscoder(charset));
}
| Create a client builder with a basic string transcoder using the supplied Charset. |
static void loadActionMap(LazyActionMap map){
map.put(new Actions(Actions.TOGGLE_SORT_ORDER));
map.put(new Actions(Actions.SELECT_COLUMN_TO_LEFT));
map.put(new Actions(Actions.SELECT_COLUMN_TO_RIGHT));
map.put(new Actions(Actions.MOVE_COLUMN_LEFT));
map.put(new Actions(Actions.MOVE_COLUMN_RIGHT));
map.put(new Actions(Actions.RESIZE_LEFT));
map.put(new Actions(Actions.RESIZE_RIGHT));
map.put(new Actions(Actions.FOCUS_TABLE));
}
| Populates TableHeader's actions. |
protected void initModel() throws Exception {
if (m_Model == null) {
m_Model=(Classifier)SerializationHelper.read(m_ModelFile.getAbsolutePath());
}
}
| loads the serialized model if necessary, throws an Exception if the derserialization fails. |
@Override public void teardown(){
}
| a noop |
public DenseFeatureStore(){
this.instanceList=new ObjectArrayList<>();
this.featureNames=null;
}
| Creates an empty feature store |
public ImageIcon loadImage(String imageName){
try {
ClassLoader classloader=getClass().getClassLoader();
java.net.URL url=classloader.getResource(imageName);
if (url != null) {
ImageIcon icon=new ImageIcon(url);
return icon;
}
}
catch ( Exception e) {
e.printStackTrace();
}
throw new IllegalArgumentException("Unable to load image: " + imageName);
}
| Helper method to load an image file from the CLASSPATH |
public void remove(XAtom atom){
atoms.remove(atom);
}
| Removes atom from the list. Does nothing if arrays doesn't conaint this atom. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
return new Integer(!Sage.WINDOWS_OS ? 0 : Sage.readDwordValue(Sage.HKEY_LOCAL_MACHINE,"SOFTWARE\\Frey Technologies\\Common\\DSFilters\\MpegDeMux","AudioDelay"));
}
| Gets the audio delay in milliseconds to apply when playing back MPEG2 files (Windows only) |
public int rank(DoubleMatrix2D A){
return svd(A).rank();
}
| Returns the effective numerical rank of matrix <tt>A</tt>, obtained from Singular Value Decomposition. |
private String encodeToString(String in,int flags) throws Exception {
String b64=Base64.encodeToString(in.getBytes(),flags);
String dec=decodeString(b64);
assertEquals(in,dec);
return b64;
}
| Encodes the string 'in' using 'flags'. Asserts that decoding gives the same string. Returns the encoded string. |
public boolean login(final String userName,final String hashedPassword){
final Connection con=Database.getConnection();
try {
PreparedStatement ps=con.prepareStatement("select username from ta_users where username = ? and password = ?");
ps.setString(1,userName);
ps.setString(2,hashedPassword);
final ResultSet rs=ps.executeQuery();
if (!rs.next()) {
return false;
}
ps.close();
rs.close();
ps=con.prepareStatement("update ta_users set lastLogin = ? where username = ? ");
ps.setTimestamp(1,new Timestamp(System.currentTimeMillis()));
ps.setString(2,userName);
ps.execute();
ps.close();
return true;
}
catch ( final SQLException sqle) {
s_logger.log(Level.SEVERE,"Error validating password name:" + userName + " : "+ " pwd:"+ hashedPassword,sqle);
throw new IllegalStateException(sqle.getMessage());
}
finally {
DbUtil.closeConnection(con);
}
}
| Validate the username password, returning true if the user is able to login. This has the side effect of updating the users last login time. |
public long xminimum(){
return this.minValue;
}
| deprecated Returns the minimum element legal to the stored in the receiver. Remark: This does not mean that such a minimum element is currently contained in the receiver. |
public StringRequest(int method,String url,Listener<String> listener,ErrorListener errorListener){
super(method,url,errorListener);
mListener=listener;
}
| Creates a new request with the given method. |
public void test_getPeerPort() throws NoSuchAlgorithmException {
SSLEngine e=getEngine();
assertEquals("Incorrect default value of peer port",-1,e.getPeerPort());
e=getEngine("www.fortify.net",80);
assertEquals("Incorrect peer port",80,e.getPeerPort());
}
| Test for <code>getPeerPort()</code> method |
public static boolean allAscii(String s){
int len=s.length();
for (int i=0; i < len; ++i) {
if ((s.charAt(i) & 0xff80) != 0) {
return false;
}
}
return true;
}
| Determines if a string contains only ascii characters |
public DoubleVector cat(DoubleVector v){
DoubleVector w=new DoubleVector(size() + v.size());
w.set(0,size() - 1,this,0);
w.set(size(),size() + v.size() - 1,v,0);
return w;
}
| Combine two vectors together |
public void removeKey(K key){
map.remove(key);
}
| Completely removes all values associated with a key |
protected JvmRuntimeMeta createJvmRuntimeMetaNode(String groupName,String groupOid,ObjectName groupObjname,MBeanServer server){
return new JvmRuntimeMetaImpl(this,objectserver);
}
| Factory method for "JvmRuntime" group metadata class. You can redefine this method if you need to replace the default generated metadata class with your own customized class. |
public boolean calculateTaxTotal(){
log.fine("");
DB.executeUpdateEx("DELETE C_OrderTax WHERE C_Order_ID=" + getC_Order_ID(),get_TrxName());
m_taxes=null;
BigDecimal totalLines=Env.ZERO;
ArrayList<Integer> taxList=new ArrayList<Integer>();
MOrderLine[] lines=getLines();
for (int i=0; i < lines.length; i++) {
MOrderLine line=lines[i];
Integer taxID=new Integer(line.getC_Tax_ID());
if (!taxList.contains(taxID)) {
MOrderTax oTax=MOrderTax.get(line,getPrecision(),false,get_TrxName());
oTax.setIsTaxIncluded(isTaxIncluded());
if (!oTax.calculateTaxFromLines()) return false;
if (!oTax.save(get_TrxName())) return false;
taxList.add(taxID);
}
totalLines=totalLines.add(line.getLineNetAmt());
}
BigDecimal grandTotal=totalLines;
MOrderTax[] taxes=getTaxes(true);
for (int i=0; i < taxes.length; i++) {
MOrderTax oTax=taxes[i];
MTax tax=oTax.getTax();
if (tax.isSummary()) {
MTax[] cTaxes=tax.getChildTaxes(false);
for (int j=0; j < cTaxes.length; j++) {
MTax cTax=cTaxes[j];
BigDecimal taxAmt=cTax.calculateTax(oTax.getTaxBaseAmt(),isTaxIncluded(),getPrecision());
MOrderTax newOTax=new MOrderTax(getCtx(),0,get_TrxName());
newOTax.setClientOrg(this);
newOTax.setC_Order_ID(getC_Order_ID());
newOTax.setC_Tax_ID(cTax.getC_Tax_ID());
newOTax.setPrecision(getPrecision());
newOTax.setIsTaxIncluded(isTaxIncluded());
newOTax.setTaxBaseAmt(oTax.getTaxBaseAmt());
newOTax.setTaxAmt(taxAmt);
if (!newOTax.save(get_TrxName())) return false;
if (!isTaxIncluded()) grandTotal=grandTotal.add(taxAmt);
}
if (!oTax.delete(true,get_TrxName())) return false;
if (!oTax.save(get_TrxName())) return false;
}
else {
if (!isTaxIncluded()) grandTotal=grandTotal.add(oTax.getTaxAmt());
}
}
setTotalLines(totalLines);
setGrandTotal(grandTotal);
return true;
}
| Calculate Tax and Total |
Log createLogFromClassName(String classLabel) throws Exception {
Class<?> clazz=Class.forName(logClassName);
@SuppressWarnings("unchecked") Constructor<Log> constructor=(Constructor<Log>)clazz.getConstructor(String.class);
return constructor.newInstance(classLabel);
}
| Try to create the log from the class name which may throw. |
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:13.733 -0500",hash_original_method="AF3B09D914ADDB679280100B7539789D",hash_generated_method="AF3B09D914ADDB679280100B7539789D") void restartConnection(boolean proceed){
if (HttpLog.LOGV) {
HttpLog.v("HttpsConnection.restartConnection():" + " proceed: " + proceed);
}
synchronized (mSuspendLock) {
if (mSuspended) {
mSuspended=false;
mAborted=!proceed;
mSuspendLock.notify();
}
}
}
| Restart a secure connection suspended waiting for user interaction. |
public void addHam(Reader stream) throws java.io.IOException {
addTokenOccurrences(stream,hamTokenCounts);
hamMessageCount++;
}
| Adds a message to the ham list. |
public void addTree(Tree tree,HashMap<String,Integer> taxonMap){
samples++;
List<Clade> clades=new ArrayList<Clade>();
List<Clade> parentClades=new ArrayList<Clade>();
getClades(tree,tree.getRoot(),parentClades,clades,taxonMap);
for ( Clade c : clades) {
if (cladeProbabilities.containsKey(c.getBits())) {
Clade tmp=cladeProbabilities.get(c.getBits());
tmp.addHeight(c.getHeight());
}
else {
c.addHeight(c.getHeight());
cladeProbabilities.put(c.getBits(),c);
}
}
}
| increments the number of occurrences for all conditional clades |
public void createUnderlying(){
if (Platform.isFxApplicationThread()) {
options=new com.lynden.gmapsfx.shapes.PolylineOptions();
if (path != null) {
LatLong[] ary=path.stream().map(null).collect(Collectors.toList()).toArray(new LatLong[0]);
MVCArray a=new MVCArray(ary);
options.path(a);
if (getStrokeColor() != null) {
options.strokeColor(getStrokeColor());
}
options.clickable(isClickable());
options.draggable(isDraggable());
options.editable(isEditable());
options.visible(isVisible());
options.strokeOpacity(getStrokeOpacity());
options.strokeWeight(getStrokeWeight());
options.zIndex(getZIndex());
options.geodesic(isGeodesic());
}
}
}
| Creates the underlying PolylineOptions |
@Override public int read() throws IOException {
return in.read();
}
| Reads a single byte from the filtered stream and returns it as an integer in the range from 0 to 255. Returns -1 if the end of this stream has been reached. |
public MP3Player(PlayerCallback playerCallback){
this(playerCallback,DEFAULT_AUDIO_BUFFER_CAPACITY_MS,DEFAULT_DECODE_BUFFER_CAPACITY_MS);
}
| Creates a new player. |
@Override protected void onPause(){
super.onPause();
LOG.d(TAG,"Paused the activity.");
if (this.appView != null) {
this.appView.handlePause(this.keepRunning);
}
}
| Called when the system is about to start resuming a previous activity. |
protected void detailExecuteLogic(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
logger.info("Inicio de detailExecuteLogic");
ServiceRepository services=ServiceRepository.getInstance(ServiceClient.create(getAppUser(request)));
GestionAuditoriaBI service=services.lookupGestionAuditoriaBI();
String idPista=request.getParameter(Constants.ID);
if (idPista != null && idPista.trim().length() > 0) {
TrazaVO pista=service.getPista(idPista);
request.setAttribute(AuditoriaConstants.PISTA_KEY,pista);
List datos=service.getDatosPista(idPista);
request.setAttribute(AuditoriaConstants.DETALLE_PISTA_KEY,datos);
request.setAttribute(AuditoriaConstants.FICHA_XSL_KEY,getDefaultTemplate());
}
saveCurrentInvocation(KeysClientsInvocations.AUDITORIA_DETALLEPISTA,request);
setReturnActionFordward(request,mapping.findForward(Constants.FORWARD_DETALLE_PISTA));
}
| Muestra el detalle de una pista pistas de auditoria. |
private void createLanesFor3WayNetwork(MutableScenario sc){
LaneDefinitions11 lanes=new LaneDefinitions11Impl();
LaneDefinitionsFactory11 fac=lanes.getFactory();
LanesToLinkAssignment11 l2l=fac.createLanesToLinkAssignment(Id.create(13,Link.class));
lanes.addLanesToLinkAssignment(l2l);
LaneData11 lane=fac.createLane(Id.create(1,Lane.class));
l2l.addLane(lane);
lane.addToLinkId(Id.create(32,Link.class));
lane=fac.createLane(Id.create(2,Lane.class));
l2l.addLane(lane);
lane.addToLinkId(Id.create(34,Link.class));
l2l=fac.createLanesToLinkAssignment(Id.create(23,Link.class));
lanes.addLanesToLinkAssignment(l2l);
lane=fac.createLane(Id.create(1,Lane.class));
l2l.addLane(lane);
lane.addToLinkId(Id.create(34,Link.class));
lane=fac.createLane(Id.create(2,Lane.class));
l2l.addLane(lane);
lane.addToLinkId(Id.create(31,Link.class));
l2l=fac.createLanesToLinkAssignment(Id.create(43,Link.class));
lanes.addLanesToLinkAssignment(l2l);
lane=fac.createLane(Id.create(1,Lane.class));
l2l.addLane(lane);
lane.addToLinkId(Id.create(31,Link.class));
lane=fac.createLane(Id.create(2,Lane.class));
l2l.addLane(lane);
lane.addToLinkId(Id.create(32,Link.class));
sc.addScenarioElement(Lanes.ELEMENT_NAME,LaneDefinitionsV11ToV20Conversion.convertTo20(lanes,sc.getNetwork()));
}
| Creates lanes for the 3 way network, ids ascending from left to right |
public void testReadTime() throws Exception {
long currentTimeMillis;
long count=0;
for (int i=0; i < 5; i++) {
logger.info("System.currentTimeMillis() invocation count: " + count);
for (int j=0; j < 1000000; j++) {
count++;
currentTimeMillis=0;
currentTimeMillis=System.currentTimeMillis();
assertTrue(currentTimeMillis > 0);
}
}
}
| Test the time required to read time from the VM. |
public static int safeNegate(int value){
if (value == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer.MIN_VALUE cannot be negated");
}
return -value;
}
| Negates the input throwing an exception if it can't negate it. |
@Override public void println(int priority,String tag,String msg,Throwable tr){
String useMsg=msg;
if (useMsg == null) {
useMsg="";
}
if (tr != null) {
msg+="\n" + Log.getStackTraceString(tr);
}
Log.println(priority,tag,useMsg);
if (mNext != null) {
mNext.println(priority,tag,msg,tr);
}
}
| Prints data out to the console using Android's native log mechanism. |
@Nullable private Figure readElement(IXMLElement elem) throws IOException {
if (DEBUG) {
System.out.println("SVGInputFormat.readElement " + elem.getName() + " line:"+ elem.getLineNr());
}
Figure f=null;
if (elem.getNamespace() == null || elem.getNamespace().equals(SVG_NAMESPACE)) {
String name=elem.getName();
if (name == null) {
if (DEBUG) {
System.err.println("SVGInputFormat warning: skipping nameless element at line " + elem.getLineNr());
}
}
else if (name.equals("a")) {
f=readAElement(elem);
}
else if (name.equals("circle")) {
f=readCircleElement(elem);
}
else if (name.equals("defs")) {
readDefsElement(elem);
f=null;
}
else if (name.equals("ellipse")) {
f=readEllipseElement(elem);
}
else if (name.equals("g")) {
f=readGElement(elem);
}
else if (name.equals("image")) {
f=readImageElement(elem);
}
else if (name.equals("line")) {
f=readLineElement(elem);
}
else if (name.equals("linearGradient")) {
readLinearGradientElement(elem);
f=null;
}
else if (name.equals("path")) {
f=readPathElement(elem);
}
else if (name.equals("polygon")) {
f=readPolygonElement(elem);
}
else if (name.equals("polyline")) {
f=readPolylineElement(elem);
}
else if (name.equals("radialGradient")) {
readRadialGradientElement(elem);
f=null;
}
else if (name.equals("rect")) {
f=readRectElement(elem);
}
else if (name.equals("solidColor")) {
readSolidColorElement(elem);
f=null;
}
else if (name.equals("svg")) {
f=readSVGElement(elem);
}
else if (name.equals("switch")) {
f=readSwitchElement(elem);
}
else if (name.equals("text")) {
f=readTextElement(elem);
}
else if (name.equals("textArea")) {
f=readTextAreaElement(elem);
}
else if (name.equals("title")) {
}
else if (name.equals("use")) {
f=readUseElement(elem);
}
else if (name.equals("style")) {
}
else {
if (DEBUG) {
System.out.println("SVGInputFormat not implemented for <" + name + ">");
}
}
}
if (f instanceof SVGFigure) {
if (((SVGFigure)f).isEmpty()) {
return null;
}
}
else if (f != null) {
if (DEBUG) {
System.out.println("SVGInputFormat warning: not an SVGFigure " + f);
}
}
return f;
}
| Reads an SVG element of any kind. |
public static Matrix read(BufferedReader input) throws java.io.IOException {
StreamTokenizer tokenizer=new StreamTokenizer(input);
tokenizer.resetSyntax();
tokenizer.wordChars(0,255);
tokenizer.whitespaceChars(0,' ');
tokenizer.eolIsSignificant(true);
java.util.Vector<Object> v=new java.util.Vector<Object>();
while (tokenizer.nextToken() == StreamTokenizer.TT_EOL) ;
if (tokenizer.ttype == StreamTokenizer.TT_EOF) throw new java.io.IOException("Unexpected EOF on matrix read.");
do {
v.addElement(Double.valueOf(tokenizer.sval));
}
while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);
int n=v.size();
double row[]=new double[n];
for (int j=0; j < n; j++) row[j]=((Double)v.elementAt(j)).doubleValue();
v.removeAllElements();
v.addElement(row);
while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
v.addElement(row=new double[n]);
int j=0;
do {
if (j >= n) throw new java.io.IOException("Row " + v.size() + " is too long.");
row[j++]=Double.valueOf(tokenizer.sval).doubleValue();
}
while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);
if (j < n) throw new java.io.IOException("Row " + v.size() + " is too short.");
}
int m=v.size();
double[][] A=new double[m][];
v.copyInto(A);
return new Matrix(A);
}
| Read a matrix from a stream. The format is the same the print method, so printed matrices can be read back in (provided they were printed using US Locale). Elements are separated by whitespace, all the elements for each row appear on a single line, the last row is followed by a blank line. |
public static String[] explode(final String str,final char delimiter){
return explode(str,delimiter,0);
}
| Splits a string at the specified delimiter into multiple substrings. This method is similar to <code>String.split()</code>, but does only take a single char as a delimiter and not a regular expression, making this method a lot faster than <code>String.split()</code> if no regular expressions are required. |
public NetworkResponse performRequest(Request<?> request) throws HttpException {
while (true) {
HttpResponse httpResponse=null;
byte[] responseContents=null;
Map<String,String> responseHeaders=new HashMap<String,String>();
try {
Map<String,String> headers=new HashMap<String,String>();
httpResponse=mHttpStack.performRequest(request,headers);
int statusCode=httpResponse.getResponseCode();
responseHeaders=httpResponse.getHeaders();
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,null,responseHeaders,true);
}
if (httpResponse.getContentStream() != null) {
responseContents=responseToBytes(request,httpResponse);
}
else {
responseContents=new byte[0];
}
if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}
return new NetworkResponse(statusCode,responseContents,responseHeaders,false);
}
catch ( SocketTimeoutException e) {
if (request.getRequestCacheConfig().isRetryWhenRequestFailed()) {
retryOnException(request,new HttpException("socket timeout",HttpError.ERROR_SOCKET_TIMEOUT));
}
else {
throw new HttpException("socket timeout",HttpError.ERROR_SOCKET_TIMEOUT);
}
}
catch ( MalformedURLException e) {
throw new RuntimeException("Bad URL " + request.getUrl(),e);
}
catch ( IOException e) {
int statusCode=0;
if (httpResponse != null) {
statusCode=httpResponse.getResponseCode();
}
else {
throw new HttpException("NoConnection error",HttpError.ERROR_NO_CONNECTION);
}
CLog.d("Unexpected response code %s for: %s",statusCode,request.getUrl());
if (responseContents != null) {
if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
if (request.getRequestCacheConfig().isRetryWhenRequestFailed()) {
retryOnException(request,new HttpException("auth error",HttpError.ERROR_UNAUTHORIZED));
}
else {
throw new HttpException("auth error",HttpError.ERROR_UNAUTHORIZED);
}
}
else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
if (request.getRequestCacheConfig().isRetryWhenRequestFailed()) {
retryOnException(request,new HttpException("redirect error",HttpError.ERROR_REDIRECT));
}
else {
throw new HttpException("redirect error",HttpError.ERROR_REDIRECT);
}
}
else {
throw new HttpException("server error, Only throw ServerError for 5xx status codes.",HttpError.ERROR_SERVER);
}
}
else {
throw new HttpException("responseContents is null",HttpError.ERROR_RESPONSE_NULL);
}
}
}
}
| Actually executing a request |
public ObjectiveComparator(int objective){
this.objective=objective;
}
| Constructs a comparator for comparing solutions using the value of the specified objective. |
public void analyzeFrames(){
log.debug("Analyzing frames");
timePosMap=new HashMap<Integer,Long>();
samplePosMap=new HashMap<Integer,Long>();
int sample=1;
Long pos=null;
if (videoSamplesToChunks != null) {
int compositeIndex=0;
CompositionTimeSampleRecord compositeTimeEntry=null;
if (compositionTimes != null && !compositionTimes.isEmpty()) {
compositeTimeEntry=compositionTimes.remove(0);
}
for (int i=0; i < videoSamplesToChunks.size(); i++) {
MP4Atom.Record record=videoSamplesToChunks.get(i);
int firstChunk=record.getFirstChunk();
int lastChunk=videoChunkOffsets.size();
if (i < videoSamplesToChunks.size() - 1) {
MP4Atom.Record nextRecord=videoSamplesToChunks.get(i + 1);
lastChunk=nextRecord.getFirstChunk() - 1;
}
for (int chunk=firstChunk; chunk <= lastChunk; chunk++) {
int sampleCount=record.getSamplesPerChunk();
pos=videoChunkOffsets.elementAt(chunk - 1);
while (sampleCount > 0) {
samplePosMap.put(sample,pos);
double ts=(videoSampleDuration * (sample - 1)) / videoTimeScale;
boolean keyframe=false;
if (syncSamples != null) {
keyframe=syncSamples.contains(sample);
if (seekPoints == null) {
seekPoints=new LinkedList<Integer>();
}
int keyframeTs=(int)Math.round(ts * 1000.0);
seekPoints.add(keyframeTs);
timePosMap.put(keyframeTs,pos);
}
int size=(videoSamples.get(sample - 1)).intValue();
MP4Frame frame=new MP4Frame();
frame.setKeyFrame(keyframe);
frame.setOffset(pos);
frame.setSize(size);
frame.setTime(ts);
frame.setType(TYPE_VIDEO);
if (compositeTimeEntry != null) {
int consecutiveSamples=compositeTimeEntry.getConsecutiveSamples();
frame.setTimeOffset(compositeTimeEntry.getSampleOffset());
compositeIndex++;
if (compositeIndex - consecutiveSamples == 0) {
if (!compositionTimes.isEmpty()) {
compositeTimeEntry=compositionTimes.remove(0);
}
compositeIndex=0;
}
}
frames.add(frame);
pos+=size;
sampleCount--;
sample++;
}
}
}
log.debug("Sample position map (video): {}",samplePosMap);
}
if (audioSamplesToChunks != null) {
sample=1;
for (int i=0; i < audioSamplesToChunks.size(); i++) {
MP4Atom.Record record=audioSamplesToChunks.get(i);
int firstChunk=record.getFirstChunk();
int lastChunk=audioChunkOffsets.size();
if (i < audioSamplesToChunks.size() - 1) {
MP4Atom.Record nextRecord=audioSamplesToChunks.get(i + 1);
lastChunk=nextRecord.getFirstChunk() - 1;
}
for (int chunk=firstChunk; chunk <= lastChunk; chunk++) {
int sampleCount=record.getSamplesPerChunk();
pos=audioChunkOffsets.elementAt(chunk - 1);
while (sampleCount > 0) {
double ts=(audioSampleDuration * (sample - 1)) / audioTimeScale;
int size=(audioSamples.get(sample - 1)).intValue();
MP4Frame frame=new MP4Frame();
frame.setOffset(pos);
frame.setSize(size);
frame.setTime(ts);
frame.setType(TYPE_AUDIO);
frames.add(frame);
pos+=size;
sampleCount--;
sample++;
}
}
}
}
Collections.sort(frames);
log.debug("Frames count: {}",frames.size());
if (audioSamplesToChunks != null) {
audioChunkOffsets.clear();
audioChunkOffsets=null;
audioSamplesToChunks.clear();
audioSamplesToChunks=null;
}
if (videoSamplesToChunks != null) {
videoChunkOffsets.clear();
videoChunkOffsets=null;
videoSamplesToChunks.clear();
videoSamplesToChunks=null;
}
if (syncSamples != null) {
syncSamples.clear();
syncSamples=null;
}
}
| Performs frame analysis and generates metadata for use in seeking. All the frames are analyzed and sorted together based on time and offset. |
public boolean isBlank(){
if (blank == null) {
blank=Boolean.valueOf(StringUtil.isBlank(nodeValue));
}
return blank.booleanValue();
}
| Returns <code>true</code> if text content is blank. |
public final void turnTo(double azimuth,double elevation){
if (!is3dMode) elevation=0.0d;
heading.azimuth=Geometric.clampAngleRadians(azimuth);
heading.elevation=Geometric.clampAngleRadians(elevation);
velocity.set(heading.toCartesian());
}
| Turn the agent to the given angle given in radians. |
public boolean containsNeuron(final Neuron n){
return neuronList.contains(n);
}
| True if the group contains the specified neuron. |
public static int EIO(){
return Errno.EIO.intValue();
}
| I/O error |
public static long addCap(long a,long b){
long res=a + b;
if (res < 0L) {
return Long.MAX_VALUE;
}
return res;
}
| Cap an addition to Long.MAX_VALUE |
public UnsyncBufferedOutputStream(OutputStream out){
buf=new byte[size];
this.out=out;
}
| Creates a buffered output stream without synchronization |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
public static final byte composeDatagramMode(byte esmClass){
return composeMessagingMode(esmClass,SMPPConstant.ESMCLS_DATAGRAM_MODE);
}
| Messaging Mode. |
public void onPackageDisappeared(String packageName,int reason){
}
| Called when a package disappears for any reason. |
public boolean canBeShortAddress(int address){
return ((address >= 1) && (address <= 127));
}
| The short addresses 1-127 are available |
public Generator(Grammar grammar,Precedences precedences,Verbosity verbosity){
this.grammar=grammar;
this.precedences=precedences;
this.verbosity=verbosity;
this.debugOut=System.out;
}
| A generator needs a grammar and precedences (optional) to do its work. The given verbosity tells the generator how many debug messages are requested. |
public char next(char c) throws JSONException {
char n=this.next();
if (n != c) {
throw this.syntaxError("Expected '" + c + "' and instead saw '"+ n+ "'");
}
return n;
}
| Consume the next character, and check that it matches a specified character. |
public static boolean pointInPolygon(double[] x,double[] y,double lat,double lon){
assert x.length == y.length;
boolean inPoly=false;
for (int i=1; i < x.length; i++) {
if (x[i] < lon && x[i - 1] >= lon || x[i - 1] < lon && x[i] >= lon) {
if (y[i] + (lon - x[i]) / (x[i - 1] - x[i]) * (y[i - 1] - y[i]) < lat) {
inPoly=!inPoly;
}
}
}
return inPoly;
}
| simple even-odd point in polygon computation 1. Determine if point is contained in the longitudinal range 2. Determine whether point crosses the edge by computing the latitudinal delta between the end-point of a parallel vector (originating at the point) and the y-component of the edge sink NOTE: Requires polygon point (x,y) order either clockwise or counter-clockwise |
public void addFilter(NodeFilter f){
this.filters.add(f);
updateShownNodes();
if (this.refreshTimer == null) {
this.refreshTimer=new Timer(AUTO_REFRESH_DELAY,this);
this.refreshTimer.start();
}
}
| Adds a new node filter to the node chooser |
public PeriodType withMinutesRemoved(){
return withFieldRemoved(5,"NoMinutes");
}
| Returns a version of this PeriodType instance that does not support minutes. |
public boolean equals(Object other){
if (this == other) return true;
if (!(other instanceof CRLExtensions)) return false;
Collection<Extension> otherC=((CRLExtensions)other).getAllExtensions();
Object[] objs=otherC.toArray();
int len=objs.length;
if (len != map.size()) return false;
Extension otherExt, thisExt;
String key=null;
for (int i=0; i < len; i++) {
if (objs[i] instanceof CertAttrSet) key=((CertAttrSet)objs[i]).getName();
otherExt=(Extension)objs[i];
if (key == null) key=otherExt.getExtensionId().toString();
thisExt=map.get(key);
if (thisExt == null) return false;
if (!thisExt.equals(otherExt)) return false;
}
return true;
}
| Compares this CRLExtensions for equality with the specified object. If the <code>other</code> object is an <code>instanceof</code> <code>CRLExtensions</code>, then all the entries are compared with the entries from this. |
private boolean saveBitmap(String fullPath,Bitmap bitmap){
if (fullPath == null || bitmap == null) return false;
boolean fileCreated=false;
boolean bitmapCompressed=false;
boolean streamClosed=false;
File imageFile=new File(fullPath);
if (imageFile.exists()) if (!imageFile.delete()) return false;
try {
fileCreated=imageFile.createNewFile();
}
catch ( IOException e) {
e.printStackTrace();
}
FileOutputStream out=null;
try {
out=new FileOutputStream(imageFile);
bitmapCompressed=bitmap.compress(CompressFormat.PNG,100,out);
}
catch ( Exception e) {
e.printStackTrace();
bitmapCompressed=false;
}
finally {
if (out != null) {
try {
out.flush();
out.close();
streamClosed=true;
}
catch ( IOException e) {
e.printStackTrace();
streamClosed=false;
}
}
}
return (fileCreated && bitmapCompressed && streamClosed);
}
| Saves the Bitmap as a PNG file at path 'fullPath' |
void updatePendingNodes(final int newLandmarkIndex,final Node toNode,final RouterPriorityQueue<Node> pendingNodes){
Iterator<Node> it=pendingNodes.iterator();
PreProcessLandmarks.LandmarksData toRole=getPreProcessData(toNode);
ArrayList<Double> newEstRemTravCosts=new ArrayList<Double>();
ArrayList<Node> nodesToBeUpdated=new ArrayList<Node>();
while (it.hasNext()) {
Node node=it.next();
AStarNodeData role=getData(node);
PreProcessLandmarks.LandmarksData ppRole=getPreProcessData(node);
double estRemTravCost=role.getExpectedRemainingCost();
double newEstRemTravCost=estimateRemainingTravelCost(ppRole,toRole,newLandmarkIndex);
if (newEstRemTravCost > estRemTravCost) {
nodesToBeUpdated.add(node);
newEstRemTravCosts.add(newEstRemTravCost);
}
}
for ( Node node : nodesToBeUpdated) {
pendingNodes.remove(node);
}
for (int i=0; i < nodesToBeUpdated.size(); i++) {
Node node=nodesToBeUpdated.get(i);
AStarNodeData data=getData(node);
data.setExpectedRemainingCost(newEstRemTravCosts.get(i));
pendingNodes.add(node,getPriority(data));
}
}
| If a landmark has been added to the set of the active landmarks, this function re-evaluates the estimated remaining travel time based on the new set of active landmarks of the nodes contained in pendingNodes. If this estimation improved, the node's position in the pendingNodes queue is updated. |
@Override public void eUnset(int featureID){
switch (featureID) {
case GamlPackage.ACTION_ARGUMENTS__ARGS:
getArgs().clear();
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public String cancelReview(){
manageReviewModel.setServiceReview(null);
setForwardUrl(getRequest());
return OUTCOME_MARKETPLACE_REDIRECT;
}
| Sets the current service review to null to discard changes on the review. |
public CacheMetricsImpl(GridCacheContext<?,?> cctx){
assert cctx != null;
this.cctx=cctx;
if (cctx.isNear()) dhtCtx=cctx.near().dht().context();
if (cctx.store().store() instanceof GridCacheWriteBehindStore) store=(GridCacheWriteBehindStore)cctx.store().store();
delegate=null;
}
| Creates cache metrics; |
public boolean xPathExists(String xpathExpr){
try {
if (XPath.selectSingleNode(this.xmlDocument,xpathExpr) == null) return false;
return true;
}
catch ( Exception ex) {
return false;
}
}
| Does an xPath expression exist |
@RequestMapping(value={"/",""},method=RequestMethod.POST) @ResponseBody public RestWrapper update(@ModelAttribute("busdomain") @Valid BusDomain busDomain,BindingResult bindingResult,Principal principal){
RestWrapper restWrapper=null;
if (bindingResult.hasErrors()) {
BindingResultError bindingResultError=new BindingResultError();
return bindingResultError.errorMessage(bindingResult);
}
try {
com.wipro.ats.bdre.md.dao.jpa.BusDomain jpaBusDomain=new com.wipro.ats.bdre.md.dao.jpa.BusDomain();
jpaBusDomain.setBusDomainId(busDomain.getBusDomainId());
jpaBusDomain.setBusDomainName(busDomain.getBusDomainName());
jpaBusDomain.setBusDomainOwner(busDomain.getBusDomainOwner());
jpaBusDomain.setDescription(busDomain.getDescription());
busDomainDAO.update(jpaBusDomain);
restWrapper=new RestWrapper(busDomain,RestWrapper.OK);
LOGGER.info(RECORDWITHID + busDomain.getBusDomainId() + " updated in BusDomain by User:"+ principal.getName()+ busDomain);
}
catch ( MetadataException e) {
LOGGER.error(e);
restWrapper=new RestWrapper(e.getMessage(),RestWrapper.ERROR);
}
return restWrapper;
}
| This method calls proc UpdateBusDomain and updates the record passed. It also validates the values passed. |
private int[] readTypeAnnotations(final MethodVisitor mv,final Context context,int u,boolean visible){
char[] c=context.buffer;
int[] offsets=new int[readUnsignedShort(u)];
u+=2;
for (int i=0; i < offsets.length; ++i) {
offsets[i]=u;
int target=readInt(u);
switch (target >>> 24) {
case 0x00:
case 0x01:
case 0x16:
u+=2;
break;
case 0x13:
case 0x14:
case 0x15:
u+=1;
break;
case 0x40:
case 0x41:
for (int j=readUnsignedShort(u + 1); j > 0; --j) {
int start=readUnsignedShort(u + 3);
int length=readUnsignedShort(u + 5);
readLabel(start,context.labels);
readLabel(start + length,context.labels);
u+=6;
}
u+=3;
break;
case 0x47:
case 0x48:
case 0x49:
case 0x4A:
case 0x4B:
u+=4;
break;
default :
u+=3;
break;
}
int pathLength=readByte(u);
if ((target >>> 24) == 0x42) {
TypePath path=pathLength == 0 ? null : new TypePath(b,u);
u+=1 + 2 * pathLength;
u=readAnnotationValues(u + 2,c,true,mv.visitTryCatchAnnotation(target,path,readUTF8(u,c),visible));
}
else {
u=readAnnotationValues(u + 3 + 2 * pathLength,c,true,null);
}
}
return offsets;
}
| Parses a type annotation table to find the labels, and to visit the try catch block annotations. |
public double doOperation() throws OperatorFailedException {
if (DEBUG) {
c2cLikelihood.outputTreeToFile("beforeTSSA.nex",false);
}
BranchMapModel branchMap=c2cLikelihood.getBranchMap();
double logq=0;
NodeRef i;
ArrayList<NodeRef> eligibleNodes=getEligibleNodes(tree,branchMap);
i=eligibleNodes.get(MathUtils.nextInt(eligibleNodes.size()));
double eligibleNodeCount=eligibleNodes.size();
final NodeRef iP=tree.getParent(i);
final NodeRef CiP=getOtherChild(tree,iP,i);
final NodeRef PiP=tree.getParent(iP);
final double delta=getDelta();
final double oldHeight=tree.getNodeHeight(iP);
final double newHeight=oldHeight + delta;
AbstractCase iCase=branchMap.get(i.getNumber());
AbstractCase iPCase=branchMap.get(iP.getNumber());
AbstractCase CiPCase=branchMap.get(CiP.getNumber());
AbstractCase PiPCase=null;
if (PiP != null) {
PiPCase=branchMap.get(PiP.getNumber());
}
if (resampleInfectionTimes) {
if (iCase != iPCase) {
iCase.setInfectionBranchPosition(MathUtils.nextDouble());
}
if (PiPCase == null || CiPCase != PiPCase) {
CiPCase.setInfectionBranchPosition(MathUtils.nextDouble());
}
}
if (delta > 0) {
if (PiP != null && tree.getNodeHeight(PiP) < newHeight) {
NodeRef newParent=PiP;
NodeRef newChild=iP;
while (tree.getNodeHeight(newParent) < newHeight) {
newChild=newParent;
newParent=tree.getParent(newParent);
if (newParent == null) break;
}
if (branchMap.get(newChild.getNumber()) != branchMap.get(iP.getNumber())) {
throw new OperatorFailedException("invalid slide");
}
tree.beginTreeEdit();
if (tree.isRoot(newChild)) {
tree.removeChild(iP,CiP);
tree.removeChild(PiP,iP);
tree.addChild(iP,newChild);
tree.addChild(PiP,CiP);
tree.setRoot(iP);
if (tree.hasNodeTraits()) {
tree.swapAllTraits(newChild,iP);
}
if (tree.hasRates()) {
final double rootNodeRate=tree.getNodeRate(newChild);
tree.setNodeRate(newChild,tree.getNodeRate(iP));
tree.setNodeRate(iP,rootNodeRate);
}
}
else {
tree.removeChild(iP,CiP);
tree.removeChild(PiP,iP);
tree.removeChild(newParent,newChild);
tree.addChild(iP,newChild);
tree.addChild(PiP,CiP);
tree.addChild(newParent,iP);
}
tree.setNodeHeight(iP,newHeight);
tree.endTreeEdit();
final int possibleSources=intersectingEdges(tree,newChild,oldHeight,branchMap,branchMap.get(iP.getNumber()),null);
logq-=Math.log(possibleSources);
}
else {
tree.setNodeHeight(iP,newHeight);
logq+=0.0;
}
}
else {
if (tree.getNodeHeight(i) > newHeight) {
return Double.NEGATIVE_INFINITY;
}
if (tree.getNodeHeight(CiP) > newHeight) {
List<NodeRef> newChildren=new ArrayList<NodeRef>();
final int possibleDestinations=intersectingEdges(tree,CiP,newHeight,branchMap,branchMap.get(iP.getNumber()),newChildren);
if (newChildren.size() == 0) {
return Double.NEGATIVE_INFINITY;
}
final int childIndex=MathUtils.nextInt(newChildren.size());
NodeRef newChild=newChildren.get(childIndex);
NodeRef newParent=tree.getParent(newChild);
if (resampleInfectionTimes) {
AbstractCase newChildCase=branchMap.get(newChild.getNumber());
if (newChildCase != iPCase) {
newChildCase.setInfectionBranchPosition(MathUtils.nextDouble());
}
}
tree.beginTreeEdit();
if (tree.isRoot(iP)) {
tree.removeChild(iP,CiP);
tree.removeChild(newParent,newChild);
tree.addChild(iP,newChild);
tree.addChild(newParent,iP);
tree.setRoot(CiP);
if (tree.hasNodeTraits()) {
tree.swapAllTraits(iP,CiP);
}
if (tree.hasRates()) {
final double rootNodeRate=tree.getNodeRate(iP);
tree.setNodeRate(iP,tree.getNodeRate(CiP));
tree.setNodeRate(CiP,rootNodeRate);
}
}
else {
tree.removeChild(iP,CiP);
tree.removeChild(PiP,iP);
tree.removeChild(newParent,newChild);
tree.addChild(iP,newChild);
tree.addChild(PiP,CiP);
tree.addChild(newParent,iP);
}
tree.setNodeHeight(iP,newHeight);
tree.endTreeEdit();
logq+=Math.log(possibleDestinations);
}
else {
tree.setNodeHeight(iP,newHeight);
logq+=0.0;
}
}
if (swapInRandomRate) {
final NodeRef j=tree.getNode(MathUtils.nextInt(tree.getNodeCount()));
if (j != i) {
final double tmp=tree.getNodeRate(i);
tree.setNodeRate(i,tree.getNodeRate(j));
tree.setNodeRate(j,tmp);
}
}
if (swapInRandomTrait) {
final NodeRef j=tree.getNode(MathUtils.nextInt(tree.getNodeCount()));
if (j != i) {
tree.swapAllTraits(i,j);
}
}
if (logq == Double.NEGATIVE_INFINITY) throw new OperatorFailedException("invalid slide");
if (DEBUG) {
c2cLikelihood.getTreeModel().checkPartitions();
c2cLikelihood.outputTreeToFile("afterTSSA.nex",false);
}
double reverseEligibleNodeCount=getEligibleNodes(tree,branchMap).size();
logq+=Math.log(eligibleNodeCount / reverseEligibleNodeCount);
return logq;
}
| Do a probabilistic subtree slide move. |
public void removeConversation(String name){
conversations.remove(name.toLowerCase());
}
| Removes a conversation by name |
public Desert(){
super();
}
| Needed by CGLib |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public static synchronized void init(String recoverTest){
RecoverTester tester=RecoverTester.getInstance();
if (StringUtils.isNumber(recoverTest)) {
tester.setTestEvery(Integer.parseInt(recoverTest));
}
FilePathRec.setRecorder(tester);
}
| Initialize the recover test. |
private Validator createValidator(FaceletContext ctx){
String id=owner.getValidatorId(ctx);
if (id == null) {
throw new TagException(owner.getTag(),"A validator id was not specified. Typically the validator id is set in the constructor ValidateHandler(ValidatorConfig)");
}
return ctx.getFacesContext().getApplication().createValidator(id);
}
| Template method for creating a Validator instance |
@Override protected void loadPlugins(){
this.pickingPlugin=new PickingGraphMousePlugin<V,E>();
this.animatedPickingPlugin=new AnimatedPickingGraphMousePlugin<V,E>();
this.translatingPlugin=new TranslatingGraphMousePlugin(InputEvent.BUTTON1_MASK);
this.scalingPlugin=new ScalingGraphMousePlugin(new CrossoverScalingControl(),0,in,out);
this.rotatingPlugin=new RotatingGraphMousePlugin();
this.shearingPlugin=new ShearingGraphMousePlugin();
add(scalingPlugin);
setMode(Mode.TRANSFORMING);
}
| create the plugins, and load the plugins for TRANSFORMING mode |
public <T extends JCTree>void printExprs(List<T> trees,String sep) throws IOException {
if (trees.nonEmpty()) {
printExpr(trees.head);
for (List<T> l=trees.tail; l.nonEmpty(); l=l.tail) {
print(sep);
printExpr(l.head);
}
}
}
| Derived visitor method: print list of expression trees, separated by given string. |
public Tee(){
this(null);
}
| initializes the object, with a default printstream. |
public void omitField(final Class<?> definedIn,final String fieldName){
if (fieldAliasingMapper == null) {
throw new InitializationException("No " + FieldAliasingMapper.class.getName() + " available");
}
fieldAliasingMapper.omitField(definedIn,fieldName);
}
| Prevents a field from being serialized. To omit a field you must always provide the declaring type and not necessarily the type that is converted. |
public boolean isRunning(){
return running;
}
| Return <code>true</code> if the UDP relay server is running. |
@Override protected DocWriter createWriter(final MBasicTable table,final Document document,final OutputStream out){
final RtfWriter2 writer=RtfWriter2.getInstance(document,out);
final String title=buildTitle(table);
if (title != null) {
final HeaderFooter header=new RtfHeaderFooter(new Paragraph(title));
header.setAlignment(Element.ALIGN_LEFT);
header.setBorder(Rectangle.NO_BORDER);
document.setHeader(header);
document.addTitle(title);
}
final Paragraph footerParagraph=new Paragraph();
final Font font=FontFactory.getFont(FontFactory.TIMES_ROMAN,12,Font.NORMAL);
footerParagraph.add(new RtfPageNumber(font));
footerParagraph.add(new Phrase(" / ",font));
footerParagraph.add(new RtfTotalPageNumber(font));
footerParagraph.setAlignment(Element.ALIGN_CENTER);
final HeaderFooter footer=new RtfHeaderFooter(footerParagraph);
footer.setBorder(Rectangle.TOP);
document.setFooter(footer);
return writer;
}
| We create a writer that listens to the document and directs a RTF-stream to out |
public double manhattanDistance(final Int3D p){
final double dx=Math.abs((double)this.x - p.x);
final double dy=Math.abs((double)this.y - p.y);
final double dz=Math.abs((double)this.z - p.z);
return dx + dy + dz;
}
| Returns the manhtattan distance FROM this Double3D TO the specified point |
public MultipartBuilder attachment(InputStream is,String filename){
return bodyPart(new StreamDataBodyPart(ATTACHMENT_NAME,is,filename));
}
| Adds a named attachment. |
public static IMethodBinding findOverriddenMethod(IMethodBinding overriding,boolean testVisibility){
List<IMethodBinding> findOverriddenMethods=findOverriddenMethods(overriding,testVisibility,true);
if (findOverriddenMethods.isEmpty()) {
return null;
}
return findOverriddenMethods.get(0);
}
| Finds the method that is overridden by the given method. The search is bottom-up, so this returns the nearest defining/declaring method. |
public String globalInfo(){
return "Evaluate the performance of batch trained clusterers.";
}
| Global info for this bean |
public static RenameFileDialogFragment newInstance(OCFile file){
RenameFileDialogFragment frag=new RenameFileDialogFragment();
Bundle args=new Bundle();
args.putParcelable(ARG_TARGET_FILE,file);
frag.setArguments(args);
return frag;
}
| Public factory method to create new RenameFileDialogFragment instances. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.