Replace one button with another on click

Question: I am new to stackoverflow, and I am also an amateur javascript programmer. I am trying to make a program in which, when I click one button, a prompt appears, asking for my name. Alongside that, I also want that button to disappear, and be replaced with another button with the value: Hello 'name'. How do I do this? My code that I currently have in javascript asks me for my name, but does not make the button disappear. My current js is as follows:
var button = document.getElementById("button");
function naming() {
    var getName = prompt("What is your name?");
    button.style.display = "none";
};

And my html for the button:
<button id="button" onclick="naming();"> Name Here</button>

Answer: This would work, it does not remove the button but use it ones again for the name that the user inputs.
HTML
<button id="button">Name here</button>
JS
var button = document.getElementById('button');
button.addEventListener('click', function() {
    var name = prompt("What is your name?");
    this.innerHTML = name
}, false);

http://jsfiddle.net/rYU7Q/
Comment: It works in the jsfiddle, but can't work in my html file, I am pretty sure that the syntax is right. What do you suggest?
Comment: I will mark this answer as correct, because the code works perfectly in jsfiddle, but the problem lies somewhere in my actual computer. When I put the same js and html code in jsfiddle, it worked.
Comment: I'm guessing it because the javascript runs before the DOM has loaded. Check this answer for the solution, so that the code is executed after the DOM has loaded :)

http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the
Comment: I will try executing the code after loading the DOM, but in the js that you gave me, in the .addEventListener thing, there is a function named function(). I already have one with that name. So, if i change its name to like, naming(), will it work?
Answer: another method
<button class="btn btn-primary" id = "del-btn">Old btn</button>


How do I use CSSTransitionGroup on children columns immediately under a row?

Question: I'm using Bootstrap's grid system in my ReactJS project. Under a row, I have multiple columns (col-md-4) which I want to animate as they are added to or removed from the row as the component state changes. But Using CSSTransitionGroup immediately under a row to let the columns render as children leaves a span under the row and above the columns ruining the columns' left float.

    <ReactCSSTransitionGroup
        transitionName={`fadeIn`}
        transitionEnterTimeout={200}
        transitionLeaveTimeout={200}>

           {list.map(user => { return (

            )})}
     </ReactCSSTransitionGroup>

YIELDS:

                ...

What is the correct approach to this?
Comment: I'm facing Same problem :(
Answer: Solved : just add className="row" in CSSTransitionGroup element
Sample code Here:
<CSSTransitionGroup
    transitionName="item"
    transitionEnterTimeout={500}
    transitionLeaveTimeout={300}
    className="row">

      {myIndustries}

</CSSTransitionGroup>


Core Data, No Inverse Relationship

Question: I'm working to get rid of a bunch of warnings in our codebase of the form:
Entity.relationship should have an inverse.

In general, although our code does not reach through these inverses, it sounds like it is a good idea to put them in anyway.
My question is about how I would do this.

Should I make these changes through a lightweight migration?  That is, should I be creating another xcdatamodel?
For the given data model, what if we already have multiple versions/migrations.  For example supposed we have the ReportsDataModel.  And underneath that are ReportsDataModel1, ReportsDataModel2, and ReportsDataModel3.  It seems like XCode 7 is giving me the same warnings on each data model.  So if I fixed them in a lightweight migration to ReportsDataModel4, it seems like it wouldn't get rid of the previous warnings.

