text:
Q: Cómo puedo actualizar una aplicacion propia en android desde mi servidor? necesito que mi aplicación se actualice desde mi servidor cuando le doy click al boton "actualizar" encontre lo siguiente pero da error con el "uri"

Intent promptInstall = new Intent(Intent.ACTION_VIEW) .setDataAndType(Uri.parse("content:///path/to/your.apk"), "application/vnd.android.package-archive"); startActivity(promptInstall);

A: Usar un Intent para descargar un .apk y abrirlo no es posible desde la API 24, lo que debes realizar es descargar el .apk y abrirlo de esta forma.
Define un provider en tu AndroidManifest.xml, define en android:authorities el paquete de tu aplicación:
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="<paquete de aplicacion>"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

crea el archivo file_paths.xml definiendo el nombre del .apk:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="myApplication.apk" path="" />
</paths>

Mediante este código puedes abrir el .apk para que sea instalado, esto mediante un Intent:
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        saveFile.setReadable(true, false);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(saveFile), "application/vnd.android.package-archive");
        startActivity(intent);
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //*Define el paquete de aplicación.
        Uri fileUri = FileProvider.getUriForFile(getApplicationContext(),<Paquete de aplicación>, saveFile);
        intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }

A: File saveFile = null;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        saveFile.setReadable(true, false);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(saveFile), "application/vnd.android.package-archive");
        startActivity(intent);
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //*Define el paquete de aplicación.
        Uri fileUri = FileProvider.getUriForFile(getApplicationContext(),"com.example.ejemplo", saveFile);
        intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }


text:
Q: Tonejs sequencer does not recognise variables into an object I am trying to build an object that contains a sequencer using p5.js, p5.sound library and tone.js
The problem is that my code does not recognise the variables written in one function that is inside one object.
All other functions inside class tr909 can recognise the variables that I declared in the class constructor,  but the variable "sequence" doesn't recognise them.
As you can see below, tr909 class has sX and sY variables , but when I am in the function called sequence ( inside the tr909 class, on the bottom), this function won't recognise the variables anymore.
do you know why this happen?
thanks ! :)
 //object
let tr9091;
let bL9091 = 16; //beat lenght

let posX9091 = 100; //positionX 909
let posY9091 = 220; //positionY 909

let sX9091 = 320; //sizeX of 909
let sY9091 = 60; //sizeY of 909

// var cellWidth = sX9091 / bL9091; //dont know why, if I put it in constructor of 909 object, sequence function does not recognise cellWidth

//Pre-load  audio files
let hh909, clp909m, bd909;

let time;
let beatIndex;
var sX;
let sequence;
// var sX = 1;

function preload() {

  bd909 = loadSound('assets/bass_sample.mp3');
  hh909 = loadSound('assets/hh_sample.mp3');
  clp909 = loadSound('assets/clap_sample.mp3');

}

function setup() {
  createCanvas(600, 400);

  tr9091 = new tr909(bd909, hh909, clp909, bL9091, posX9091, posY9091, sX9091, sY9091);

}

function draw() {

}

function keyPressed() {
  if (key === ' ') {
    tr9091.clicked();
  }
}

function mousePressed() {
  tr9091.rectPressed();
}

class tr909 {

constructor(bd, hh, clp, beatLenght, pX, pY, sX, sY) {
    //variables
    this.bd = bd;
    this.hh = hh;
    this.clp = clp;

    this.beatLenght = beatLenght;

    this.pX = pX; //positionX 909
    this.pY = pY; //positionY 909

    this.sX = sX; //sizeX 909
    this.sY = sY; //sizeY 909

    this.cellWidth = this.sX / this.beatLenght;

    //sequences
    this.bdPat = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0];
    this.hhPat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
    this.clpPat = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0];

    this.sPat = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

    this.cursorPos = 0;

    //phrases
    this.bdPhrase = new p5.Phrase('bd', (time) => {
      this.bd.play(time)
    }, this.bdPat);

    this.hhPhrase = new p5.Phrase('hh', (time) => {
      this.hh.play(time)
    }, this.hhPat);

    this.clpPhrase = new p5.Phrase('clp', (time) => {
      this.clp.play(time)
    }, this.clpPat);

    //parts
    this.drums = new p5.Part();

    //adding phrase to parts
    this.drums.addPhrase(this.bdPhrase);
    this.drums.addPhrase(this.hhPhrase);
    this.drums.addPhrase(this.clpPhrase);

    this.drums.addPhrase('seq', this.sequence, this.sPat);

    //BPM
    let bpmCTRL;
    this.bpmCTRL = createSlider(30, 120, 120, 1);
    this.bpmCTRL.position(pX + 10, pY + 70);
    this.bpmCTRL.input(() => {
      this.drums.setBPM(this.bpmCTRL.value())
    });
    this.drums.setBPM('120');

    this.drawMatrix();

  } //final constructor

  clicked() { //play loop
    this.drums.loop();
  }

  rectPressed() {
    //Y mouse click inside the object
    if ((mouseY > this.pY && mouseY < this.pY + this.sY) && (mouseX > this.pX && mouseX < this.pX + this.sX)) {
      this.rowClicked = floor(3 * (mouseY - this.pY) / this.sY);
      this.indexClicked = floor(16 * (mouseX - this.pX) / this.sX);

      if (this.rowClicked === 0) {
        console.log("firstrow " + this.indexClicked);
        this.bdPat[this.indexClicked] = +!this.bdPat[this.indexClicked];
      } else if (this.rowClicked === 1) {
        console.log("secondtrow");
        this.hhPat[this.indexClicked] = +!this.hhPat[this.indexClicked];
      } else if (this.rowClicked === 2) {
        console.log("thrtrow");
        this.clpPat[this.indexClicked] = +!this.clpPat[this.indexClicked];
      }
      this.drawMatrix();
    }
  }

//visual interface
  drawMatrix() {

    fill(80);
    stroke('gray');
    strokeWeight(2);
    rect(this.pX, this.pY, this.sX, this.sY);

    stroke('gray');
    strokeWeight(2);

    //vertical lines
    for (let i = 0; i < this.beatLenght; i++) {
      line(this.pX + i * this.cellWidth, this.pY, this.pX + i * this.cellWidth, this.pY + this.sY);
    }

    for (let i = 0; i < 4; i++) {
      line(this.pX, this.pY + i * this.sY / 3, this.pX + this.sX, this.pY + i * this.sY / 3);
    }

    //draw circles

    for (let i = 0; i < this.beatLenght; i++) {
      if (this.bdPat[i] === 1) {
        ellipse(this.pX + i * this.cellWidth + 0.5 * this.cellWidth, this.pY + this.sY / 6, 10);
      }
      if (this.hhPat[i] === 1) {
        ellipse(this.pX + i * this.cellWidth + 0.5 * this.cellWidth, this.pY + this.sY / 2, 10);
      }
      if (this.clpPat[i] === 1) {
        ellipse(this.pX + i * this.cellWidth + 0.5 * this.cellWidth, this.pY + this.sY * 5 / 6, 10);
      }
    }

  }

  sequence(time, beatIndex) {

    this.cellWidth = this.sX / this.beatLenght;

    stroke('red');
    fill(255, 0, 0, 30);
    rect(beatIndex * this.cellWidth, this.sX, this.cellWidth, this.sY);
    console.log(beatIndex);
  }

} //final object

A: Because here:
this.drums = new p5.Part();
//adding phrase to parts
this.drums.addPhrase(this.bdPhrase);
this.drums.addPhrase(this.hhPhrase);
this.drums.addPhrase(this.clpPhrase);
this.drums.addPhrase('seq', this.sequence, this.sPat);

You pass it as a callback function. Check the first answer in this thread:
How to access the correct `this` inside a callback?
Either replace the argument this.sequence with:
function(){ this.sequence() }.bind( this )

or even shorter:
this.sequence.bind(this);

or like this:
()=>{ this.sequence() }

or, when you want to pass in arguments or return value:
(...args) => this.sequence(...args)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Writing HTML that contains PHP tags to file I think what I'm trying to do must be impossible; incredibly difficult; or pretty easy, and I just don't know how to express what I want correctly to Google.
What I want to do is the following:
For the purposes of templating, I am outputting HTML to a file.  However, I want the file to contain PHP tags - not the parsed value of the PHP code (this value will change based upon included scripts in the output file) - but the actual <?php ?> tags themselves - containing the unmodified code, such that the code is still executable at run time.
This is an example of what I want to get outputted:

        <img src="<?php echo IMG_PATH;?>img.jpg" />

What I'm getting is a combination of things that are wrong, depending on which method I use.  Basically, I need to be able to write parsable PHP code to a HTML file.  Now, whether or not this is a good idea is debatable, and a subject I'm not too interested in at the moment.  I just want to know if a sane solution exists.
I came up with the following insane solution:
$content='';
file_put_contents($file,$content);

$command='perl -p -i.bktmp -e "s/zxzxzx/</g" '.$file.' 2>'.$path.'error.log';
$command2='perl -p -i.bktmp -e "s/qjqjqj/>/g" '.$file.' 2>'.$path.'error.log';
exec($command);
exec($command2);

Now, on one hand, this feels devilishly clever.  And, it also feels insane.  Is there a better/possible way to do this?

A: You are misinterpreting how PHP operates. The following code:
<?php

echo 'This string <?php echo 'contains' ?> some PHP code';

Will produce as output
This string <?php echo 'contains' ?> some PHP code

You will NOT get:
This string contains some PHP code

PHP's parser is not recursive. PHP code embedded inside PHP code, e.g. inside a string, as it is above, is NOT treated as PHP code - it'll just be some text.
If you want to write out some PHP code, then just write it out:
$string = 'This string <?php echo 'contains' ?> some PHP code';
file_put_contents('file.php', $string);

You don't need to take any special measures for the PHP code in the string to be written out, it'll just "work".
Now, that being said, if you ever put that string into a context where it COULD be evaluated as code, e.g.
eval($string);

then you WILL have to take measures to keep PHP from seeing the opening <?php tag and switching into "code mode".

A: Instead your HTML file needs to be a PHP file. See below:
File: test.php

        <? echo 'My PHP embedded in HTML'; ?>
        <img src="<? echo $imagePath; ?>"/>


text:
Q: How to change the list in a SelectOneMenu, if the value is changed in another? I want to change the SelectItem[] array in the second SelectOneMenu, if the value is changed in the first one. Is that possible?

A: I figured this out, but I used RichFaces's AJAX functionality, not only JSF. Just added the  tag to my first selectOneMenu, and it works:)
<a4j:support event="onchange" action="#{bean.onChange}"
             reRender="otherSelectOneMenuID"/>

Thanks for the response anyway!

A: Should be possible if you bind a value change listener to the first selectOneMenu.
Get the new value from the ValueChangeEvent and update the list accordingly. the JSF page should then display the updated list.
Hope that makes sense!

