text:
Q: How do I stop the "[A" showing sometimes when I press the up arrow key? I use bash and the up arrow key sometimes to be able to quickly get the previous commands I used. What is irritating is sometimes when I do this I get a [A instead of a previous command. After doing some research online it looks like this is a key code representing the up arrow key being sent to the computer.
I can't seem to find any answers to this online. How can I stop this from happening in the future?

A: The sequence is actually Escape[A, and it's part of a set that was adopted by Ecma in 1976 as standard ECMA-48, being supported by ANSI as a separate but almost identical standard for a number of years (later withdrawn) and also ratified by ISO/IEC 6429 on the way. The upshot of this multiple standardisation is that although they are frequently referenced as ANSI escape codes they should properly be called ECMA-48 control functions*.
The usual reason for seeing [A on the screen instead of the action will be that the inital Escape code has been absorbed unexpectedly. I cannot reproduce this on my keyboard unless I first press Ctrl V, which tells the terminal line driver to process the next character as a literal.
So, we can then get this sequence Ctrl VEscape[A, producing the visible output [A.
You'll notice that if you press the sequence of characters Escape[A in quick succession the cursor will indeed go upwards. However, if you pause after the first character you'll fail to get a cursor movement, and this is because the Escape character has a timeout associated with it. On slow serial lines to UNIX systems this used to be a real problem, and the closest equivalent is a slow or intermittent network connection, with a brief lag during this sequence transmission.
Now to your question, how to prevent this. There isn't much you can do if you're on an intermittent network connection, except maybe use one of the alternate sequences such as Escapek...k...k that are available during command editing in "vi mode" (set -o vi).

* Much like JavaScript should be called ECMAScript, I suppose

A: As mentioned by @roaima, this used to be a well-known problem, seen frequently in programs running over a network or serial line where transmission delays interfere with programs (such as vi) attempting to distinguish a plain escape character from an escape sequence.  Since most users don't run programs on time-shared servers any more, they don't notice this.
The problem is that the program has to delay a "short" time to allow it to see if an escape character is followed by other characters which could be part of one of the escape sequences it is waiting for.  Conventionally, special keys (such as cursor-keys, function keys, etc), are sent as escape sequences.
If you happen to hold a key down, so that the key-repeat feature starts, then it's possible to send those escape sequences faster than (some) programs may read them.  When that happens, the time between individual characters tends to increase — and eventually exceed the "short" time allocated to distinguishing the escape character versus an escape sequence.
readline (part of/bundled with) bash attempts to distinguish different sequences of characters, which (like vi) may begin in the same way.  It has a feature which can change that "short" time:

8.3.1 Readline Init File Syntax

keyseq-timeout

Specifies the duration Readline will wait for a character when reading an ambiguous key sequence (one that can form a complete key sequence using the input read so far, or can take additional input to complete a longer key sequence). If no input is received within the timeout, Readline will use the shorter but complete key sequence. Readline uses this value to determine whether or not input is available on the current input source (rl_instream by default). The value is specified in milliseconds, so a value of 1000 means that Readline will wait one second for additional input. If this variable is set to a value less than or equal to zero, or to a non-numeric value, Readline will wait until another key is pressed to decide which key sequence to complete. The default value is 500.

That is, you could put this in your ~/.inputrc file:
set keyseq-timeout 0

and readline would wait indefinitely for those cursor-keys.  The drawback is that it can produce unexpected results when you happen to type some characters which combine to match something in its repertoire.

A: All very good answers. The quick and dirty is to use h,j,k,l as your arrow keys. Or install the the full vim package. The Ubuntu distro, if I remember correctly defaults to vim??-runtime, if you just install vim?? then the problem "fixes" itself. ?? is whatever the latest full package version. On Ubuntu apt-cache search vim will tell tell you.
h = up, j = down, k = left, l = right


text:
Q: iOS 5 and Three20 SDK i want to make compatible my apps with iOS 5. Everything goes well with iOS 4.3. After changing the main project and target compiler settings to Apple LLVM compiler 3.0, and set the Three20 project and target settings to LLVM GCC 4.2 i ran the application. Application runs well but at the photo gallery screen there is something which i do not want. There is the screenshot.
iOS 5 http://www.portxl.com/ios/5.png
There is a rectangular block above the thumbnails. I ran the same application with the same codes in iOS 4.3 and there is no block. Screenshot is below.

(source: portxl.com)
Waiting your suggestions, thanks in advance.
There is a quick note : when i change Three20 project and target settings to Apple LLVM compiler 3.0, there is an error in a class of three20. When i scroll the tableview rectangular block comes with the tableview.

A: the problem is in TTTableViewDelegate,
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section;

in iOS 5, this method must return 0 if you don't want the header section.
you can check the latest three20, it's been resolved.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ValidationError with Passport.js I'll preface this by mentioning that I am very new to programming, node, js, and especially passport/authentication in general. I have searched relentlessly and found similar issues on stack but am unable to formulate a solution based on the answers I found. I apologize if my for the lengthy question and if it breaks any SO etiquette.
I know the user input values are correctly being passed from the ejs form to my my authController function (I can log each in the console through req.body...). I also know my database is working properly as I have accessed it in other areas. One thing I suspect based on my research is that the password could be passed as an object and isn't properly serialized somehow. That being said, in my app.js file, I am sure to do the following which I believe should avoid this issue:
var User = require('./models/users');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

I am receiving the following error:
ValidationError: User validation failed: user_password: Path `user_password` is required.

 message: 'Path `user_password` is required.',
    name: 'ValidatorError',
    properties: [Object],
    kind: 'required',
    path: 'user_password',
    value: undefined,
    reason: undefined,
    '$isValidatorError': true

/models/users.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var UserSchema = new Schema(
  {
    first_name: {type: String, required: true, max:100},
    last_name: {type:String, required: true, max: 100},
    email_address: {type: String, required:true, max: 100},
    username: {type:String, required: true, max: 100},
    user_password: {type: String, required:true, max: 100}
  }
);

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', UserSchema);

authController.js
userController.doRegister = function(req, res) {
  console.log(req.body.user_password);
  var newUser = new User({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    email_address: req.body.email_address,
    username: req.body.username
  });
  User.register(newUser, req.body.user_password, function(err, user) {
    if (err) {
      console.log(err);
      return res.render('register', { user : user });

    }

    passport.authenticate('local')(req, res, function () {
      res.redirect('/');

      console.log('reached end of doregister in auth contro');
    });
  });
};

register.ejs

First Name	<input type="text" name="first_name" >

Last Name	<input type="text" name="last_name" >

Email Address	<input type="text" name="email_address" >

Username	<input type="text" name="username" >

Password	<input type="text" name="user_password" >

<input type="submit" value="Register" >

A: As I can see, your error is probably related to this:
var newUser = new User({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    email_address: req.body.email_address,
    username: req.body.username
 });

Here you should have to have user_password
var newUser = new User({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    email_address: req.body.email_address,
    username: req.body.username,
    user_password: req.body.user_password
});

Since this is required you cannot create a new user without it.
A better approach is to treat the password in the before save, there you hash and validate it.

A: First of all, you don't want to handle user password in your schema (i.e. remove user_password in your user schema).  That is not safe since you did not hash and salt your user password, that is also the reason why you want to use passport library.  Since obviously you don't want to touch password hashing and salting, so please just let passport-local-mongoose does it for you.
Next, the real problem in your controller middleware is that you did not pass your user mongoose object to req.login. passport.authenticate('local', (err, authUser) => { (do_something) }) is a middleware, which gives you the authenticated user object ass a call back, but it does not populate req.user object until you decide to "login" the user.  So you should try this instead:
userController.doRegister = function(req, res) {
  console.log(req.body.user_password);

  const newUser = new User({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    email_address: req.body.email_address,
    username: req.body.username
  });

  User.register(newUser, req.body.user_password, function(err, user) {
    if (err) {
      console.log(err);
      return res.render('register', { user : user });
    }

    req.login(user, err => {
      if (err) throw err;
      console.log('reached end of doregister in auth contro');
      return res.redirect('/');
    });

  });
};

Note: Please don't use var since we now have const.


text:
Q: Graalvm unknown identifier when passing java object to js I am trying to run this Graalvm sample code:
package org.homi.scripting.experimental;
import org.graalvm.polyglot.*;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;

import java.io.File;
import java.io.IOException;
public class ScriptEngine {

    public static class Name {
        @HostAccess.Export public String name = "hello";

        @HostAccess.Export
        public String getName() {
            return name;
        }
    }

    public static void main(String[] args) {
        Name n = new Name();
        Context context = Context.newBuilder("js")
                .allowAllAccess(true)
                .allowIO(true)
                .allowPolyglotAccess(PolyglotAccess.ALL)
                .build();
        context.getPolyglotBindings().putMember("name", n);
        context.eval("js", "var name = Polyglot.import('name');");
        context.eval("js", "console.log(name.getName())");

    }
}

I am getting this exception:
Exception in thread "main" TypeError: invokeMember (getName) on org.homi.scripting.experimental.Name@2313052e failed due to: Unknown identifier: getName
    at <js> :program(Unnamed:1:12-25)
    at org.graalvm.sdk/org.graalvm.polyglot.Context.eval(Context.java:379)
    at ScriptEngine/org.homi.scripting.experimental.ScriptEngine.tester(ScriptEngine.java:43)
    at ScriptEngine/org.homi.scripting.experimental.ScriptEngine.main(ScriptEngine.java:29)

I'm new to graalvm, what am I doing wrong? I was following this demo from the documentation (see the section on host interoperability):
https://www.graalvm.org/sdk/javadoc/

A: The code and the stack trace don't match, for example the code lacks the tester method
    at ScriptEngine/org.homi.scripting.experimental.ScriptEngine.tester(ScriptEngine.java:43)

When you specify allowAllAccess(true) you allow all access, so the HostAccess stops being necesary.
The code in the question works for me and prints hello as expected.


text:
Q: Verilog: Mix of blocking and non-blocking assignments to variable  is not a recommended coding practice I have the following Verilog code:
//////////////////////////////////////////////////////////////////////////////
//
//  Xilinx, Inc. 2010                 www.xilinx.com
//
//  XAPP xxx - 1:5 Differential Data De-serializer
//
//////////////////////////////////////////////////////////////////////////////
//
//  File name :       serdes_1_to_5_diff_data.v
//
//  Description :     This module instantiates IODELAY2 and ISERDES2 primitives
//                    to receive TMDS differential data in 1:5 format
//
//  Note:
//
//  Author :    Bob Feng
//////////////////////////////////////////////////////////////////////////////
//
//  Disclaimer:
//
//    This disclaimer is not a license and does not grant any rights to the materials
//    distributed herewith. Except as otherwise provided in a valid license issued to you
//    by Xilinx, and to the maximum extent permitted by applicable law:
//    (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS,
//    AND XILINX HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY,
//    INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR
//    FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether in contract
//    or tort, including negligence, or under any other theory of liability) for any loss or damage
//    of any kind or nature related to, arising under or in connection with these materials,
//    including for any direct, or any indirect, special, incidental, or consequential loss
//    or damage (including loss of data, profits, goodwill, or any type of loss or damage suffered
//    as a result of any action brought by a third party) even if such damage or loss was
//    reasonably foreseeable or Xilinx had been advised of the possibility of the same.
//
//  Critical Applications:
//
//    Xilinx products are not designed or intended to be fail-safe, or for use in any application
//    requiring fail-safe performance, such as life-support or safety devices or systems,
//    Class III medical devices, nuclear facilities, applications related to the deployment of airbags,
//    or any other applications that could lead to death, personal injury, or severe property or
//    environmental damage (individually and collectively, "Critical Applications"). Customer assumes
//    the sole risk and liability of any use of Xilinx products in Critical Applications, subject only
//    to applicable laws and regulations governing limitations on product liability.
//
//  THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT ALL TIMES.
//
//////////////////////////////////////////////////////////////////////////////

`timescale 1ps/1ps

module serdes_1_to_5_diff_data # (
  parameter DIFF_TERM = "TRUE",
  parameter SIM_TAP_DELAY = 49,
  parameter BITSLIP_ENABLE = "FALSE"
)(
  input  wire        use_phase_detector,  // '1' enables the phase detector logic
  input  wire        datain_p,            // Input from LVDS receiver pin
  input  wire        datain_n,            // Input from LVDS receiver pin
  input  wire        rxioclk,             // IO Clock network
  input  wire        rxserdesstrobe,      // Parallel data capture strobe
  input  wire        reset,               // Reset line
  input  wire        gclk,                // Global clock
  input  wire        bitslip,             // Bitslip control line
  output wire [4:0]  data_out             // Output data
);

  wire       ddly_m;
  wire       ddly_s;
  wire       busys;
  wire       rx_data_in;
  wire       cascade;
  wire       pd_edge;
  reg  [8:0] counter;
  reg  [3:0] state;
  reg        cal_data_sint;
  wire       busy_data;
  reg        busy_data_d;
  wire       cal_data_slave;
  reg        enable;
  reg        cal_data_master;
  reg        rst_data;
  reg        inc_data_int;   //THIS LINE (81) IS CAUSING THE ERROR
  wire       inc_data;
  reg        ce_data;
  reg        valid_data_d;
  reg        incdec_data_d;
  reg  [4:0] pdcounter;
  wire       valid_data;
  wire       incdec_data;
  reg        flag;
  reg        mux;
  reg        ce_data_inta ;
  wire [1:0] incdec_data_or;
  wire       incdec_data_im;
  wire [1:0] valid_data_or;
  wire       valid_data_im;
  wire [1:0] busy_data_or;
  wire       all_ce;

  wire [1:0] debug_in = 2'b00;

  assign busy_data = busys ;

  assign cal_data_slave = cal_data_sint ;

  /////////////////////////////////////////////////
  //
  // IDELAY Calibration FSM
  //
  /////////////////////////////////////////////////
  always @ (posedge gclk or posedge reset)
  begin
  if (reset == 1'b1) begin
    state <= 0 ;
    cal_data_master <= 1'b0 ;
    cal_data_sint <= 1'b0 ;
    counter <= 9'h000 ;
    enable <= 1'b0 ;
    mux <= 1'h1 ;
  end
  else begin
      counter <= counter + 9'h001 ;
      if (counter[8] == 1'b1) begin
      counter <= 9'h000 ;
      end
      if (counter[5] == 1'b1) begin
      enable <= 1'b1 ;
      end
      if (state == 0 && enable == 1'b1) begin       // Wait for IODELAY to be available
      cal_data_master <= 1'b0 ;
      cal_data_sint <= 1'b0 ;
      rst_data <= 1'b0 ;
        if (busy_data_d == 1'b0) begin
        state <= 1 ;
      end
      end
      else if (state == 1) begin          // Issue calibrate command to both master and slave, needed for simulation, not for the silicon
        cal_data_master <= 1'b1 ;
        cal_data_sint <= 1'b1 ;
        if (busy_data_d == 1'b1) begin        // and wait for command to be accepted
          state <= 2 ;
        end
      end
      else if (state == 2) begin          // Now RST master and slave IODELAYs needed for simulation, not for the silicon
        cal_data_master <= 1'b0 ;
        cal_data_sint <= 1'b0 ;
        if (busy_data_d == 1'b0) begin
          rst_data <= 1'b1 ;
          state <= 3 ;
        end
      end
      else if (state == 3) begin          // Wait for IODELAY to be available
        rst_data <= 1'b0 ;
        if (busy_data_d == 1'b0) begin
          state <= 4 ;
        end
      end
      else if (state == 4) begin          // Wait for occasional enable
        if (counter[8] == 1'b1) begin
          state <= 5 ;
        end
        end
        else if (state == 5) begin          // Calibrate slave only
        if (busy_data_d == 1'b0) begin
          cal_data_sint <= 1'b1 ;
          state <= 6 ;
        end
      end
        else if (state == 6) begin          // Wait for command to be accepted
        cal_data_sint <= 1'b0 ;
        if (busy_data_d == 1'b1) begin
          state <= 7 ;
        end
      end
      else if (state == 7) begin          // Wait for all IODELAYs to be available, ie CAL command finished
          cal_data_sint <= 1'b0 ;
        if (busy_data_d == 1'b0) begin
          state <= 4 ;
        end
      end
  end
  end

always @ (posedge gclk or posedge reset)        // Per-bit phase detection state machine
begin
if (reset == 1'b1) begin
  pdcounter <= 5'b1000 ;
  ce_data_inta <= 1'b0 ;
  flag <= 1'b0 ;              // flag is there to only allow one inc or dec per cal (test)
end
else begin
  busy_data_d <= busy_data_or[1] ;
    if (use_phase_detector == 1'b1) begin       // decide whther pd is used
    incdec_data_d <= incdec_data_or[1] ;
    valid_data_d <= valid_data_or[1] ;
    if (ce_data_inta == 1'b1) begin
      ce_data = mux ;
    end
    else begin
      ce_data = 64'h0000000000000000 ;
    end
      if (state == 7) begin
      flag <= 1'b0 ;
    end
      else if (state != 4 || busy_data_d == 1'b1) begin // Reset filter if state machine issues a cal command or unit is busy
      pdcounter <= 5'b10000 ;
        ce_data_inta <= 1'b0 ;
      end
      else if (pdcounter == 5'b11111 && flag == 1'b0) begin // Filter has reached positive max - increment the tap count
        ce_data_inta <= 1'b1 ;
        inc_data_int <= 1'b1 ;
      pdcounter <= 5'b10000 ;
      flag <= 1'b1 ;
    end
        else if (pdcounter == 5'b00000 && flag == 1'b0) begin // Filter has reached negative max - decrement the tap count
        ce_data_inta <= 1'b1 ;
        inc_data_int <= 1'b0 ;
      pdcounter <= 5'b10000 ;
      flag <= 1'b1 ;
      end
    else if (valid_data_d == 1'b1) begin      // increment filter
        ce_data_inta <= 1'b0 ;
      if (incdec_data_d == 1'b1 && pdcounter != 5'b11111) begin
        pdcounter <= pdcounter + 5'b00001 ;
      end
      else if (incdec_data_d == 1'b0 && pdcounter != 5'b00000) begin  // decrement filter
        pdcounter <= pdcounter + 5'b11111 ;
      end
      end
      else begin
        ce_data_inta <= 1'b0 ;
      end
    end
    else begin
    ce_data = all_ce ;
    inc_data_int = debug_in[1] ;
    end
end
end

assign inc_data = inc_data_int ;

assign incdec_data_or[0] = 1'b0 ;             // Input Mux - Initialise generate loop OR gates
assign valid_data_or[0] = 1'b0 ;
assign busy_data_or[0] = 1'b0 ;

assign incdec_data_im = incdec_data & mux;          // Input muxes
assign incdec_data_or[1] = incdec_data_im | incdec_data_or;      // AND gates to allow just one signal through at a tome
assign valid_data_im = valid_data & mux;          // followed by an OR
assign valid_data_or[1] = valid_data_im | valid_data_or;     // for the three inputs from each PD
assign busy_data_or[1] = busy_data | busy_data_or;       // The busy signals just need an OR gate

assign all_ce = debug_in[0] ;

IBUFDS #(
  .DIFF_TERM    (DIFF_TERM))
data_in (
  .I            (datain_p),
  .IB           (datain_n),
  .O            (rx_data_in)
);

//
// Master IDELAY
//
IODELAY2 #(
  .DATA_RATE            ("SDR"),
  .IDELAY_VALUE         (0),
  .IDELAY2_VALUE        (0),
  .IDELAY_MODE          ("NORMAL" ),
  .ODELAY_VALUE         (0),
  .IDELAY_TYPE          ("DIFF_PHASE_DETECTOR"),
  .COUNTER_WRAPAROUND   ("STAY_AT_LIMIT"), //("WRAPAROUND"),
  .DELAY_SRC            ("IDATAIN"),
  .SERDES_MODE          ("MASTER"),
  .SIM_TAPDELAY_VALUE   (SIM_TAP_DELAY)
) iodelay_m (
  .IDATAIN              (rx_data_in),      // data from IBUFDS
  .TOUT                 (),                // tri-state signal to IOB
  .DOUT                 (),                // output data to IOB
  .T                    (1'b1),            // tri-state control from OLOGIC/OSERDES2
  .ODATAIN              (1'b0),            // data from OLOGIC/OSERDES2
  .DATAOUT              (ddly_m),          // Output data 1 to ILOGIC/ISERDES2
  .DATAOUT2             (),                // Output data 2 to ILOGIC/ISERDES2
  .IOCLK0               (rxioclk),         // High speed clock for calibration
  .IOCLK1               (1'b0),            // High speed clock for calibration
  .CLK                  (gclk),            // Fabric clock (GCLK) for control signals
  .CAL                  (cal_data_master), // Calibrate control signal
  .INC                  (inc_data),        // Increment counter
  .CE                   (ce_data),         // Clock Enable
  .RST                  (rst_data),        // Reset delay line
  .BUSY                 ()                 // output signal indicating sync circuit has finished / calibration has finished
);

//
// Slave IDELAY
//
IODELAY2 #(
  .DATA_RATE            ("SDR"),
  .IDELAY_VALUE         (0),
  .IDELAY2_VALUE        (0),
  .IDELAY_MODE          ("NORMAL" ),
  .ODELAY_VALUE         (0),
  .IDELAY_TYPE          ("DIFF_PHASE_DETECTOR"),
  .COUNTER_WRAPAROUND   ("WRAPAROUND"),
  .DELAY_SRC            ("IDATAIN"),
  .SERDES_MODE          ("SLAVE"),
  .SIM_TAPDELAY_VALUE   (SIM_TAP_DELAY)
) iodelay_s (
  .IDATAIN              (rx_data_in),  // data from IBUFDS
  .TOUT                 (),            // tri-state signal to IOB
  .DOUT                 (),            // output data to IOB
  .T                    (1'b1),        // tri-state control from OLOGIC/OSERDES2
  .ODATAIN              (1'b0),        // data from OLOGIC/OSERDES2
  .DATAOUT              (ddly_s),      // Slave output data to ILOGIC/ISERDES2
  .DATAOUT2             (),            //
  .IOCLK0               (rxioclk),     // High speed IO clock for calibration
  .IOCLK1               (1'b0),
  .CLK                  (gclk),        // Fabric clock (GCLK) for control signals
  .CAL                  (cal_data_slave), // Calibrate control signal
  .INC                  (inc_data),       // Increment counter
  .CE                   (ce_data),        // Clock Enable
  .RST                  (rst_data),       // Reset delay line
  .BUSY                 (busys)        // output signal indicating sync circuit has finished / calibration has finished
);

//
// Master ISERDES
//

ISERDES2 #(
  .DATA_WIDTH       (5),
  .DATA_RATE        ("SDR"),
  .BITSLIP_ENABLE   (BITSLIP_ENABLE),
  .SERDES_MODE      ("MASTER"),
  .INTERFACE_TYPE   ("RETIMED"))
iserdes_m (
  .D                (ddly_m),
  .CE0              (1'b1),
  .CLK0             (rxioclk),
  .CLK1             (1'b0),
  .IOCE             (rxserdesstrobe),
  .RST              (reset),
  .CLKDIV           (gclk),
  .SHIFTIN          (pd_edge),
  .BITSLIP          (bitslip),
  .FABRICOUT        (),
  .Q4               (data_out[4]),
  .Q3               (data_out[3]),
  .Q2               (data_out[2]),
  .Q1               (data_out[1]),
  .DFB              (),
  .CFB0             (),
  .CFB1             (),
  .VALID            (valid_data),
  .INCDEC           (incdec_data),
  .SHIFTOUT         (cascade));

//
// Slave ISERDES
//

ISERDES2 #(
  .DATA_WIDTH       (5),
  .DATA_RATE        ("SDR"),
  .BITSLIP_ENABLE   (BITSLIP_ENABLE),
  .SERDES_MODE      ("SLAVE"),
  .INTERFACE_TYPE   ("RETIMED")
) iserdes_s (
  .D                (ddly_s),
  .CE0              (1'b1),
  .CLK0             (rxioclk),
  .CLK1             (1'b0),
  .IOCE             (rxserdesstrobe),
  .RST              (reset),
  .CLKDIV           (gclk),
  .SHIFTIN          (cascade),
  .BITSLIP          (bitslip),
  .FABRICOUT        (),
  .Q4               (data_out[0]),
  .Q3               (),
  .Q2               (),
  .Q1               (),
  .DFB              (),
  .CFB0             (),
  .CFB1             (),
  .VALID            (),
  .INCDEC           (),
  .SHIFTOUT         (pd_edge));

reg [7:0] rxpdcntr = 8'h7f;
always @ (posedge gclk or posedge reset) begin
  if (reset)
    rxpdcntr <= 8'h7f;
  else if (ce_data)
    if (inc_data)
      rxpdcntr <= rxpdcntr + 1'b1;
    else
      rxpdcntr <= rxpdcntr - 1'b1;
end

endmodule

I keep getting the following error when I try to generate a netlist for this design in Xilinx Platform Studio:
ERROR:HDLCompiler:1511 - "/home/eamorr/Desktop/Dropbox/UCD/digitalEye/Atlys_HDMI_PLB_demo/project/pcores/hdmi_in_v1_00_a/hdl/verilog/serdes_1_to_5_diff_data.v" Line 82: Mix of blocking and non-blocking assignments to variable <inc_data_int> is not a recommended coding practice.
ERROR:EDK:546 - Aborting XST flow execution!
ERROR:EDK:440 - platgen failed with errors!
make: *** [implementation/system_microblaze_0_wrapper.ngc] Error 2

I'm totally stuck and don't know what to do.

A: For inferring sequential logic for synthesis, you should use nonblocking assignments (<=) instead of blocking assignments (=).  For example, change:
  ce_data = mux ;

to:
  ce_data <= mux ;

A: That is from the HDMI example on the website digilentic I assume.
Look at all the inc_data_int assignments:
inc_data_int <= 1'b1 ;
inc_data_int <= 1'b0 ;
inc_data_int = debug_in[1] ;

I would comment out the last one since I assume it is for debugging purposes.
(I got the HDMI working like that.)


text:
Q: Parse string with square brackets to json I would like to parse this string to Json:
String str="[{\"property\":\"insert_date\",\"direction\":\"ASC\"}]"

I have tried with this:
dynamic myObject=Newtonsoft.Json.JsonConvert.DeserializeObject(str)

but it returns some JArray.
I would like to read values simple like:
String dir=myObject.direction;

One option is to parse string and remove square object from string. Than it would work. But i would like to do it on more proper way.

A: One way is to create a class and deserialize it as a List<ThatClass>.
For example:
public class Foo
{
    [JsonProperty("property")]
    public string Property { get; set; }
    [JsonProperty("direction")]
    public string Direction { get; set; }
}

and use it like this:
var foos = JsonConvert.DeserializeObject<List<Foo>>(str);
var foo = foos.First();
Console.WriteLine(foo.Direction);

The other way is using dynamic, and simply accessing the first element of the JArray:
String str = "[{\"property\":\"insert_date\",\"direction\":\"ASC\"}]";
dynamic objects = JsonConvert.DeserializeObject<dynamic>(str);
Console.WriteLine(objects[0].direction);

A: Well I suppose you simply need to do this:
String dir = myobject[0].direction;

It could be the best option I think


text:
Q: Display sum of item quantity in PDF export I'm having issues displaying total quantity of all items at the bottom of my PDF export script I'm using with my Wordpress site.
I've been able to display total quantity of each item using
<?php echo esc_html( $item->get_quantity() ) ?>

Then I want to calculate the sum of all item quantities and show that as a single figure at the bottom of the table
Would I use
echo sum_array ( $item->get_quantity() )

A: I hope you are showing each quantity via some loop, if yes then before loop define a variable like
$sum = 0;

Now change  code like this (inside loop):

  <?php
     $sum += (int)$item->get_quantity();
     echo esc_html( $item->get_quantity() ) ?>

And now in the end use this $sum variable to show total quantity.
<?php echo $sum;?>


text:
Q: ¿Cómo descarto cambios no indexados en Git? ¿Cuál es la mejor manera de descartar los cambios de mi copia de local de trabajo que no están indexados aún?

*

*git stash save --keep-index

*git checkout -- .

*git-clean

*git diff | git apply --reverse

*git clean -df

A: Debería ser una combinación de git checkout -- . y git clean -df
git checkout -- . y git diff | git apply --reverse no tienen en cuenta los archivos que no están trackeados.
git stash  sirve pero se guardan copias de los objetos.
git clean -df descarta todos los archivos y directorios que no están bajo control de versiones. Pero no descarta las modificaciones de los archivos que si estan bajo control.
Hay que combinar ambos:
git checkout -- .
git clean -df

A: Si por indexados, de verdad quisiste decir, en el index, osea, en el staging area, puedes probar primero con:
$ git clean -n  # Y vemos que archivos se irán a borrar
would remove archivo_no_en_el_index1
would remove archivo_no_en_el_index2
would remove archivo_no_en_el_index3
$ git clean -f  # Si nos gusta lo que vemos, entonces le ponemos el parámetro -f

Si quieres salvar los archivos que tienes en tu workdir, primero has un:
$ git stash push -m "nombre de estos cambios"

Esto aplica con archivos que ya están trackeados; si aún no lo están, añadelos con git add <archivos a trackear>, y ahora si repite el comando de arriba.
Y se guardarán en una cola a la que podrás acceder con:

*

*git stash list, para ver la cola y sus índices

*git stash apply "stash@{<numero de stash>}", para aplicar los cambios que habías guardado en el stash

*git stash clean, para no ser cochino y tener un stash limpio luego de los cambios aplicados


text:
Q: Skip the open file I have the code below that opens each .xlsx file in a folder and calls another sub to it.  When it reaches the file that is open (unavoidable to have it open due to preceding subs), I need this to skip this file and continue.  This was modified from an online source as I don't fully comprehend using paths.  Thanks in advance!
Sub OpenFilesVBA()
    Dim Wb As Workbook
    Dim strFolder As String
    Dim strFil As String

    Application.ScreenUpdating = False

    strFolder = Application.ActiveWorkbook.path
    strFil = Dir(strFolder & "\*.xlsx*")
    Do While strFil <> vbNullString
        Set Wb = Workbooks.Open(strFolder & "\" & strFil)
'===========Run Objective Macro==========================================
        Call PoG_Report_Prep
'========================================================================
        ActiveWorkbook.Save
        Wb.Close False
        strFil = Dir
    Loop
End Sub

A: Presumably the file containing this code is saved as .xlsm (rather than .xlsx), which means the file will be skipped as the code only looks for files saved as .xlsx
If the file is saved as .xlsx you could check whether the file being opened matches the filename of the current file only run the code if the names are different. See example code below. MsgBox statements for testing purposes only, remove these in the final code.
Sub OpenFilesVBA()
    Dim Wb As Workbook
    Dim strFolder As String
    Dim strFil As String
    Dim strActiveFil As String '

    Application.ScreenUpdating = False

    strFolder = Application.ActiveWorkbook.Path
    strActiveFil = Application.ActiveWorkbook.Name
    strFil = Dir(strFolder & "\*.xlsx*")
    Do While strFil <> vbNullString
        MsgBox strFil
        If strFil <> strActiveFil Then
            MsgBox "run" '
            Set Wb = Workbooks.Open(strFolder & "\" & strFil)
'===========Run Objective Macro==========================================
            'Call PoG_Report_Prep
'========================================================================
            ActiveWorkbook.Save
            Wb.Close False
            strFil = Dir
        Else
            MsgBox "not run"
            strFil = Dir
        End If
    Loop
End Sub

A: I ended up doing a save as in a new (non-.xlsx) format and killing the original file. I used .xlsm to keep the original formatting, but .csv worked also. This comes from a report that is downloaded, so getting a new copy of the killed original isn't difficult should I need it.  The first step of my entire module is as follows:
'OF = Original File
Dim strFullName As String, OF As String, CurrentWB As Workbook
Set CurrentWB = ActiveWorkbook
strFullName = CurrentWB.path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) &
".xlsm"

OF = Application.ActiveWorkbook.FullName
ActiveWorkbook.SaveAs Filename:=strFullName,
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

'' Delete Original File
Kill OF

A: This should work. As long as the file that contains this code is saved as *.xlsm
Option Explicit

Sub OpenFilesVBA()
    Dim Wb As Workbook
    Dim strFolder As String
    Dim strFil As String
    Dim fso As Object
    Dim fil As Object
    Dim fldr As Object

    Application.ScreenUpdating = False

    Set fso = CreateObject("Scripting.FileSystemObject")

    Set fldr = fso.GetFolder(Application.ActiveWorkbook.Path)

    For Each fil In fldr.Files
        If LCase(fso.GetExtensionName(fil.Path)) = "xlsx" Then
            Set Wb = Workbooks.Open(fil.Path)
'===========Run Objective Macro==========================================
            Call PoG_Report_Prep
'========================================================================
            ActiveWorkbook.Save
            Wb.Close False
            Set Wb = Nothing
        End If
    Next

    Set fil = Nothing
    Set fldr = Nothing
    Set fso = Nothing

    Application.ScreenUpdating = True

End Sub

A: Check the status of the workbook first:
Set Wb = Workbooks.Open(strFolder & "\" & strFil)
If Not Wb.ReadOnly Then '// workbook is readonly
    PoG_Report_Prep
    Wb.Save
End If

Wb.Close
Set Wb = Nothing

If the ReadOnly status after opening is True then we can probably assume that the workbook was already open elsewhere before you opened it in code.
It's a bit dirty, but would work for your purpose.


text:
Q: TCP Packet Encode/Decode I'm learning c++ and coming from a Network Engineer background, and it is fun for me to program something that I'm familiar with it on the network side. I started creating a BGP speaker.
Here is my environment:
[mybgp]<------------TCP-Port-179------------->[bird]
Here is my current code.
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>

#define BIND_ADDR INADDR_ANY
#define BIND_PORT htons(179)

int createServerSocket(){
    //Create Socket
    int serverSocket = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket < 0) {
        fprintf(stderr, "socket(): %s\n", strerror(errno));
        return 1;
    }
    return serverSocket;
}

int createBind(const int &serverSocket, sockaddr_in &serverAddr){
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = BIND_PORT;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    int bind_ret = bind(serverSocket, (sockaddr *) &serverAddr, sizeof(serverAddr));
    // if (bind(serverSocket, (struct sockaddr*) &serverAddr, sizeof(serverAddr)) == -1) {
    //     std::cerr << "Can't bind to ip/port";
    //     return -2;
    // }
    if (bind_ret < 0) {
        fprintf(stderr, "bind(): %s\n", strerror(errno));
        close(serverSocket);
        return 1;
    }
    return bind_ret;
}

int createListener(const int &serverSocket){
    int amount;
    int listen_ret = listen(serverSocket, 3);
    if (listen_ret < 0) {
        fprintf(stderr, "listen(): %s\n", strerror(errno));
        close(serverSocket);
        return 1;
    }
    return listen_ret;

}

int acceptConnect(const int &serverSocket, sockaddr_in &clientAddr){
    fprintf(stderr, "waiting for any client...\n");
    char ip_str[INET_ADDRSTRLEN];
    socklen_t caddr_len = sizeof(clientAddr);
    int serverConn = accept(serverSocket, (sockaddr *) &clientAddr, &caddr_len);
    if (serverConn < 0) {
        fprintf(stderr, "accept(): %s\n", strerror(errno));
        close(serverSocket);
        close(serverConn);
        return 1;
    }
    inet_ntop(AF_INET, &(clientAddr.sin_addr), ip_str, INET_ADDRSTRLEN);
    fprintf(stderr, "accept(): new client from %s.\n", ip_str);
    return serverConn;

}

int main(){
    //Create Socket
    int serverSocket = createServerSocket();
    // declare server and client address struct
    // bind socket.
    sockaddr_in serverAddr, clientAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    int bind_ret = createBind(serverSocket, serverAddr);

    // listening for connection
    int listen_ret = createListener(serverSocket);
    int serverConn = acceptConnect(serverSocket, clientAddr);
    // we only do one at a time, no new client.
    char buffer[4048] = {0};
    char valread;
    valread = read( serverConn , buffer, 4048);
    printf("%s\n",buffer );
    close(serverSocket);
    return 0;
}

My current state is that I'm able to:

*

*Create Socket

*Bind the Socket to IP

*Listening

*Accept a Single Connection(Single thread for now)

*Received Data

At step 5, I received a gibberish TCP Message from the BGP speaker(BIRD). Knowing how the BGP Protocol works, this TCP message is in an OPEN Message Format. To establish BGP peering, mybgp and bird need to go back and for with different types of messages and agree.
For me to be able to accomplish this peering, I have to:

*

*Decode[Received Package]

*Encode[send package]

How can I decode/encode the TCP packet so I can start the process of BGP peering.


text:
Q: How Can I Merge Multiple Directories into One keeping the subdirectories I have multiple directories and each one contains multiple subdirectories. How do I send all subdirectories to the same directory?

A: What tool are you using? cp rsync scp
They all have a way to do a "recursive" function
I know with cp you can copy multiple recursive directories pretty easily. With cp you can list 100+ directories or files to copy, and what ever is listed last on your cp command is the destination for all.
cp --help shows
    Usage: cp [OPTION]... [-T] SOURCE DEST
      or:  cp [OPTION]... SOURCE... DIRECTORY
      or:  cp [OPTION]... -t DIRECTORY SOURCE...
    **Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.**
...
-R, -r, --recursive          copy directories recursively

Ex:
cp -rv /path/to/copy1 /path/to/copy2 /path/to/copy3 /dest/dir


text:
Q: ios6 mapkit error simulator after updating to ios6 and running my app in ios6 Simulator i get following error:
   2012-09-24 16:58:47.988 Pigeons[628:c07] <GEOTileSource: 0x99aa380>:
Error downloading     tiles Server Error: Error Domain=GEOErrorDomain Code=-204 "The operation couldn't be completed. (GEOErrorDomain error -204.)" UserInfo=0x19989ff0 {UnderlyingErrors=(
    "Error Domain=GEOErrorDomain Code=-204 \"The operation couldn\U2019t be completed. (GEOErrorDomain error -204.)\""
)}

Has anyone got any idea why this error occurs.
On device or older simulator the error doesn't occur.
Greetings,
Jaco

A: Seems this is just some internal problems downloading tiles from server for the new Apple maps. I also see similar errors, but they do not affect anything and are not related to your code.


text:
Q: Java Regex Explanation Can someone please explain the meaning of \\A and \\z to me? I am assuming that they have a special meaning in this regular expression because they are being escaped (but I could be wrong and they could just stand for A and z, respectively). Thanks!
private static final Pattern PATTERN = Pattern.compile("\\A(\\d+)\\.(\\d+)\\z");

A: This Java expression:
Pattern.compile("\\A(\\d+)\\.(\\d+)\\z")

produces this regex:
\A(\d+)\.(\d+)\z

where \A means "start-of-string" and \z means "end-of-string".
So, that pattern matches any string consisting of one or more digits, plus a decimal point, plus one or more digits.
For details about all aspects of Java regex notation, see the Javadoc for java.util.regex.Pattern.

A: \A means "start of string", and \z means "end of string".
You might have seen ^ and $ in this context, but their meaning can vary: If you compile a regex using Pattern.MULTILINE, then they change their meaning to "start of line" and "end of line". The meaning of \A and \z never changes.
There also exists \Z which means "end of string, before any trailing newlines", which is similar to what $ does in multiline mode (where it matches right before the line-ending newline character, if it's there).

A: check out this reference
http://www.regular-expressions.info/reference.html
according to that \A matches the start of input, and \z matches the end of input.
the reason why they have \\ before them instead of just 1 \ is because the \ is also being escaped.


text:
Q: async i/o and process results as they become available I has a simple console app where I want to call many Urls in a loop and put the result in a database table. I am using .Net 4.5 and using async i/o to fetch the URL data. Here is a simplified version of what I am doing. All methods are async except for the database operation. Do you guys see any issues with this? Are there better ways of optimizing?
   private async Task Run(){
        var items = repo.GetItems(); // sync method to get list from database
        var tasks = new List<Task>();

        // add each call to task list and process result as it becomes available
        // rather than waiting for all downloads
        foreach(Item item in items){
            tasks.Add(GetFromWeb(item.url).ContinueWith(response => { AddToDatabase(response.Result);}));
        }
        await Task.WhenAll(tasks); // wait for all tasks to complete.
    }

    private async Task<string> GetFromWeb(url) {
       HttpResponseMessage response = await GetAsync(url);
       return await response.Content.ReadAsStringAsync();
    }

    private void AddToDatabase(string item){
        // add data to database.
    }

A: Your solution is acceptable. But you should check out TPL Dataflow, which allows you to set up a dataflow "mesh" (or "pipeline") and then shove the data through it.
For a problem this simple, Dataflow won't really add much other than getting rid of the ContinueWith (I always find manual continuations awkward). But if you plan to add more steps or change your data flow in the future, Dataflow should be something you consider.

A: Your solution is pretty much correct, with just two minor mistakes (both of which cause compiler errors).  First, you don't call ContinueWith on the result of List.Add, you need call continue with on the task and then add the continuation to your list, this is solved by just moving a parenthesis.  You also need to call Result on the reponse Task.
Here is the section with the two minor changes:
tasks.Add(GetFromWeb(item.url)
    .ContinueWith(response => { AddToDatabase(response.Result);}));

Another option is to leverage a method that takes a sequence of tasks and orders them by the order that they are completed.  Here is my implementation of such a method:
public static IEnumerable<Task<T>> Order<T>(this IEnumerable<Task<T>> tasks)
{
    var taskList = tasks.ToList();

    var taskSources = new BlockingCollection<TaskCompletionSource<T>>();

    var taskSourceList = new List<TaskCompletionSource<T>>(taskList.Count);
    foreach (var task in taskList)
    {
        var newSource = new TaskCompletionSource<T>();
        taskSources.Add(newSource);
        taskSourceList.Add(newSource);

        task.ContinueWith(t =>
        {
            var source = taskSources.Take();

            if (t.IsCanceled)
                source.TrySetCanceled();
            else if (t.IsFaulted)
                source.TrySetException(t.Exception.InnerExceptions);
            else if (t.IsCompleted)
                source.TrySetResult(t.Result);
        }, CancellationToken.None, TaskContinuationOptions.PreferFairness, TaskScheduler.Default);
    }

    return taskSourceList.Select(tcs => tcs.Task);
}

Using this your code can become:
private async Task Run()
{
    IEnumerable<Item> items = repo.GetItems(); // sync method to get list from database

    foreach (var task in items.Select(item => GetFromWeb(item.url))
        .Order())
    {
        await task.ConfigureAwait(false);
        AddToDatabase(task.Result);
    }
}

A: Just though I'd throw in my hat as well with the Rx solution
using System.Reactive;
using System.Reactive.Linq;
private Task Run()
{
    var fromWebObservable = from item in repo.GetItems.ToObservable(Scheduler.Default)
                            select GetFromWeb(item.url);

    fromWebObservable
                    .Select(async x => await x)
        .Do(AddToDatabase)
        .ToTask();

}


text:
Q: ReactJs Todo List push state I have written the start of a todo list in reactjs and was looking to improve the functionality of how the todos are added to the state. Currently I am concat(ting) the value in put to an array which is in the state, then splicing off the selected li element. It seems to be a bit buggy when you add the first todo.  Should i be using reacts immutability helpers to acheive this? Seems overkill to add another thing that can be acheived in plain js.
//Input component
const Input = props => {
  return (

      <input
        className="form-control"
        value={props.value}
        onChange={props.update}
        type="text"
      />
      <button className="btn btn-default" onClick={props.handleClick}>
        Add Todo
      </button>

  );
};
//display list of todos
const Displaytodo = (props) => {
  const todolist = props.todo;
  const listItems = todolist.map((todo, index) =>

      {todo}

  );

  return
{listItems}
;
};
//controlled state component
class Layout extends React.Component {
  constructor() {
    super();
    this.state = { text: "Hello", todo: [], highlight: false };
  }
  update(e) {
    this.setState({ text: e.target.value });
  }
  handleClick() {
    const text = this.state.text;
    if (text.length > 0) {
      this.setState(
        { todo: this.state.todo.concat(text), text: "", highlight: false },
        function() {
          console.log(this.state.todo);
        }
      );
    } else {
      alert("please enter something");
    }
  }
  removeTodo(e) {
    this.state.todo.splice(e, 1);
    this.setState({ todo: this.state.todo });
  }

  changeHighlight(index, e) {
    const highlight = this.state.highlight;

    this.setState(prevState => ({
      highlight: !prevState.highlight
    }));
  }

  render() {
    return (

Todo List

              <Input
                value={this.state.text}
                update={this.update.bind(this)}
                handleClick={this.handleClick.bind(this)}
              />
              <Displaytodo
                removeTodo={this.removeTodo.bind(this)}
                todo={this.state.todo}
                changeHighlight={this.changeHighlight.bind(this)}
                highlight={this.state.highlight}
              />

    );
  }
}

const app = document.getElementById("app");

ReactDOM.render(<Layout />, app);

https://codepen.io/mhal12/pen/MomWVg
Also when the user clicks the green tick, it will highlight the row by toggling class 'highlight' off and on, but in console it giving an error. which links to
https://facebook.github.io/react/docs/error-decoder.html?invariant=94&args[]=onClick&args[]=boolean

A: Simply remove the onClick on .
As for the highlighting on each todo, it's a bit more complex. You have to have an id on each todo, and then pass the id to the changeHighlight function. You have to remove highlight from global state, and assign a highlight boolean on each todo. Then you have to display todos accordingly.
Same stuff for the removeTodo function, you pass in an id to remove it in the parent component.
Here's the full code :
const Input = props => {
  return (

      <input
        className="form-control"
        value={props.value}
        onChange={props.update}
        type="text"
      />
      <button className="btn btn-default" onClick={props.handleClick}>
        Add Todo
      </button>

  );
};
const Displaytodo = (props) => {
  const changeHighlight = function(id) {
    props.changeHighlight(id);
  }

  const removeTodo = function(id) {
    props.removeTodo(id);
  }

  const todolist = props.todo;
  const listItems = todolist.map((todo, index) =>

      {todo.text}

  );

  return
{listItems}
;
};
class Layout extends React.Component {
  constructor() {
    super();
    this.state = {text: "Hello", todo: []};
  }
  update(e) {
    this.setState({ text: e.target.value });
  }
  handleClick() {
    const text = this.state.text;
    if (text.length > 0) {
      this.setState(
        { todo: this.state.todo.concat({
          id: this.state.todo.length + 1,
          text: this.state.text,
          highlight: false
        }), text: ""},
        function() {
          console.log(this.state.todo);
        }
      );
    } else {
      alert("Please enter something");
    }
  }
  removeTodo(id) {
    let todos = this.state.todo;

    for (let i = 0; i < todos.length; i++) {
      let todo = todos[i];
      if (todo.id == id) {
        todos.splice(i, 1);
      }
    }

    this.setState({ todo: todos });
  }

  changeHighlight(id) {
    let todos = this.state.todo;

    for (let i = 0; i < todos.length; i++) {
      let todo = todos[i];
      if (todo.id == id) {
        todos[i].highlight = !todos[i].highlight;
      }
    }

    this.setState({
      todo : todos
    });
  }

  render() {
    return (

Todo List

              <Input
                value={this.state.text}
                update={this.update.bind(this)}
                handleClick={this.handleClick.bind(this)}
              />
              <Displaytodo
                removeTodo={this.removeTodo.bind(this)}
                todo={this.state.todo}
                changeHighlight={this.changeHighlight.bind(this)}
              />

    );
  }
}

const app = document.getElementById("app");

ReactDOM.render(<Layout />, app);


text:
Q: Asking for the 'last used row/col' with Excel C-API function `xlfGetDocument` returns values past the 'actual used range' I'm using a .NET library, Excel-DNA, that exposes Excel's C-API to C# code. Using the xlfGetDocument function like this (I specifically want ints):
int rowLast = ((int)(double)XlCall.Excel(XlCall.xlfGetDocument, 10, sheetName) > 0) ? (int)(double)XlCall.Excel(XlCall.xlfGetDocument, 10, sheetName) - 1 : 0;
int colLast = ((int)(double)XlCall.Excel(XlCall.xlfGetDocument, 12, sheetName) > 0) ? (int)(double)XlCall.Excel(XlCall.xlfGetDocument, 12, sheetName) - 1 : 0;

returns me a rowLast and a rowFirst that is somewhat beyond my data range. According to the Steve Dalton book "Financial Applications using Excel add-in development in C/C++", the '10' and '12' arguments to this function should return the last USED col/row. But this is not the case.
Why is this?
Following from getting the used-range of a sheet above, I'm using Excel-DNA to get the actual contents:
contentReference = new ExcelReference(0, rowLast, 0, colLast);
contents = (object[,])contentReference.GetValue();

How can I get the actual used range without applying a filter to contents (seems like that should just be unnecessary overhead)?

A: Because Excel uses a sparse matrix storage scheme it considers the last used row/column to be the row and column of the last cell that contains data or is formatted (or did contain data or formatting).
You are probably better off using the COM interface to do a Range.Find * if you want the real last used range.


text:
Q: Mapping numbers to letters I had an interview question asking this:

text file has following lines>
            1: A C D
            4: A B
            5: D F
            7: A E
            9: B C

*Every line has a unique integer followed by a colon and one or
  more letters. These letters are
  delimited spaces (one or more)>
                            #2 Write a short program in the language

of your choice that outputs a sorted
  list like
            A: 1 4 7
            B: 4 9
            C: 1 9
            D: 1 5
            E: 7
            F: 5

I'm not looking for someone to solve it, but I always get confused with problems like this.  I'd like to do it in C# and was wondering should I store each line in a 2d array?  What is the best way to handle this.  After storing it how do I relist each line with letters rather then numbers?
Just looking for pointers here.

A: You can solve the problem by creating a Lookup mapping letters to a collection of numbers. You can use the extension method ToLookup to create a Lookup.

Warning: Spoilers ahead
Using LINQ you can do it like this (breaks on invalid input):
var text = @"1: A C D
4: A B
5: D F
7: A E
9: B C";

var lookup = text
  .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
  .Select(
    line => new {
      Number = Int32.Parse(line.Split(':').First()),
      Letters = line.Split(':').Skip(1).First().Split(
        new[] {' '}, StringSplitOptions.RemoveEmptyEntries
      )
    }
  )
  .SelectMany(x => x.Letters, (x, letter) => new { x.Number, Letter = letter })
  .OrderBy(x => x.Letter)
  .ToLookup(x => x.Letter, x => x.Number);

foreach (var item in lookup)
  Console.WriteLine(item.Key + ": " + String.Join(" ", item.ToArray()));

A: The thing that will help you solve this
IDictionary<char, IList<int> >

Yet Another Linq Masturbatory Implementation ("Look Ma! No loops!")
using System;
using System.IO;
using System.Linq;

public static class Program
{
    public static void Main(string[] args)
    {
        File.ReadAllLines("input.txt")
            .Select(line =>
            {
                var split = line.Split(":".ToCharArray(), 2);
                return new { digit = split[0].Trim().Substring(0,1),
                     chars = split[1]
                        .Split(" \t".ToCharArray())
                        .Select(s=>s.Trim())
                        .Where(s => !String.IsNullOrEmpty(s))
                        .Select(s => s[0])
                    };
            })
            .SelectMany(p => p.chars.Select(ch => new { p.digit, ch }))
            .GroupBy(p => p.ch, p => p.digit)
            .ToList()
            .ForEach(g => Console.WriteLine("{0}: {1}", g.Key, string.Join(" ", g)));
    }
}

Of course you can replace GroupBy with ToLookup

A: In case you are familiar with LINQ the below code can give you what you are looking for:
var result = File.ReadAllLines("inFile").SelectMany(line =>
                {
                    var ar = line.Split(" ".ToCharArray());
                    var num = int.Parse(ar[0].Split(":".ToCharArray())[0]);
                    return ar.Skip(1).Select(s => new Tuple<string, int>(s, num));
                }).GroupBy(t => t.Item1).OrderByDescending(g => g.Count())
                .Select(g => g.Key + ": " + g.Select(t => t.Item2.ToString()).Aggregate( (a,b) => a + " " + b));
            File.WriteAllLines("outFile", result);

A: I know you said you didn't want full answers, but this kind of thing is fun. It looks like others have come up with similar solutions, but here's another way to represent it - in "one line" of code (but lots of brackets!) :)
var data = @"1: A C D
4: A B
5: D F
7: A E
9: B C";

Console.WriteLine(
    String.Join(
        Environment.NewLine,
        (from line in data.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
         let lineParts = line.Split(new[] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries)
         from letter in lineParts.Skip(1)
         select new { Number = lineParts[0], Letter = letter })
        .ToLookup(l => l.Letter, l => l.Number)
        .OrderBy(l => l.Key)
        .Select(l => String.Format("{0}: {1}", l.Key, String.Join(" ", l)))));

Oh, and would I write code like that in production? Probably not, but it's fun in an exercise like this!

A: I will use a Dictionary<string,List<int>> I will read the input and add 1 into the list at keys A,C,D, A at keys A,B etc, so having the result is just a lookup by letter.
So like this, in a non esoteric way:
 string inp = @"1: A C D
            4: A B
            5: D F
            7: A E
            9: B C";
            Dictionary<string, List<int>> res = new Dictionary<string, List<int>>();
            StringReader sr = new StringReader(inp);
            string line;
            while (null != (line = sr.ReadLine()))
            {
                if (!string.IsNullOrEmpty(line))
                {
                    string[] tokens = line.Split(": ".ToArray(),StringSplitOptions.RemoveEmptyEntries);
                    int idx = int.Parse(tokens[0]);
                    for (int i = 1; i < tokens.Length; ++i)
                    {
                        if (!res.ContainsKey(tokens[i]))
                            res[tokens[i]] = new List<int>();
                        res[tokens[i]].Add(int.Parse(tokens[0]));
                    }
                }
            }

res will contain the result of letter->list of numbers.

A: String parsing using Split(":") and Split(" ").
Then fill
Dictionary<int, List<string>>

and translate it into
Dictionary<string, List<int>>

A: You could store the input in an IDictionary, and reverse it to produce your output.
Take a look at this question.

A: I see that multiple similar (loops) and not so similar (linq) solutions were already posted but since i've written this i thought i'd throw it in the mix.
static void Main(string[] args)
{
    var result = new SortedDictionary<char, List<int>>();
    var lines = System.IO.File.ReadAllLines(@"input.txt");
    foreach (var line in lines)
    {
        var split = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
        var lineNumber = Int32.Parse(split[0].Substring(0,1));
        foreach (var letter in split.Skip(1))
        {
            var key = letter[0];
            if (!result.ContainsKey(key))
            {
                result.Add(key, new List<int> { lineNumber });
            }
            else
            {
                result[key].Add(lineNumber);
            }
        }
    }
    foreach (var item in result)
    {
        Console.WriteLine(String.Format("{0}: {1}", item.Key, String.Join(" ", item.Value)));
    }
    Console.ReadKey();
}

A: An important part of the interview process is asking about and verifying assumptions. Although your description states the file is structured as an integer followed by letters, the example you give shows the integers in increasing order. If that's the case, you can avoid all of the LINQ craziness and implement a much more efficient solution:
var results = new Dictionary<char, List<int>>();

foreach (var line in File.ReadAllLines(@"input.txt"))
{
    var split = line.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);
    var num = int.Parse(split[0].TrimEnd(':'));

    for (int i = 1; i < split.Length; i++)
    {
        char letter = split[i][0];
        if (!results.ContainsKey(letter))
            results[letter] = new List<int>();

        results[letter].Add(num);
    }
}


text:
Q: proof by natural deduction without premises I'm currently stuck on this question:

"Henry never wears his jacket and tie together at the same time. I.e. when Henry is dressed, he either doesn't wear his jacket, or he doesn't wear his tie, (or neither of the two items)."
Formalize the reasoning as a statement logic sequence by using the following variables:

*

*$k$: "Henry wears his jacket."

*$f$: "Henry wears his tie."

Prove the sequence using natural deduction.

I think the sequence would look like this:
$$\vdash \neg(k \land f)$$
But how do I prove this? Is it even possible without any premises?

A: Since the exercise claims that it is specifying some reasoning instead of merely a claim, then I agree with Ten O'Four that the best guess is that they must be specifying an argument of the form "Conclusion, since Premise." (However, it is technically incorrect to interpret 'I.e.,'—which starts the second sentence and is read "that is"—as "since".)
Premise: when Henry is dressed, he either doesn't wear his jacket, or he doesn't wear his tie, (or he wears neither of the two items).
$$(\lnot k \land f) \lor (\lnot k \land \lnot f) \lor (k\land \lnot f) $$
Conclusion: Henry never wears his jacket and tie together at the same time.
$$\neg(k \land f)$$
Argue using disributive laws.


text:
Q: Navigating back to the same Google Chrome page in Windows 8 after accessing another program I started developing Android apps using Eclipse IDE with Windows 7. In the course of developing I would be constantly consulting SO via Google Chrome and navigating back to Eclipse IDE to try out a solution that I found; and then back to SO if the solution didn't work.
Recently, I bought a computer with Windows 8, and each time I navigate back to Eclipse (which is on a taskbar on desktop) I lose the SO page that I was on and can't return to it.When I navigate to Google Chrome I just get a new page.I know it sounds so simple, but how do I navigate back to the  page I was on previously? ....(I have the same problem with Gmail)
(I would like to be able to continue working in the way I did with Windows 7; if that is possible.)

A: I think I found the answer to my dilemma: Whenever I navigated back to desktop,  I did so by "grabbing" the current page from the top and "dragging" it down; thereby destroying it. I should rather, have navigated via the pop-up window in the top left corner of the screen, thereby conserving the present page..(elementary, my dear Watson)


text:
Q: How fast do the magnetic domains align with the external field? Let say we bring a normal (not super strong) magnet near sort of an unmagnetized iron block.
1) Do the magnetic domains align instantly? Does it make any difference on magnetization strength if we keep the magnet there for a second or for a minute?
2) If we do not use a strong enough external field, not all the domains align with the field. Am I right on this?

A: Sorry in advance for a brief answer: I am writing it fast and from the top of my head.
In general "no" and "no".
First answer is always "no". Have you heard of hysteresis? Look it up. The magnetization time depends on the type of ferromagnet (diamagnet) and on the strength of magnetic field (also temperature etc., but that is secondary). Second question is always definite "no" quantum mechanically. Magnetization is alignment of spin domains with respect to external magnetic field... Spins... Does spin vector have a definite alignment direction? Classically, there are cases when at max magnetization you can assume complete alignment.
However, if your interest is limited by some general physics course, you might be dealing with models, where approximation of instantaneous magnetization can be applicable and where domain walls-related effects are neglected. Then your answers are "yes" and "yes".
For the future: please, specify theoretical framework you are working in or at least cite sources that you are using. Otherwise the answers will always be broad and fairly useless...

A: *

*Answer is no. Alignment begins quickly. Nothing is instantaneous, but some magnetization begins to build right away. However the time scale to reach the ultimate equilibrium can be very long with ferromagnets; years even. Consider, for example, old-fashioned cans of food sitting in the larder. They would slowly get magnetized by earth's field over a period of years.

*I can't help thinking that you won't get full alignment at a non-zero temperature. For a ferromagnet this may be a very small effect (because the effective internal field is large), but I think the alignment is not quite complete at any temperature except absolute zero. At non-zero temperature, there is a competition between thermal fluctuation which tends to randomize the magnetization and internal + applied field which tends to increase the magnetization. In consequence, low applied field gives strong but not complete magnetization; strong applied field gives somewhat stronger magnetization.


text:
Q: Angular 2 - Plug in dynamic data from API with parameter to HTML? I'm fairly new to Angular 2, and I'm trying to find the best way to pass data to a nested component, call a method (REST API) using that data, and return the result into the parent HTML.
I understand how to pass the data - just use the @Input decorator on a variable in the child component.  That gets the data in.  Now I want to process that data and compute a result.  I can't do that in the constructor of the child component, because in the constructor, the input value has not yet been passed.  So where do I do it? Is there a render event I can use? I arrived at a solution that seems to work very well, I just don't know if I'm breaking some rules or causing issues.
Since I'm using Typescript, I can use setters.  I defined a setter for the input value, so in the setter I can run code to process the data.  Here is my working code:

import { Component, Input } from "@angular/core";
import { Http } from "@angular/http";
import { AppService } from "./../../services/appservice";
import { UserProfileService } from "./../../services/userprofileservice";

@Component({
    selector: "displayname",
    template: "{{displayName}}",
    providers: [AppService, UserProfileService]
})

export class DisplayName {

    public displayName: string;
    private profiler: UserProfileService;

       constructor(private appService: AppService) {
           this.profiler = new UserProfileService(this.appService);
       }

 @Input("login")
    set login(newLogin: string) {
        this.profiler.getUserProfile(newLogin, (profile) => {
            this.displayName = profile ? profile.displayName : newLogin;
        });
    }
}

What this code does is take a login name as input, fetch the user's display name, and set the displayName variable to the result.  If the result is null, it just returns the login name.  Using the @Input decorator on the setter works great, I've just never seen it done before in any examples so I don't know if there is a better way.
My HTML code looks like this (simplified for this example):

  <displayname [login]="user.loginName"></displayname>

Another way to ask this question is to back up to my basic use case, which I think must be very common.  How do you dynamically insert data from a REST API into an HTML page?  In this case I want to pass in the login name, and render the Display Name, that is fetched from a REST API.  In this case I don't need any HTML formatting (you can see my template is just a variable, no HTML) - is there a simpler way to do this?  Should I be using an @Output?
Thanks,
Randy


text:
Q: Why are there duplicate messages in the Build Output window in VS2015 and VS2017? I created a brand new WPF application.  The only code I added is the code which intentionally generates two warnings as shown below.
Both warnings show up twice in the Build Ouptut window in both Visual Studio 2015 and 2017.
Why is this?
How do I make the warnings only show up once?
    public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();

        if (false) {
            int i = 5;
        }
    }
}

Here is the output (paths shortened for clarity...sorry it's hard to read due to the word wrap...):
1>------ Build started: Project: HelloWorld, Configuration: Debug Any CPU ------
1>C:...\HelloWorld\MainWindow.xaml.cs(25,5,25,8): warning CS0162: Unreachable code detected
1>C:...\HelloWorld\MainWindow.xaml.cs(25,9,25,10): warning CS0219: The variable 'i' is assigned but its value is never used
1>C:...\HelloWorld\MainWindow.xaml.cs(25,5,25,8): warning CS0162: Unreachable code detected
1>C:...\HelloWorld\MainWindow.xaml.cs(25,9,25,10): warning CS0219: The variable 'i' is assigned but its value is never used
1>  HelloWorld -> C:...\HelloWorld\bin\Debug\HelloWorld.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
EDIT:  Here is a link to the full MS Build Output (Output Level: Detailed)
MS BUild Ouput Trace


text:
Q: given string= welcome to python. I want output as 'welcome-to-python', getting an error in following code def split_and_join(line):
    line=input('enter the string\n')
    w= line.split(' ')
    print('-'.join(w))
split_and_join(line)

Here I am getting following error.

Traceback (most recent call last):
    File "F:\python files\practice python\strprg1.py", line 5, in
      split_and_join(line)
  NameError: name 'line' is not defined

Thanks in Advance!

A: line=input('enter the string\n')

Should not be inside the function.
Move it before you call it.

A: when you call the split_and_join what is the line variable ? call split_and_join without any parameters
split_and_join()

or put line = input('enter the string\n') out side of the function
line=input('enter the string\n')
def split_and_join(line):
    ...
split_and_join(line)

A: When you call split_and_join the variable line isn't defined. Given your function, there's no need to pass in the variable as the first thing you do is to read it. This would do just fine:
def split_and_join():
    line=input('enter the string\n')
    w= line.split(' ')
    print('-'.join(w))

split_and_join()

A: The error is due to the fact that the function is called with a parameter line which you did not define before. There are two solutions:
1) Put the definition of line out of the function, and before calling the function, as follows:
def split_and_join(line):
    w= line.split(' ')
    print('-'.join(w))

line=input('enter the string\n')
split_and_join(line)

2) Remove the argument line from the function definition, and so call the function without any parameter, as follows:
def split_and_join():
    line=input('enter the string\n')
    w= line.split(' ')
    print('-'.join(w))

split_and_join()

A: In case you need a 1-liner:
print('-'.join(input().split()))

# welcome to python
# welcome-to-python


text:
Q: Render emoji in browser from JS I have a JSON object with strings defined like this: var obj = {text:"Iconic. \n\\ud83d\\udd25"}, where \ud83d\udd25 should be the fire emoji.
EDIT: The string is passed in this escaped format from an external source.
I then pass this value into a div as
var caption = document.getElementById('caption');
caption.innerHTML = obj.text;

I also have <meta charset="UTF-8"> set in my head.
How do I get this to render as the emoji rather than the unicode string?

A: Fixing this at source so that the data is not double escaped would be the best approach to solving this problem.
If you cannot do that, then you can wrap the data in double quotes to turn it into a string containing a JSON representation of a string, then parse that JSON.

const obj = {
  text: "Iconic. \\n\\ud83d\\udd25"
};
const text = JSON.parse('"' + obj.text + '"');
var caption = document.getElementById('caption');
caption.innerHTML = text;

    data
    data

    data
    data

NB: In a comment you said For example, new lines are coming through in the string as \\n so rendering as \n so I updated the code in  your example to match that. This won't work if that isn't the case.


text: Q: Coinciding linear operators on eigen values and eigen vectors. If f and g are two linear operators in a vector space L over C, which are coinciding on all eigen values and eigen vectors does it mean f=g ?


text:
Q: Alternative to using HttpGetAttribute I have a ASP .NET MVC 4 project
I have something like this
   public class FooController : ApiController
        {

            [HttpGet]
            public models.Terminal read(long id)
            {

            }
        }

Is there an alternative to using the attribute? Is there somewhere else in the Project I can specify that its a HttpGet request method rather than in the Controller?

A: No.  Well, not really.
Using the [HttpGet] attribute is a form of metaprogramming as you're trying to declare some additional information about the method.  The Controller is the interface between your clients and your API, so this is the place it belongs.  The Controller is responsible for handling HTTP requests and executing code appropriately, so an attribute that provides additional information (or a constraint) on how HTTP requests are handled belongs in the Controller.  So even if there was some way to achieve the same functionality without an attribute, you really shouldn't do it.


text:
Q: Allow selection on disabled form control in Angular 9 I'm using a dynamic form with Angular 9 and i'd like to select text on disabled fields but i'm not able to.
I use this form for both the edition and the readonly usage.
Here is an exemple of one of the inputs on my form
<input class="form-control" type="text" id="title" formControlName="title">

Do you now how i could allow a text selection on my form controls without enabling the edition on the field?
If you need more details about my code, feel free to ask.


text:
Q: Antlr4 tree parser I have problems with numbers like (9-34)*9 I have created a tree with antlr4.The tree performs the calculation steps, for +, -., * and /. The tree works perfectly for positive numbers, my problem is, for negative numbers, like when I enter (9-40)*10 or so, it doesn't work anymore.
My code is:
calculator:
    (d)*| ;

c:
    c '*' c | c '/' c | c '+' c | c '-' c | '(' c ')' | b | a ;
d:
     a '=' c ;

b :   '-'?[0-9]+;
a: [a-zA-Z][a-zA-Z0-9]*;

WS  :   [ \t\r\n]+ -> skip ;

A: (please be careful to verify your source before your post.  The grammar, as posted, is not valid ANTLR.  Probably because you changed rule names to a, b, etc. and forgot to keep Lexer rules uppercase.)
If I assume to be the case, here's a modified grammar to address your problem.
grammar calc
    ;

calculator: (d)*;

c
    : c '*' c
    | c '/' c
    | c '+' c
    | c '-' c
    | '(' c ')'
    | '-'? NBR // <-- The fix
    | ID
    ;
d: ID '=' c;

NBR: [0-9]+; // <-- removed the '-'?
ID:  [a-zA-Z][a-zA-Z0-9]*;

WS: [ \t\r\n]+ -> skip;

The source of the problem is, that by putting the - in the Lexer rule, ANTLR will match the "-40" as a NBR token, since it's a longer string of characters than "40".  The solution is to handle the negation as an alternative in you parser rule for c (aka expression)
It's always a good idea to use the ANTLR tool (aka grun) the the -tokens option to get a dump of your token stream to ensure that your Lexer rules are giving the parser the token stream that it needs.


text:
Q: If-else working, switch not I am making an app that has a grid of images with text and each one opens a different activity. It works fine but just for design purposes I want to replace my if-else statements with switch statements (which I assume I can do) however it doesn't work. Right now my working code to set the label on each image is:
if(position == 0)
        textView.setText(R.string.zero);
    else if(position == 1)
        textView.setText(R.string.one);
    else if(position == 2)
        textView.setText(R.string.two);
    else if(position == 3)
        textView.setText(R.string.three);
    else if(position == 4)
        textView.setText(R.string.four);
    else if(position == 5)
        textView.setText(R.string.five);
ect....

I want to use:
switch(position)
case 0:
   textView.setText(R.string.zero);
case 1:
   textView.setText(R.string.one);
case 2:
   textView.setText(R.string.two);
case 3:
   textView.setText(R.string.three);
case 4:
   textView.setText(R.string.four);

but when I did that ever label was the last one that I defined (in my example it would be "four"). I also have a similar code for each object to start a different intent with the position variable however that does the opposite and makes every intent equal to the first one. Is my syntax wrong or will this not work for my situation?

A: Using a break statement after each case should fix the problem.  I would also use a default statement as well after the last case.

A: This is the solution. You need to use break to avoid going through each case:
switch(position)
case 0:
   textView.setText(R.string.zero);
   break;
case 1:
   textView.setText(R.string.one);
   break;
case 2:
   textView.setText(R.string.two);
   break;
case 3:
   textView.setText(R.string.three);
   break;
case 4:
   textView.setText(R.string.four);
   break;

I would recommend to read the oracle documentation about the switch statement.

A: You need to break; after each statement in a case, otherwise execution flows down (all cases below the one you want will also get called), so you'll always get the last case.
switch(position) {
case 0:
    textView.setText(R.string.zero);
    break;
case 1:
    textView.setText(R.string.one);
    break;
case 2:
    textView.setText(R.string.two);
    break;
case 3:
    textView.setText(R.string.three);
    break;
case 4:
    textView.setText(R.string.four);
    break;
}

Here's the official tutorial explaining when to and when not to use break;.

A: You need to use break statement after eace case operations. In a switch-case statement if you dont use a break statement then all the cases after that specific one will be executed also
case 0:
   textView.setText(R.string.zero);
   break;

A: Don't forget to put break; after each case: like that:
switch(position){
case 0:
   textView.setText(R.string.zero);
   break;
case 1:
   textView.setText(R.string.one);
   break;
case 2:
   textView.setText(R.string.two);
   break;
case 3:
   textView.setText(R.string.three);
   break;
case 4:
   textView.setText(R.string.four);
   break;
}

A: In the Switch-case statements, you need to put break; after each case.
switch(position){
case 0:
   textView.setText(R.string.zero);
   break;
case 1:
  textView.setText(R.string.one);
  break;
case 2:
  textView.setText(R.string.two);
  break;
case 3:
  textView.setText(R.string.three);
  break;
case 4:
  textView.setText(R.string.four);
  break;
default:
    System.out.println("not available");
}

Also you need to put default: at last, because when all case are wrong that time perform default: action.
In the switch-case statement not forgot about break; and default action.

A: You need to break; after each branch:
switch (position) {
    case 0:
        textView.setText(R.string.zero);
        break; // <-- here
    // etc
}

Legitimate uses of switch when you don't break exist, those are called fall throughs; or because you return or throw.:
switch (someNumber) {
    case 0:
        return 0;
        // no need for break here
    case 1:
        throw new IllegalArgumentException();
        // no need to break here
    case 2:
        System.out.println("Oh, I got two!");
        // fall through
    case 3:
        return 3;
    default:
        System.out.println("Meh")
        // No need to break: last possible branch
}

return -1;

will return 3 even if you enter 2.
But otherwise you need to break.

A: Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
Switch is faster than if-else statement
Bottom line : Default is optional(works like else statement in switch), Break is mandatory.
Interesting fact: you won't see any compilation error, even if you forgot to place the break statement.

A: The switch needs a break with in each case. But in your case it could be done much simpler by defining an array as shown below.
String values = {R.string.zero, R.string.one, R.string.two, ... };

Use this to populate textView : textView.setText(values[position]);


text:
Q: Facebook pixel form submission tracking on gatsbyjs I'm trying to find a way on Gatsbyjs site to add custom Facebook pixel conversion when visitors submit the contact form. Couldn't figure it out even using facebook pixel documentation.
The plugin that I'm using - https://github.com/gabefromutah/gatsby-plugin-facebook-pixel
The event that I need to track is:
fbq('track', 'Lead', {content_name: 'ContactForm'});
Is it the best way to do it through button click on the contact form? If so, how do I add it in?
Any help would be appreciated. Thanks

A: This plugin (gatsby-plugin-facebook-pixel) only works in production build (i.e gatsby build && gatsby serve), perhaps that's why you're not seeing any tracking?
It sounds like you only want to track successful submission? If so, you might want to avoid only tracking button click and instead track after the submission's been received. For example, if you're using fetch to send your data, it might look roughly like so:
const submitHandler = (data) => fetch(url, {
  method: 'POST',
  body: JSON.stringify(data)
})
  .then(res => res.json())
  .then(res => {
    if (res.ok) {
      fbq('track', ...)
    }
  })
  .catch(err => ...)


text:
Q: Appending to $PATH vs using aliases: Which is better? In at least some cases, aliases and adding $PATH locations can be used interchangeably. For example, looking at the python tool couchapp, I need to either alias the executable (as helpfully described here) or make the executable available via $PATH.
These are the two lines that can achieve this:
alias couchapp="~/Library/Python/2.7/bin/couchapp"

OR
export PATH=$PATH:~/Library/Python/2.7/bin/

Is there a very definite 'better' option of these two? Why or why not?

A: *

*An alias is a shell feature: any environment that invokes utilities directly, without involving a shell will not see aliases.

*

*Note: Even when calling shell commands from languages such as Python (using, e.g., os.system()), user-specific shell initialization files are typically not called, so user-specific aliases still won't be visible.

*A directory added to the $PATH environment variable is respected by any process that tries to invoke an executable by mere filename, whether via a shell or not.

*

*Similarly, this assumes that any calling process sees the $PATH environment-variable additions of interest, so additions made by the user-specific initialization files are typically not seen, unless the calling process was launched from an interactive shell.

Lookup cost
If you know that a shell will be involved in invoking your utility, you can keep overhead down by defining aliases that invoke your executables by their full path.
Of course, you need to do this for each executable you want to be callable by name only.
By contrast, adding directories to the $PATH variable potentially increases the overhead of locating a given executable by mere filename, because all directories listed must be searched one by one until one containing an executable by the specified name is found (if any).
Precedence
If a shell is involved, aliases take precedence over $PATH lookups.
Of course, later alias definitions can override earlier ones.
If no shell is involved or no alias by a given name exists, $PATH lookups happen in the order in which the directories are listed in the variable.

A: As your example shows, $PATH allows you to do one line for all of your executables in that location. For that reason I use the latter option. You can also chain many $PATH statements together, allowing you to easily add many more locations to your "executables" from the command line.
If for some reason you do not want to make all of the executables available alias would be better.


text:
Q: Store HTML and CSS of target container I have a container div containing some html - for example:

Bla bla

     Send

and some css related to the container:
#container {background:red;}
#container h1 {font-size:30px;}
#container .myItem {color:red;font-size:12px;}

I would like to store all the html inside the container and all the related css to it in some variable/database/whatever is available, and then load it back on a new page. The content is dynamic and it's up to the user to style the container and it's content.
How could I accomplish this? One way I was thinking was to retrieve all this properties using javascript and than store them somehow in the database to load them back later or try to do this with html5 webstorage.
Is there any plugin that does this?
EDIT:
I've also tried html2canvas but it's support for css3 is not good enough to render the elements correctly.

A: If the CSS and HTML are both stored within the page, you can just grab the content (based on the wrapper) and store it in localStorage (if this works for your purpose).
An example with jQuery and localStorage... you will need to change where things are being saved from to fit your case.
jsFiddle
Saving the items:
var html = $('#container').html();
localStorage.setItem('html', html);

var css = $('#csscontainer').html();
localStorage.setItem('css', css);

Pulling/showing the items:
var showHtml = localStorage.getItem('html');
var showCss = localStorage.getItem('css');

$('#showHtml').html(showHtml);
$('#showCss').html(showCss);


text:
Q: My spacecraft was built backwards; gimbal always lies I put a probe into orbit and is now on a Kerbin escape path, but it has a really annoying quirk; the engines are mounted to the "top" of the probe so the gimbal always seems flipped 180°.  In order to do any maneuvers, I need to look where the marker is, then flip the ship.
Can I get a retrograde marker to use instead?  Can I just fix this some other way in the game?  Can I flip a bit or whatever in the save file to perform this innocuous change?

A: You could do this in the config file, but it's easier to make this change in game (although you may have to do it each time you switch to it).  This requires that you have a docking port pointed in the prograde direction.  If you do, right click on that, and select Control from here, and you're done.  The gimble will flip, and everything will be pointed in the correct direction.
If you don't have part that you can do a Control from here on (and is pointed the correct way), then it is possible to make the change in your persistence file.  In a text editor, open %KSP_DIR%/saves/<save name>/persistent.sfs, and under the VESSELS section, find the probe you want to edit.  Find the PART section for the probe body, and change the value for rotation.  I don't know the format for that value*, so this could use some experimentation, but set it to 0,0,0,-1 and see what that does.
*I don't have time right now to test this to tell you for sure what it should be, otherwise I would.

A: For anyone else out there with the same problem: MechJeb has a very useful feature in its Smart A.S.S. in case you accidentally build your ship upside down:

*

*Use the Maneuver Planner or map view to create a node that does what you want

*Open Smart A.S.S.

*Set it to "ADV" mode

*As Reference select "MANEUVER_NODE"

*As Direction select "BACK"

*Hit Execute

*MechJeb will now point the vessel "away" from the node.

*Execute your burn manually

It may seem complicated, but it was simple enough to save two Kerbins on their return trip from Minmus.


text:
Q: How can I insert non-repeated records into BigQuery using the bigrquery library? I'm trying to insert a non-repeated record into BigQuery but keep receiving the error Array specified for non-repeated field: record..
My question is: How can I insert non-repeated records into BigQuery using the bigrquery library?
If I have the following schema:
bqSchema <- bq_fields(list(
  bq_field(name = "record", type = "RECORD", fields = list(
    bq_field(name = "a", type = "INTEGER"),
    bq_field(name = "b", type = "STRING")
  ))
))

And this data frame:
df <- tibble(
  record = list(
    a = 1,
    b = "B"
  )
)

Inserting the data as below causes the error in BigQuery:
bq_perform_upload(bqTableObj, df, fields = bqSchema)
# Array specified for non-repeated field: record

I think this is in part because bigrquery converts the dataframe to JSON with jsonlite::stream_out(), but doesn't use the argument auto_unbox = TRUE, resulting in arrays, rather than objects. This results in the following newline delimited JSON being sent to BigQuery:
{"record": [1]}
{"record": ["B"]}

The correct NDJSON that should be sent to BigQuery I believe should be:
{"record": {"a": 1, "b", "B"}}

Has anyone had this problem before, or have ideas how I can resolve this?

A: You should try the following where you set mode = "REPEATED" :
bqSchema <- bq_fields(list(
  bq_field(name = "record", type = "RECORD", mode = "REPEATED",
           fields = list(bq_field(name = "a", type = "INTEGER"),
                         bq_field(name = "b", type = "STRING")
                         )
           )
 ))


text:
Q: IOS 6 Cache Manifest I'm noticing some oddities now that I'm checking out the iOS 6 <--> OS X Web Console. It seems that when I update a css file that's supposed to be cached, iOS 6 downloads the new version automatically even if I do not update the manifest file. Under 5.x.x I had expected behavior once I got it all sorted out.
myapp.appcache
CACHE MANIFEST

#Version 1.42505

CACHE:
css/main.css
images/myimage.jpg

etc...

The debugging tools make it clear the the file has NOT be redownloaded when there's not a change (~100b "transfered" on the 5kb file).
Furthermore, myimage.jpg will often transfer when neither itself nor the manifest is updated.
Any suggestions or at least confirmations of similar behavior?


text:
Q: React Native - Strange error caught - {"line":25722,"column":33,"sourceURL":"http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify= My react native application is running on android virtual device (API 23)
Android Gradle Plugin Version - 7.2.0
Gradle Version - 7.4.2
build.gradle
buildscript {
    ext {
        kotlinVersion = "1.5.0"
        RNNKotlinVersion = kotlinVersion
        buildToolsVersion = "31.0.0"
        minSdkVersion = 23
        compileSdkVersion = 31
        targetSdkVersion = 28
...

}
An http request (http://10.0.2.2:8888/myapp/auth) is made to confirm login to my localhost server.
I get an http response code 500 (email/password is incorrect).
AccessService calls FetchTool to fetch http.
FetchTool throws a new Error('incorrect email/password').
But AccessService receives a ghost different error as described below:
LOG ERROR..:{"line":25722,"column":33,"sourceURL":"http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false&app=com.myapp&modulesOnly=false&runModule=true"}

Why don't I get the error 500 thrown in FetchTool in AccessService's catch?
export default class AccessService {

    static confirmLogon(email, password) {

        const login = {
            email: email,
            password: password
        };

        const headers = {
            'Content-Type': 'application/json',
        }

        const uri = properties.appurl + '/auth';

        return FetchTool.post(uri, headers, login)
            .then(credentials => {
                return credentials;
            })
            .catch(error => {
                // the ghost error is captured here
                console.log('ERROR..:' + JSON.stringify(error))
                throw error;
            });
    }

}

export default class FetchTool {

    static post(uri, headers, playload) {
        return this.executeRequest(uri, headers, playload, 'POST');
    }

    static executeRequest(uri, headers, playload, method) {

        if (headers['Content-Type'] && headers['Content-Type'] == 'application/json') {
            playload = JSON.stringify(playload);
        }

        const requestInfo = {
            method: method,
            body: playload,
            headers: headers
        }

        //uri = http://10.0.2.2:8888/myapp/auth

        return fetch(uri, requestInfo)
            .then(response => {

                if (response.ok) {
                    //some code return json ok
                } else {
                    return response.text()
                        .then(responseText => JSON.parse(responseText))
                        .then(responseObject => {
                            if(responseObject.statusCode === 500) {
                                //the error scenario takes place here
                                throw new Error(JSON.stringify(responseObject));
                            } else {
                                // some code
                            }
                        })
                }
            })

    }

}

A: Just remove JSON.stringify like so:
console.log('ERROR: ', error)

And you 'll see the error message as expected.


text:
Q: Combine two sklearn pipelines into one I have a text preprocessing Pipeline:
pipe = Pipeline([
  ('count_vectorizer', CountVectorizer()),
  ('chi2score', SelectKBest(chi2, k=1000)),
  ('tfidf_transformer', TfidfTransformer(norm='l2', use_idf=True)),
])

and I want to perform cross validation on a pipeline with multiple estimators. This is a solution that is working, but honestly I don't really like it. There should be a better way to do it. Maybe somehow convert the Pipeline to a transformer?
pipe_nb = Pipeline([*pipe.steps, ('naive_bayes', MultinomialNB())])

That's an approach that I perceive as an ideal one, but unfortunately it does not merge steps into new pipeline and causes issues.
pipe_nb = make_pipeline(
  pipe,
  MultinomialNB()
)

How to merge two pipelines into one, in a nice pythonic way?

A: Why do not simply append a new step into pipe.steps rather than to recreate a new one?
pipe.steps.append(('naive_bayes', MultinomialNB()))
print(pipe)

# Output
Pipeline(steps=[('count_vectorizer', CountVectorizer()),
                ('chi2score', SelectKBest(k=1000, score_func=1)),
                ('tfidf_transformer', TfidfTransformer()),
                ('naive_bayes', MultinomialNB())])

Or:
# Don't forget the *
pipe2 = make_pipeline(*pipe, MultinomialNB())
print(pipe2)

# Output
Pipeline(steps=[('countvectorizer', CountVectorizer()),
                ('selectkbest', SelectKBest(k=1000, score_func=1)),
                ('tfidftransformer', TfidfTransformer()),
                ('multinomialnb', MultinomialNB())])


text:
Q: Insert Query in ASP.Net a and c variable's errorNot inserting properly, Invalid column or can't convert to char from int if I add '' to it. Also Hardcoding a value in the string makes it work there.
" and ' have been tried..
            int a = Convert.ToInt32(TextBox1.Text);
            int c = Convert.ToInt32(TextBox3.Text);

            string a3 = a.ToString();
            string c3 = c.ToString();

            string a2 = TextBox1.Text;
            string c2 = TextBox3.Text;

            int i1 = 77;
            int i2 = 5;

            string b = TextBox2.Text;
            string d = TextBox4.Text;
            string ee = TextBox5.Text;
            string f = TextBox6.Text;
            string g = TextBox7.Text;
            string h = TextBox8.Text;

            //RETRIVE VALUES FROM CURRENT BOXES
            //(Id,Username,Age,Gender,Contact,Email,City,Password)
            string update = dbhelper.ExecuteScalar("INSERT INTO
            dbo.UserDetails VALUES(a,'b',c,'d','ee','f','g','h') ");

            Action_Performed.Text = "User Details Updated Successfully";

A: You could solve it by doing something like this, important to use SQL parameters to avoid sql injection through your inputs;
string sql =  "INSERT INTO UserDetails(a,b,c) VALUES(@a,@b,@c)";

using (SqlConnection connection = new SqlConnection(connectionString))
{
   connection.Open();
   SqlCommand command = new SqlCommand(queryString, connection);
   command.Parameters.AddWithValue("@a", a);
   command.Parameters.AddWithValue("@b", b);
   command.Parameters.AddWithValue("@c", c);
   command.ExecuteNonQuery();
}


text:
Q: InvalidArgumentException: Message: invalid argument: invalid locator error coming I was doing a project related to flight price when I truing to web scrape dept time I got the error .
url is https://flight.yatra.com/air-search-ui/dom2/trigger?ADT=1&CHD=0&INF=0&class=Economy&destination=BOM&destinationCountry=IN&flexi=0&flight_depart_date=22%2F01%2F2022&hb=0&noOfSegments=1&origin=DEL&originCountry=IN&type=O&unique=254010891105&viewName=normal
my code was:
dept_time=driver.find_elements("//div[@class='i-b col-4 no-wrap text-right dtime col-3']")
dept= []
for i in dept_time:
    a = i.get_attribute('innerText')
    print(a)
    dept.append(a)
print(dept)

I also tried "//div[@class='i-b pr']
but same error I received

A: Instead of
dept_time=driver.find_elements("//div[@class='i-b col-4 no-wrap text-right dtime col-3']")

Try
dept_time=driver.find_elements_by_xpath("//div[@class='i-b col-4 no-wrap text-right dtime col-3']")

Or
dept_time=driver.find_elements(By.XPATH, "//div[@class='i-b col-4 no-wrap text-right dtime col-3']")

Also, don't forget about wait / delay to use with your code to let the elements loaded before you are reading their inner texts.