What is the recommended way to get around this issue?
-Arjun
Answer: First of all, you would be correct that you should implement the inverse relationships, as Xcode requires them. It's a good database practice, and you can virtually ignore the excess relationships if you're not using them.
Yes, you should be able to perform a lightweight migration, that is, create a new data model and let Xcode infer the changes. Here, Apple states that lightweight migration supports adding relationships.
Regarding your second question, true, creating another data model will not actually solve the warning in the older ones. You must leave the older models in Xcode so it can compute the lightweight migration process. If you erase a model and a user updates from an older version that uses that model, their data will be corrupted. (However, if you haven't published a version of the app with a particular data model, you can delete that data model.)
However, you can try suppressing the inverse relationship warning entirely.

In Xcode, click on your project file.
Click the Build Settings tab.
Search for MOMC.
Set Suppress momc warnings on missing inverse relationships to Yes.

EDIT about getting rid of the warnings on only the old models: This question suggests that you could move the old data model out of Xcode and place it elsewhere, and add a Copy Files action to Build Phases to copy the file back in at compile time. This way the file and it's extraneous warnings could be out of your way. Sorry there isn't a less "hacky" solution.
Comment: It would be nice to suppress that warning on individual versions, but I don't think it's possible.
Comment: @TomHarrington - Yeah thats exactly what I was hoping for :(
Comment: @TomHarrington I edited my answer with a possible solution to get around this unfortunate limitation of Xcode.

Core Data, No Inverse Relationship


access data from document referenced inside firestore collection

Question: I have a collection inside firestore database that consists of several data fields and references. Structure looks like this:
firstCollection document sample
{
  name: 'parent',
  //more fields,
  second: //reference to document from second collection
}

secondCollection referenced document sample
{
   title: 'document title',
   more: 3456,
   etc: '...'
}

I have angular application with angularfire2 library included. In one of my html files I need to print data from the first collection including some field values from document of the second collection. Document from the second collection has valid reference from the first collection (see above). This is what I want to do:

  this works - {{first.name}}

  Now the question is, How can I access document data from the second collection here?
  What I need is something like the following:

  {{first.second.title}} - this doen't work because 'second' is just reference

Answer: Reading data from Cloud Firestore is shallow.  This means when you read the first document, you have not yet loaded any of the data in the second document (to which you have a reference).
You'll have to perform another get() or listen operation on that reference in order to get the data.
https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md
Comment: Thank you very much for your response. I was hoping that there is something builtin that can help manipulating with the referenced docs when required. I think that I will denormalize collection and copy fields that I need from referenced document instead of doing `get` operation for every "firstCollection" document.


How does JUnit mask checked exceptions?

Question: JUnit 5 masks checked exceptions with this code:
public static RuntimeException throwAsUncheckedException(Throwable t) {
    Preconditions.notNull(t, "Throwable must not be null");
    ExceptionUtils.throwAs(t);

    // Appeasing the compiler: the following line will never be executed.
    return null;
}

@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwAs(Throwable t) throws T {
    throw (T) t;
}

In the call to throwAs, how does Java decide on the value of the type variable T?
More importantly, how does this code mask a checked exception?
Comment: In which class did you find this source code? Why is the return type `RuntimeException`. Setting the return type to `void` will not need to 'appease the compiler'. I wonder why there is no need to `try-catch` around the call of `throwAs`
Comment: The code is from org.junit.platform.commons.util.ExceptionUtils. According to the source code, "the return type is merely present to allow this method [throwAsUncheckedException] to be supplied as the operand in a throw statement."
Answer: I believe that T is inferred to be RuntimeException. I'm inferring that from making the following change to the code of throwAsUncheckedException:
var o = ExceptionUtils.throwAs(t);

... and changing the declaration of throwAs to:
private static <T extends Throwable> T throwAs(Throwable t) throws T

(Note that I'm using var from Java 10 to let the compiler infer the type without any further information being provided.)
After compiling and then using javap -c you can see that there's a checkcast to RuntimeException:
invokestatic  #2  // Method throwAs:(Ljava/lang/Throwable;)Ljava/lang/Throwable;
checkcast     #3  // class java/lang/RuntimeException
astore_1

That makes it fine for throwAs not to declare that it throws anything else - it's only calling a method that declares that it throws T, so RuntimeException in this case.
Further somewhat specious evidence for this is in JLS section 18, which includes this line:

Otherwise, if the bound set contains throws αi, and each proper upper bound of αi is a supertype of RuntimeException, then Ti = RuntimeException.

No other concrete exception types, or Throwable, are mentioned in that section. Unfortunately I find section 18 pretty much impenetrable, so this is really more of a "yes, that vaguely supports my theory" rather than good evidence.
In this particular case, I believe it would actually be fine (and simpler in terms of understanding) for the throwAsUncheckedException method to just specify the type argument explicitly:
ExceptionUtils.<RuntimeException>throwAs(t);

So that's how the compiler is molified. It thinks that only RuntimeException will be thrown. The actual value thrown is whatever's passed in though. The cast to T is ignored for all the normal type erasure reasons... if you change the code to actually cast to RuntimeException, it will fail for any checked exception. That's why it needs to be a generic method: to include a cast that satisfies the compiler without really casting at execution time.
The JVM allows this because as far as I'm aware, checked exceptions are purely a compiler aspect, and there's no validation for them in the JVM itself. It just knows about throwing exceptions.

How does JUnit mask checked exceptions?


How the pre and post increment work in c++?

Question: i want to know if increment/decrement operator results vary from compiler to compiler or it is independent of the compiler. as I am getting different results in different compilers of c/c++ (tested in G++, TDM, gcc) for the same expression.
Comment: The compiler doesn't execute it. The machine code it generates will vary depending on the processor that it's compiling for.
Comment: The "exact way" is clearly going to depend on the compiler and the language. (And, to nitpick: the compiler doesn't "execute" any of the code it finds; it simply compiles it to an intermediate form for the linker to use later.)
Comment: If you want to know the **exact way**, the only correct answer is to look at the source code for the compiler you care about.
Comment: this is a useful tool for exploring what the compiler does to your code. http://gcc.godbolt.org/ just enter your code and it will show you the assembly code that gcc will generate. Remember to turn off optimizations if you want it to be an exact translation.
Comment: These operators can be overloaded in C++, I assume you are asking for built-in types (`int`, `float` ...) ? Your question should be more precise.
Answer: Let's look at the internal llvm assembly. Which isn't hard to do.
C++ code:
<code>void preincrement() __attribute__((noinline));
void preincrement() {
    volatile int x = 10;
    volatile int y = ++x;
}

void postincrement() __attribute__((noinline));
void postincrement() {
    volatile int x = 10;
    volatile int y = x++;
}

int main()
{
    preincrement();
    postincrement();
}
</code>
Resultant LLVM Assembly (minus some leading and trailing text that isn't interesting):
<code>; Function Attrs: noinline nounwind uwtable
define void @_Z12preincrementv() #0 {
  %x = alloca i32, align 4
  %y = alloca i32, align 4
  store volatile i32 10, i32* %x, align 4
  %1 = load volatile i32* %x, align 4
  %2 = add nsw i32 %1, 1
  store volatile i32 %2, i32* %x, align 4
  store volatile i32 %2, i32* %y, align 4
  ret void
}

; Function Attrs: noinline nounwind uwtable
define void @_Z13postincrementv() #0 {
  %x = alloca i32, align 4
  %y = alloca i32, align 4
  store volatile i32 10, i32* %x, align 4
  %1 = load volatile i32* %x, align 4
  %2 = add nsw i32 %1, 1
  store volatile i32 %2, i32* %x, align 4
  store volatile i32 %1, i32* %y, align 4
  ret void
}

; Function Attrs: nounwind uwtable
define i32 @main() #1 {
  tail call void @_Z12preincrementv()
  tail call void @_Z13postincrementv()
  ret i32 0
}
</code>
We can see here pretty clearly the only difference: In the post increment version, we use the original value, instead of the upgraded value.
In both cases, we just use a traditional add opcode to do the real work.


Solution for route or path marking with bends

Question: I want to give my users an easy way to visually trace a route on a map or a picture. The solution must let the users add control points that they can use to put bends into the route.
It should work with html5 canvas - I currently use the Konvajs library so a solution that uses this would be good.
In the interests of sharing & learning, if you can suggest solutions using other HTML5 canvas libraries that would be good to see too.
Note: This is not the original question posed. However it emerged over time that this was the actual requirement. The OP asked for means to find an arbitrary  point part way along a line / curve in an HTML5 canvas so that a draggable control point could be added at that point to edit the line / curve. The accepted answer does not meet this need. However, an answer to this original question would involve serious collision-detection math and potentially use of bezier control points - in other words it would be a big ask whilst the accepted answer is a very approachable solution with consistent UX.
The original question can be seen in via the edit links below this question.
Comment: What is the intended UX for the knot - is it to become a handle for 'bending' the stick of the arrow?
Comment: Yea. It is to be able to manipulate the arrow so that it can go wherever the user takes it on a map for example by adding multiple knots.
Comment: ok - so like they were showing a route on a map - start from here, turn left here...turn right there...etc?  Where I see this done in other apps the user clicks a point to drop a map-pin (the finish point) and the line extends as a straight line to that point. There is then a small 'knot' half way between the last point and the pin, and the user can drag the knot to make a curve.  The effect is to let the user bend the route line around curves in the route and sharp bends. Is that it?
Comment: If you have a question about adding code, please also show the code you already have (in [mcve] form).
Comment: Ah, that could work. Right now I click and drag to create a two point arrow. The step I was originally thinking to edit it was to double click to go into edit mode to add more knots. But as per suggestion, maybe just click on the canvas to create the points as you go to create the final arrow, then you would have editable points to play around in the end. No adding new points is possible, but you probably have enough points to play with anyway to do minor edits.
Answer: How about this idea. You click where you want the next point and the route line extends with new positioning handles along the line segments. If you need arrows you can extend the objects herein as you require. You can easily change colours, stroke width, circle opacity etc with attributes of the route class. The points are available in an array and in the standard Konva.js line points list. The JS is vanilla, no other libraries needed or used.
The Export button shows how to grab the (x,y) fixed point objects for export purposes.
Example video here, working code in below snippet.

// Set up the canvas / stage
var s1 = new Konva.Stage({container: 'container1', width: 600, height: 300});

// Add a layer for line
var lineLayer = new Konva.Layer({draggable: false});
s1.add(lineLayer);

// Add a layer for drag points
var pointLayer = new Konva.Layer({draggable: false});
s1.add(pointLayer);

// Add a rectangle to layer to catch events. Make it semi-transparent
var r = new Konva.Rect({x:0, y: 0,  width: 600, height: 300, fill: 'black', opacity: 0.1})
pointLayer.add(r)

// Everything is ready so draw the canvas objects set up so far.
s1.draw()

// generic canvas end

// Class for the draggable point
// Params: route = the parent object, opts = position info, doPush = should we just make it or make it AND store it
var DragPoint = function(route, opts, doPush){
  var route = route;

  this.x = opts.x;
  this.y = opts.y;
  this.fixed = opts.fixed;
  this.id = randId();  // random id.

  if (doPush){  // in some cases we want to create the pt then insert it in the run of the array and not always at the end
    route.pts.push(this);
  }

  // random id generator
  function randId() {
     return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
  }

  // mark the pt as fixed - important state, shown by filled point
  this.makeFixed = function(){
    this.fixed = true;
    s1.find('#' + this.id)
        .fill(route.fillColor);
  }

  this.kill = function(){
    s1.find('#' + this.id)
        .remove();
  }

  this.draw = function(){
    // Add point & pt
    var circleId = this.id;

    var pt = new Konva.Circle({
      id: circleId,
      x: this.x,
      y: this.y,
      radius: route.pointRadius,
      opacity: route.pointOpacity,
      strokeWidth: 2,
      stroke: route.strokeColor,
      fill: 'transparent',
      draggable: 'true'
    })
    pt.on('dragstart', function(){
        route.drawState = 'dragging';
    })
    pt.on('dragmove', function(){
      var pos = this.getPosition();
      route.updatePt(this.id(), pos)
      route.calc(this.id());
      route.draw();
    })
    pt.on('dragend', function(){

      route.drawState = 'drawing';
      var pos = this.getPosition();

      route.updatePt(this.getId(), pos);

      route.splitPts(this.getId());

      route.draw();
    })

    if (this.fixed){
      this.makeFixed();
    }

    route.ptLayer.add(pt);
    route.draw();

  }

}

var Route = function() {

    this.lineLayer = null;
    this.ptLayer = null;
    this.drawState = '';

    this.fillColor = 'Gold';
    this.strokeColor = 'Gold';
    this.pointOpacity = 0.5;
    this.pointRadius = 10;
    this.color = 'LimeGreen';
    this.width = 5;

    this.pts = []; // array of dragging points.

    this.startPt = null;
    this.endPt = null;

    // reset the points
    this.reset = function(){
      for (var i = 0; i < this.pts.length; i = i + 1){
        this.pts[i].kill();
      }
      this.pts.length = 0;
      this.draw();
    }

    // Add a point to the route.
    this.addPt = function(pos, isFixed){

      if (this.drawState === 'dragging'){  // do not add a new point because we were just dragging another
        return null;
      }

      this.startPt = this.startPt || pos;
      this.endPt = pos;

      // create this new pt
      var pt = new DragPoint(this, {x: this.endPt.x, y: this.endPt.y, fixed: isFixed}, true, "A");
      pt.draw();
      pt.makeFixed(); // always fixed for manual points

      // if first point ignore the splitter process
      if (this.pts.length > 0){
        this.splitPts(pt.id, true);
      }

      this.startPt = this.endPt; // remember the last point

      this.calc(); // calculate the line points from the array
      this.draw();  // draw the line
    }

  // Position the points.
  this.calc = function (draggingId){
    draggingId = (typeof draggingId === 'undefined' ? '---' : draggingId); // when dragging an unfilled point we have to override its automatic positioning.

    for (var i = 1; i < this.pts.length - 1; i = i + 1){

      var d2 = this.pts[i];
      if (!d2.fixed && d2.id !== draggingId){      // points that have been split are fixed, points that have not been split are repositioned mid way along their line segment.

        var d1 = this.pts[i - 1];
        var d3 = this.pts[i + 1];
        var pos = this.getHalfwayPt(d1, d3);

        d2.x = pos.x;
        d2.y = pos.y;
      }
      s1.find('#' + d2.id).position({x: d2.x, y: d2.y}); // tell the shape where to go
    }
  }

  // draw the line
  this.draw = function (){

    if (this.drawingLine){
      this.drawingLine.remove();
    }
    this.drawingLine = this.newLine(); // initial line point

    for (var i = 0; i < this.pts.length; i = i + 1){
      this.drawingLine.points(this.drawingLine.points().concat([this.pts[i].x, this.pts[i].y]))
    }

    this.ptLayer.draw();
    this.lineLayer.draw();
  }

  // When dragging we need to update the position of the point
  this.updatePt = function(id, pos){

      for (var i = 0; i < this.pts.length; i = i + 1){
        if (this.pts[i].id === id){

          this.pts[i].x = pos.x;
          this.pts[i].y = pos.y;

          break;
        }
      }
  }

  // Function to add and return a line object. We will extend this line to give the appearance of drawing.
  this.newLine = function(){
    var line = new Konva.Line({
        stroke: this.color,
        strokeWidth: this.width,
        lineCap: 'round',
        lineJoin: 'round',
        tension : .1
      });

    this.lineLayer.add(line)
    return line;
  }

  // make pts either side of the split
  this.splitPts = function(id, force){
    var idx = -1;

    // find the pt in the array
    for (var i = 0; i < this.pts.length; i = i + 1){
      if (this.pts[i].id === id){
        idx = i;

        if (this.pts[i].fixed && !force){
          return null; // we only split once.
        }

        //break;
      }
    }

    // If idx is -1 we did not find the pt id !
    if ( idx === -1){
      return null
    }
    else if (idx === 0  ) {
      return null
    }
    else { // pt not = 0 or max

      // We are now going to insert a new pt either side of the one we just dragged
      var d1 = this.pts[idx - 1]; // previous pt to the dragged pt
      var d2 = this.pts[idx    ]; // the pt pt
      var d3 = this.pts[idx + 1]; // the next pt after the dragged pt

      d2.makeFixed()// flag this pt as no longer splittable

      // get point midway from prev pt and dragged pt
      var pos = this.getHalfwayPt(d1, d2);
      var pt = new DragPoint(this, {x: pos.x, y: pos.y, foxed: false}, false, "C");
      pt.draw();
      this.pts.splice(idx, 0, pt);

      if (d3){
        // get point midway from dragged pt to next
        pos = this.getHalfwayPt(d2, d3);
        var pt = new DragPoint(this, {x: pos.x, y: pos.y, foxed: false}, false, "D");
        pt.draw();
        this.pts.splice(idx + 2, 0, pt); // note idx + 2 !

      }

    }

  }

  // convert last point array entry to handy x,y object.
  this.getPoint = function(pts){
    return {x: pts[pts.length - 2], y: pts[pts.length - 1]};
  }

  this.getHalfwayPt = function(d1, d2){
    var pos = {
          x: d1.x + (d2.x - d1.x)/2,
          y: d1.y + (d2.y - d1.y)/2
      }
    return pos;
  }

  this.exportPoints = function(){
    var list = [], pt;
    console.log('pts=' + this.pts.length)
    for (var i = 0; i < this.pts.length; i = i + 1){
      pt = this.pts[i]
      if (pt.fixed){
        console.log('push ' + i)
        list.push({x: pt.x, y: pt.y});
      }
    }
    return list;
  }

}

var route = new Route();
route.lineLayer = lineLayer;
route.ptLayer = pointLayer;

route.fillColor = 'AliceBlue';
route.strokeColor = 'Red';
route.pointOpacity = 0.5;
route.pointRadius = 7;
route.color = '#2982E8'

// Listen for mouse up on the stage to know when to draw points
s1.on('mouseup touchend', function () {

  route.addPt(s1.getPointerPosition(), true);

});

// jquery is used here simply as a quick means to make the buttons work.

// Controls for points export
$('#export').on('click', function(){

  if ($(this).html() === "Hide"){
    $(this).html('Export');
    $('#points').hide();
  }
  else {
    $(this).html('Hide');
    $('#points')
      .css('display', 'block')
      .val(JSON.stringify(route.exportPoints()));
  }

})

// reset button
$('#reset').on('click', function(){
  route.reset();
  })
p
{
  padding: 4px;
}
#container1
{
background-image: url('https://i.stack.imgur.com/gADDJ.png');
}
#ctrl
{
position: absolute;
z-index: 10;
margin: 0px;
border: 1px solid red;
}
#points
{
width: 500px;
height: 100px;
display: none;
}

Click to add a point, click to add another, drag a point to make a bend, etc.

<button id='reset'>Reset</button>
<button id='export'>Export</button>
<textarea id='points'></textarea>

Comment: This is fantastic! Exactly what I described:) thank you!! I will probably play with the code a little bit and see how I get on and learn from this as well. Thanks again!
Comment: @Huy - Thanks glad to help. Couple of points - first please could you mark my answer as correct so as to help future folks searching for help to judge the quality, and second would you mind if I edited your question to make it a bit more representative of the generic requirement for 'marking a route or path on a canvas'. Again this is for future folk looking for something similar who may not recognise your question as being the same subject.
Comment: I marked it as correct and no problem with you modifying the original post. Thanks a bunch!


Compute SHA1 of Strings in python

Question: I have a file which contains a lot of Strings. I am trying to compute SHA1 hashes of these strings individually and store those
import hashlib
inp = open("inp.txt" , "r")
outputhash  = open("outputhashes.txt", "w")
for eachpwd in inp:
    sha_1 = hashlib.sha1()
    sha_1.update(eachpwd)
    outputhash.write(sha_1.hexdigest())
    outputhash.write("\n")

The issue I am facing is once a strings SHA1 is computed the next string is being appended(I feel this is why I am not getting the correct hashes) and its hash is being computed. Hence I am not getting the correct hashes. I am new to python. I know what to do but don't know how to do it. Can you point me in the right direction to go about this?
Answer: You're iterating over a file, which is going to return the lines, including the line terminator (a \n character at the end of the string)
You should remove it:
import hashlib
inp = open("inp.txt" , "r")
outputhash  = open("outputhashes.txt", "w")
for line in inp:            # Change this
    eachpwd = line.strip()  # Change this

    # Add this to understand the problem:
    print repr(line)

    sha_1 = hashlib.sha1()
    sha_1.update(eachpwd)
    outputhash.write(sha_1.hexdigest())
    outputhash.write("\n")

Compute SHA1 of Strings in python


Need help with 3-way wiring (diagram included)

Question: Could really use some help. I'm putting in some GE Z-Wave plus switches in my new house and have come across my first 3-way switch.

I think the far left Romex in box #1 is the cable that goes between both boxes. The Internet seems to suggest that the black wire there is no longer needed and can be capped at both ends. That leaves me with the traveler and the neutral wires at box #2, which is exactly what the GE add-on switch takes.
At box #1, far left Romex, I capped the black, put the red on the traveler of the new switch, and put a jumper from the neutral of the switch to the bundle of neutrals.
This leaves me with only the red wire going up into the center Romex. Since the top black wire from the fan switch also goes into the center, I want to say the red is the load for the light, but originally it was connected to the common terminal of the old switch. I'm not sure how this switch gets power.
I'm very confused and not an electrician. Please help me.
Comment: What model is the z-wave switch you're putting in?
Comment: @ThreePhaseEel GE 14294 (dimmer) and GE 12723 (add-on)
Answer: What you have here is a line-side traveller loop.  The white wire in the leftmost 14/3 cable takes power out to the switch in Box #2, while the red and black wires in that cable are the travellers going back to the switch in Box #1, which then feeds the load.
The fortunate thing about this configuration is that it's relatively easy to hook your smart switches up to it.  You'll just need a couple of pigtails for the line and neutral on your new dimmer, and a couple of wirenuts to cap off the unused black wire in the cable between the two switch boxes.

Make sure the power's off at the breaker.
Remove the old switches.

In the first box:

Remove the white wire that's bundled in with the black wires from that junction and join it and the white pigtail to the existing bundle of white wires.  (These are your neutrals.)  Remove any tape or paint flags or markings on the white wire in the leftmost cable.  It will become a neutral once again, as it was a hot previously.
Nut the black pigtail into the existing bundle of black wires.  (This is your hot feed coming into the box.)
Connect the existing ground pigtail that grounded the old switch to the ground terminal on the smart switch if the old switch was grounded.  If it was not grounded, post a comment here and I'll update the instructions.
Connect the black pigtail to the line terminal on the smart switch.
Connect the white pigtail to the neutral terminal on the smart switch.
Connect the red wire from the leftmost cable to the traveller terminal on the smart switch.
Cap off the black wire from the leftmost cable with a wirenut.
Connect the red wire from the center cable to the load terminal on the smart switch.

In the second box:

Remove any tape flags or paint markings present from the white wire.
Cap off the black wire with a wirenut.
Connect the ground wire (if present) to the remote's ground terminal.  If no ground wire is present, post a comment here.
Connect the red wire to the remote's traveller terminal.
Connect the white wire to the remote's neutral terminal.
Put everything back together in both boxes.
Turn the power back on and configure the smart dimmer.


To Substitute or Not ... $2\sin 2x = 3\tan x$, in interval $0\le x<360^\circ$

Question: The Question
Solve $2\sin 2x = 3\tan x$, in interval $0\le x<360^\circ$
I thought this straightforward enough, used the identity $\sin^2 x + \cos^2 x \equiv 1$, shown below in the working, which clearly is not right. My question is what have I done wrong here - why is the substitution of $(1-\sin^2x)$ for $\cos^2x$ wrong?
My Solution
$$\Rightarrow 4\sin x \cos x = \frac{3\sin x}{\cos x}$$
$$\Rightarrow 4\sin x \cos^2 x = 3\sin x$$
$$\Rightarrow 4\sin x(1 - \sin^2 x) - 3\sin x = 0$$
$$\Rightarrow \sin x - 4\sin^3x = 0$$
$$\Rightarrow \sin x(1 - 4\sin^2 x) = 0$$
$$\Rightarrow \sin x = 0, \sin^2 x = \frac{1}{4}$$
The alarm bells started ringing at this point as $2\sin 90^\circ \neq 3\tan 45^\circ$
Correct Approach
So, looking at it, using the identity $\sin^2 x + \cos^2 x \equiv 1$ was the error.
So:
$$\Rightarrow 4\sin x \cos x = \frac{3\sin x}{\cos x}$$
$$\Rightarrow 4\sin x \cos^2 x = 3\sin x$$
$$\Rightarrow \sin x (4\cos^2 x - 3) = 0$$
$$\Rightarrow \sin x = 0, \cos^2 x = \frac{3}{4}$$
I'd be very grateful if anyone could explain why making the substitution I made was wrong. I thought they could be used as-and-when. Have I misunderstood something significant?
Or is is that the substitution can't be used because it gives the wrong answer? But this begs the question of how can you know when it's OK to use it.
Thanks in advance for your insights.
Comment: As pointed out below, I made a foolish mistake: I wrote down $\sin x = \pm\frac {1}{\sqrt2}$ instead of $\sin x = \pm\frac {1}{2}$
Answer: Your original solution is correct as well. It's just that $x=45^\circ$ doesn't satisfy $\sin^2 x = \frac14$. If $\sin^2 x = \frac14$, then $\sin x = \pm\frac12$, while $\sin 45^\circ = \frac{1}{\sqrt{2}}$. The solutions for $\sin^2 x = \frac14$ with $0\leq x<360^\circ$ are $30^\circ, 150^\circ, 210^\circ$ and $330^\circ$.
Comment: Well, wow. What a mistake to make, thanks for pointing that out. You are right, I wrote down $\sin x = \pm\frac {1}{\sqrt2}$
Comment: @Bangkockney Don't worry, it happens :)


disable rsh on ubuntu server

Question: I installed rsh-server in my system for test purposes, but now I want to disable it without removing its package. I don't know how I can check rsh status. I can not see it with:

sudo service rshd status

Noted that, I don't install rsh under xinetd.
Answer: I don't have an Ubuntu system on my hands, but I believe its started by xinetd:
Edit /etc/xinetd.d/rsh and set disable=yes.
You need to restart the xinetd service once you're done.
Comment: I don;t install xinetd at all, but install rsh-server in my system. Then installed rsh-client to test rsh-server. When I run rshd localhost, I can login to my system. There is same situation for telnetd. But it is exist in /etc/inietd.conf. please see http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch16_:_Telnet,_TFTP,_and_xinetd#.VGdYM_mUdPQ
Comment: Package `rsh-server` has a dependency on `openbsd-inetd` but I can't verify this at the moment.

disable rsh on ubuntu server


Plot the x-axis and y-axis in Matlab

Question: I am asked to plot the graph of a function in Matlab and I would like to add the x-axis and y-axis in the graph. But how can I achieve this?
Comment: Although this is not the right place for such questions (stackoverflow probably is), what you want is probably the functions `xlabel` and `ylabel`.
Comment: What do you mean "plot the x-axis and y-axis" do you want to plot labels, or data on the x and y axes? This question belongs on stackoverflow.com by the way.
Answer: In Octave you can do:
<code>x = [1:100]/10;
plot(x,sin(x),';legend;')
xlabel('xlabel')
ylabel('ylabel')
</code>
Comment: Matlab uses single quotes, not double
Comment: @LuisMendo: Thanks! I forgot to mention I was using Octave.

Plot the x-axis and y-axis in Matlab


How to generate a thumbnail of flash movie (.flv)

Question: I'm using ColdFusion and need to generate a thumbnail from a flash movie stored on the server. I have heard of ffMpeg but have no idea how to use it. (Once you put it on your server what's the next step?)
Answer: Documentation of FFMpeg: http://www.ffmpeg.org/documentation.html
You might want to check: http://blog.prashanthellina.com/2008/03/29/creating-video-thumbnails-using-ffmpeg/
http://www.flashcomguru.com/index.cfm/2006/4/25/ffmpegthumbs
with ColdFusion its not possible but check this: http://old.nabble.com/Create-a-thumbnail-image-from-.flv-video-file-once-uploaded-td22683497.html
Comment: although it's true to say that there is no native method to do this in ColdFusion it's not entirely accurate to say it is not possible.
Comment: I am not aware of ColdFusion but I have tried FFMPEG in the past.
Answer: You can use cfexecute to run a command line on the CF server.
Karthik linked a blog post that suggests the following syntax for ffmpeg:

ffmpeg  -itsoffset -4  -i test.avi
  -vcodec mjpeg -vframes 1 -an -f rawvideo -s 320x240 test.jpg

So you could do something like this:
<cfexecute
    name="c:\pathto\ffmpeg\ffmpeg.exe"
    arguments="-itsoffset -4  -i #sourcevideo# -vcodec mjpeg -vframes 1 -an -f rawvideo -s 320x240 #thumbnaildestination" />

I haven't run ffmpeg like this and you'll likely need to experiment with the syntax to get a result you like, but once you do your workflow is pretty straightforward.
You may also run into issues executing fmpeg.exe depending on the user account your ColdFusion server instance is running as.
Comment: thanks, I was wondering how you use the ffmpeg command but I see that it goes in a cfexecute tag.
Comment: I did a search through the folder and also manually looked through all of the folders and there is no ffmpeg.exe or any file that has an extension of .exe. Which file do I need to point to?
Comment: @nick is your CF server on windows or some other OS?
Comment: windows, I figured it out though, I found a copy that was already compiled.


R function to create data.frame based on variable in a column

Question: I'm new to R and having some trouble. If I have a df call 'xyz' as below.

C1
C2
C3

x
1
Three

x
2
Three

y
1
Three

y
0
Three

z
2
Three