A: Well I used a4j and it worked.
<code>
//JSF
<h:outputLabel value="First selectOneMenu: "/>
<h:selectOneMenu value="#{yourBackingBean.selectedItem}">
<f:converter converterId="defaultConverter"/>
<f:selectItem id="df01" itemLabel="Item01" itemValue="1" />
<f:selectItem id="df02" itemLabel="Item02" itemValue="2" />
<f:selectItem id="df03" itemLabel="Item03" itemValue="3" />
<a4j:support event="onchange" reRender="secondSelectOneMenu"/> //secondSelectOneMenu is the id of the dropdown you want to change
</h:selectOneMenu>

<h:outputLabel value="Second selectOneMenu: "/>
<h:selectOneMenu value="#{yourBackingBean.attributeToStoreSelectedValue}" id="secondSelectOneMenu">
<f:converter converterId="defaultConverter"/>
<f:selectItem id="df00" itemLabel="Select" itemValue="0" /> //Default value
<f:selectItems value="#{yourBackingBean.returnByChoice}" />
</h:selectOneMenu>

//Converter

public class DefaultConverter implements Converter {
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
    return value;
}

public String getAsString(FacesContext ctx, UIComponent component, Object value) {
    String label = "";
    if (value != null) {
        label = value.toString();
    }
    return label;
}
}

//Backing Bean Sample
public List<SelectItem> returnByChoice() { //it must return a list of SelectItems so it can be displayed on the jsf page
   String id = (String) getSelectedItem(); //this is the value chosen from the first dropDownMenu wich selectedItem is the attribute onthe binding of the first dropDownMenu.
   ArrayList<SelectItem> arrItems = new ArrayList<SelectItem>();
   if (id != null) {

            List<YourClass> yourObjectList = yourDao.findAllItemsFromType(new Integer(id));

         Iterator<YourClass> iterator = yourObjectList.iterator();
         String tempName = "";
         String tempId = "";
         YourClass tempYourObject = null;

        while (iterator.hasNext()) {
           tempYourObject = iterator.next();
           tempId = String.valueOf(tempYourObject.getId());
           tempName = tempYourObject.getName();
           arrItems.add(new SelectItem(tempId, tempName));
        }
    }
    return arrProfiles;
}
</code>


text:
Q: C# resource file - how to access internal resources from XAML? This is my simple (newbie) understanding:
We have a choice for the Ressource Code Generator: internal or public. The default appears to be internal. I understand the resources are created with an internal or public accessor depending on that choice.
Therefore, if the accessor is public I can use something like:

Text="{x:Static resx:Resources.SomeLabelID}"

... in my XAML.
My question is either/both:

*

*What use is a generated internal accessor when the XAML shown above does not work (more precisely it 'works' in design mode but not at run time thus creating confusion for a newbie)?
Note: There are many answers in SO that simply say to change the accessor to 'public' without explaining why, which I think would by nice to understand, especially since the default appears to be internal.
-OR-

*

*Is there another way to access resource strings (from XAML) when the code is generated with the internal accessor ?

Thank you

A: Everything defined in XAML is using internal access modifier. That is by design of WPF framework, simply so you will not be able to access locally defined controls in different assembly.
Generally if you are going to use strings for "static" controls (i.e. Label) then you can simply go a head with changing access modifier.


text:
Q: Using db.execute in postgresql using the LIKE operator with variables within flask, no information passed I'm trying to get my db.execute to work, managed to resolve the syntax error when using the LIKE operator along with a variable passed in from HTML, but it still doesn't give me results.
(got closed by admin, so re-posting)
Used flask console to print and find out if any values passed at all, and it didn't.
found variable not returning anything from dbExecute function
Why are my results not getting passed from db.execute?
My code extracted below:
@app.route("/search", methods=["POST"])
def search():
    """Search for books"""

    # best example, but no data passed:
    found = db.execute("SELECT * FROM books_table WHERE (isbn LIKE :lookingFor) OR (title LIKE :lookingFor) OR (title LIKE :lookingFor) OR (year::text LIKE :lookingFor)", {"lookingFor": f"%{searchBookVariableOnApplication_py}%"}).fetchall();

    return render_template("search.html", found=found)

A: The problem here is that you are not binding your wildcard string literals correctly to your query string.  You should be using a prepared statement here.  Assuming you are using psycopg2, you may try:
import psycopg2

searchBook = request.form['searchBook']
sql = """SELECT *
         FROM books_table
         WHERE isbn LIKE %s OR title LIKE %s OR year::text LIKE %s"""
param = "%" + searchBook + "%"
found = db.execute(sql, (searchBook, searchBook, searchBook,))

A: You're using an f-string in an attempt to use the variable searchBookVariableOnApplication_py, but not interpolating it within the f-string.
This:
{"lookingFor": f"\"%searchBookVariableOnApplication_py%\""}

Should be this:
{"lookingFor": f"\"%{searchBookVariableOnApplication_py}%\""}


text:
Q: rspec feature spec with javascript enabled throw error "couldn't find with id" I know there has been answers related to this question, but I haven't found the answer for my problem. Consider the following spec:
feature "Order Feature", :js do
  let!(:product) { create :product }

  scenario "buy a product" do
    visit product_path(product)
  end
end

The above spec will throw error as follows:
Couldn't find Product with 'id'=3

I have tried the following solution and none helped:

*

*turning off transactional fixtures

*database cleaner with truncation strategy on example with :js enabled (reference)

*shared connection with transactional fixtures turned on (reference)

I have used selenium-webdriver and poltergeist, both seem to have the same symptoms, which can be summarized as follows:
I can see the product being created on the console if I debug the spec, but I could not see any product from the browser.
I have read several articles that this is related to the capybara is run on the different thread than the spec. But I haven't found anything that helped me resolve this issue.

For completeness, I use the following code for shared connection approach:
RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

class ActiveRecord::Base
  mattr_accessor :shared_connection
  @@shared_connection = nil

  def self.connection
    @@shared_connection || retrieve_connection
  end
end

Spring.after_fork do
  # Forces all threads to share the same connection. This works on
  # Capybara because it starts the web server in a thread.
  ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
end

And I use the following for the database cleaner approach:
RSpec.configure do |config|
  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js) do
    DatabaseCleaner.strategy = :truncation
  end

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
end


text:
Q: What is the '*' used for in this example? I am trying to figure out how to design a type for trees in F# and was looking at this thread for some help Tree Representation in F#.
In it, they define:
type Tree =
  | Branch of string * Tree list
  | Leaf of string

I am not sure what the * operator between string and Tree is supposed to do. I have been seeing it all over the place, but don't know what to search to find the answer.
Thanks!

A: This is the Tuple type name, from Microsoft Documentation

Names of Tuple Types
When you write out the name of a type that is a
tuple, you use the * symbol to separate elements. For a tuple that
consists of an int, a float, and a string, such as (10, 10.0, "ten"),
the type would be written as follows.

int * float * string

A: In types declarations, * (asterisk) indicates pairing in a tuple:
https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/tuples#names-of-tuple-types


text:
Q: IsMemberOf() returns false incorrectly I'm am creating an ASP.net intranet site and I'm trying to get group membership.  I have the following code:
PrincipalContext cntxt = new PrincipalContext(ContextType.Domain);
GroupPrincipal adminGroup = new GroupPrincipal(cntxt, "Help");
UserPrincipal user = UserPrincipal.FindByIdentity(cntxt, "domainuser");

var boolvalue =user.IsMemberOf(adminGroup);

boolvalue is returning as false.
If I debug with:
var foo = User.GetGroups();

I get a list of all the groups that the user is a member of.
but
var bar = adminGroup.GetMembers();

shows that it can't seem to get the group from AD as all the members are null.
I've tried using
PrincipalContext cntxt =new PrincipalContext(ContextType.Domain, "ADdomain.local");

but that didn't fix the issue.
I'm not getting any build or syntax errors either.


text:
Q: AngularJS Simple Signature Pad Directive (without jQuery) With the help of stackoverflow i got me a simple canvas signature directive. The problem is that it works with mouse events (mousedown, mouseup, mousemove) but is not working with touch events (touchstart,touchmove,touchend). I have ngTouch in my main app module and in the module that holds the directive. I hope you can help me. Here's the code:
var sig = angular.module('signature', ['ngTouch']);

sig.directive("mjav", ['$document', function ($document) {
    return {
        restrict: "A",
        link: function (scope, element) {
            var ctx = element[0].getContext('2d');

            ctx.canvas.width = window.innerWidth - 20;
            var tempCanvas = document.createElement('nanavas');

            // variable that decides if something should be drawn on mousemove
            var drawing = false;

            // the last coordinates before the current move
            var lastX;
            var lastY;

            element.on('touchstart', function (event) {
                if (event.offsetX !== undefined) {
                    lastX = event.offsetX;
                    lastY = event.offsetY;
                } else {
                    lastX = event.layerX - event.currentTarget.offsetLeft;
                    lastY = event.layerY - event.currentTarget.offsetTop;
                }

                // begins new line
                ctx.beginPath();

                drawing = true;
            });
            element.on('touchmove', function (event) {
                if (drawing) {
                    // get current mouse position
                    if (event.offsetX !== undefined) {
                        currentX = event.offsetX;
                        currentY = event.offsetY;
                    } else {
                        currentX = event.layerX - event.currentTarget.offsetLeft;
                        currentY = event.layerY - event.currentTarget.offsetTop;
                    }

                    draw(lastX, lastY, currentX, currentY);

                    // set current coordinates to last one
                    lastX = currentX;
                    lastY = currentY;
                }
            });

            $document.on('touchend', function (event) {
                // stop drawing
                drawing = false;
            });

            // canvas reset
            function reset() {
                element[0].width = element[0].width;
            }

            function draw(lX, lY, cX, cY) {
                // line from
                ctx.moveTo(lX, lY);
                // to
                ctx.lineTo(cX, cY);
                // color
                ctx.strokeStyle = "#000";
                // draw it
                ctx.stroke();
           }
        }
    };
}]);

A: If someone will need a simple signature directive for AngularJS this is what I came up with in the end:
var sig = angular.module('signature', []);

sig.controller('signatureCtrl', ['$scope', function ($scope) {
    $scope.clearVal = 0;
    $scope.saveVal = 0;

    $scope.clear = function () {
        $scope.clearVal += 1; //On this value change directive clears the context
    }

    $scope.saveToImage = function () {
        $scope.saveVal = 1; //On this value change directive saves the signature
    }
}]);