z
1
Three

from the df above, I want to crate separate data frames named with variables in c1 such as:
data frame name 'x'

C1
C2
C3

x
1
Three

x
2
Three

data frame name 'y'

C1
C2
C3

y
1
Three

y
0
Three

data frame name 'z'

C1
C2
C3

z
2
Three

z
1
Three

sorry if it is already answered but I couldn't find any good solution for now.
Comment: Try `split(df,df$C1)`
Comment: Thank you so much it is working but how do we save those separate files?
Answer: Try list2env(split(df,df$C1),envir=.GlobalEnv).
This will split df by C1 and save each dataframe into a variable with the name of the C1 value.
Comment: Excellent! Just what I want to do. Thank you!
Answer: Since you are new to R its ideal to stick to base R.
But keeping a dplyr option for future use as well.
df %>%
  group_by(`C1`) %>%
  group_walk( ~ write_csv(
    .x,
    paste0(
      "path_to_your_folder",
      "file_prefix_if_required_",
      .y$C1,
      ".csv"
    ) #paste0 function willbuild a custom filename as per your needs
  ), .keep = TRUE) #.keep=T will keep the grouped column in the file.

Pls check help on dplyr::group_walk and it has an example as well.


Does the weather affect Shadows in Palaces?

Question: The game makes it quite clear that adverse weather affects the Shadows in Mementos, whether it makes them more likely to call for backup, have Treasure Demons appear, or enter the battle despaired. However, the fact that it specifies the Shadows in Mementos led me to believe that it only affects those Shadows.
While rushing through the third Palace on a rainy day (no one was available to hang out, so it seemed like the best time to go), I encountered 3-4 Queen's Necklaces, which is roughly 3-4 more Treasure Demons than I usually encounter when exploring a Palace. I know that Rainy days increase the chance of rare Shadows appearing, but I thought that was only for Mementos. Does the weather affect Shadows in Palaces, as well?
Comment: In Persona 4 Golden rainy days caused new "rare" shadows to appear (like Rainy Brother/Sister) in all the worlds but since there is no battles in the "hub" world (since the TV Studio is like Tartarus Ground floor and  Abyss of Time in Persona 3) i'm not sure if the floors/sections/worlds in Persona 3 and 4 = Persona 5's Palaces
Comment: @Memor-X the tutorial specifically says it affects Shadows in Mementos, so it seems like it would only be for Shadows there. I either had extremely good luck or the weather affects Palaces, too.
Answer: Rain /Storms
No effect in Palace
Heat Wave
Enemies may start battle with Burn status ailment. Use Garu or Frei magic to inflict Technical damage.
Flu Season
Enemies may suffer from the Despair status ailment (death after three turns) from the start of battle. Use Psi magic to inflict Technical damage.
There is a spoiler available for the end part of the game dealing with Flu Season - be careful when researching about the end of that.
Pollen Warning
Enemies in Momentos / Palaces are more likely to be asleep, making sneak attacks (and combat in general) easier. Any kind of attack will result in Technical damage for a sleeping enemy.
Enemies will ask for Eye Drops during Negotiation.


Python: Reset a timer after completing what was desired

Question: I am looking for knowledge.
I am currently working on a program which, if no one is detected by my sensor for 30 seconds, launches a video. I am currently using time.time() but the concern is that despite trying to reset, the timer continues and does not reset to 0 once the video is finished.
So I tried some new research and I came across a topic about time.clock() and I ended up with this: Python's time.clock() vs time.time()
But I'm not sure I fully understand the role of timeit, time.process_time() or time.perf_counter(), is there a possibility to use these in the way I want? Or is it only used to calculate the execution time of a code as found in several examples?
Precision:
When I reach 30 seconds, I enter the if to launch the video, the launch video, followed by a time.sleep(). The timer does not pause and continues while the video is running. Once the video is finished I try to reset the timer, also once the 50 seconds are reached but I can't do it, I probably don't reset what I need. The timer therefore never stops and my other functions which require a timer (if timer> 7) are launched directly since the condition is fulfilled (whereas they should start again from 0 when entering the other functions)
PS: When a video is running, the other videos are not superimposed on it, they kindly wait their turn
while True:
    if ...:
        try:
            if(200 <= DD): # If we are more than 200 cm away
                # We count the number of seconds between the last checkpoint and now
                face_walking_apparition_time = time.time() - walking_timer # (t+3) - t = 3, it's how u calculate timer

                # Then we check if a face has appeared for more than 30 seconds:
                if face_walking_apparition_time > 30: # If the block is detected more than 30 seconds
                    # Display video
                    time.sleep(25)
                    face_motionless_apparition_time = 0 # I try to reset here
                    face_walking_apparition_time = 0 # I try to reset here
                if face_walking_apparition_time >= 50: # After 20 seconds of video, reset
                    face_walking_apparition_time = 0 #I try to reset here
                    face_motionless_apparition_time = 0 # I try to reset here

            elif (50 < DD) and (DD < 200):
                # As we don't see no face, we have to reset our checkpoint to "now"
                face_motionless_apparition_time = 0 # I try to reset here
                face_walking_apparition_time = 0 # I try to reset here

PS: I'm new to python so my code might be horrible to read
Comment: i'm not sure to understand what is your problem, could you be more precise (for exemple which timer is causing problems) ? and could you also isolate the chunk of code that is  concerned directly ?
Comment: time is not a timer,  time is a library of time related functions.  time.time() is the current time now, you can't pause the progression of time, not even with python.
Comment: @JeffUK So is there a way to create a timer that can meet my expectations ? (a new edit has been made)
Answer: I think you may misunderstand how the "timer" works
what we usually do is intitializing a variable with time.time() wich represents the number of seconds elapsed since 01/01/1970 and then when we want to mesure the time like a timer, we substract a second instance of time.time() with the previous one, which give us the mesured time between the two.
Using time.sleep(n) simply waits n seconds before going to the next line, so it won't reset your timer
you need to rethink your code around these notions


What are these wire connectors and where can I get replacements?

Question: The closest name I found from searching online is "crimp terminals", specifically the first I believe would be "female round crimp terminal" and the second "female right angle crimp terminal", however I am not sure if that is descriptive enough to ensure I can find and order the proper replacements.
These are from a Dyson vacuum if it helps. The wire itself is severed, so I was planning to purchase same gauge wire (AWG22) and the 2 terminals.
Comment: I have never seen the first one.  For the second  search for  "right angle female spade terminal" There are different sizes so you may go to an auto parts store and get a few  to see what size you have. You could also check with Dyson for the part numbers.
Comment: I think the top ones are female Winchester but the wrong crimping tool was used. The bottom is a 1/4" female spade or disconnect with a 90 these are more common and this one was properly crimped on the conductor and insulator.
Comment: The top ones can be purchased at any appliance repair shop. Those connectors are commonly used in  electric skillets, Crockpots, electric grills, etc.
Answer: The first (2) photo's show a Female "Bullet" crimp connector. The third shows a Female "Spade" connector. Both are available on Amazon.
They are sized according to wire gauge; that is the color coded crimp connector's only accommodate certain wire diameter's.
You may want to consider that a new bullet connector may not fit securely enough to stay in place. You may want to consider soldering the wire at the break and wrapping it with shrink tube. I've made repairs similar to your's and had to reduce the opening of the new bullet to keep it secure.
Comment: some are colour coded, these ones aren't
Comment: I ended up buying the whole "assembly", the part name is "Dyson DC43 and DC66 Yoke Loom".


Does bounded variation and continuous means total variation continuous

Question: $F$ is of bounded variation and continuous. Is it true that total variation is continuous ?
In case, $F$ is absolutely continuous it is trivial to see. But for the above case how to proceed ?
Answer: Yes, this is true. Let $F:[a,b]\to\mathbb R$ be as in your post, and denote by $V(x)$ the variation of $F$ on $[a,x]$. It is a standard fact  that both $V+F$ and $V-F$ are nondecreasing functions on $[a,b]$.
Suppose $V$ is discontinuous from the left at $c\in (a,b]$ (discontinuity from the right can be ruled out in the same way; or just flip the function). This means $V$ has an upward jump at that point: $\delta:= V(c)-V(c-)>0$. Define $$\tilde V (x) = \begin{cases} V(x), \quad & x<c \\ V(x)-\delta,\quad & x\ge c\end{cases}$$
Observe that $\tilde V+F$ and $\tilde V-F$ are still nondecreasing, since both $V\pm F$ had the same upward jump, the removal of which preserves the nondecreasing property.
The representation  $$F = \frac12(\tilde V+F) - \frac12(\tilde V-F)$$  implies that the variation of $F$ on $[a,b]$ is at most the sum of variations of the two functions, i.e., $$\frac{1}{2} (\tilde V(b) +F(b)-F(a)) + \frac{1}{2} (\tilde V(b) - F(b)+ F(a)) $$  But the latter simplifies to $\tilde V(b)$, which is strictly less than $V(b)$ —  contradicting the fact that $V(b)$ is the variation of $F$ on $[a,b]$.


Processing for Android, use of libraries