sig.directive("signatureDir", ['$document', '$log', '$rootScope', function ($document, $log, $rootScope) {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            var ctx = element[0].getContext('2d');

            ctx.canvas.width = window.innerWidth - 30;

            // the last coordinates before the current move
            var lastPt;

            function getOffset(obj) {
                return { left: 15, top: 116 }; //Got a fixed offset
            }

            attrs.$observe("value", function (newValue) {
                ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            });

            attrs.$observe("saveVal", function (newValue, dnid) {
                var imagedata = ctx.canvas.toDataURL();
                $rootScope.signatureTemp.push({'dnid':dnid, 'signature':imagedata});
            });

            element.on('touchstart', function (e) {
                e.preventDefault();
                ctx.fillRect(e.touches[0].pageX - getOffset(element).left, e.touches[0].pageY - getOffset(element).top, 2, 2);
                lastPt = { x: e.touches[0].pageX - getOffset(element).left, y: e.touches[0].pageY - getOffset(element).top };
            });
            element.on('touchmove', function (e) {
                e.preventDefault();
                if (lastPt != null) {
                    ctx.beginPath();
                    ctx.moveTo(lastPt.x, lastPt.y);
                    ctx.lineTo(e.touches[0].pageX - getOffset(element).left, e.touches[0].pageY - getOffset(element).top);
                    ctx.stroke();
                }
                lastPt = { x: e.touches[0].pageX - getOffset(element).left, y: e.touches[0].pageY - getOffset(element).top };
            });

            element.on('touchend', function (e) {
                e.preventDefault();
                lastPt = null;
            });
        }
    };
}]);

Markup:

Signature

            <canvas saveVal="{{ saveVal }}" value="{{ clearVal }}" style="border: 1px solid black;" id="canvas1" width="200" height="200" signatureDir></canvas>
            <button class="btn btn-warning" ng-click="clear()">Clear</button>
            <button class="btn btn-primary" ng-click="ok()">Save</button>

If anyone can see some bad code in here please correct me!


text:
Q: Pass labels for legend in matplotlib from a csv file I have a csv file with a large amount of data that I am plotting as a scatter plot using pandas and matplotlib. Each data point corresponds to a different specimen I have tested. I wanted to assign each specimen a specific color/marker with the legend indicating the name of the specimen that each point corresponds to. In my csv file I have a column for specimen name, a column for force, a column for displacement, the color I assigned, and marker type. I defined this function below.
> def master_plot(df):
>
>
>     y = df["Force"]
>     x = df["Displacement"]
>     z = df["Volume"]
>     z1 = z.values.tolist()
>     c1 = df["Color"]
>     c1 = c1.values.tolist()
>     m = df["Marker"]
>     m = m.values.tolist()
>
>     fig = plt.figure()
>     ax = fig.add_subplot(111)
>
>     plt.scatter(x,y,c = c1, label = z)
>     plt.plot( [0,25000],[0,25000])
>
>     ax.set_aspect('equal', adjustable='box')
>
>     plt.title("Force vs Displacement")
>     plt.ylabel("Force")
>     plt.xlabel("Displacement")
>
>
>     plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
> master_plot(df)

I can get the scatter plot to output the colors but I just get a list of the different samples in the legend without the color assignment. I have tried including z as an an argument of plt.legend but that results in no output.
I'd like for the legend to have the appropriate color next to sample name
Here is also a snippet of the csv file to show what I am passing through to my function.
> Volume,Force,Displacement,,Color,Marker,
> 1_762-68335-L45-3x,1434.645679,.45,blue,o
> 1_762-68335-L45-3x,952.316311,.23,,blue,v

A: Couple of things I noticed... the data you provided has extra , which I assume is an error. Also, think you have volume in your data, but Name in code. So, I used your data provided with some additional rows like this
>> df
    Name                Force      Displacement Color   Marker
0   1_762-68335-L45-3x  1434.645679 0.45    blue    o
1   1_762-68335-L45-3x  952.316311  0.23    blue    o
2   1_762-68335-L45-4x  2234.645679 0.51    green   v
3   1_762-68335-L45-4x  2982.316311 0.22    green   v
4   1_762-68335-L45-5x  3134.645679 0.44    red x
5   1_762-68335-L45-5x  3052.316311 0.19    red x
6   1_762-68335-L45-6x  4334.645679 0.48    maroon  <
7   1_762-68335-L45-6x  4121.316311 0.20    maroon  <

The code is simplified and is as below... I have used matplotlib, as I believe that is the library you prefer. Seaborn would make this a little easier...
Now added code to get the marker. It will pick the first marker from each set of colors in each case
def master_plot(df):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    for color in df["Color"].unique():
        ax.scatter(df[df.Color==color].Displacement, df[df.Color==color].Force,
                  c = color, label = df[df.Color==color].Name.unique(),
                  marker = df[df.Color==color].Marker.to_list()[0])
    plt.plot([0,25000],[0,25000])
    ax.set_aspect('equal', adjustable='box')
    plt.title("Force vs Displacement")
    plt.ylabel("Force")
    plt.xlabel("Displacement")
    plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')

master_plot(df)

Output plot

EDIT - New Req
If you need a different combination for each entry and you want to show ALL the different entries in the plot, then you can use this data (slightly modified)
>>  df
    Name    Force   Displacement    Color   Marker
0   1_762-68335-L45-3x  2434.645679 0.45    blue    o
1   1_762-68335-L45-3x  952.316311  0.23    blue    v
2   1_762-68335-L45-4x  4234.645679 0.51    green   x
3   1_762-68335-L45-4x  6982.316311 0.22    green   <
4   1_762-68335-L45-5x  8134.645679 0.44    red o
5   1_762-68335-L45-5x  10052.316310    0.19    red v
6   1_762-68335-L45-6x  13334.645680    0.48    maroon  x
7   1_762-68335-L45-6x  16121.316310    0.20    maroon  <

and this code...
def master_plot(df):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    mylabels = []  ##Declare and build an array of labels
    mylabels.append('Diagonal')  ##...with the diagonal line as first entry
    for i in range(len(df)):
        ax.scatter(df.iloc[i,2], df.iloc[i,1], c = df.iloc[i,3], marker = df.iloc[i,4])
        mylabels.append(df.iloc[i,0])
    plt.plot([0,25000],[0,25000])
    ax.set_aspect('equal', adjustable='box')
    plt.title("Force vs Displacement")
    plt.ylabel("Force")
    plt.xlabel("Displacement")
    ax.legend(labels=mylabels, bbox_to_anchor=(1.05, 1.0), loc='upper left')

master_plot(df)

...will give you this plot


text:
Q: How to broadcast in messenger platform? There is a way to broadcast message to many (or to all) users who added bot to their contact list?
Or I need to use https://graph.facebook.com/v2.6/me/messages for each of users?

A: Facebook has introduced Broadcast API that allows you to send messages to all open conversations. You can also label users so that broadcast will be sent to a specific label: https://developers.facebook.com/docs/messenger-platform/reference/broadcast-api

A: Facebook now supports the broadcast API
Your page need to have the following permissions:

*

*pages_messaging

*pages_messaging_subscriptions
Steps to take:

*

*Create a Broadcast Message

curl -X POST -H "Content-Type: application/json" -d '{
  "messages":[
    <MESSAGE_OBJECT>
  ]
}' "https://graph.facebook.com/v2.11/me/message_creatives?access_token=<PAGE_ACCESS_TOKEN>"

*Store the response BROADCAST_MESSAGE_ID

{
  "message_creative_id": <BROADCAST_MESSAGE_ID>,
}

*Send a Broadcast Message

curl -X POST -H "Content-Type: application/json" -d '{
  "message_creative_id": <BROADCAST_MESSAGE_ID>,
  "notification_type": "<REGULAR | SILENT_PUSH | NO_PUSH>",
  "tag": "<MESSAGE_TAG>"
}' "https://graph.facebook.com/v2.11/me/broadcast_messages?access_token=<PAGE_ACCESS_TOKEN>"

*Store the BROADCAST_ID

{
  "broadcast_id": <BROADCAST_ID>
}

A: You could keep a running list of ID's for everyone who has interacted with your bot.
Then all you have to do is make a wrapper function for your sendTextMessage function that will loop through all the users in the list and send them the same message


text:
Q: Why PhoneGap app starts with a delay? Is there any way to avoid it? I am developing an android app using phonegap. This app consists of location service, google account integration, google play service ,cordova plugins, custom plugins etc. The native version app starts without any delay and runs smoothly. But when I developed this same app on PhoneGap, it seemed to me slower than the native one. Even this app starts with a delay of 10 seconds.
I have also tested some other apps developed on Phonegap. Those also have the same problem. Is this a common problem of PhoneGap? Is there any way to recover this delay issue? If so, please put your valuable response.
Thank you.

A: It may be loading something API-related, or something extra Phonegap puts in - unless your phone is a little bit older/slower than the average these days? Personally I use Eclipse/Android SDK, so maybe take a look at them too.

A: Phonegap doesn't take that long to start up, unless you have set a splash screen to show for 10sec :p. Personally I would profile any (blocking) JavaScript that runs upon initial page load. Performance of the Android JavaScript engine is very poor until recently.


text:
Q: Percentages and Interest In the question shown in the image, does the question mean that there will be a total increase of $4\%$ each year to the amount in the bond?
So will the answer be $450 \cdot (1.04)^5 = £547.49$ (to the nearest pence)

A: The answer would be
$$ 450 * 1.02^5 \approx 496.84 $$
At the end of the year they add 2%, which is the same as multiplying by 1.02, this happens for 5 years so you multiply by 1.02 5 times, which is 1.02^5


text:
Q: Can we do a T-Test when we have two columns of average data? I have a data set assume as shown below:

I wanted to know that can I use a paired T-Test to test if the average time spent is different Pre and Post change? (I am a little unsure because the each data point is an average in itself)

A: This question came back in the list. It is an old question, but to ensure that it is not misleading for the reader, I feel that it is important to stress that the answer really depends on the very nature of the data. Doing so requires to be sure that the person analyzing the data understand the data and has clear objectives in mind. For instance, with the information provided, we do not know why the data has been grouped by day. Does the specificity of each day explain the significant differences that we can observe from one day to another? Indeed, a lot of information is hidden when averaged by day... It is possible that the average for day 5 is 107 for Pre and 76 for Post, but this very same day, most of time "Post" data were greater than "Pre" data for the majority except for some cases that were surprisingly low and produced this average. Frequency of the visits per day is another aspect to consider to avoid a Simpson paradox.
So, I do not think the short answer should be yes without knowing more about the data and the goal of the analysis.

A: The short answer is yes.  The slightly longer answer is that if this is a real data set, then at some point someone compressed a number of raw data into a mean, reducing the amount of information and power you have.  There are techniques that can handle that slightly more complicated type of data.  And they would be better.