Question: I have a Processing sketch that works fine on my computer.
I'm now trying to get it running on my Android tablet using Processing Android mode. But I'm getting a lot of compiler errors saying "cannot find symbol".
I'm using some Processing libraries I've created using https://github.com/processing/processing-library-template .
These libraries don't actually access system resources or call the Processing library themselves. Or any other external Java except Java.util. They're just manipulating data-structures.
However it seems Android mode has a problem with them.
Googling around it seems that a lot of Processing libraries don't work with Android Mode, but I can't find anything explicit : should I simply assume that external libraries can't work at all with Android mode? Or are there specific things that won't work? Or should I be looking for a specific bug somewhere in my code?
Update : Further details. I believe Processing Android mode targets Android 2.3.3. I'm using Processing 2.21. The libraries I'm talking about are my own.
Comment: which version of Processing, which version(s) of Android, and which versions of which libraries? (Please update your post with that information =)
Comment: Care to provide the compiler output? Then we could see which symbols cannot be found.
Comment: Could you give us a short snippet of the error logs to have a better understanding.
Comment: Can you compile your utility to a jar and copy it to the lib directory on the android device (this may be wrong, as I don't know very much about java on android)
Comment: @interstar Please provide us the error. Also, did you try one of the releases?
Answer: From a related Git Issue page , a comment by omerjerk

The master branch of this repository is not buildable with the master
  branch of processing. processing has moved ahead and we haven't
  updated this repository yet.  Why are you really building the Android
  mode yourself ? If you want to run your processing sketches on your
  phone, then just download processing 2.2.1 from the main website, open
  the IDE and from there, download the Android mode. In case, if you
  really want to build Android mode from source, apply this pull request
  - #98 .

See if this helps
Comment: Thanks. To be clear. I AM able to get Processing running on my tablet. The problem is that I can't use a library that I compiled and packaged as a Processing Library (using the Processing Library Template)

My work-around has been to just copy all the source-code of the library directly into my Processing sketch where it compiles perfectly and runs OK on Android. Similarly, when running in Java mode, the packaged libraries. work. It's some incompatibility with the Android-Processing and the Processing Libraries.
Comment: I see, error logs would be really useful, provide them, also ensure build.properties is correct. In general the error is possibly there.


The fourth order accuracy of $f''(x_0)$

Question: Could you please give me formulas for the fourth order of accuracy $O(h^4)$ of the $``$forward and backward$"$ difference methods to find the approximation of $f''(x_0)$?
Comment: You can find arbitrary formulas [here](https://en.wikipedia.org/wiki/Finite_difference#Higher-order_differences)
Answer: Add the two Taylor series
$f(x\pm h)
=f(x)\pm hf'(x)+h^2f''(x)/2\pm h^3f'''(x)/6
+O(h^4)
$.
Comment: Please, I need the fourth order of accuracy : Forward and Backward difference methods for the secondderivative. What you wrote is the second order finite difference method for the second derivative.
Answer: Thanks a lot for your efforts. I answer the question:
I used the coefficients in this table:
https://en.wikipedia.org/wiki/Finite_difference_coefficient
The forward is
\begin{align}
f''(x_0) =& \frac{1}{h^2} \Big(\frac{15}{4}f(x_0) - \frac{77}{6}f(x_0+h)
+ \frac{107}{6}f(x_0+2h) - 13 f(x_0+3h) \\&+ \frac{61}{12} f(x_0+4h) - \frac{5}{6} f(x_0+5h)\Big)
\end{align}
The bachward is
\begin{align}
f''(x_0) =& \frac{1}{h^2} \Big(-\frac{15}{4}f(x_0) + \frac{77}{6}f(x_0-h) - \frac{107}{6}f(x_0-2h) + 13 f(x_0-3h) \nonumber\\
 &- \frac{61}{12} f(x_0-4h) + \frac{5}{6} f(x_0-5h)\Big).
\end{align}

The fourth order accuracy of $f''(x_0)$


PHP vTiger6 Issue creating account with vtwsclib

Question: I am trying to figure out how to programmatically create a "Account"  in vTiger6.5 using its Web Services API.
I am currently using the official vtwsclib v1.5 PHP Library. The log in, appears to succeed and I can also successfully perform a doDescribe on the module, however doCreate returns 'false' no matter what I do.
Sample below. Am I missing anything?
$url = 'http://vtiger.mydomain.com/';
$client = new Vtiger_WSClient($url);
$login = $client -> doLogin('systemuser', 'O8nFgnotrealkey');
if (!$login)
    echo 'Login Failed';
else {
    $module = "Accounts";
    $record = $client -> doCreate($module, Array('accountname'=>'S1',
                           'account_type'=>'Prospect', 'phone'=>'75584'));

    if ($record) {
        $recordid = $client -> getRecordId($record['id']);
    }
}

Returns:
$record: bool(false)

Answer: With $client->lastError() i now what my error ,I have create same mandatory fields
 $module = 'Accounts';
 $record = $client->doCreate($module, Array('accountname'=>'c2', 'account_type'=>'Prospect', 'industry'=>'444', 'phone'=>'4555',cf_753=>'Code',cf_755=>'45588','assigned_user_id' => '14x4'));
    if($record) {
        echo "done";
        //$recordid = $client->getRecordId($record['id']);
        //echo "Record ".$recordid;
    }
    else {
        $wasError= $client->lastError();
        if($wasError) {
            echo "
last error : ".$wasError['code'] . ':' . $wasError['message'];
        }

    }


Playframework: Is persistance of form values is possible?

Question: I am curious to know how can we persist values of form while reloading the page in Play framework. For example, I have a drop down with List of countries. On selection of Drop down only, user can move forward to selection in another drop down which allows user to select parameters of that country. Here is the code

                <select name="ddlCountries">
                                @for(countries <- countrylist) {
                            <option value="@countries.countryId"
                            @if(countries.countryId == Integer.parseInt(selected)) {
                            selected="selected"
                            }
                            >
                            @countries.countryDesc</option>
                        }
                        </select>

The "countryselected()" function has
  document.getElementById("postButton").click();

which creates a artificial click, But when I  come back to the page I have the List of countries also modified to default.
For example, If I select a country I go back to code get the filled form and again send the filled form  along with the list of countries to the SCALA page. Hence the countries drop down selection is lost and it is again ordered in the same way. Any good way of tackling this.
Answer: I would make your onchange event an ajax call and respond with some json to update your page using javascript


Is a stack of steel plate as strong as a single plate of the sum thickness?

Question: I'd like to put a 4'x8' steel plate across my driveway gutter, so cars don't bottom out in the dip.  I've seen 1/2" plates used for this, but at 650+ lbs. (https://www.chapelsteel.com/weight-steel-plate.html), it will be a beast transport.  Will a stack of two 1/4" pieces have roughly the same bearing capacity?
Comment: No, it's not as strong, but how far are you spanning across your driveway gutter?
Comment: Would you consider shearing the 8' long plate into several sections (ie four 4'x2' pieces)? This could reduce the per-piece weight; the pieces could then be joined on site by welding or by splicing with thinner plate fastened by bolts, rivets, etc.
Comment: @LeeSam I'd like to span 4 feet; it's a fairly deep gutter and the road has been repaved to a high camber.  It needs to be strong enough to hold a Prius (about 3k lbs. curb weight and fairly low clearance), but occasionally a 1/2 ton truck (estimated 2.4k per axle, when loaded)
Comment: Can you weld or set rivets?
Comment: Only the heavy load determines the strength required.
Comment: I'm with @GregHill here.  You'd find it easiest and simplest to put down something analogous to a  bunch of  "12 by  4" lumber sheets.  If they're well seated at both ends you don't absolutely have to bolt them together at all, or just mount the equivalent of a couple bar-clamps on the underside to keep the assembly aligned.
Comment: if you have access to a half-ton truck how is 650lb a problem?  pull it off the back with a rope tied to something solid, then work it into place with crowbars and rollers. (or a winch if you can borrow one)  if you a don't want to D.I.Y get the steel place to send a crane-truck to deliver it.
Answer: No.  When you stack sheets of thin material, their strengths merely add.  And a thin sheet is exponentially weaker in bending than a thick one, so added up they are still quite poor.  The reason is they are free to slip past each other.
Think about how a wrapped 500-sheet pack of paper is fairly rigid,  but once you break the package, the 500 sheets are a wet noodle.  The strength is actually in the vertical sides of the package wrapper - and in turn, that vertical is being kept from  twisting by the horizontal sheets.
What makes a thick sheet so much stronger is having vertical sides inside the material itself. It's like the material has an internal truss.
The material doesn't even need to be solid, it just needs to be braced - the vertical element carries the weight, and horizontal elements keep the vertical from twisting or buckling.
For instance, you might use a stack of C-channel or Unistrut, with each segment bolted to the next.  The reason to bolt is both to distribute the weight and allow them to mutually reinforce each other.  Bolts should be well chosen, of comparable material/stretch (e.g. don't use Grade 8 bolts to bolt mild steel), and of suitable interval.
Answer: Not unless you can bond them together into a single piece so they won't flex independently.  Otherwise it will act like a leaf spring.  But bonding them together defeats the goal of trying to reduce the weight of a 1/2" piece because they would just become one 1/2" piece.
Comment: unless you can bond them on site
Answer: I'm with @GregHill here.  You'd find it easiest and simplest to put down something analogous to a  bunch of  "12 by  4" lumber sheets.  If they're well seated at both ends you don't absolutely have to bolt them together at all, or just mount the equivalent of a couple bar-clamps on the underside to keep the assembly aligned.
So if you use half-inch, or even 3/4-inch, plates  6 feet long and 1 foot wide (8 pieces) , that gives you plenty of footing space at both ends.    But really, I'd look into similarly sized grating plates rated for the kind of vehicle weights of interest. THey'll be much lighter, will drain & stay clean more easily, and so on.
Answer: The simpler, easier, and cheaper solution is to make a culvert... you put a properly sized galvanized or pvc pipe in the gutter to allow drainage, (I can't say a size without seeing your driveway but 1 foot diameter is the most common, anything smaller can get leaves and other debris stuck inside too easily.)
then concrete (ed: atop fill) over its top to level out your drive way. If you need more than 0.5-1 cubic yard / 13ish-27 cubic feet of concrete, price check a concrete truck delivery service, as mixing your own by the bag quickly becomes more expensive than a delivery even with a small load fee tacked on.
For an example you can look for any road with a ditch alongside it. It should have a culvert at every drive way and intersection to prevent flooding.
Closing thought: I'mm slightly concerned you talking about the gutter in your street, in which case I don't think there is much you could do other than maybe have your drive way r made to a better angle. You wouldn't be allowed to modify city property and having half inch plates sticking out into the road would be a hazard.


R: converting xts or zoo object to a data frame

Question: What is an easy way of coercing time series data to a data frame, in a format where the resulting data is a summary of the original?
This could be some example data, stored in xts or zoo object:
t,                  V1
"2010-12-03 12:00", 10.0
"2010-11-04 12:00", 10.0
"2010-10-05 12:00", 10.0
"2010-09-06 12:00", 10.0
...and so on, monthly data for many years.

and I would like to transform it to a data frame like:
year, month, V1
2010, 12,    a descriptive statistic calculated of that month's data
2010, 11,    ...
2010, 10,    ...
2010, 9,     ...

The reason I'm asking this, is because I want to plot monthly calculated summaries of data in the same plot. I can do this quite easily for data in the latter format, but haven't found a plotting method for the time series format.
For example, I could have temperature data from several years measured in a daily interval and I would like to plot the curves for the monthly mean temperatures for each year in the same plot. I didn't figure out how to do this using the xts-formatted data, or if this even suits the purpose of the xts/zoo formatting of the data, which seems to always carry the year information along it.
Comment: you know it's never too late to accept some answers as "best answer"
Answer: Please provide a sample of data to work with and I will try to provide a less general answer.  Basically you can use apply.monthly to calculate summary statistics on your xts object.  Then you can convert the index to yearmon and convert the xts object to a data.frame.
x <- xts(rnorm(50), Sys.Date()+1:50)
mthlySumm <- apply.monthly(x, mean)
index(mthlySumm) <- as.yearmon(index(mthlySumm))
Data <- as.data.frame(mthlySumm)

Comment: @user442446 if it answered your question, you should accept it as the "best answer".  You should also do this for the other 5 questions you've asked, since you haven't marked any "best answers" for any of your questions.
Comment: And you can pull out the year and month with `format` with lines like `as.numeric(format(index(x), "%Y"))` and `as.numeric(format(index(x), "%m"))`
Comment: These were very helpful, thanks. I was missing the index()-function as well as the format()-functions. Now it's easier to play with my data.
Comment: Joshua Ulrich gave a very helpful answer to a similar question on zoo/data frame conversion at http://stackoverflow.com/questions/14064097/ which has the advantage of example data and output.
Answer: Here's a solution using the tidyquant package, which includes functions as_xts() for coercing data frames to xts objects and as_tibble() for coercing xts objects to tibbles ("tidy" data frames).
Recreating your data:
> data_xts
           V1
2010-09-06 10
2010-10-05 10
2010-11-04 10
2010-12-03 10

Use as_tibble() to convert to a tibble. The preserve_row_names = TRUE adds a column called "row.names" with the xts index as character class. A rename and mutate are used to clean up dates. The output is a tibble with dates and values.
> data_df <- data_xts %>%
     as_tibble(preserve_row_names = TRUE) %>%
     rename(date = row.names) %>%
     mutate(date = as_date(date))
> data_df
# A tibble: 4 × 2
        date    V1
      <date> <dbl>
1 2010-09-06    10
2 2010-10-05    10
3 2010-11-04    10
4 2010-12-03    10

You can go a step further and add other fields such as day, month, and year using the mutate function.
> data_df %>%
     mutate(day   = day(date),
            month = month(date),
            year  = year(date))
# A tibble: 4 × 5
        date    V1   day month  year
      <date> <dbl> <int> <dbl> <dbl>
1 2010-09-06    10     6     9  2010
2 2010-10-05    10     5    10  2010
3 2010-11-04    10     4    11  2010
4 2010-12-03    10     3    12  2010


Using a conditional if statement in a Linq query

Question: I'm trying to write a linq query that uses an if statement.
In the code below I'm searching for matches of
n.SAU_ID = sau.SAUID where
ReportingPeriod column contains "Oct1" then
 FiscalYear - aprYearDiff = sau.SAUYearCode.
Else
FiscalYear - octYearDiff = sau.SAUYearCode.
My code is only giving matches for the SAUID and "Oct1".
What code is needed to implement theese statements?
<code>    int FiscalYear = 2014;

    List<String> addtowns = new List<string>();

    List<Stage_Reorg> reorg = _entities.Stage_Reorg.ToList();

    int aprYearDiff = 2;
    int octYearDiff = 1;

    foreach (var sau in reorg)
    {
        addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
        .Where(n => n.SAU_ID == sau.SAUID
            && (n.ReportingPeriod == "Oct1"
            ? (FiscalYear - aprYearDiff) == sau.SAUYearCode
            : (FiscalYear - octYearDiff) == sau.SAUYearCode))
        .Select(n =>  n.TownCode ));
    }
</code>
Comment: you can fix the syntax but I don't think it will work with EF anyway.
Comment: `.where( a => { /*some code */  return /*some bool value*/} )`
Comment: @EugenePodskal That was actually easier to read before the edit.
Comment: @DCShannon Well, I do not say that I've made some really good formatting there. Just I am a firm believer in fair use of tabs and abundant use of parentheses to make code more readable (at least for me). Overall it is a matter of taste and personal preferences, so feel free to rollback it.
Answer: Here is a possible way but this probably won't work with EF. You will need to load all records into memory then perform the filtering:
<code>addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
    .Where(n => {
                   bool b = n.ReportingPeriod == "Oct1"
                           ? (FiscalYear - aprYearDiff) == sau.SAUYearCode
                           : (FiscalYear - octYearDiff) == sau.SAUYearCode);
                  return b && n.SAU_ID == sau.SAUID;
                 }).Select(n =>  n.TownCode ))
</code>
Comment: I take to long to type. but I agree completely
Answer: This is a bad idea anyway. Transform the condition to
<code>(n.ReportingPeriod == "Oct1" && (FiscalYear - aprYearDiff) == sau.SAUYearCode)
|| (n.ReportingPeriod != "Oct1" && (FiscalYear - octYearDiff) == sau.SAUYearCode)
</code>
Comment: Could elaborate on why it's a bad idea, but upvoted anyway, as this should work better and is logically equivalent.
Comment: Because declarative code is better than imperative code and this one is simpler.


Invalid Column Name for the non digit password

Question: I am trying to do a login application form using C#.
In the code below, I am getting an exception

Invalid Column Name

when I used a non digit password. When I used only digit password it works perfectly.
The type of the Password column in the database is nvarchar(Max).
if (ValidateTextBoxes())
{
   SqlConnection oConn = new SqlConnection();

   oConn.ConnectionString = "Data Source=MCOEELIMENEM\\sqlexpress;Initial Catalog=Database;Integrated Security=True";
   oConn.Open();

   string strQuery = "select id from Register where Username='" + textBox1.Text + "' and Password=" + textBox2.Text + "";
   SqlCommand cmd = new SqlCommand(strQuery, oConn);

   var retVal = cmd.ExecuteScalar();

   if (retVal != null)
   {
      MessageBox.Show("Login Successfully Done");
   }
   else
   {
      MessageBox.Show("Access Denied, password username mismatched");
   }
}

Comment: Time to learn about parametrized queries.
Comment: 1) Your code is wide open to SQL injection vulnerabilities.  You may very well be experiencing the side-effect of that now.  2) Never, ***never*** store passwords in plain text like this.  User passwords should be stored using a 1-way hash so the values can't be retrieved.  Anything less is *very* irresponsible to your users.
Comment: And furthermore: I don't think a password should ever really be **1 billion characters** long - so please use a more appropriate, more suitable datatype than `nvarchar(max)` - don't just use `(max)` types everywhere because you're too lazy to determine the appropriate length!
Comment: I am curious why people are trying to close this question as 'too broad'. There is a clear question with a clear resolution, there is nothing broad about either. While I appreciate that his approach is far from ideal, please respect the rules of the site and deal with the question accordingly.
Answer: Your sql is not quoted correctly, try this;
string strQuery = "select id from Register where Username='" + textBox1.Text +
"' and Password='" + textBox2.Text + "'";