text:
Q: Is there any way to get few fields from nested records of beam pipeline? I'm reading an Avro file, which is having nested schema with too many fields. for example : employeeId, empName, empPersonalInfo.Address.city etc. I want to write a parDo function to get only few fields from pipeline records(employeeId, empPersonalInfo.Address.city)
schema of an avro file is :
{
     "namespace"    : "studentjoin.avro",
     "type"         : "record",
     "name"         : "student",
     "fields"       : [
      {"name": "personalInfo",
       "type": { "type" : "array", "items": {
           "type" : "record",
               "name" : "studentinfo",
           "fields": [
                 {"name": "studentId", "type": "int"},
                 {"name": "studentName",  "type": ["string", "null"]},
                 {"name": "studentAddress", "type": {
                    "type" : "array", "items" : {
                        "type": "record", "name" : "addressInfo",
                        "fields":
                         [
                            {"name" : "streetName", "type": ["string", "null"] },
                            {"name": "city", "type": ["string","null"]}
                         ] }}},

                 {"name": "studentBranch", "type": ["string", "null"]}
                 ]
        } }
    }

    ]
}

if there are no nested fields than below runs perfectly:
fields_of_interest = (p | 'Projected' >> beam.Map(
          lambda row: {f: row[f] for f in selected_fileld_names}))

There is unnest builtin function in java SDk, which first convert all nested fields on one level, if same kind of the things possible in python than it will be helpful.

A: pl = (pl |
      "Extract" >> beam.Map(lambda x:
         (x["student"]["personalInfo"][0]["studentInfo"]["studentId"], x["student"]["personalInfo"][0]["studentInfo"]["studentAddress"][0]["addressInfo"]))

You can't simply flatten the dictionary, it contains lists (specified by the 'type':'array', which means there's different ways to flatten it. What if there are multiple addresses (whith multiple city names)? Return the first, or all? In the implementation above, it returns only the first element.


text:
Q: Struggling in drawing State machine diagram Hey there I'm trying to draw state machine diagram for this scenario but It's missing lots of information. If someone here could help out with it.
The Scenario

*

*Tourists will start the journey by selecting the trip using the
Automated Ticketing system (ATS).

*The Automated Ticketing System (ATS) will display the trip details.

*This Trip details will include the seat-number and destination.

*Based on provided trip details, the ATS will compute payment.

*The tourist has the option to pay the payment by cash or credit
card.

*If the tourist will insert a wrong amount of cash, the ATS will
display "Insert More Cash" message on the screen until the correct
amount will be inserted.

*If payment by card was selected by the tourist, the ATS will perform
two parallel tasks. It will validate the expiration date of the card
and check the credit balance. If card is accepted, the bank will
authorize the payment and will update the account of the tourist.
However, if card is not accepted or invalid, the ATS will again ask
for payment option (back to step 5) from the tourist.

*After payment is complete, the ticket and receipt are printed by the
ATS.

*Cash payment might result in some change, so the change is also
dispensed by the ATS. The tourist will then get the ticket and the
change.

*ATS will display the message "Transaction Complete" at the end of
 the transaction.

My Drawing:

A: Ok, so I try to give you some hints. A state machine is always created for a single class, not the overall system under consideration. So let's assume the ATS is a single class (in reality it will probably be more a component consisting of several classes). Now this ATS will in the beginning be idle. It is triggered somehow when a trip is selected. It then has to complete the journey details. It waits for payment and finally it will spit out a ticket. Now (basically!) the state machine looks like this:

This is a scaffold and it was done without reading the details above. Note that instead of the cancel transitions you could use a general exception from an interruptible region which eventually clears payments. In practice you would likely do that since a cancellation should (from a user perspective) be possible at any point. A time out of course would also be possible (what if already some cash had been paid?).
Also I did not include the do/entry/exit actions. For the cash this would be something like add new cash sum so we know when enough money has been paid.


text:
Q: How to encrypt a file buffer with XOR? I'm trying to read in a file to buffer and encrypt each byte with my XOR encryption key. I have implemented it like the following but it segfaults for some reason.
int main(char argc, char *argv[]) {
    fileIn = fopen("data.bin", "rb"); // open input file (binary)
    if (fileIn==NULL) {
        puts("Error opening input file");
        exit (1);
    }

    // obtain file size.
    fseek(fileIn , 0 , SEEK_END);
    lSize = ftell(fileIn);
    rewind(fileIn);
    printf("Filesize: %d bytes.\n", lSize);

    // allocate memory to contain the whole file.
    buffer = (unsigned char*) malloc (lSize);
    if (buffer == NULL) {
        puts("malloc for input file buffer failed (not enough memory?)");
        exit (2);
    }

    // copy the file into the buffer.
    fread (buffer, 1, lSize, fileIn);

    char *enckey = "enckey123";

    unsigned char *buf = buffer;
    int index = 0;
    while (buf < buf + lSize - 1) {
        *buf++ ^= enckey[index++ % 9]; // 9 is the length of the encryption key
    }
}

It segfaults right at this like *buf++ ^= enckey[index++ % 9];.
Debugging with gdb, I can see that lSize is something like 2000, but index has the value of 128585.
What am I doing wrong?

A: This loop:
while (buf < buf + lSize - 1) {

never finishes.
Perhaps you meant
while (buf < buffer + lSize) {

?
P.S. the -1 means it doesn't encrypt the last character.

A: The loop will never end.
I think the loop needs a better way to iterate over only lSize bytes.
I did it by changing the last few lines to this:
    // ...
    // Calculate where to stop the iteration
    const unsigned char *buf_end = buf + lSize - 1;
    // Walk over lSize bytes in the buffer
    while (buf < buf_end) {
        *buf++ ^= enckey[index++ % 9]; // 9 is the length of the encryption key
    }
    // ...

A: Similar to other answers, but I think this is more readable:
Instead of this:
while (buf < buf + lSize - 1) {
    *buf++ ^= enckey[index++ % 9]; // 9 is the length of the encryption key
}

This:
for (size_t i = 0; i < lSize; i++) {
   buf[i] = enckey[i % 9];
}


text:
Q: How to poll data using Ajax request? I am trying to poll my data in HighCharts. The graph in this link is what I am trying to achieve. I am using Ajax request to retrieve my data. Here is my code:
setInterval(RefreshGraph, 3000);

...

...

function RefreshGraph() {
            var options = {
                chart: {
                    type: 'spline'
                },
                title: {
                    text: 'Text'
                },
                xAxis: {
                    title: {
                        text: 'TIMEFRAME'
                    },
                    categories: ['-4m', '-3m', '-2m', '-1m', 'Now']
                },
                yAxis: {
                    title: {

                        text: 'NUMBER'
                    },
                },
                tooltip: {
                    crosshairs: true,
                    shared: true
                },
                plotOptions: {
                    spline: {
                        marker: {
                            radius: 4,
                            lineColor: '#666666',
                            lineWidth: 2
                        }
                    }
                },
                series: [{}]
            };

        Highcharts.ajax({
            url: "/Home/GetData",
            success: function (data) {
                var formattedData = FormatData(data);
                //Graph 1
                options.series[0] = formattedData[0];
                //Graph 2
                options.series[1] = formattedData[1];

                Highcharts.chart("container", options);
            }
        });
    }

However, the entire graph gets redrawn with my above code. How can I enable live polling for the above code?

A: You create a chart every time data is received. You need to create a chart and then update it. Example:
const options = {...};

const chart = Highcharts.chart("container", options);

function RefreshGraph() {
  Highcharts.ajax({
    url: "/Home/GetData",
    success: function(data) {
      var formattedData = FormatData(data);

      chart.update({
        series: [formattedData[0], formattedData[1]]
      });
    }
  });
}

setInterval(RefreshGraph, 3000);

Live demo: http://jsfiddle.net/BlackLabel/6d5stjab/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update


text:
Q: jdbc program to find the square of a number using callable statement (stored procedure ) import java .sql.*;
class Pro
{
public static void main(String args[]) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
Connection conn = DriverManager.getConnection (url,"root","password");
CallableStatement cst=conn.prepareCall("{call fileproc(?,?)}");
cst.setInt(1,10);
cst.registerOutParameter(2,Types.INTEGER);
cst.execute();
int i=cst.getInt(2);
System.out.println("the number is :" +i);
cst.close();
conn.close();
}
}

In MYSQL:
fileproc:
CREATE  PROCEDURE fileproc(IN x INT,OUT y INT)
BEGIN
y := x * x;
END;
/

i'm getting an error at line 3 before entering END in fileproc as
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near ':= x
* x' at line 3.

what is the correct syntax?
please help.
Thank You.

A: mysql>create database <database-name>;
     ->use <database-name>;
      delimiter //
      Create Procedure fileproc(in x int, out y int)
      begin
      set y = x * X;
      end //
mysql> delimiter ;
mysql> call(10,@y);
mysql> Select @y;

A: In the mysql stored procedure, remember to use 'set' keyword.


text:
Q: Linear subspace closed under all special orthogonal matrices
Let $n\in \mathbb N$ and $E$ be an $n$ dimensional vector space over $\mathbb R$.
Let $F$ be a linear subspace of $E$ such that $\forall f\in SO(E), f(F)\subset F$
Prove that $F=\{0\}$ or $F=E$

Although the result is quite intuitive, I haven't been able to write up a proof. I've noticed that the orthogonal complement is closed under $SO(E)$ as well.
I tried a proof by contradiction. If $\dim F\in\{1,\ldots,n-1\}$, one may consider some well-chosen reflection...

A: Hint: let $P$ be the permutation matrix
$$
\pmatrix{
&&&&1\\
&1\\
&&\ddots\\
&&&1}
$$
Let $Q$ be any orthogonal matrix (change of basis to any orthonormal basis). Note that $QPQ^T$ is orthogonal.
Note that the span of $e_1,P e_1,\dots,P^{n-1}e_1$ is $E$ (where $e_1$ is the first basis vector).

A: To prove the result, it will suffice to show that if $F$ contains some line$~L_0$ through the origin (in other words if $F\neq\{0\}$) then $F$ contains every line through the origin (in other words if $F=E$). Let $L_1$ be an arbitrary line through the origin; one needs to find of $g\in SO(E)$ such that $g(L_0)=L_1$; then the property of being $SO(E)$-stable will force $F$ to contain $L_1$, because it contains $L_0$.
Your idea of using reflections works. After choosing spanning unit vectors $v_0,v_1$ of $L_0,L_1$ respectively (and assuming $v_0\neq v_1$) one can apply the orthogonal reflection in the hyperplane orthogonal to $v_1-v_0$ to send $v_0$ to $v_1$, and therefore $L_0$ to $L_1$. The reflection is in $O(E)$ but not in $SO(E)$, but this can be remedied by composing with the orthogonal reflection in the hyperplane orthogonal to $v_1$, which fixes $L_1$. The composition of both reflections is your $g$.
Another approach is to use orthonormal bases, and notably the fact that for a given line one can always choose an orthonormal basis starting with a vector from this line.
After choosing one reference ordered orthonormal basis$\def\B{\mathcal B}~\B$, the elements $g\in SO(E)$ are in bijection the set of ordered orthonormal bases of$~E$ with the same orientation as$~\B$; the bijection is simply taking the image of$~\B$ under$~g$. Now choose $\B$ to start with a vector from$~L_0$, and choose another orthonormal basis to start with a vector from$~L_1$; one can arrange (by flipping a sign in the latter basis if necessary) that the two bases have the same orientation. The unique $g\in SO(E)$ sending$~\B$ to the second basis will have $g(L_0)=L_1$.


text:
Q: Logical Purpose or Usefulness for assigning a sub class object to super class reference Parent parent = new Child();
parent.someMethod();

In what situations,assinging like above is useful or what is the logical explanation behind it? instead of the following:
Child child = new Child();
child.someMethod();

In both the cases,Child's method is only going to be called,anyway.So,why this kind of representation is allowed? Isn't it an unnecessary feature allowed in the design?
The only reason I could come up with,depending on some fiddling I did is that,it lets you know that "someMethod()" is not available in the Parent if it is not present in the Parent,at the time of writing "parent.someMethod()"!
Can you please shed some light as to how it is useful/necessary and give me some perspective related to object oriented concepts? I know it relates to Polymorphism here.But I don't find any necessity to use such representations.
Practical real-world example is much appreciated. Thanks.
I check the following SO question,but I don't feel like I have the answers I am looking for.
Using superclass to initialise a subclass object java

A: It gives you the oppurtinity to behave same to different objects.
For example Object class. Object has a toString() method. And every class extending Object has toString() method. (Every class implicityly extends Object class.)
Now , imagine you have the following objects from different classes. A person(Person class), a car(Car class), a lamp(Lamp class).
You want to write a method that calls each object's toString() method. You have to write 3 different version of this method.
callToString(Person p) {p.toString();}
// A method that accepts person objects.

callToString(Car c){c.toString();}
// A method that accepts car objecs.

callToString(Lamp l){l.toString();}
// A method that accepts lamp objects.

We know that each 3 classes extends from Object class and Object class has toString() method. We can write a method that accepts Object class objects.
callToString(Object o){o.toString();}

Now as this method accepts Object class object, we can use it with Car, Person and Lamp because all of them extends from Object class.
Usage of the new method.
Person john = new Person();
Car ferrari = new Car();
Lamp philips = new Lamp();

callToString(john);
callToString(ferrari);
callToString(philips);


text:
Q: Formatting Instant Search Hits section I'm trying to show a hit section from a Algolia Instant Search as simple as a dropdown-item from bootstrap:

one result per line as a  link, without images.
But I only get this one:

How can I get the dropdown-item (above) style , One item per line, without that borders and overlapping ?
Code HTML for seachbox:
<form class="form-inline md-form my-0 mr-5 text-white ">

</form>

Code JS :
search.addWidget(
instantsearch.widgets.searchBox({
container: "#searchbox",
placeholder: "Search",
showSubmit: false,
autofocus: false
})
);

  search.addWidget(
    instantsearch.widgets.hits({
      container: "#hits",
      templates: {
        empty: "None.",
        item: function(item) {
           return `<a class="dropdown-item" href="/question/${item.id_question}">${item.str_question}</a>`;
        }
      }
    })
    );

A: Without being able to see the inside of

I am guessing there is a ul and li
you need to make those display: block
and a few more css properties
probably white-space: pre;
Can you provide the inside html for

? so we can provide a better answer.


text:
Q: Second inputs onclick() function doesn't work There were similar questions, but not exactly what I'm looking for. I have a filter for my table with 1 button that changes the value of a textbox to the currant date. That works fine, but right next to it, theres a button to clear the content in the textbox. This second button doesnt seem to work.
My code :

function today() {

  var today = new Date();
  var dd = String(today.getDate()).padStart(2, '0');
  var mm = String(today.getMonth() + 1).padStart(2, '0');
  var yyyy = today.getFullYear();

  today = yyyy + '.' + mm + '.' + dd;

  document.getElementById("myInput").value = today;
}

function clear() {

  document.getElementById("myInput").value = "";
}

  Filter By:
  <input class="input-xsmall" type="text" maxlength="10" placeholder="yyyy.mm.dd" id="myInput" style="width: 100px; margin-bottom: 10px; display: inline-block">
  <input type="button" value="Today" onclick="today()">
  <input type="button" value="Clear" onclick="clear()">

Not sure how to get it to work. When I switched the onclick function in the first input as clear() it worked so for some reason the second input button doesnt work. How can I fix that?

A: Try to change the name of that clear() function. And also consider looking into event handlers.

A: You need to change the js function name from clear() to something else. Because clear() is a javascript built in function/method.
Javascript Clear fields Function Not Working?

A: clear is not a reserved keyword. It is a scope problem
But still if you want to use same function name. can try below code.
Changing your existing function onClick="clear()" to window.clear() can fix your issue.
Refer this Ans
<input type="button" value="clear" onclick="window.clear()">

A: Unlike what is written here, clear is not a word reserved in js.
Here is the list of reserved words(from s3 site)

Felix Kling Explained here, why sometimes it acts as a reserved word

A: Or just add an event listener instead
document.querySelector("[type='button'][value='Clear']").addEventListener("click", clear);


text:
Q: Golang foreach difference func Benchmark_foreach1(b *testing.B) {
        var test map[int]int
        test = make(map[int]int)
            for i := 0; i < 100000; i++ {
                        test[i] = 1
            }
            for i := 0; i < b.N; i++ {
                    for i, _ := range test {
                            if test[i] != 1 {
                                    panic("ds")
                            }
                    }
            }
}

func Benchmark_foreach2(b *testing.B) {
            var test map[int]int
            test = make(map[int]int)
            for i := 0; i < 100000; i++ {
                    test[i] = 1
            }
            for i := 0; i < b.N; i++ {
                    for _, v := range test {
                            if v != 1 {
                                    panic("heh")
                            }
                    }
            }
}

run with result as below
goos: linux
goarch: amd64
Benchmark_foreach1-2         500           3172323 ns/op
Benchmark_foreach2-2        1000           1707214 ns/op

why is foreach-2 slow?

A: I think Benchmark_foreach2-2 is about 2 times faster - it requires 1707214 nanoseconds per operation, and first one takes 3172323. So second one is 3172323 / 1707214 = 1.85 times faster.
Reason: second doesn't need to take value from a memory again, it already used value in v variable.

A: The test[k] statement in BenchmarkForeachK takes time to randomly read the value, so BenchmarkForeachK takes more time than BenchmarkForeachV, 9362945 ns/op versus 4213940 ns/op   .
For example,
package main

import "testing"

func testMap() map[int]int {
    test := make(map[int]int)
    for i := 0; i < 100000; i++ {
        test[i] = 1
    }
    return test
}

func BenchmarkForeachK(b *testing.B) {
    test := testMap()
    b.ReportAllocs()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        for k := range test {
            if test[k] != 1 {
                panic("eh")
            }
        }
    }
}

func BenchmarkForeachV(b *testing.B) {
    test := testMap()
    b.ReportAllocs()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        for _, v := range test {
            if v != 1 {
                panic("heh")
            }
        }
    }
}