However, as others have suggested, you should really be using parameterized queries for a number of reasons.


Azure Key Vault secrets with ServiceBusTrigger Attribute on Web App Jobs

Question: I have Web App Job project which is configured to pluck messages from an Azure Service Bus and process them.
Presently I have a Functions class and a MessageReceived() method which is used as such:
public async Task MessageReceived( [ServiceBusTrigger("some-queue", Connection="ServiceBusConnectionString")], SomeClass someInstance, int deliveryCount, DateTime enqueuedTimeUtc, string messageId, ILoggerlog) { //message procesing code }
I also have all the KeyVault infrastructure in place, but I don't know how to get the Azure Secrets work with the [ServiceBusTrigger] attribute.
Normally I would use @Microsoft.KeyVault(VaultName=myvault;SecretName=mysecret) in code, but I don't know how to use it with the trigger.
I have tried to pass the Secret to the Attribute, but that wouldn't work because attributes expect constant values.
Any concrete examples would be appreciated.
Answer:
Well, you can directly save the reference of the key vault secret in the application settings in the following format

@Microsoft.KeyVault(VaultName=<Keyvault name>;SecretName=<Secret Name> ;  SecretVersion = <Secret version >)

The application settings are under the configuration tab

Here in code my connection string is set to name connection so we must use the same name for the key vault reference.

output of the service bus trigger:
Comment: I was specifically referring to the ServiceBusTriggerAttribute


Sentence Similarity Estimate with word2vec

Question: If I have a list of sentences, how can I get a score for the similarity for each pair of sentences using word2vec? Besides, for sentence similarity, is using word2vec better than other methods, such as cosine similarity?
Comment: Did you try doc2vec from gensim?
Answer: If I remember correctly, word2vec produces vector mappings from words to vectors, but doesn't propose a vector representation for a larger structure such as a sentence. In order to find the similarity between two sentences you need to go from the vector representations of the words in each sentence to a vector representation of each sentence itself. From there you can use the usual vector distance metric (cosine similarity, computer as the dot product of the normalised vectors) to compare them.
It's up to you how to combine word vectors into sentence vectors, but a simple way would be to add the word vectors all together.


Getting a stronger induction principle in Coq

Question: Assume the following:
Inductive bin : Set := Z | O.

Fixpoint fib (n : nat) : list bin :=
  match n with
    | 0   => [Z]
    | S k => match k with
               | 0    => [O]
               | S k' => fib k' ++ fib k
             end
  end.

I would like to show:
Theorem fib_first : forall n,
    Nat.Even n -> n > 3 -> exists w, fib n = Z :: w.

However, by performing induction on n, I get a really useless inductive
hypothesis fixing n, stating that IH : Nat.Even n -> n > 3 -> exists w : list bin, fib n = Z :: w.
What I would ideally have is the following: IH : forall n : nat, Nat.Even n -> n > 3 -> exists w : list bin, fib n = Z :: w. Naturally I cannot assume the original proposition, but it feels like I need to prove something stronger perhaps?
My idea for the inductive reasoning would be made possible by expanding F n = F n-2 . F n-1, we know F n-2 is even iff F n is even, and since neither of F n-2 or F n-1 is empty, we can show the substring is shorter, therefore sufficient for the inductive hypothesis - how does one express this in Coq?
Answer: The trick is to unfold the definition of Nat.Even and do induction on n / 2 instead of n:
Theorem fib_first : forall n,
  Nat.Even n -> exists w, fib n = Z :: w.
Proof.
intros n [m ->].
induction m as [|m IH].
- now exists nil.
- rewrite <- mult_n_Sm, plus_comm.
  generalize (2 * m) IH. clear m IH. simpl.
  intros n [w ->].
  simpl. eauto.
Qed.

Note that your n > 3 hypothesis is not actually needed.
Comment: I can see why now that you've pointed it out - however figuring it out is an entirely different matter :).


Copy a MySQL row with unknown structure

Question: I'm trying to copy a row from a structure I technically know nothing about.
This is what I have so far. This code does work but I'm pretty sure this isn't the most appropriate. Anyone have a better way or a right way of doing this? Any suggestions would be appreciated.
/*
   $table is the table name
   $id_field is the primary key
   $id_value is the row I want to copy
*/

$selectEntity = $dbh->prepare("SELECT * FROM {$table} WHERE {$id_field} = :id_value");
$selectEntity->execute(array(':id_value' => $id_value));
$entity = $selectEntity->fetch(PDO::FETCH_ASSOC);

foreach ($entity as &$value){ if(is_null($value) == true) { $value = "NULL"; } else { $value = "'".htmlspecialchars($value, ENT_QUOTES)."'"; } }

//remove the primary key
$entity[$id_field] = "'"; // the ' was the only way I could get NULL to get in there

$insertCloned = $dbh->prepare("INSERT INTO {$table} (".implode(", ",array_keys($entity)).") VALUES ('".implode(", ",array_values($entity)).")");
$insertCloned->execute();
$lastInsertedID = $dbh->lastInsertId();

It's very messy.
Answer: Your quoting is not correct -- you have quotes around the entire VALUES list, they should be around each individual value. Also, you should use $dbh->escape($value) to escape the values; htmlspecialchars is for encoding HTML when you want to display it literally on a web page.
But it's better to use query parameters rather than substituting into the SQL. So try this:
$entity[$id_field] = null;
$params = implode(', ', array_fill(0, count($entity), '?'));
$insertCloned = $dbh->prepare("INSERT INTO {$table} VALUES ($params)");
$insertCloned->execute(array_values($entity));

You don't need to list the column names in the INSERT statement when the values are in the same order as the table schema. And since you used SELECT * to get the values in the first place, they will be.
Comment: Hmm. Thanks for the help @Barmar but I get a `Array to string conversion` error / `Column not found: 1054 Unknown column 'Array'`
Comment: Oops, forgot to implode it into a string. Fixed.

Copy a MySQL row with unknown structure


how to evaluate equality of big O notation?

Question: I've been asked a question that seems strange to me. Given the following two equalities, which is true, and which is false (or are they both either true or false)?

O(n^2) = O(n^3)
O(n^3) = O(n^2)

To me, this question seems absurd, since O(f(n)) just means that for some time function T(n), lim as n -> infty of T(n) <= c * f(n).
Comment: https://math.stackexchange.com/a/86096/219337, particularly the part where it says "When one asserts that E1=E2 where E1 and E2 are sets represented by expressions like the above, one should always interpret it to mean that E1⊆E2". So number 1 is correct and number 2 is false.
Answer: O(f(n)) can be thought of as  the class of all functions whose growth is bounded above by f(n). Taking into account this, the two options are false.


Repository adding > problem

Question: After running those two commands:
sudo add-apt-repository ppa:tualatrix/next
sudo apt-get update

I am getting this output:
Reading package lists... Done
W: The repository 'ppa.launchpad.net/tualatrix/next/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch ppa.launchpad.net/tualatrix/next/ubuntu/dists/xenial/main/binary-amd64/Packages  404  Not Found
E: Failed to fetch ppa.launchpad.net/tualatrix/next/ubuntu/dists/xenial/main/binary-i386/Packages  404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.

I don't really understand the error in the last few lines.
(Had to remove the http: before the ppa (no more then 2 Links...)
If I dismiss these errors.
The installation of ubuntu-tweak does not work
sudo apt-get install ubuntu-tweak

This output:
niclas@ThinkPad:~$ sudo apt-get install ubuntu-tweak
[sudo] password for niclas:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package ubuntu-tweak

Would be thankfull for any help
Answer: use this repository
sudo add-apt-repository ppa:tualatrix/ppa

Comment: Didn't work still unable to locate package.
Answer: If you don't succeed to install Ubuntu tweak from ppa, you can install it from debian package (.deb) following these steps:

Download package from Ubuntu Tweak website.
Open terminal and change your working directory where you downloaded the file (e.g Download directory).
cd Download

Now you can install Ubuntu Tweak with this command:
sudo dpkg -i <package>

(change <package> with .deb name, e.g. ubuntu-tweak_0.8.7-1-trusty2_all.deb)

You can get more info about dpkg command reading manual with this command:
man dpkg

I hope this could help you.

EDIT:
If your error is caused by some missing packages  you can try to solve it with the following command that will fix package dependencies:
sudo apt-get install -f

After this you can try to reinstall Ubuntu-tweak.
If previous solution doesn't work, it could means that Ubuntu Tweak package could be not ready for Ubuntu 16.04, since last update was made two years ago. I didn't find any information about compatibility with Ubuntu 16.04 neither on ubuntu wiki nor on official website. Hence I suggest to you to wait for a while and see if it will be released a new version.
Meanwhile you can try to install unity-tweak-tool. It is a similar program that let you tweak some aspects of Unity. There isn't an Apps manager or Janitor, but if you only want to change appearance you can use it. You can install it with this command:
sudo apt-get install unity-tweak-tool

Comment: If I try that I am getting this error in the end:
Errors were encountered while processing:
 ubuntu-tweak
Comment: Is it possible that ubuntu tweak doesn'w work yet with 16.04?
Comment: @Niclas - that might be it.
Comment: Okay so I am now using unity tweak tool. That one is working fine. ( installed over software center)
Comment: But I still had the problem that some repositorys does not seem to work. Even simple things like themes wouldn't be installed. Might be caused by 16.04 just aswell...
Comment: @Niclas You can try to install `Numix` theme from its `ppa`. Watch the answer of this post http://askubuntu.com/questions/640608/how-to-fix-numix-theme-on-ubuntu-14-04 I am almost sure that works also on Ubuntu 16.04
Comment: Numix worked but sth like Flatabulous didn't work :S

Repository adding > problem


Not able to connect to websocket using Nginx and Uvicorn

Question: I built a docker container with Django, Uvicorn, Nginx and Redis, and am using django-channels but when I run this it says it cannot connect to the websocket and this is seen in the browser console:

WebSocket connection to 'ws://127.0.0.1:8080/ws/notifications/' failed

It is working fine when I use Django's runserver command for development but when I include Nginx and Uvicorn it breaks.
Entrypoint.sh:
gunicorn roomway.asgi:application --forwarded-allow-ips='*' --bind 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker

Nginx config:
upstream django {
    server app:8000;
}

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

server {
    listen 8080;

    location /static {
        alias /vol/static;
    }

    location /ws/ {
        proxy_pass http://0.0.0.0:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }

    location / {
        proxy_pass http://django;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_redirect off;
        proxy_buffering off;
    }
}

settings.py:
CHANNEL_LAYERS={
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('redis', 6379)],  #Redis port
        }
    }
}