Output:
$ go test foreach_test.go -bench=.
BenchmarkForeachK-4    200    9362945 ns/op    0 B/op    0 allocs/op
BenchmarkForeachV-4    300    4213940 ns/op    0 B/op    0 allocs/op


text:
Q: How to obtain IServiceProvider and IMarkupServices from HTMLDocument (mshtml) Im doing some test creating an instance of HTMLDocument this way:
object[] pageText = { "
some text...
" };
var document = new HTMLDocumentClass();
var document2 = (IHTMLDocument2)document;
document2.write(pageText);

and need to get a reference to a IMarkupServices.
This is the code I'm currently using:
Guid IID_IMarkupServices = new Guid("3050F4A0-98B5-11CF-BB82-00AA00BDCE0B");
IMarkupServices markupServices = GetService<IMarkupServices>(document, ID_IMarkupServices);

static Guid HTMLDocumentClassGuid = new Guid("25336920-03F9-11CF-8FD0-00AA00686F13");
private static T GetService<T>(IHTMLDocument2 document, Guid riid)
{
    var serviceProvider = (IServiceProvider) document;
    object service;
    serviceProvider.QueryService(ref HTMLDocumentClassGuid, ref riid, out service);
    return (T)service;
}

When i run it (it's hosted in a Console App) the following exception is thrown:
Unhandled Exception: System.InvalidCastException: Unable to cast COM object of type 'mshtml.HTMLDocumentClass' to interface type 'IServiceProvider'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{4C9A623C-FF69-3A3B-B592-43371C50DF88}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
at ConsoleApplication3.Program.GetService[T](IHTMLDocument2 document, Guid riid) in c:\users\admin\documents\visual studio 010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 35
at ConsoleApplication3.Program.Main(String[] args) in c:\users\admin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 29

Note:
What i'm trying to do is to unit test some objects i have implemented with mshtml. When i run the same code in an BHO (within Internet Explorer) it works fine.
Thank you very much
Edit: here´s the code I finaly used to get this working
I got it working by inspecting the following WatiN's implementation: http://www.java2s.com/Open-Source/CSharp/Web-Testing/WatiN/WatiN/Examples/MsHtmlBrowser/MsHtmlNativeBrowser.cs.htm
based on Sheng Jiang helpful answer.
public class Program
    {
        [Guid("7FD52380-4E07-101B-AE2D-08002B2EC713")]
        [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IPersistStreamInit
        {
            void GetClassID(out Guid pClassID);
            int IsDirty();
            void Load(System.Runtime.InteropServices.ComTypes.IStream pStm);
            void Save(System.Runtime.InteropServices.ComTypes.IStream pStm, bool fClearDirty);
            void GetSizeMax(out long pcbSize);
            void InitNew();
        }

        [STAThread]
        static void Main(string[] args)
        {
            var anHtmlDocument = new HTMLDocumentClass();
            var aPersistStream = (WB.Program.IPersistStreamInit)anHtmlDocument;
            aPersistStream.InitNew();

            var anHtmlDocument2 = (IHTMLDocument2)anHtmlDocument;
            anHtmlDocument2.write(new object[] { "test  foo " });
            anHtmlDocument2.close();

            while (anHtmlDocument.readyState != "complete")
            {
                //This is also a important part, without this DoEvents() appz hangs on to the "loading"
                Application.DoEvents();
            }

            var aMarkupService = (IMarkupServices)anHtmlDocument;

            IMarkupPointer aPointer;
            aMarkupService.CreateMarkupPointer(out aPointer);

            var anHtmlBody = (IHTMLBodyElement)anHtmlDocument.body;
            var aSelection = anHtmlBody.createTextRange();
            aSelection.findText("foo", 0, 0);
        }
    }

A: QI for IMarkupServices after you loaded the document via the IPersistStreamInit interface, preferably with a Url moniker as a proxy.


text:
Q: Swaps and comparisons in shell sort I am trying to figure out how to find the total amount of swaps and comparisons used in a shell sort function, but I'm not really sure where to place the additions of swaps and comparisons.
I am putting the additions in this insertionSort function below.
void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
    int i = 0;
    int j = 0;
    int temp = 0;

    for (i = startIndex + gap; i < numbersSize; i += gap) {
        j = i;
        while (j - gap >= startIndex && numbers[j] < numbers[j - 1]) {
            temp = numbers[j];
            numbers[j] = numbers[j - gap];
            numbers[j - gap] = temp;
            j = j - gap;
            totalComps++; //declared globally
            totalSwaps++; //declared globally
        }

    }
}

I know that the totalSwaps is fine where it is, but I'm not too sure where to put totalComps, since we're also comparing in the while loop.

A: You can use a pair of function objects, one that does the comparison and the other the swaps.
struct counted_less
{
    int count = 0;
    bool operator()(int lhs, int rhs)
    {
        ++count;
        return lhs < rhs;
    }
}

struct counted_swap
{
    int count = 0;
    void operator()(int & lhs, int & rhs)
    {
        ++count;
        using std::swap;
        swap(lhs, rhs);
    }
}

std::pair<int, int> insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
    counted_less less;
    counted_swap swap;

    for (int i = startIndex + gap; i < numbersSize; i += gap) {
        for (int j = i; j - gap >= startIndex && less(numbers[j], numbers[j - 1]); j -= gap) {
            swap(numbers[j], numbers[j - gap]);
        }
    }

    return { less.count, swap.count };
}

A: I think the compare should be count even if the condition was false
It meant only to array elements compares, not to each compare in your code...
see the following code
void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
    int i = 0;
    int j = 0;
    int temp = 0;

    for (i = startIndex + gap; i < numbersSize; i += gap) {
        j = i;
        while (j - gap >= startIndex) {
            //each iteration is compare so increment here
            totalComps++; //declared globally
            if( numbers[j] < numbers[j - 1])  {
              temp = numbers[j];
              numbers[j] = numbers[j - gap];
              numbers[j - gap] = temp;
              j = j - gap;
              //had a swap
              totalSwaps++; //declared globally
            }
            else break;
        }

    }
}

A: Increment the conditional counter everytime you make a test.
A compact way to do so is to prefix the increment operation to every test with && (which will succeed since the count is positive, since the variable is pressumably unsigned):

for (i = startIndex + gap; ++totalComps && (i < numbersSize); i += gap) {

and

while (++totalComps && (j - gap >= startIndex) && ++totalComps && (numbers[j] < numbers[j - 1])) {


text:
Q: Python triplet of numbers I would like to write a program for Pythagorean Triplet. Program for numbers a, b, c return Pythagorean three natural numbers a1, b1, c1 such that a1 >= a, b1 >= b, c1 >= c.
def Triplet(a, b, c):
    a1 = a
    b1 = b
    n = 5
    m = 0
    while True:
        m += 1
        while b1 <= (b + n * m):
            a1 = a
            while a1 <= b1:
                #while c1 > c:
                    c1 = (a1 * a1 + b1 * b1) ** .5
                    if c1 % 1 == 0:
                        return a1, b1, int(c1)
                    a1 += 1
            b1 += 1

print(Triplet(3,4,6))

For input: (3, 4, 6), output should be: (6, 8, 10). Where is the error?

A: The issue is that you've commented out your incorrect check for c1 > c, but not replaced it with anything.
If you just add that condition back before the return, it works:
def Triplet(a,b,c):
    a1=a
    b1=b
    n=5
    m=0
    while True:
        m+=1
        while b1<=(b+n*m):
            a1=a
            while a1<=b1:
                c1=(a1*a1+b1*b1)**.5
                if c1>=c and c1%1==0:
                    return a1,b1,int(c1)
                a1+=1
            b1+=1

print(Triplet(3,4,6))

A: If you change  the condition to if c1%1==0 and c1>=c: then the issue will get fixed.
I ran it locally and i got (6, 8, 10)


text:
Q: Workaround for unrecognized  tags in older browsers I have a pair of nested section tags to set the width of my content, but am having problems with browsers (or versions of browsers) that don't recognize the  tag: they're just allowing the content to fill the entire width of the parent container.
My code looks essentially like this:

Bunch of Text Here That Forms The Content

Now in browsers that don't recognize the
 tag, the content in the inner
 behaves as if the tag does not exist, and the content simply fills the width of the page. Any idea what I can do about it?

A: If you don't mind your site's design and layout depending on JavaScript for older browsers (mainly IE versions 6-8), you can use the HTML5 JavaScript shim for IE or Modernizr:

    <meta charset="utf-8" />
    <title>Stack Overflow Rocks!</title>

    <link rel="stylesheet" href="/path/to/file.css" media="all" />

To use this script, it must be included before the  element (i.e. in the ) but doesn't matter if it appears before or after any CSS. However, for the sake of performance, it's preferable to include any CSS before this script.
A clever and somewhat creative approach that doesn't rely on JavaScript is to insert an element that IE/Win 6-8 understands, (such as a plain old
) inside of the semantic HTML5 elements:

        ...

You can then apply your CSS using either the ID (for older browsers) or the HTML5 element (for modern browsers):
aside,
#sidebar {
    ...
}

While this approach adds an extra set of tags for each HTML5 element — and arguably isn't a pure as the native HTML5 method — it doesn't depend on JavaScript and your site's layout can look the same with or without JavaScript enabled.

For further reading about HTML5 elements and IE/Win, see The Story of the HTML5 Shiv.

A: Most browsers treat unknown tags as if they had display: inline applied to them. You'll want to apply display: block to
 (and other block-level HTML5 tags, if you plan to use them) in your stylesheet. (Reset stylesheets, like Eric Meyer's, often take care of this for you.)
Older versions of IE, in contrast, won't allow you to style tags at all if they don't know about them (e.g. IE 6 was not aware of the  tag even though it was in the HTML 4 spec), unless you create that an instance of the tag via JavaScript. That's what the HTML5 shiv does.


text:
Q: Drawing a tree-like graph - how to organize the storage array? The question is generally language-independent (although if that matters, I am using Java/Processing). I need to draw a tree-like graph using some database output. The rules are are simple:
Graph has only one Root.
Each Node can have several children, but only one parent.
I am having trouble wrapping my head around how to serve data to the drawing function. The database I am getting data from (it's Rails/MySQL) has following structure (I am using pseudocode to avoid unnecessary self-referential has_many :through details) :
Graph
 has_many :nodes

Node
 has_many :siblings
 has_one :parent
 has_many :children

Question is - how should I organize the array that I put the Nodes information into and how to loop through that array? A pseudo-code for the algo would be amazing.
If you find that some info is missing for the answer to happen, let me know, I will be happy to expand the question / add data.
P.S. I am not really looking for suggestions on some frameworks/services that can draw graphs for me, I actually need to do that using my current tools.
Thanks!
EDIT :
That's how I am drawing graph now...  It takes word one by one from an array like ['0root', '2child', 2child2', '4child_child'] and reconstructs the tree assuming that if (int) prefix of next element of array is larger by 2 it's a child and if it's smaller by 2, it's  one level up (sibling of a parent). The position relative to siblings is calculated from total number of elements with the same prefix in the array.. I wonder if there is a more elegant way to do that..?
Graph() {
        wordList = new ArrayList();
        nodeList = new ArrayList();
        sibList = new ArrayList();
      }
  Integer sibNumber(int idx<char>) {
    Map<Integer, Integer> sibCount = new HashMap<Integer, Integer>();
    for (Integer sibling: sibList) {
      Integer count = sibCount.get(sibling);
      sibCount.put(sibling, (count==null) ? 1 : count+1);
    }
    Integer result = sibCount.get(idx);
    return result;
  }

  void update(String wrd) {
    wordList.add(wrd);

    String word = wrd;
    String[][] m = matchAll(wrd, "(\\d*)");
    int index = (int) m[0][0];
    char number = (char) index;
    sibList.add(index);
//    println(wrd);
    word = word.replaceAll(number,"");
    Integer siblingsNum = sibNumber(index);
    if (sibList.size()>=2) {
      lastIndex = sibList.get(sibList.size()-2);
      int indexDiff = index-lastIndex;
      if (indexDiff != 0) {
        for (int i=sibList.size()-1; i>0; i--) {
          if (index-sibList.get(i) == 2) {
            parNode = nodeList.get(i);
            break;
          }
        }
      }
    }
    if (index == 2) {
      parNode = nodeList.get(0);
    }

    node = new Node(word, index, siblingsNum, parNode);
    nodeList.add(node);

  }

  void clean() {
    nodeList = new ArrayList<Node>();
    sibList = new ArrayList<Integer>();
  }

  void display() {
    for (int i = 0; i < nodeList.size(); i++) {
      nd =  nodeList.get(i);

      if (nd.parent != null) {

        stroke(255, 0, 0);
        VerletSpring2D spring=new VerletSpring2D(nd.origin,nd.parent.origin,80,0.01);
        physics.addParticle(nd.origin);
        physics.addSpring(spring);
        line(nd.origin.x+nd.w/2, nd.origin.y, nd.parent.origin.x+nd.w/2, nd.parent.origin.y+nd.parent.h);
      }
      nd.display();
    }
  }
}

A: Do you have to use an array? The natural solution to this problem is to implement a 'Node' class, which has references to child Nodes. This lends itself to a recursive algorithm which will allow you to (for example) find a specific Node.
All you then need to start with is a reference to the root Node.
public class Node {
  private Node parent;
  private List<Node> children;

  public Node findNode(String nodeName) {
    // Is it this node?
    // Iterate through all child nodes, calling findNode on each
  }
}


text:
Q: How to store values from loop to a dataframe? I have created a loop that generates some values. I want to store those values in a data frame. For example, completed one loop, append to the first row.
def calculate (allFiles):

    result = pd.DataFrame(columns = ['Date','Mid Ebb Total','Mid Flood Total','Mid Ebb Control','Mid Flood Control'])

    total_Mid_Ebb = 0
    total_Mid_Flood = 0
    total_Mid_EbbControl = 0
    total_Mid_FloodControl = 0

    for file_ in allFiles:
        xls = pd.ExcelFile(file_)
        df = xls.parse('General Impact')
        Mid_Ebb = df[df['Tidal Mode'] == "Mid-Ebb"] #filter
        Mid_Ebb_control = df[df['Station'].isin(['C1','C2','C3'])] #filter control
        Mid_Flood = df[df['Tidal Mode'] == "Mid-Flood"] #filter
        Mid_Flood_control = df[df['Station'].isin(['C1','C2','C3', 'SR2'])] #filter control
        total_Mid_Ebb += Mid_Ebb.Station.nunique() #count unique stations = sample number
        total_Mid_Flood += Mid_Flood.Station.nunique()
        total_Mid_EbbControl += Mid_Ebb_control.Station.nunique()
        total_Mid_FloodControl += Mid_Flood_control.Station.nunique()

    Mid_Ebb_withoutControl = total_Mid_Ebb - total_Mid_EbbControl
    Mid_Flood_withoutControl = total_Mid_Flood - total_Mid_FloodControl

    print('Ebb Tide: The total number of sample is {}. Number of sample without control station is {}. Number of sample in control station is {}'.format(total_Mid_Ebb, Mid_Ebb_withoutControl, total_Mid_EbbControl))
    print('Flood Tide: The total number of sample is {}. Number of sample without control station is {}. Number of sample in control station is {}'.format(total_Mid_Flood, Mid_Flood_withoutControl, total_Mid_FloodControl))