The JS file which handles the socket:
var wsStart = "ws://"
var webSocketEndpoint =  wsStart + window.location.host + '/ws/notifications/'
const notificationSocket = new WebSocket(webSocketEndpoint)

asgi.py:
application = ProtocolTypeRouter({
    "http": django_asgi_app,
    "websocket": AuthMiddlewareStack(
        URLRouter([
            url(r'^ws/notifications/', NotificationConsumer.as_asgi()),
            path("ws/<str:room_name>/", ChatConsumer.as_asgi())
        ])
    )
})

Nginx throws this error with the above code:
[error] 23#23: *4 connect() failed (111: Connection refused) while connecting to upstream, server: , request: "GET /ws/notifications/ HTTP/1.1", upstream: "http://0.0.0.0:8000/ws/notifications/", host: "127.0.0.1:8080"

When I change the proxy_pass to http://django instead of 0.0.0.0, Nginx does not throw that error anymore but I get the same error on the console. Also this time Django throws these warnings:
[WARNING] Unsupported upgrade request.
[WARNING] No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually.

Comment: Try installing `uvicorn[standard]` instead:`pip uninstall uvicorn && pip install uvicorn[standard]`. It seems websocket support may not be included in the base install
Comment: Do you need to change proxy_pass to  send the request to your django container `proxy_pass http://django;`? Currently you're just passing it to "0.0.0.0"
Comment: @lian I tried that right now but am still getting the same error on the console. Though this time, I get a warning from the Django app which says:
[WARNING] Unsupported upgrade request.
[WARNING] No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually.

Which is strange considering I have django-channels installed
Comment: channels will not install uvicorn for you, if you want to run gunicorn/uvcorn you will need to install it
Comment: I have already have gunicorn==20.1.0 and uvicorn==0.15.0 installed on the container
Comment: Yes that was it!! Thanks man. I also moved Twisted to version 20.3 because of some compatibilty issues.
Comment: installing ```uvicorn[standard``` did iit for me. Thanks man, @IainShelvington
Comment: @IainShelvington I wish I could see your answer earlier, it could save nearly a week of efforts.
Answer: As noted in a comment by Iain Shelvington, it seems like websockets are not included in the base install of uvicorn
pip uninstall uvicorn
pip install 'uvicorn[standard]'

Comment: On some shells it may complain that the package cannot be found. You have to quote the package: `pip install 'uvicorn[standard]'`
Answer: pip uninstall uvicorn
pip install "uvicorn[standard]"

Use Double Quotation
Answer: If you use "uvicorn[standart]" maybe cannot see websocket
if occures error like that: install websocket pip install websocket


Throwing numberformatexception regardless

Question: Im writing a class for a card that takes in two string parameters,
When I check the string if it's an "a" it throws the NumberFormatException error.
Card(String s, String  f)
{
    suit = s;
    if(f == "a")
    {
        value = 11;
    }

    else if (f == "j" || f == "k" || f == "q")
    {
        value = 10;
    }

    else
    {
        value = Integer.parseInt(f);
    }
    face  = f;
}

Comment: Please give a [mcve]. Be sure to include an example run of your program.
Comment: Also read about [how to compare strings in Java](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java).
Answer: You can't compare strings with ==. That only compares the "shallow" reference values of the two strings, whether if they point to the same string object (most). You have to use the .equals function of the string to check equality with strings.
Comment: I knew that, my brain is just fried from a long day. Thanks!