The dataframe result contains 4 columns. The date is fixed. I would like to put total_Mid_Ebb, Mid_Ebb_withoutControl, total_Mid_EbbControl to the dataframe.

A: I believe you need append scalars in loop to list of tuples and then use DataFrame constructor. Last count differences in result DataFrame:
def calculate (allFiles):

    data = []
    for file_ in allFiles:
        xls = pd.ExcelFile(file_)
        df = xls.parse('General Impact')
        Mid_Ebb = df[df['Tidal Mode'] == "Mid-Ebb"] #filter
        Mid_Ebb_control = df[df['Station'].isin(['C1','C2','C3'])] #filter control
        Mid_Flood = df[df['Tidal Mode'] == "Mid-Flood"] #filter
        Mid_Flood_control = df[df['Station'].isin(['C1','C2','C3', 'SR2'])] #filter control
        total_Mid_Ebb = Mid_Ebb.Station.nunique() #count unique stations = sample number
        total_Mid_Flood = Mid_Flood.Station.nunique()
        total_Mid_EbbControl = Mid_Ebb_control.Station.nunique()
        total_Mid_FloodControl = Mid_Flood_control.Station.nunique()
        data.append((total_Mid_Ebb,
                     total_Mid_Flood,
                     total_Mid_EbbControl,
                     total_Mid_FloodControl))

    cols=['total_Mid_Ebb','total_Mid_Flood','total_Mid_EbbControl','total_Mid_FloodControl']

    result = pd.DataFrame(data, columns=cols)
    result['Mid_Ebb_withoutControl'] = result.total_Mid_Ebb - result.total_Mid_EbbControl
    result['Mid_Flood_withoutControl']=result.total_Mid_Flood-result.total_Mid_FloodControl

    #if want check all totals
    total = result.sum()
    print (total)

    return result

A: Here is an example of loading data per column in a dataframe after each iteration of a loop. While this is not THE only method, it's one that helps understand concept better.
Necessary imports
import pandas as pd
from random import randint

First define an empty data-frame of 5 columns to match your problem
df = pd.DataFrame(columns=['A','B','C','D','E'])

Next we iterate through for loop and generate value using randint() and add one value at a time to each column Staring with 'A' all the way to 'E',
for i in range(5): #add 5 rows of data
    df.loc[i, ['A']] = randint(0,99)
    df.loc[i, ['B']] = randint(0,99)
    df.loc[i, ['C']] = randint(0,99)
    df.loc[i, ['D']] = randint(0,99)
    df.loc[i, ['E']] = randint(0,99)

We get a DF whose 5 rows are populated.
>>> df
    A   B   C   D   E
0   4  74  71  37  90
1  41  80  77  81   8
2  14  16  82  98  89
3   1  77   3  56  91
4  34   9  85  44  19

Hope above helps and you are able to tailor to your needs.

A: Note this does not produce a row per file as requested, but it more of a comment about general use of Pandas for problems like this - it is often easier to read all the data then process using the pandas files than to write your own loops over different cases.
I think you are not using pandas in the idiomatic way here. I think you will save a lot of code and get a more understandable result if you do it this way:
controlstations = ['C1', 'C2', 'C3', 'SR2']
df = pd.concat(pd.read_excel(file_, sheetname='General Impact') for file_ in files)
df['Control'] = df.Station.isin(controlstations)
counts = df.groupby(['Control', 'Tidal Mode']).Station.agg('nunique')

So here you are reading all the excel files into a single dataframe first, then adding a column to indicate if that is a control station or not, then using groupby to count the different combinations.
counts is a series with a two-dimensional index (for some made up data):
Control  Tidal Mode
False    Mid-Ebb       2
         Mid-Flood     2
True     Mid-Ebb       2
         Mid-Flood     2

You can access the values you have in your function like this:
total_Mid_Ebb = counts['Mid-Ebb'].sum()
total_Mid_Ebb_Control = counts['Mid-Ebb', True]
total_Mid_Flood = counts['Mid-Flood'].sum()
total_Mid_Flood_Control = counts['Mid-Flood', True]

After which you can easily add them to a DataFrame:
import datetime
today = datetime.datetime.today()
totals = [total_Mid_Ebb, total_Mid_Flood, total_Mid_Ebb_Control, total_Mid_Flood_Control]
result = pd.DataFrame(data=[totals], columns=['Mid Ebb Total', 'Mid Flood Total', 'Mid Ebb Control', 'Mid Flood Control'],
                       index=[today])


text:
Q: CSS - Sidebar height won't expand I'[m a newbie and not sure how to solve this CSS problem (or what I think is caused by the CSS).  My sidebar height will not expand to include all the content:http://soundcues.net/wordpress/edu-discount/
The content does take a moment to load so this may also be why the height loads at the incorrect size?
Any ideas?

A: div.sidebar-wrapper.span4 { is set to "position:absolute" remove that and it will work.


text:
Q: convert string to number node.js I'm trying to convert req.params to Number because that is what I defined in my schema for year param.
I have tried
req.params.year = parseInt( req.params.year, 10 );

and
Number( req.params.year);

and
1*req.params.year;

but non of them works.
Do I need to install something?

A: Not a full answer
 Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

A: You can parse string to number in several ways.
-Number()
-parseInt()
-parseFloat()
Example:
Number("256.123") //returns 256.123
Number("252px") //returns NaN
parseInt("256.123") //returns 256
parseInt("256px") //returns 256
parseFloat("256") //returns 256
parseFloat("256.123") //returns 256.123
parseFloat("256.23px") //returns 256.23

A: You do not have to install something.
parseInt(req.params.year, 10);

should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

A: Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.
function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

See results of below test cases.
console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));

result:
CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN


text:
Q: How to remove the comma from dollar amount from a text file using pandas/python I am new to python and I am trying to add headers to the results from a text file but I keep getting the following error :

pandas.errors.ParserError: Error tokenizing data. C error: Expected 3 fields in line 4, saw 4.

After researching on this is because on the dollar amount when it is on the thousands, have a comma and pandas is looking as it would be an extra field (which is not).  I would want to remove the comma from the dollar amount so when I add the headers it would not give me the error above.Any help is greatly appreciated.
Text file information:
19140E020603,$0.00,payment not received

13141W000119,$0.00,payment not received

99141V009055,$3,468.07,payment received

29141N005785,$0.00,payment not received

79141M009249,$3,468.07,payment received

15141Q005785,$127.73,payment received

Expected result:
id     Amount     Comments

19140E020603,$0.00,payment not received

13141W000119,$0.00,payment not received

99141V009055,$3,468.07,payment received

29141N005785,$0.00,payment not received

79141M009249,$9,398.07,payment received

15141Q005785,$127.73,payment received

Code:
import pandas as pd

fhand = open("results.txt")
result = pd.read_csv(fhand)
result.columns = ["id","Amount","Comments"]
print(result)

A: Start from reading the source file, using read_csv, but with
non-existing separator (I chose a vertical bar):
df = pd.read_csv('Input.csv', sep='|', names=['row'])

This way each row is read as a single field.
Then extract each actual field using regex:
df.row.str.extract(r'(?P<id>[^,]+),(?P<Amonut>\$[\d,]+\.\d{2}),(?P<Comments>.+)')

The key to success is proper formulation of the regex.
It contains 3 named capturing groups, for each field.
If something is unclear, search the Web for a regex tutorial.

A: Try this:
df = pd.read_csv("results.txt"', sep=",", header=None, names=["id", "Amount", "Comments"])

Further discussion here: Load data from txt with pandas

A: You could use something like .replace(",", "") to change the value before it is printed.
import pandas as pd

fhand = open("results.txt")
result = pd.read_csv(fhand)
result.columns["Amount"] = result.columns["Amount"].replace(",", "")
result.columns = ["id","Amount","Comments"]
print(result)


text:
Q: How to offset NSDate with UTC timezone offset without hardcoded manual calculation Imagine the current local time being 15:11 UTC. I retrieve a data set from the server showing the opening closing time of a business displayed like so:
{
close = {
   day = 3;
   time = 0200;
};
open = {
   day = 2;
   time = 1700;
};

I also receive a utc-offset property exposed like so: "utc_offset" = "-420"; which I imagine is a minute offset giving an hour offset of 7 hours which seems right considering the timezone I'm in is UTC and the business location's opening hours information I'm receiving is for a business in Los Angeles who are 7 hours behind.
How do I use this property to then be able to do any time calculations on it
I want to determine whether the current local time falls between the open and close time that bit I have figured out but the calculations come out wrong considering the time comparison is done in the local timezone when it needs to be offset before calculating against that time range.
I'm trying to avoid doing things like
Psuedocode:
NSDate.date hour componenent + (UTC_offset / 60 = -7 hours)
Update:
Here's how I'm currently checking if the business is open right now
        if currentArmyTime.compare(String(openInfo.time)) != .OrderedAscending && currentArmyTime.compare(String(closeInfo.time)) != .OrderedDescending {
            //The business is open right now, though this will not take into consideration the business's time zone offset.
        }

Is it easier to offset the current time?

A: Before you can use the 'open' and 'close' times in date operations you need to create an NSDate from a calendar that has been set to the time zone for those times.   Here's an example:
// Create calendar for the time zone
NSInteger timeOffsetInSeconds = -420 * 60;
NSTimeZone *tz = [NSTimeZone timeZoneForSecondsFromGMT:timeOffsetInSeconds];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
calendar.timeZone = tz;

// Create an NSDate from your source data
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = 1;
comps.month = 1;
comps.year = 2016;
comps.hour = 8;
comps.minute = 0;
NSDate *openTime = [calendar dateFromComponents:comps];

// 'openTime' can now be to compared with local time.
NSLog(@"openTime = %@", openTime);  // Result is openTime = 2016-01-01 15:00:00 +0000

You should put the above code into a method that takes in the raw time and the time offset to apply.


text:
Q: Puppeteer Jasmine Travis-CI with multiple spec files just run the first spec I having some troubles to make puppeteer with jasmine works in travis-ci like in my local repo. I'm writing a kind of component compiler similar to Svelte but with multiple differences. The point is that, in my pc i run all the test successfully but when i do a pull request and travis start to work, only the first spec test file works properlly. Here are the files that do the test job:
Update:
Here's the code:
.travis.yml
dist: trusty
sudo: required
language: node_js
node_js:
  - "node"
  - "9"
install:
  - npm i
script:
  - npm run build
  - npm run build:test:components
  - npm test
cache:
  directories:
    - "node_modules"

test/index.ts
import Jasmine from 'jasmine';
import JasmineConsoleReporter from 'jasmine-console-reporter';

// setup Jasmine
const jasmine = new Jasmine({});
jasmine.loadConfig({
  spec_dir: 'test/specs',
  spec_files: ['**/*[sS]pec.js'],
  random: false,
  seed: null,
  stopSpecOnExpectationFailure: false
});
jasmine.jasmine['DEFAULT_TIMEOUT_INTERVAL'] = 15000;

// setup console reporter
const reporter = new JasmineConsoleReporter({
  colors: 1,
  emoji: true,
  verbosity: 4,
  cleanStack: 1,
  timeUnit: 'ms',
  listStyle: 'indent',
  activity: 'bouncingBar',
  timeThreshold: { ok: 500, warn: 1000, ouch: 3000 },
});

// initialize and execute
jasmine.env.clearReporters();
jasmine.addReporter(reporter);
jasmine.execute();

test/utils.ts
import { resolve } from 'path';
import { readFileSync } from 'fs';
import puppeteer, { LaunchOptions, Browser, Page, JSHandle, ScriptTagOptions } from 'puppeteer';

const width = 1366;
const height = 768;

export async function getBrowser(options: LaunchOptions = {}) {
  const browser = await puppeteer.launch(Object.assign({
    headless: true,
    args: [`--window-size=${width},${height}`, '--no-sandbox']
  }, options));
  return browser;
}

export async function getPage(browser: Browser, ...files: string[]) {
  const page = await browser.newPage();
  await page.setContent('');
  await page.setViewport({ width, height });
  const scripts: ScriptTagOptions[] = files
    .map(file => ({ content: readFileSync(resolve(__dirname, `./components/${file}.js`), 'utf8') }));
  scripts.unshift({ content: scriptInit(files[0][0].toUpperCase() + files[0].slice(1)) });
  scripts.reverse().forEach(async script => {
    await page.addScriptTag(script);
  });
  return page;
}

export async function getComponent<T, K>(page: Page, component: string): Promise<[JSHandle<T>, JSHandle<K>]> {
  const windowHandle = await page.evaluateHandle(() => window);
  const instance: JSHandle<K> = await windowHandle.getProperty('instance');
  const Component: JSHandle<T> = await windowHandle.getProperty(component);
  windowHandle.dispose();
  return [Component, instance];
}

export async function exec<T extends any>(handle: JSHandle<T>, cb: (obj: T) => any) {
  return handle.evaluate(cb);
}

function scriptInit(component: string) {
  const i = 'instance';
  return `const main = document.createElement('main');
  document.body.append(main);
  const ${i} = new ${component}();
  ${i}.$mount('main');
  window.${i} = ${i};`;
}

This is an example spec that currentlly doesn't work because only the first spec file pass the test. All spec files are here
import { Page, Browser, JSHandle, ElementHandle } from 'puppeteer';
import { getBrowser, getPage, getComponent, exec } from '../utils';

describe('Component Conditions', () => {
  let page: Page;
  let browser: Browser;
  let instance: JSHandle<Component>;

  beforeAll(async () => {
    browser = await getBrowser();
    page = await getPage(browser, 'condition');
    [, instance] = await getComponent<typeof Component, Component>(page, 'Condition');
  });

  afterAll(async () => {
    await browser.close();
  });

  it('`$if` should be rendered', async () => {
    const span: ElementHandle<HTMLSpanElement> = await page.$('main span');
    expect(await exec(span, s => s.textContent)).toBe('1');
  });

  it('`$else-if` should be rendered', async () => {
    await exec(instance, i => i.$set('condition', 2));
    const span: ElementHandle<HTMLSpanElement> = await page.$('main span');
    expect(await exec(span, s => s.textContent)).toBe('2');
  });

  it('`$else` should be rendered', async () => {
    await exec(instance, i => i.$set('condition', 3));
    const span: ElementHandle<HTMLSpanElement> = await page.$('main span');
    expect(await exec(span, s => s.textContent)).toBe('other');
  });

  it('`$if` only should be rendered', async () => {
    const div: ElementHandle<HTMLDivElement> = await page.$('main div');
    expect(await exec(div, d => d.textContent)).toBe('1');
  });

  it('`$if` only should be hidden', async () => {
    await exec(instance, i => i.$set('condition_1', 2));
    let div: ElementHandle<null> = await page.$('main div');
    expect(div).toBeNull();
  });
});

to run the test:
node test/index.js

The repo is TreborJS and i'm working on the development brach
This is the output of travis: https://travis-ci.org/InDIOS/trebor/jobs/618791065?utm_medium=notification&utm_source=github_status
I hope you guys can help me soon and very thanks in advances
PS: Forgive my english, i'm not an english speaker


text:
Q: WSL2 dynamic File Paths based on the username for linux and windows I've created a bash script and would like to have a dynamic file path for windows and linux part of WSL2.
#!/bin/bash

# Create the workspace
mkdir /mnt/c/Users/FINIX/Documents/Workspace/test/

# Go to the workspace
cd /mnt/c/Users/FINIX/Documents/Workspace/test/

# Create the temp file to store the branches
touch /home/finix/test.txt

# Clone the repo
git clone https://github.com/test/test.git

# Going to the downloaded repo
cd /mnt/c/Users/FINIX/Documents/Workspace/test/TEST/

I'd like to dynamically change the username finix to whatever username of the machine would be from the linux side and windows side of WSL2.

A: There may be a better way, but here's what I came up with:
To retrieve the Windows user name from within bash:
winuser=$(powershell.exe -c "Write-Host -NoNewLine ([Environment]::UserName)")
You should then be able to use that to dynamically create the directory, like so:
mkdir /mnt/c/Users/${winuser}/Documents/Workspace/test/
The Linux user is much easier.  That one can, as @terdon was alluding to, be simply:
touch ${HOME}/test.txt
Or, alternatively, touch /home/${USER}/test.txt.
Of course, the Windows side assumes that the Windows home is always /mnt/C/Users/username
If it's somewhere else, then you'd need the PowerShell incantation to get the user's Windows home directory.  That would be:
winhome==$(powershell.exe -c 'Write-Host -NoNewLine  $env:userprofile' | xargs -0 wslpath) (Thanks @Panki for that answer).


text:
Q: Drupal 7: Unable to find the wrapper "public" Can anyone help me with this major issue I have. I have downloaded my Drupal 7 site running fine on current server, but I cant run it on localhost or on the new server where I am trying to move it...
It just gives me the "White Screen of Death"... and after commenting "set_error_handler" in boostrap.inc, I find out that the errors are all related to "public://" wrapper.
This is how all the errors look like:

Warning: is_dir() [function.is-dir]: Unable to find the wrapper "public" - did you forget to enable it when you configured PHP

All these errors are coming from the following file:

/includes/file.inc

A: I solved this problem by just flushing all the caches. Used drush for that - drush cc all

A: The wrappers are not loaded in the early stages of the drupal bootstrap, so you might want to double check if the wrappers are already instantiated at the time of calling them (which is not the case in hook_boot() or in the installation/update process).
The solution by Raheel Hasan (which he also posted on d.o) is realy bad, as it includes hacking core, removing core flexibility and adding a custom file to your root which makes your site suspectible to ddos attacks and of which the functionality is already found under the performance page on the admin panel.
At the moment I see no solution where you can use the stream wrappers before a full bootstrap is done.

A: I was getting this error not like OP, but when I was trying to use Drush to do a node-export-export for a large amount of content so I can migrate from a D6 to D7 site.  In the D6 site, in the Site Configuration > Node Export settings page at the bottom it was trying to do a local file export to public://, so I set that to "Remote File Export, URL" and that error went away, because I have FTP access and can manually download the files.

A: It took me many hours to find the solutions. I have posted it here:
drupal.org/node/158043#comment-6490390


text:
Q: How to trigger scanner hardware from web application hosted on server I have a Java web application hosted on Weblogic server. I am going to use a passport scanner(hardware) to scan a document so that when browser reach to the page, it able to display whatever text it scanned to prevent human error.
first of all, there is some dll, .jar that scanner is provided as well as C# sample code,VB.net sample code and Java sample code to interact with Scanner
What I understand is
I cannot use the jar to trigger the Scanner on Java because it is in Server side.
Solutions that i think of

*

*standalone application running on background on client machine to interact with Scanner which

*

*it will store the scanned text to a text file

*xhtml will get the text from the text file

*standalone application running on background on client machine to interact with Scanner which

*

*it will display the scanned text directly on text field on browser. It is something like getElementByID and set method.

*do it on Front end (xhtml) to call the jar on client machine.
What I have tried
I tried to call the jar from browser using JavaScript. Browser shows cross-origin security policy error and i have google it that browser will not allow to access client directory which will cause security breach.
My Question
I want to know is that my provided solution is workable? Is there others good solutions?
Thank you.


text:
Q: Example of a homeomorphic regular morphism of affine algebraic sets that's not an isomorphism of affine algebraic sets? As the title suggests, can anyone give me an example of a homeomorphic regular morphism of affine algebraic sets that is not an isomorphism of affine algebraic sets? Many thanks in advance.

A: We expand on Takumi Murayama's comment. The standard example is to take $$X = \mathbb{A}_k^1, \text{ }Y = V(x^3 - y^2) \subset \mathbb{A}_k^2,$$ and define$$F: X \to Y,\text{ }F(t) = (t^2, t^3).$$It is not hard to see this is a bijection. Because the Zariski closed subset of $X$, resp. $Y$, are $X$ itself, resp. $Y$ itself, together with all finite subsets, $F$ is a homeomorphism. But it is not an isomorphism, because the map of coordinate rings is not an isomorphism.
A more interesting example is the aforementioned Frobenius morphism (ubiquitous in positive characteristic algebra). Let $k$ be an algebraically closed field of positive characteristic $p$. Let $n \ge 1$ and define$$F: \mathbb{A}_k^n \to \mathbb{A}_k^n,\text{ }F(x_1, \dots, x_n) = (x_1^p, \dots, x_n^p).$$This is a bijection because every element of $k$ has a unique $p$th root. Moreover, for every polynomial $g \in k[x_1, \dots, x_n]$, $g^p = F^*(h)$ for some element $h \in k[x_1, \dots, x_n]$. Therefore,$$V(g) = V(g^p) = F^{-1}(V(h)) \implies F(V(g)) = V(h).$$So $F$ is a closed, continuous bijection, i.e., $F$ is a homeomorphism. However, $F$ is not an isomorphism since there is no $h \in k[x_1, \dots, x_n]$ such that $F^*h = x_1$.