text:
Q: Promise.resolve() isn't being executed I'm trying to save a brand new object into my database but only if it doesn't exists yet. For this, I created this method in other to make two validations: (1) if object is missing and (2) if object already exists. If everything is ok, then save. Code is below:
exports.new = (obj) => {
  return Promise.resolve(() => {
    if (!obj) throw Error('object is missing');

    this.getOneAsync(obj).then(repeatedObj => {
      if (repeatedObj.length != 0) throw Error('Object already saved!');
      return obj;
    });
  }).then(obj => {
    var newObj = createModel(obj);

    return newObj.saveAsync();
  })
};

Unfortunately, Promise.resolve() aren't being executed. My code jump straight to then() clause and obj isn't what I expected, always returning { length: 0, name: '' }.
What am I doing wrong? Any help will be appreciated.

A: Promise.resolve() is executed, but not the function you pass to it. Promise.resolve immediately resolves the promise with the value you pass to it. It does not call the function. .then is called with the function you pass to Promise.resolve.
Promise.resolve is not useful in your case. Instead do something like
exports.new = (obj) => {
  if (!obj) return Promise.reject(new Error('object is missing'));

  return this.getOneAsync(obj)
    .then(repeatedObj => {
      if (repeatedObj.length != 0) throw Error('Object already saved!');
      var newObj = createModel(obj);
      return newObj.saveAsync();
    });
};

A: After clarifications here, this way works using Promise.resolve():
exports.new = (obj) => {
  return Promise.resolve().then(() => {
    if (!obj) throw Error('object is missing');

    this.getOneAsync(obj).then(repeatedObj => {
      if (repeatedObj.length != 0) throw Error('Object already saved!');
      return obj;
    });
  }).then(obj => {
    var newObj = createModel(obj);

    return newObj.saveAsync();
  })
};


text:
Q: Bootstrap Modal not working(nothing happens when button clicked) I have importaed javascript into my layout template:
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js">

I have the following bootstrap modal triggered by a button

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Did I forget to do something here? I have never done a bootstrap modal before but this should open a modal upon hitting the button correct? I thought it was because perhaps I was missing bootstrap javascript but I imported it from cloudflare min file and still doesn't do anything. What I am missing?

A: You need to use a script tag for the bootstrap JS cdn not a link tag like so:

Also make sure you are using jQuery

A: Bootstrap JavaScript is written in a script tag, not a link one. The link one is for CSS.
Yours:
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js">

It should be:

You also need to include jQuery like this

Otherwise your code is just fine!

redpajama_set_name: RedPajamaStackExchange


text:
Q: @After each test, remove all users - JUnit I have the following tests to add users to a list:
@Test
public void testTheSizeOfUserListAfterAddingThreeUsers() {
    User james = new User(001, "JamesBond", "JB007", "Admin");
    User billy = new User(002, "BillyBob", "WOOHOONASCAR", null);
    User jane = new User(003, "CaliGurl88", "surfboardz", null);
    manager.addUser(james);
    manager.addUser(billy);
    manager.addUser(jane);
    assertEquals(3, manager.getSize());
    manager.removeUser(james);
    manager.removeUser(billy);
    manager.removeUser(jane);
}

However, I have to remove each user after each test, in order to start fresh for the next test.
Is there anyway I can use the @After annotation to remove all users created for each test? Maybe using a for loop?

A: A test must not have any influence over another. The safest solution is to recreate the manager object @Before each test.
public class MyTest{

    private Manager manager;

    @Before
    public void setUp(){
        manager = new Manager();
    }

    ...

}

But if you really need to use the same instance in all tests, make sure you create a very good clean up method (@After).

A: Store the test objects in a List, then remove later:
public class TestClass{

    private List<User> createdUsers = new ArrayList<>();

    private Manager manager; //instantiate

    @Before
    public void setupUsers(){
        User james = new User(001, "JamesBond", "JB007", "Admin");
        User billy = new User(002, "BillyBob", "WOOHOONASCAR", null);
        User jane = new User(003, "CaliGurl88", "surfboardz", null);
        createdUsers.add(james);
        createdUsers.add(billy);
        createdUsers.add(jane);
    }

    @After
    public void cleanUsers(){
        for(User createdUser : createdUsers){
            manager.removeUser(createdUser); //but if you test the behaviour of manager, then remove the created instances independently from manager
        }
        createdUsers.clear();
    }
}

A: The @After annotation is used with a method that will execute after each test. In this method, you can do whatever you want to clean your test environment.
@After
public void cleanup() {
    // Cleaning code goes here
}

You can use the name you want as your method name.
You can save the User instances in a List<User>, property of your test class, and then remove them in the @After method. Don't forget to remove users from your List once you've removed them from the manager list.
public class MyTestClass {

private List<User> users = new ArrayList<User>();

@Test
public void testTheSizeOfUserListAfterAddingThreeUsers() {
    User james = new User(001, "JamesBond", "JB007", "Admin");
    User billy = new User(002, "BillyBob", "WOOHOONASCAR", null);
    User jane = new User(003, "CaliGurl88", "surfboardz", null);
    manager.addUser(james);
    manager.addUser(billy);
    manager.addUser(jane);
    users.add(james);
    users.add(billy);
    users.add(jane);
    assertEquals(3, manager.getSize());
}

@After
public void cleanup() {
    for (User user : users) {
        manager.removeUser(user);
    }
    users.clear();
}
}


text:
Q: Probability of Choosing a Card from a Deck There were quite a few deck of cards probability problems and I went through a few but couldn't find anything close so please forgive me if this is a repeat.
The question is as follows:

Two cards are chosen without replacement at random from a standard 52-card deck. What is
  the probability that
  (b) the first card is a heart and the second card is a 10?

We will be dividing by C(52,2) since we're choosing two cards from a deck of 52. This quantity is 1326.
Our first choice must be a heart so we have C(13,1) since there are 13 hearts in a deck and we're choosing one.
Second choice must be a 10 so we need C(4,1)
Thus, we get $\frac{C(13,1)C(4,1)}{C(52,2)}$ = 3.92%
Is my logic correct?
Thanks.

A: The way that I would approach this question is to approach the two events separately and then multiply their probabilities.
So first we try to find the probability of choosing a heart out of the deck, this is pretty obvious as there are only $4$ suits, and therefore:
$$P(\text{Heart})=\frac{1}{4}$$
Next we look at the probability of choosing a $10$ considering that we've just taken a heart of unknown value out of the deck:
$$\begin{align}P(10\mid \text{Heart already taken})&=P(10\text{ of Hearts removed})P(10 \mid 10\text{ of Hearts removed}) \\ &+ P(10\text{ of Hearts not removed})P(10\mid 10\text{ of Hearts not removed})\\
&= \frac{1}{13}\times\frac{3}{51}+\frac{12}{13}\times\frac{4}{51}=\frac{1}{13}\end{align}$$
We then multiply the two probabilities together to get:
$$\begin{align}P(\text{Heart followed by a }10)&=P(\text{Heart})P(10\mid \text{Heart already taken}) \\ &= \frac{1}{4}\times\frac{1}{13}=\frac{1}{52}\approx1.92\% \end{align}$$

A: We can still make your counting-based approach work by considering two disjoint cases: either the first card is 10 of hearts or not.
If the first card is 10 of hearts, then there are only three 10's remaining in the deck, for a total of $1 \cdot 3 = 3$ outcomes in this case.
If the first card is any of the other twelve hearts, then all four 10's remain in the deck, for a total of $12 \cdot 4 = 48$ outcomes in this case.
Taken together, we find the probability is
$$
\frac{3 + 48}{52 \cdot 51} = \frac{1}{52} \approx 1.92\%.
$$
As André points out in the comments, the denominator is $52 \cdot 51$ rather than $C(52,2)$ since you are distinguishing between the first card and the second card (i.e. you are counting ordered pairs).


text:
Q: PreferenceManager.setDefaultValues readAgain parameter and new preferences I'm using PreferenceManager.setDefaultValues(context,R.xml.preferences,false) to set the default values of the preferences in my application and I've noticed that if I add a new preference then my PreferenceFragment does not show a default value for it, even if it is set in the preferences.xml..
Is this due to the fact that I specify readAgain as false?
I know I can simply try-and-see, but I just wanted to be sure that the readAgain is meant for this purpose, i.e. re-read the default values not to re-set user settings but to set the new properties' default values. If this is exactly the purpose of the readAgain flag, then can you give me a reason not to always set readAgain to true, given that it does not reset user preferences?

A: Setting the readagain flag to true will ensure that all unset-default values are set again. That's the summary.
Setting the readagain will cause extra overhead since basically it means that, the code will go through the entire SharedPreference  once more to check them.  With the readAgain false,all it does is to check whether the file  ( has_set_default_values.xml ) which is used as a marker for setting default values is present or not.
In any case, It won't set any values that are already set .


text:
Q: Separating the interface from an implementation in Java How can you separate the interface from an implementation in Java?
In C/C++, this can be done by creating 2 files a .c and .h file with the same file name.
How can you do this in Java?

A: The closest analogy to .h and .c separation is interfaces.
MyInterface.java
interface MyInterface {

    void doSomething();

}

MyImplementation.java
class MyImplementation implements MyInterface {

    public void doSomething() {
        System.out.println("Hello world");
    }

}

You then use the interface type everywhere except for the actual constructor
MyInterface instance = new MyImplementation();

Of course, there are several differences.

*

*A single class may implement multiple interfaces, and multiple classes may a single interface

*Member values are not included in an interface, only methods.

*Only public methods appears in a Java interface.

*No implementation is ever allowed in an interface (as opposed to C++ templates, which depend on .h implementation).

But this is how "programming to interfaces" is accomplished.

There is no consistent convention for naming interfaces vs concrete classes in Java. C# (nearly identical in its treatment of interfaces) has a convention which I have come to use where the interface begins with I, e.g. IList. The Java standard libraries tend to use the "pure" name for the interface, and then modify it for the concrete implementation, such as List (interface) and ArrayList (implementation).

A: By creating an interface, and implementing it also (generally) in two files -
Say.java the interface -
public interface Say {
  public void say(String msg);
}

and Hello.java, the concrete implementation (and in this case) also a main() method -
public class Hello implements Say {
  @Override
  public void say(String msg) {
    System.out.printf("%s, World!%n", msg);
  }
  public static void main(String[] args) {
    Say s = new Hello();
    s.say("Hello");
  }
}

Note: In Java you can have multiple classes with main() methods. It is also a good practice to use the @Override annotation.

A: You don't.  You could do it via Java interfaces, but doing that for every class would be bad design.  Interfaces should only be used when you expect multiple classes to implement them, or when used as a callback function description.  Really the point of separating the code from the .h file in C++ is
1)To prevent bloating the binary as compilers would make multiple versions of each function for each file its included in
2)To make it easier to read for those who just want the implementation.
In java, 1 isn't an issue.  And Java prefers to solve 2 via automated documentation tools (JavaDoc).
TLDR-  you don't.

A: In Java, interfaces and classes (ie "implementation") are NOT distinguished at file level or by their names. They are both declarations. Specifically, a class declares which interface(s) it implements. For example:
public class MyClass implements Interface1, Interface2, .... {
    // implementations
}

Java does not have the same "linking" concept as in C/C++. You can call your class or interface in any legal form. The "link" between an interface and its implementation classes at runtime are done through the class loader.

A: To have an interface and implementation separated, suggest below steps..
( 1).Identify methods which be part of definition of your class. This becomes your template for new classes with similar functionality.
(2 ). Create a new interface which contains methods which were identified to be part of interface definition (may be many interfaces)
( 3.) Modify your class to implement the interface(s) you have created


text:
Q: XDocument change schema I'm working on an XML validator with XSD files. The XML has to be validated with any XSD file, which means the XSD schema has to be added to the XML file, but of course the schema has to be deleted from the XML first (if it exists).
My workaround:
-I'm successfully removing the schema from the XML file with recursion.
-I'm successfully adding the XSD schema to the XML.
The problem that I have, is with the validation:
XDocument doc = XDocument.Load(filename);

/* adding/deleting schemas recursively */
doc.Save("temp.xml");

using (XmlReader reader = XmlReader.Create("temp.xml", settings))
       doc = XDocument.Load(reader, LoadOptions.SetLineInfo);

The reason I'm using XmlReader and not the .Validate() method is that I need to highlight the actual error rows and the .Validate() method does not give me back the LineNumber from the ValidationEventHandler exception.
Is there another way to change the schema of an XML, and still validate it through lines without saving the new xml to a temp file?

A: I do not understand...in the ValidationEventHandler you get ValidationEventArgs which has an Exception property with LineNumber and LinePosition. Of course if you're validating against a schema, not checking if it's well-formed (which is the only thing XDocument.Load() should do, AFAIK).
About validation against an arbitrary schema: there is an extension method which adds an overload of Validate() where you can specify another schema. Unfortunately for some obscure reasons the line number information are lost. You can however perform validation during reading. First of all define schema you want to use:
var schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xmlSchema)));

Then create a XmlReaderSettings to apply your schema:
var settings = new XmlReaderSettings();
settings.Schemas = schemas;
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += (sender, e) =>
    Console.WriteLine($"{e.Exception.LineNumber}: {e.Message}");

Then load the document, it will have the required information:
using (var reader = XmlReader.Create(stream, settings))
{
    var doc = XDocument.Load(reader, LoadOptions.SetLineInfo);
|


text:
Q: Small issue with maximum modulus principle proof I'm having a bit of trouble understanding a fundamental step on a proof of the maximum modulus principle in Hoffman and Marsden's complex analysis text. The authors suppose that $f$ is analytic and has a relative maximum at $z_0$, so $|f(z)|\leq |f(z_0)|$ on some disk centered at $z_0$ with radius $r_0$. They suppose further that there is a point $z_1$ in this disk for which the inequality is strict, that is, $|f(z_1)|<|f(z_0)|$.
Letting $z_1$ equal $z_0 + re^{ia}$ with $r<r_0$, the authors say that due to continuity, we have numbers $\epsilon$ and $\delta$ such that $|f(z_0 + re^{i\theta})|<|f(z_0)|-\delta$ whenever $|\theta - a|<\epsilon$.
This is the part that confuses me in the proof, because I cannot derive this inequality from the definition of continuity. Even writing it in the form $|f(z_0)|-|f(z_0 + re^{i\theta})|>\delta$ does not shed light in this, as it doesn't seem to be a very meaningful inequality and unrelated to the notion of continuity. Can anyone explain to me what is going on in this step? I seem to be missing it.

A: Continuity implies that for a given $\gamma >0$, $|\, |f(z_0 + re^{i\theta})| - |f(z_1)| \, | < \gamma$ whenever $|\theta - a|<\epsilon$. In particular,
$$
|f(z_0 + re^{i\theta})| < |f(z_1)| + \gamma  = |f(z_0)| - \delta
$$
where $\delta := |f(z_0)| -|f(z_1)| - \gamma$, which is positive for $\gamma$ small enough, since $|f(z_0)| -|f(z_1)|>0$.

A: It's quite simple: they consider the continuous function $g(\theta)=\bigl|f(z_0+r\mathrm e^{i\theta}\bigr|$, and they observe that since $g(a)< |f(z_0)|$, for all $\varepsilon>0$ there exists a small neighbourhood of $a$ on which $|g(\theta)-g(a)| < \varepsilon$, so $g(\theta)<g(a)+\varepsilon$. If $\varepsilon$ is such that $ g(a)+\varepsilon<|f(z_0)|$, we can write $g(a)+\varepsilon=|f(z_0)|-\delta$ ($\delta>0$).


text:
Q: Mantener array de objetos en una sesion Tratando de crear un carrito de compras tengo la siguiente duda:
Tengo una clase detalleticket y añado a un array cada objeto de la clase detalleTicket que luego añado a una session.
Sucede que al querer mostrar los item dice undefined y la consola, el var_dumop devuelve objetos vacios.
Mi premisa es: No estoy poniendo "un" objeto en la session, sino un array de objetos. entonces: como se pasa por sesion un arreglo de objetos y luego se recorre:
nuevo codigo:

<?php

include_once ($_SERVER['DOCUMENT_ROOT'].'/gestionweb/models/claseTicket.php');
session_start();

    if (isset($_POST['accion'])){
   if ($_POST['accion']=="listar"){

    if(isset($_SESSION['carrito'])){
             $informacion =$_SESSION['carrito'];
            $carrito[] = unserialize($informacion);

             echo json_encode($carrito);

        }else{

      $carrito = array();
      echo json_encode($carrito);
        }

   }else if ($_POST['accion']=="agregar"){
        $id = $_POST['id'];
        $pu = $_POST['precio'];
        $cant = $_POST['cantidad'];
        $nom = $_POST['nombre'];
        $detalle = new detalleTicket($id,$pu,$cant,$nom);

     if(isset($_SESSION['carrito'])){
//predefine que la variable carrito sea un array
//desserializa la informacion, ya que la estas cada vez serializando y nunca la deserializas
            $informacion =$_SESSION['carrito'];
            $carrito[] = unserialize($informacion);
        } else {
            $carrito = array();
        }

        array_push($carrito, $detalle);

        $_SESSION['carrito'] = serialize($carrito);

    }

}

?>

Me parece que el error va por ahi.

Este es el codigo AJAX, que se carga al entrar al listado del carrito:

$(document).ready(function() {
listarDetalle();

});
function listarDetalle(){
     var accion="listar";

    $.ajax({

            type: "POST",
            url: "//localhost/gestionweb/includes/php/procesoDetalle.php",
            data: { "accion":accion},
           dataType:'json',

            error: function(){
                alert("error petición ajax");

            },

            success: function(data){

          console.log(data);

               for (var i = 0; i < data.length; i++) {

                var newRow =
                    "
" +
                    "" + data[i].idp + "	" +

                    "" + data[i].cantidad + "	" +
                    "" + data[i].nombre + "	" +
                      "" + data[i].pu + "	" +
                    "<input type='radio' id='"+data[i].idp+"' name='seleccion'/>	"+
                    "
";
                $(newRow).appendTo("#ticket tbody");

        } }

}).fail( function( jqXHR, textStatus, errorThrown ) {

  if (jqXHR.status === 0) {

    alert('Not connect: Verify Network.');

  } else if (jqXHR.status == 404) {

    alert('Requested page not found [404]');

  } else if (jqXHR.status == 500) {

    alert('Internal Server Error [500].');

  } else if (textStatus === 'parsererror') {

    alert('Requested JSON parse failed.');

  } else if (textStatus === 'timeout') {

    alert('Time out error.');

  } else if (textStatus === 'abort') {

    alert('Ajax request aborted.');

  } else {

    alert('Uncaught Error: ' + jqXHR.responseText);

  }

});;

};

A: Intenta asi:
if(isset($_SESSION['carrito'])){
//predefine que la variable carrito sea un array
//desserializa la informacion, ya que la estas cada vez serializando y nunca la deserializas
            $informacion =$_SESSION['carrito'];
            $carrito[] = unserialize($informacion);
        } else {
            $carrito = array();
        }

        array_push($carrito, $detalle);

        $_SESSION['carrito'] = serialize($carrito);

me cuentas como te fue...

A: Bueno despues de tanto luchar encontre una clase y la implemente, en la consola llegan bien los objetos, poero no los muestra, pero ya es un avance:

<?php

include_once ($_SERVER['DOCUMENT_ROOT'].'/gestionweb/models/claseTicket.php');
session_start();
class Carrito
{
    //aquí guardamos el contenido del carrito
    private $carrito = array();
    //seteamos el carrito exista o no exista en el constructor
    public function __construct()
    {
        if(!isset($_SESSION["carrito"]))
        {
            $_SESSION["carrito"] = null;
            $this->carrito["precio_total"] = 0;
            $this->carrito["articulos_total"] = 0;
        }
        $this->carrito = $_SESSION['carrito'];
    }
    //añadimos un producto al carrito
    public function add($articulo = array())
    {
        //primero comprobamos el articulo a añadir, si está vacío o no es un
        //array lanzamos una excepción y cortamos la ejecución
        if(!is_array($articulo) || empty($articulo))
        {
            throw new Exception("Error, el articulo no es un array!", 1);
        }
        //nuestro carro necesita siempre un id producto, cantidad y precio articulo
        if(!$articulo["id"] || !$articulo["cantidad"] || !$articulo["precio"])
        {
            throw new Exception("Error, el articulo debe tener un id, cantidad y precio!", 1);
        }
        //nuestro carro necesita siempre un id producto, cantidad y precio articulo
        if(!is_numeric($articulo["id"]) || !is_numeric($articulo["cantidad"]) || !is_numeric($articulo["precio"]))
        {
            throw new Exception("Error, el id, cantidad y precio deben ser números!", 1);
        }
        //debemos crear un identificador único para cada producto
        $unique_id = md5($articulo["id"]);
        //creamos la id única para el producto
        $articulo["unique_id"] = $unique_id;
        //si no está vacío el carrito lo recorremos
       /* if(!empty($this->carrito))
        {
            foreach ($this->carrito as $row)
            {
                //comprobamos si este producto ya estaba en el
                //carrito para actualizar el producto o insertar
                //un nuevo producto
                if($row["unique_id"] === $unique_id)
                {
                    //si ya estaba sumamos la cantidad
                    $articulo["cantidad"] = $row["cantidad"] + $articulo["cantidad"];
                }
            }
        }*/
        //evitamos que nos pongan números negativos y que sólo sean números para cantidad y precio
        $articulo["cantidad"] = trim(preg_replace('/([^0-9\.])/i', '', $articulo["cantidad"]));
        $articulo["precio"] = trim(preg_replace('/([^0-9\.])/i', '', $articulo["precio"]));
        //añadimos un elemento total al array carrito para
        //saber el precio total de la suma de este artículo
        $articulo["total"] = $articulo["cantidad"] * $articulo["precio"];
        //primero debemos eliminar el producto si es que estaba en el carrito
        $this->unset_producto($unique_id);
        ///ahora añadimos el producto al carrito
        $_SESSION["carrito"][$unique_id] = $articulo;
        //actualizamos el carrito
        $this->update_carrito();
        //actualizamos el precio total y el número de artículos del carrito
        //una vez hemos añadido el producto
        $this->update_precio_cantidad();
    }
    //método que actualiza el precio total y la cantidad
    //de productos total del carrito
    private function update_precio_cantidad()
    {
        //seteamos las variables precio y artículos a 0
        $precio = 0;
        $articulos = 0;
        //recorrecmos el contenido del carrito para actualizar
        //el precio total y el número de artículos
        foreach ($this->carrito as $row)
        {
            $precio += ($row['precio'] * $row['cantidad']);
            $articulos += $row['cantidad'];
        }
        //asignamos a articulos_total el número de artículos actual
        //y al precio el precio actual
        $_SESSION['carrito']["articulos_total"] = $articulos;
        $_SESSION['carrito']["precio_total"] = $precio;
        //refrescamos él contenido del carrito para que quedé actualizado
        $this->update_carrito();
    }
    //método que retorna el precio total del carrito
    public function precio_total()
    {
        //si no está definido el elemento precio_total o no existe el carrito
        //el precio total será 0
        if(!isset($this->carrito["precio_total"]) || $this->carrito === null)
        {
            return 0;
        }
        //si no es númerico lanzamos una excepción porque no es correcto
        if(!is_numeric($this->carrito["precio_total"]))
        {
            throw new Exception("El precio total del carrito debe ser un número", 1);
        }
        //en otro caso devolvemos el precio total del carrito
        return $this->carrito["precio_total"] ? $this->carrito["precio_total"] : 0;
    }
    //método que retorna el número de artículos del carrito
    public function articulos_total()
    {
        //si no está definido el elemento articulos_total o no existe el carrito
        //el número de artículos será de 0
        if(!isset($this->carrito["articulos_total"]) || $this->carrito === null)
        {
            return 0;
        }
        //si no es númerico lanzamos una excepción porque no es correcto
        if(!is_numeric($this->carrito["articulos_total"]))
        {
            throw new Exception("El número de artículos del carrito debe ser un número", 1);
        }
        //en otro caso devolvemos el número de artículos del carrito
        return $this->carrito["articulos_total"] ? $this->carrito["articulos_total"] : 0;
    }
    //este método retorna el contenido del carrito
    public function get_content()
    {
        //asignamos el carrito a una variable
        $carrito = $this->carrito;
        //debemos eliminar del carrito el número de artículos
        //y el precio total para poder mostrar bien los artículos
        //ya que estos datos los devuelven los métodos
        //articulos_total y precio_total
        unset($carrito["articulos_total"]);
        unset($carrito["precio_total"]);
        return $carrito;
    }
    //método que llamamos al insertar un nuevo producto al
    //carrito para eliminarlo si existia, así podemos insertarlo
    //de nuevo pero actualizado
    private function unset_producto($unique_id)
    {
        unset($_SESSION["carrito"][$unique_id]);
    }
    //para eliminar un producto debemos pasar la clave única
    //que contiene cada uno de ellos
    public function remove_producto($unique_id)
    {
        //si no existe el carrito
        if($this->carrito === null)
        {
            throw new Exception("El carrito no existe!", 1);
        }
        //si no existe la id única del producto en el carrito
        if(!isset($this->carrito[$unique_id]))
        {
            throw new Exception("La unique_id $unique_id no existe!", 1);
        }
        //en otro caso, eliminamos el producto, actualizamos el carrito y
        //el precio y cantidad totales del carrito
        unset($_SESSION["carrito"][$unique_id]);
        $this->update_carrito();
        $this->update_precio_cantidad();
        return true;
    }
    //eliminamos el contenido del carrito por completo
    public function destroy()
    {
        unset($_SESSION["carrito"]);
        $this->carrito = null;
        return true;
    }
    //actualizamos el contenido del carrito
    public function update_carrito()
    {
        self::__construct();
    }
}
$carrito = new Carrito();
if ($_POST['accion']=='listar'){
    $c=$carrito->get_content();
    echo json_encode($c);
}else if ($_POST['accion']=='agregar'){

    $articulo = array(
    "id"=>$_POST["id"],
    "precio"=>$_POST["precio"],
    "cantidad"=>$_POST["cantidad"]
    );
    $carrito->add($articulo);
}
?>

Funciona perfecto pero aqui una imagen(porque no muestra data?):


text:
Q: How to fix error React Native 'UMCore' build error in Xcode I'm ejecting my Expo app to Expo Kit.
I did so by running expo eject, which generated the ios and android files.
When I follow this guide to run my project, I run expo start and expo will run the app on the client.
However, when I try to follow step 3, I run into a problem.
I will go into my ios directory and run pod install like so:
cd ./ios
pod install

After this, I open up Xcode and hit the 'Run' button.
After some seconds, the build fails with 3 errors.
Here's what that looks like:

As you can see, all of these errors seem to be coming from a development Pod called 'UMCore'.
I've tried deleting all pods and reinstalling them with pod install, as well as updating cocoapods and running again, but the issue persists.
This is what my Podfile looks like
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'

target 'gearcaster-mobile' do
  pod 'ExpoKit',
    :git => "http://github.com/expo/expo.git",
    :tag => "ios/2.11.2",
    :subspecs => [
      "Core"
    ],
    :inhibit_warnings => true

  # Install unimodules
  require_relative '../node_modules/react-native-unimodules/cocoapods.rb'
  use_unimodules!(
    modules_paths: ['../node_modules'],
    exclude: [
      'expo-face-detector',
      'expo-payments-stripe',
    ],
  )

  pod 'React',
    :path => "../node_modules/react-native",
    :inhibit_warnings => true,
    :subspecs => [
      "Core",
      "ART",
      "RCTActionSheet",
      "RCTAnimation",
      "RCTCameraRoll",
      "RCTGeolocation",
      "RCTImage",
      "RCTNetwork",
      "RCTText",
      "RCTVibration",
      "RCTWebSocket",
      "DevSupport",
      "CxxBridge"
    ]
  pod 'yoga',
    :path => "../node_modules/react-native/ReactCommon/yoga",
    :inhibit_warnings => true
  pod 'DoubleConversion',
    :podspec => "../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec",
    :inhibit_warnings => true
  pod 'Folly',
    :podspec => "../node_modules/react-native/third-party-podspecs/Folly.podspec",
    :inhibit_warnings => true
  pod 'glog',
    :podspec => "../node_modules/react-native/third-party-podspecs/glog.podspec",
    :inhibit_warnings => true

  post_install do |installer|
    installer.pods_project.main_group.tab_width = '2';
    installer.pods_project.main_group.indent_width = '2';

    installer.target_installation_results.pod_target_installation_results
      .each do |pod_name, target_installation_result|

      if pod_name == 'ExpoKit'
        target_installation_result.native_target.build_configurations.each do |config|
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)']
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << 'EX_DETACHED=1'

          # Enable Google Maps support
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << 'HAVE_GOOGLE_MAPS=1'
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << 'HAVE_GOOGLE_MAPS_UTILS=1'

        end
      end

      if ['Amplitude-iOS','Analytics','AppAuth','Branch','CocoaLumberjack','FBSDKCoreKit','FBSDKLoginKit','FBSDKShareKit','GPUImage','JKBigInteger2'].include? pod_name
      target_installation_result.native_target.build_configurations.each do |config|
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '10.0'
      end
      end

      # Can't specify this in the React podspec because we need to use those podspecs for detached
      # projects which don't reference ExponentCPP.
      if pod_name.start_with?('React')
        target_installation_result.native_target.build_configurations.each do |config|
          config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '10.0'
          config.build_settings['HEADER_SEARCH_PATHS'] ||= ['$(inherited)']
        end
      end

      # Build React Native with RCT_DEV enabled and RCT_ENABLE_INSPECTOR and
      # RCT_ENABLE_PACKAGER_CONNECTION disabled
      next unless pod_name == 'React'
      target_installation_result.native_target.build_configurations.each do |config|
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)']
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << 'RCT_DEV=1'
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << 'RCT_ENABLE_INSPECTOR=0'
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << 'ENABLE_PACKAGER_CONNECTION=0'
      end

    end
  end
end

Tool versions:

*

*Cocoapods 1.7.5

*Expo-CLI 3.0.6

*React-Native: 0.59.8

A: Updating Xcode to version 10 solved this issue


text:
Q: Platform to run jupyter notebooks on schedule I am in search for a platform that will allow me to work on jupyter notebooks and  schedule them. I also need to be able upload/download files to this platform manually. The scripts are mainly for web scraping and data formatting so I do not need too much functionality.
I have been trying to use google cloud platform for this purpose but failed to build a working set up as it was too complicated for me. Also tried Azure but I find google cloud/microsoft have too many features that makes them very difficult to navigate for users like me which have simple use cases.
Any suggestions would be appreciated.
Thanks,

A: You can try a Notebooker or Mercury. Both are open-source web-based solutions for scheduling and sharing Jupyter Notebooks. The Mercury has an option to download output files.
You can also try online service with Notebooks like NaaS, Noteable, DeepNote - they have scheduling capabilities.


text:
Q: CALayer - Shadow causes a performance hit? So I am doing some custom animations on my navigationcontroller and the way it pushes and pops the viewControllers.
Everything runs smooth. As soon as I add the following code (In a subclass of UINavigationController), I face a huge performance hit. After adding a shadow all animations become very laggy. Is this expected or am I doing something wrong in the code?
// This code gets called once during NavigationController initialization.
[self.view setClipsToBounds:NO];
[self.view.layer setCornerRadius:5];
[self.view.layer setShadowOffset:CGSizeMake(0, 20)];
[self.view.layer setShadowColor:[[UIColor yellowColor] CGColor]];
[self.view.layer setShadowRadius:20.0];
[self.view.layer setShadowOpacity:1];

EDIT:
Changed my shadow radius to 1 and it's still slow

A: self.view.layer.shouldRasterize = YES;
self.view.layer.rasterizationScale = UIScreen.mainScreen.scale;

I was recently having some issues with slow CALayer shadows, and that simple line of code fixed up everything for me!

A: You should expect a slowdown from adding a shadow. A shadowRadius of 20 is very high and will be especially slow.
The other key to improve shadow rendering speed: set the shadowPath property. It can help dramatically.

A: Yes, shadow's are very expensive (especially a shadow that big -- play with the radius and you'll notice it makes a huge difference in the degree of slowdown you experience). One way to improve performance is to render it once to a CGImageContext and just display that image instead of having the layer re-render the shadow every time it redraws (but this doesn't work if the shadow needs to animate or something).

A: Using shadowPath instead of shadowOffset.
theView.layer.shadowPath = [UIBezierPath bezierPathWithRect:theView.bounds].CGPath;

Check this post: iphone - Animation's performance is very poor when view's shadow is on

A: Swift 5.3. add this code.

myView -> UIView, collectionViewCell or tableViewCell can be.

myview.layer.shadowPath = UIBezierPath(rect: cell.bounds).cgPath
myview.layer.shouldRasterize = true
myview.layer.rasterizationScale = UIScreen.main.scale

A: I'm coding app with "Neumorphism" style, so much shadow and app so laggy. But use this code below, app very smooth.
viewHasShadow.layer.shouldRasterize = true
viewHasShadow.layer.rasterizationScale = UIScreen.main.scale


text:
Q: Python Regex to Extract Genome Sequence I'm trying to use a Python Regular Expression to extract a genome sequence from a genome database; I've pasted a snippet of the database below.
>GSVIVT01031739001 pacid=17837850 polypeptide=GSVIVT01031739001 locus=GSVIVG01031739001 ID=GSVIVT01031739001.Genoscope12X annot-version=Genoscope.12X ATGAAAACGGAACTCTTTCTAGGTCATTTCCTCTTCAAACAAGAAAGAAGTAAAAGTTGCATACCAAATATGGACTCGAT TTGGAGTCGTAGTGCCCTGTCCACAGCTTCGGACTTCCTCACTGCAATCTACTTCGCCTTCATCTTCATCGTCGCCAGGT TTTTCTTGGACAGATTCATCTATCGAAGGTTGGCCATCTGGTTATTGAGCAAGGGAGCTGTTCCATTGAAGAAAAATGAT GCTACACTGGGAAAAATTGTAAAATGTTCGGAGTCTTTGTGGAAACTAACATACTATGCAACTGTTGAAGCATTCATTCT TGCTATTTCCTACCAAGAGCCATGGTTTAGAGATTCAAAGCAGTACTTTAGAGGGTGGCCAAATCAAGAGTTGACGCTTC CCCTCAAGCTTTTCTACATGTGCCAATGTGGGTTCTACATCTACAGCATTGCTGCCCTTCTTACATGGGAAACTCGCAGG AGGGATTTCTCTGTGATGATGTCTCATCATGTAGTCACTGTTATCCTAATTGGGTACTCATACATATCAAGTTTTGTCCG GATCGGCTCAGTTGTCCTTGCCCTGCACGATGCAAGTGATGTCTTCATGGAAGCTGCAAAAGTTTTTAAATATTCTGAGA AGGAGCTTGCAGCAAGTGTGTGCTTTGGATTTTTTGCCATCTCATGGCTTGTCCTACGGTTAATATTCTTTCCCTTTTGG GTTATCAGTGCATCAAGCTATGATATGCAAAATTGCATGAATCTATCGGAGGCCTATCCCATGTTGCTATACTATGTTTT CAATACAATGCTCTTGACACTACTTGTGTTCCATATATACTGGTGGATTCTTATATGCTCAATGATTATGAGACAGCTGA AAAATAGAGGACAAGTTGGAGAAGATATAAGATCTGATTCAGAGGACGATGAATAG
>GSVIVT01031740001 pacid=17837851 polypeptide=GSVIVT01031740001 locus=GSVIVG01031740001 ID=GSVIVT01031740001.Genoscope12X annot-version=Genoscope.12X ATGGGTATTACTACTTCCCTCTCATATCTTTTATTCTTCAACATCATCCTCCCAACCTTAACGGCTTCTCCAATACTGTT TCAGGGGTTCAATTGGGAATCATCCAAAAAGCAAGGAGGGTGGTACAACTTCCTCATCAACTCCATTCCTGAACTATCTG CCTCTGGAATCACTCATGTTTGGCTTCCTCCACCCTCTCAGTCTGCTGCATCTGAAGGGTACCTGCCAGGAAGGCTTTAT GATCTCAATGCATCCCACTATGGTACCCAATATGAACTAAAAGCATTGATAAAGGCATTTCGCAGCAATGGGATCCAGTG CATAGCAGACATAGTTATAAACCACAGGACTGCTGAGAAGAAAGATTCAAGAGGAATATGGGCCATCTTTGAAGGAGGAA CCCCAGATGATCGCCTTGACTGGGGTCCATCTTTTATCTGCAGTGATGACACTCTTTTTTCTGATGGCACAGGAAATCCT GATACTGGAGCAGGCTTCGATCCTGCTCCAGACATTGATCATGTAAACCCCCGGGTCCAGCGAGAGCTATCAGATTGGAT GAATTGGTTAAAGATTGAAATAGGCTTTGCTGGATGGCGATTCGATTTTGCTAGAGGATACTCCCCAGATTTTACCAAGT TGTATATGGAAAACACTTCGCCAAACTTTGCAGTAGGGGAAATATGGAATTCTCTTTCTTATGGAAATGACAGTAAGCCA AACTACAACCAAGATGCTCATCGGCGTGAGCTTGTGGACTGGGTGAAAGCTGCTGGAGGAGCAGTGACTGCATTTGATTT TACAACCAAAGGGATACTCCAAGCTGCAGTGGAAGGGGAATTGTGGAGGCTGAAGGACTCAAATGGAGGGCCTCCAGGAA TGATTGGCTTAATGCCTGAAAATGCTGTGACTTTCATAGATAATCATGACACAGGTTCTACACAAAAAATTTGGCCATTC CCATCAGACAAAGTCATGCAGGGATATGTTTATATCCTCACTCATCCTGGGATTCCATCCATATTCTATGACCACTTCTT TGACTGGGGTCTGAAGGAGGAGATTTCTAAGCTGATCAGTATCAGGACCAGGAACGGGATCAAACCCAACAGTGTGGTGC GTATTCTGGCATCTGACCCAGATCTTTATGTAGCTGCCATAGATGAGAAAATCATTGCTAAGATTGGACCAAGGTATGAT GTTGGGAACCTTGTACCTTCAACCTTCAAACTTGCCACCTCTGGCAACAATTATGCTGTGTGGGAGAAACAGTAA
>GSVIVT01031741001 pacid=17837852 polypeptide=GSVIVT01031741001 locus=GSVIVG01031741001 ID=GSVIVT01031741001.Genoscope12X annot-version=Genoscope.12X ATGTCCAAATTAACTTATTTATTATCTCGGTACATGCCAGGAAGGCTTTATGATCTGAATGCATCCAAATATGGCACCCA AGATGAACTGAAAACACTGATAAAGGTGTTTCACAGCAAGGGGGTCCAGTGCATAGCAGACATAGTTATAAACCACAGAA CTGCAGAGAAGCAAGACGCAAGAGGAATATGGCCATCTTTGAAGGAGGAACCCCAGATGATCGCCTTGACTGGACCCCAT CTTTCCTTTGCAAGGACGACACTCCTTATTCCGACGGCACCGGAAACCCTGATTCTGGAGATGACTACAGTGCCGCACCA GACATCGACCACATCAACCCACGGGTTCAGCAAGAGCTAA

What I'm trying to do is get the genome (ACGT) sequence for GSVIV01031740001 (the middle sequence), and none of the others. My current regex is
sequence = re.compile('(?<=>GSVIVT01031740001) pacid=.*annot-version=.*\n[ACGT\n]*[^(?<!>GSVIVT01031740001) pacid]')

with my logic being find the header with the genbank ID for the correct organism, give me that line, then go to a new line and give me all ACGT and new lines until I get to a header for an organism with a different genbank ID. This fails to give any results.
Yes, I know that re.compile doesn't actually perform a search; I'm searching against a file opened as 'target' so my execution looks like
>>> for nucl in target:
...     if re.search(sequence, nucl):
...         print(nucl)

Can someone tell me what I'm doing wrong, either in my regex or by using regex in the first place? When I try this on regex101.com, it works, but when I try it in the Python interpreter (2.7.1), it fails.
Thanks!

A: If I understand correctly , you want JUST the genomic sequence for a given locus. So You can do something like this.(assumes your data is in a file)
lines = [line.split(' ') for line in open('results.txt') ]
somedict = {}
for each in lines:
    locus =  each[3].split('=')[-1]
    seq = ''.join(each[6:])
    somedict[locus] = seq

print somedict

It outputs  a dictionary with the locus as key and sequence as value
{'GSVIVG01031741001': 'ATGTCCAAATTAACTTATTTATTATCTCGGTACATGCCAGGAAGGCTTTATGATCTGAATGCATCCAAATATGGCACCCAAGATGAACTGAAAACACTGATAAAGGTGTTTCACAGCAAGGGGGTCCAGTGCATAGCAGACATAGTTATAAACCACAGAACTGCAGAGAAGCAAGACGCAAGAGGAATATGGCCATCTTTGAAGGAGGAACCCCAGATGATCGCCTTGACTGGACCCCATCTTTCCTTTGCAAGGACGACACTCCTTATTCCGACGGCACCGGAAACCCTGATTCTGGAGATGACTACAGTGCCGCACCAGACATCGACCACATCAACCCACGGGTTCAGCAAGAGCTAA\n', 'GSVIVG01031740001': 'ATGGGTATTACTACTTCCCTCTCATATCTTTTATTCTTCAACATCATCCTCCCAACCTTAACGGCTTCTCCAATACTGTTTCAGGGGTTCAATTGGGAATCATCCAAAAAGCAAGGAGGGTGGTACAACTTCCTCATCAACTCCATTCCTGAACTATCTGCCTCTGGAATCACTCATGTTTGGCTTCCTCCACCCTCTCAGTCTGCTGCATCTGAAGGGTACCTGCCAGGAAGGCTTTATGATCTCAATGCATCCCACTATGGTACCCAATATGAACTAAAAGCATTGATAAAGGCATTTCGCAGCAATGGGATCCAGTGCATAGCAGACATAGTTATAAACCACAGGACTGCTGAGAAGAAAGATTCAAGAGGAATATGGGCCATCTTTGAAGGAGGAACCCCAGATGATCGCCTTGACTGGGGTCCATCTTTTATCTGCAGTGATGACACTCTTTTTTCTGATGGCACAGGAAATCCTGATACTGGAGCAGGCTTCGATCCTGCTCCAGACATTGATCATGTAAACCCCCGGGTCCAGCGAGAGCTATCAGATTGGATGAATTGGTTAAAGATTGAAATAGGCTTTGCTGGATGGCGATTCGATTTTGCTAGAGGATACTCCCCAGATTTTACCAAGTTGTATATGGAAAACACTTCGCCAAACTTTGCAGTAGGGGAAATATGGAATTCTCTTTCTTATGGAAATGACAGTAAGCCAAACTACAACCAAGATGCTCATCGGCGTGAGCTTGTGGACTGGGTGAAAGCTGCTGGAGGAGCAGTGACTGCATTTGATTTTACAACCAAAGGGATACTCCAAGCTGCAGTGGAAGGGGAATTGTGGAGGCTGAAGGACTCAAATGGAGGGCCTCCAGGAATGATTGGCTTAATGCCTGAAAATGCTGTGACTTTCATAGATAATCATGACACAGGTTCTACACAAAAAATTTGGCCATTCCCATCAGACAAAGTCATGCAGGGATATGTTTATATCCTCACTCATCCTGGGATTCCATCCATATTCTATGACCACTTCTTTGACTGGGGTCTGAAGGAGGAGATTTCTAAGCTGATCAGTATCAGGACCAGGAACGGGATCAAACCCAACAGTGTGGTGCGTATTCTGGCATCTGACCCAGATCTTTATGTAGCTGCCATAGATGAGAAAATCATTGCTAAGATTGGACCAAGGTATGATGTTGGGAACCTTGTACCTTCAACCTTCAAACTTGCCACCTCTGGCAACAATTATGCTGTGTGGGAGAAACAGTAA\n', 'GSVIVG01031739001': 'ATGAAAACGGAACTCTTTCTAGGTCATTTCCTCTTCAAACAAGAAAGAAGTAAAAGTTGCATACCAAATATGGACTCGATTTGGAGTCGTAGTGCCCTGTCCACAGCTTCGGACTTCCTCACTGCAATCTACTTCGCCTTCATCTTCATCGTCGCCAGGTTTTTCTTGGACAGATTCATCTATCGAAGGTTGGCCATCTGGTTATTGAGCAAGGGAGCTGTTCCATTGAAGAAAAATGATGCTACACTGGGAAAAATTGTAAAATGTTCGGAGTCTTTGTGGAAACTAACATACTATGCAACTGTTGAAGCATTCATTCTTGCTATTTCCTACCAAGAGCCATGGTTTAGAGATTCAAAGCAGTACTTTAGAGGGTGGCCAAATCAAGAGTTGACGCTTCCCCTCAAGCTTTTCTACATGTGCCAATGTGGGTTCTACATCTACAGCATTGCTGCCCTTCTTACATGGGAAACTCGCAGGAGGGATTTCTCTGTGATGATGTCTCATCATGTAGTCACTGTTATCCTAATTGGGTACTCATACATATCAAGTTTTGTCCGGATCGGCTCAGTTGTCCTTGCCCTGCACGATGCAAGTGATGTCTTCATGGAAGCTGCAAAAGTTTTTAAATATTCTGAGAAGGAGCTTGCAGCAAGTGTGTGCTTTGGATTTTTTGCCATCTCATGGCTTGTCCTACGGTTAATATTCTTTCCCTTTTGGGTTATCAGTGCATCAAGCTATGATATGCAAAATTGCATGAATCTATCGGAGGCCTATCCCATGTTGCTATACTATGTTTTCAATACAATGCTCTTGACACTACTTGTGTTCCATATATACTGGTGGATTCTTATATGCTCAATGATTATGAGACAGCTGAAAAATAGAGGACAAGTTGGAGAAGATATAAGATCTGATTCAGAGGACGATGAATAG\n'}


text:
Q: How can I use TypeScript to clone a node that contains an Angular selector? I have an Angular app, and in one component, the HTML contains a selector of another component, like this:

    <selector>
        Text Content
    </selector>

In my Typescript, I'm trying to clone this div using the following:
var headerClone = document.getElementById('header').cloneNode(true);

I want the headerClone that gets created to look exactly like the div above, so the selector from the other component can work properly, but instead, here is what the clone looks like (from console.log):

Text Content

It isn't copying the <selector> tag, which causes the HTML/CSS of the selector component to not load. How can I get the clone to include the <selector> tag properly?

A: What about getting the innerHtml and creating a new div?
var headerClone = document.createElement('div);
headerClone.setAttribute("id", "header");
headerClone.innerHtml = document.getElementById('header').innerHtml;


text:
Q: MongoDB count and get limited data I'm trying to get the count all the data for the query and as well as get the limited data (for pagination) but both the console output gives me the count. What is that I'm doing wrong. Pls help
const curFind = fbUser.find(find, 'firstName gender age birthday facebookId profileURL email imageUrl preferences blocked flames likes rejects location reported')

  curFind.count(function(e, count) {
    console.log(count);
    curFind.skip(0).limit(10).hint( { $natural : 1 } ).exec(function(err, data) {
      console.log(data);
    });
  });

A: As per MongoDB BLOG Here In certain situations, count can be avoided for better performance Counting things can be hard on a database. The obvious things to count, number of items in a collection or index, are easy to keep track of, but as soon as you start trying to count records based on a query, things get slower and slower. This is because the database has to do more work scanning practically every item in the database to see if it matches.
MongoDB does have an optimisation for a fast count where all the queried fields are indexed and the query is based around equivalence, but only in that circumstance.


text:
Q: What is the most advantage using Saxon for .net? I'm working in .net 4.0 C# xslt1.0.
I hesitate to migrate with saxon processor is there real différencies in performance?

A: I don't have any performance comparisons between Microsoft's XSLT 1.0 processor and the Saxon XSLT 2.0 processor on .NET.
I imagine you are talking about execution speed, but what is much more important is development speed: you can buy a decent server for about half the cost of hiring a programmer for a day. And in my experience (though it depends on the task) development productivity with XSLT 2.0 is about doubled compared with XSLT 1.0.


text:
Q: Package tab missing from project properties Attempting to create nuget package to upload to our own nuget sever, and would like to eliminate the manual process of creating and editing the nugspec file. Everything I've read, says the setting can be pulled from the project file (if using package reference). And that the settings exist on the Package tab of the project properties window. But that tab is not there.
Using vs 2019, .NetFramework 4.7.2, project is a library, and has been migrated to package reference.
I took an existing project, right clicked the references, and used the migrate option. Package tab is non-existent
I also set the nuget package manager to default to packageReference, and create a new class library.
Package tab also non-existent
The required package (when using non-SDK Style with package reference) nuget.build.tasks.pack has bee added to the references of both projects mentions
Any help would be appreciated

A: The package tab is only available for SDK style projects. Non-SDK style projects use a different project system in Visual Studio, which doesn't contain that project properties tab. The new project system (on github, the old one is closed source) was initially made to look the same as the old project system, but slowly they're diverging. The Reference/Dependencies node in Solution Explorer is one obvious example, as is the Package tab in the project properties window.
To create the MSBuild properties used by pack, you'll need to manually edit the project file as XML. Within Visual Studio, you need to right click the project in Solution Explorer, select "unload project", now when you single click the project, or right click and select edit, you'll see the project XML. Once done, right click the project again and select reload project. Alternatively, edit it with a text or XML editor outside of Visual Studio, and Visual Studio will detect the change and prompt you to reload the project when you alt-tab back.
My suggestion, however, is to convert your non-SDK style project to an SDK style project. "Standard" class library projects work fine, and I'm not aware of any disadvantages (unless some developers on your team are using Visual Studio 2015 or earlier still), given the non-SDK style project is already using PackageReference. Some other project types might have limited Visual Studio experiences when targeting .NET Framework in an SDK style project. Other project types might not be compatible with SDK style projects at all. However, most people creating NuGet packages are doing so with standard class library projects, which shouldn't have any problems.
There is a "unsupported" tool try-convert to convert non-SDK style projects to SDK style. Personally, I just delete the csproj, create an empty directory, run dotnet new classlib on the console, move the csproj to my existing project's directory, rename the project file, and delete that temporary/empty directory. If you have anything other than .cs files in your project that need explicit entries in the csproj, hand edit the csproj if you're comfortable with msbuild, otherwise load the project in Visual Studio and use the Solution Explorer and Properties windows.
Some people believe that SDK style projects are only for .NET Core or .NET Standard. That's not true, but unfortunately the Visual Studio new project templates give that impression. You will need to create the class library project targeting .NET 5, .NET Standard, or .NET Core. But once the csproj is created, edit the csproj (with SDK style projects it's no longer necessary to unload the project) and change <TargetFramework>net5.0</TargetFramework> to <TargetFramework>net472</TargetFramework>. Another advantage of SDK style projects is it's easy to multi-target, a useful technique to slowly modernize your projects to newer runtimes. Add an s to the XML element name to make it plural, and add extra target frameworks as a semi-colon delimited list <TargetFrameworks>net472;net5.0</TargetFrameworks>. When changing between TargetFramework and TargetFrameworks, Visual Studio should prompt you to reload the project, but I found that it still has some issues. So I suggest closing the solution and opening it again, then everything should work great.


text:
Q: Combine javascript functions I have a javascript function that checks to make sure radio buttons are checked, and shows a message if they are not all checked, and if you click Cancel, the message goes away so the user can check more radio buttons. If you click Ok, it submits the form anyways. It works and is great.
I have another function that checks to make sure a value greater than zero is entered in a single text(number) field. It shows a message if it is not greater than zero, and if you click Cancel the message goes away so the user can enter a number. If you click Ok, it submits the form anyways. Again, it works and is great.
Now, when I try to run them both at the same time... something odd happens. The messages show up, but if you click Cancel it submits the form anyway. I want the Cancel buttons to work the same as they do when ran separate... make sense?
Check if radio buttons are checked:
<script type="text/javascript">
            function checkform() {
                //make sure all picks have a checked value
                var f = document.entryForm;
                var allChecked = true;
                var allR = document.getElementsByTagName('input');
                for (var i=0; i < allR.length; i++) {
                    if(allR[i].type == 'radio') {
                        if (!radioIsChecked(allR[i].name)) {
                            allChecked = false;
                        }
                    }
                }
                if (!allChecked) {
                    return confirm('Not all picks entered... Submit anyway?');
                }
                return true;
            }
            function radioIsChecked(elmName) {
                var elements = document.getElementsByName(elmName);
                for (var i = 0; i < elements.length; i++) {
                    if (elements[i].checked) {
                        return true;
                    }
                }
                return false;
            }
            </script>

Check if text field greater than zero:
<script type="text/javascript">
function validate()
{
    var lgwscore;
    lgwscore = parseFloat(document.getElementById('tieBreakerPoints').value);
    if (lgwscore > 0 )
    {
        //Everything is good.
    }
    else
    {
        confirm("You may want to set LGW points\nhigher than Zero.\n\nClick Cancel to enter points.\nClick Ok to keep at Zero.");
        return false;
    }
}

Call both functions on submit:
echo '<form name="entryForm" action="entry_form.php" method="post" onsubmit="return validate() & checkform();">' . "\n";

Any help appreciated.

A: Use && (which is the logival and operator and not the bitwise and you used) and change the validate to
function validate(){
  var lgwscore = parseFloat(document.getElementById('tieBreakerPoints').value);
  if (lgwscore > 0 ) return true;
  else return confirm("You may want to set LGW points\nhigher than Zero.\n\nClick Cancel to enter points.\nClick Ok to keep at Zero.");
}

A: Use && instead of & to combine your functions. And because && short circuits, it will not call the second function if the first function returns false.
& is the bitwise and operator. It operates on numbers and returns a number. true & true is 1, and true & false is 0. Thus your code is returning either 0 or 1 instead of true or false.
&& is the logical and operator. It operates on booleans and returns a boolean. true && true is true, and true && false is false.
If you want both functions to be called regardless of whether either of them fails, you can do that with
function validateAll() {
    var result = checkform();
    result = validate() && result;
    // If you want more condition functions, you can add them here:
    // result = x() && result;
    return result;
}

A: & is a bitwise operator, it will do coercion and return a number in the end.
&& is a logical operator, it will do coercion and return a boolean in the end.
You need to use &&.
See this sample:

function a() {
  console.log('a');
  return false;
}

function b() {
  console.log('b');
  return false;
}

console.log('a() & b()', a() & b());
console.log('a() && b()', a() && b());


text:
Q: Store data on my XML file while redirecting it to my home page using PHP and Javascript I have created a PHP page where there is a form which would store data on an XML file.
I have written the code of PHP which could store the data but now I have to redirect it to my homepage also.
But the main error is when I write the Javascript code for redirecting the page, then the data is not stored.
Now I have currently written the code of Javascript in the PHP code itself.
I will provide the code for my page below.

    <title>Login</title>

<?php
if(isset($_REQUEST['ok']))
{
    $xml = new DOMDocument("1.0","UTF-8");
    $xml->load("a.xml");

    $rootTag = $xml->getElementsByTagName("document")->item(0);

    $dataTag = $xml->createElement("data");

    $aTag=$xml->createElement("a",$_REQUEST['a']);
    $bTag=$xml->createElement("b",$_REQUEST['b']);

    $dataTag->appendChild($aTag);
    $dataTag->appendChild($bTag);

    $rootTag->appendChild($dataTag);

    $xml->save("a.xml");
}
echo "
"
?>
<form action="index.php" method="post">

    User Name
     <input type="text" name="a" width="75" />

 Password
 <input type="password" name="b" width="75" />

<input type="button" name="ok" value="Login" onclick="Home()"  />

</form>

A: Try this. You need to use header("Location:navbar.php");
<?php
if(isset($_REQUEST['ok'])){
    $xml = new DOMDocument("1.0","UTF-8");
    $xml->load("a.xml");

    $rootTag = $xml->getElementsByTagName("document")->item(0);

    $dataTag = $xml->createElement("data");

    $aTag=$xml->createElement("a",$_REQUEST['a']);
    $bTag=$xml->createElement("b",$_REQUEST['b']);

    $dataTag->appendChild($aTag);
    $dataTag->appendChild($bTag);

    $rootTag->appendChild($dataTag);

    $xml->save("a.xml");
    header("Location:navbar.php");
    exit;
}
?>

<title>Login</title>

<form action="index.php" method="post">

User Name
 <input type="text" name="a" width="75" />

 Password
 <input type="password" name="b" width="75" />

<input type="submit" name="ok" value="Login"  />

</form>


text:
Q: Wordpress permalink with no error 404 page i am using wordpress permalink like url.com/article-name but i dont want errors 404 handled by my page - so redirected to the normal server error page.
I am using the following .htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Can someone help me how i have to adjust the .htaccess code that a error is not redirected to the index.php. If i deleted the .htaccess any links redirects to the server error 404 page.
thank you

A: Just add this
ErrorDocument 404 /404.php
# where 404.php is your error page

A: According to this answer at https://wordpress.stackexchange.com/ you should use
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !(robots\.txt|sitemap\.xml(\.gz)?)
    RewriteCond %{REQUEST_FILENAME} \.(css|js|html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|swf|tar|tif|tiff|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$ [NC]
    RewriteRule .* - [L]
</IfModule>

Hope it helps!


text:
Q: Java Iterator backed by network connection With some frequency I find myself writing APIs that offer an Iterator<Foo> which is backed by a network connection.  The implementation opens a network connection, reads information off the stream, and deserializes that information into Foos to pass on to the caller.  Unfortunately there is always the possibility of an IOException and also the need to close the network connection gracefully (that can be made automatic when the caller reads the last Foo, but what if that doesn't happen?).
There are already a couple of questions (here and here) about how to deal with checked exceptions that would be thrown in an implementation of Iterator, and the accepted advice is "wrap them in unchecked RuntimeExceptions".  Meanwhile to allow closing the network connection we can implement Closeable.  So we end up with something like this for a well-behaved exception-checking caller:
Iterator<Foo> iter = null;
try {
    iter = getFooIterator();
    while(iter.hasNext()) {
        Foo foo = iter.next();
        // do something with foo
    }
}
catch(RuntimeException e) {
    if(e.getCause() instanceof IOException) {
       // do something with the IOException
    }
    else throw e;
}
finally {
    if(iter instanceof Closeable) try { ((Closeable)iter).close(); } catch(IOException e) {}
}

And it seemed like such a nice idea to implement Iterator.  Is there a better way?

A: IMO the first step would be to wrap it up in an implementation- or app-specific exception, eliminating the need for catching generic RuntimeExceptions or checking the root cause.
I'd consider a specific implementation to avoid the closeable check and to wrap up the IOException.
NetworkIterator<Foo> iter = null;
try {
    iter = getFooIterator();
    while (iter.hasNext()) {
        Foo foo = iter.next();
        // do something with foo
    }
} catch (NetworkIteratorExceptiom e) {
    // do something with the IOException
} finally {
    iter.close();
}

I probably wouldn't give it method to make the boilerplate go away, but I'd be tempted; roughly:
NetworkIterator<Foo> iter = new IteratorThang<Foo>() {
    @Override public void each(Foo foo) {
        // Do something with foo
    }
};


text:
Q: Reduce latency of long distance VPN location I am connected to a clients network via ovpn. Their servers are located in Germany whilst I am currently in Indonesia which results into a very high ping of ~350ms. I found one workaround by using an Azure VM located in the US and connecting to ovpn within the Windows VM. I will get a ping of around 150 ms. Since my network is generally slow (around 30 Mbps). I am trying to find another solution to get the lowest latency possible

A: Looking at online rtt tables, between Jakarta and Frankfurt you're looking at 160/170ms. Even if you look at it theoretically; Jakarta->Frankfurt is ~11.000km in a straight line, and taking into account the refractive index of fiber media, you're looking at 53ms latency just in light travel time (one way), times two for a roundtrip is 106ms. Unless you plan to dig a fiber through the planet, you're not getting around that 100ms.
The only meaningful way to reduce the latency you're facing, without violating the laws of physics is, is to reduce the number of hops between you and the client. Every hop will introduce some latency. Ideally you'd set up your own backbone, with photonic switches, but assuming you don't have 100-200 million to set that up, it's probably best to look at commercial VPN solutions.
A commercial VPN can reduce the number of hops between you and Germany, because they control their own traffic flow (which you can't, because your ISP controls it). If you go with a big provider (CloudFlare VPN?) they are also likely to have less hops, because they would have their own backbone, and not rely on other ISPs to route their traffic, but it's probably best to try a few. I can imagine not every VPN provider would optimize for the Indonesia<->Germany path, but you might get lucky with one.
The rest is down to mitigating the impact of the latency. For example, for SSH special clients exist that do local echo and all that. Maybe you can look into latency-optimized clients for your application.


text:
Q: What is 'a in F# While learning F# and reading this page, I found this code:
type MyGenericClass<'a> (x: 'a) =
   do printfn "%A" x

I did not understand the meaning of 'a is it related any how to lifetime concept at rust or something completely different?

A: 'a is a type parameter, such as T in List<T>.  The F# syntax for type parameters is to preface the name of the parameter with the tick mark.  In your example, this means that the parameter x can be any type, and it will create a MyGenericClass of that generic type.  For example, if you called new MyGenericClass(3), you would get a MyGenericClass<int>.


text:
Q: Jquery Datatable : makeEditable not a function error This is the code I have, but it errors on firebug saying $("#updateTable").dataTable({bServerSide: true, sAjaxSource: "UpdateTS", bProcessing: true, aoColumns: [{sName: "ID"}, {sName: "Result"}]}).makeEditable is not a function
<link href="../../Content/CSS/demo_table_jui.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jQuery-1.4.4.min.js" type="text/javascript"></script>
<script src="../../Scripts/jQuery.dataTables.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.jeditable.js" type="text/javascript" />
<script src="../../Scripts/jquery.dataTables.editable.js" type="text/javascript" />
<script src="../../Scripts/jquery-ui.js" type="text/javascript" />
<script src="../../Scripts/jquery.validate.js"  type="text/javascript" ></script>
<script language="javascript" type="text/javascript">
       $(document).ready(function () {

       $('#updateTable').dataTable({
               "bServerSide": true,
               "sAjaxSource": "UpdateTS",
               "bProcessing": true,
               "aoColumns": [
                   { "sName": "ID" },
                   { "sName": "Result" }
               ]
           }).makeEditable();
   });

</script>

This error is causing the datatable not editable. Am I not using editable plug-in right?
The makeEditable function is defined in the plug-in ../../Scripts/jquery.dataTables.editable.js

A: Have you tried changing your script include for that library to:
<script src="../../Scripts/jquery.dataTables.editable.js" type="text/javascript" ></script>

instead of
<script src="../../Scripts/jquery.dataTables.editable.js" type="text/javascript" />

It looks like a few other libraries you are using might have this same issue.


text:
Q: Pgsql query with empty HTML tags I have a body column (data type text) in a posts table which is storing HTML string.
How can i write a query to get all the posts with body containing at least one empty link (e.g. )?

A: SELECT * FROM posts WHERE body ~* '^[^\>]*(>){1}$';

It means that empty links must have only one single '>' character before the ending tag.


text:
Q: How to configure i18n in Spring boot 2 + Webflux + Thymeleaf? I just start a new project based on Spring boot 2 + Webflux. On upgrading version of spring boot and replace spring-boot-starter-web with spring-boot-starter-webflux classes like

*

* WebMvcConfigurerAdapter

* LocaleResolver

* LocaleChangeInterceptor

are missing. How now can I configure defaultLocale, and interceptor to change the language?

A: Just add a WebFilter that sets the Accept-Language header from the value of a query parameter. The following example gets the language from the language query parameter on URIs like http://localhost:8080/examples?language=es:
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.adapter.HttpWebHandlerAdapter;
import reactor.core.publisher.Mono;

import static org.springframework.util.StringUtils.isEmpty;

@Component
public class LanguageQueryParameterWebFilter implements WebFilter {

    private final ApplicationContext applicationContext;

    private HttpWebHandlerAdapter httpWebHandlerAdapter;

    public LanguageQueryParameterWebFilter(final ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void loadHttpHandler() {
        this.httpWebHandlerAdapter = applicationContext.getBean(HttpWebHandlerAdapter.class);
    }

    @Override
    public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {
        final ServerHttpRequest request = exchange.getRequest();
        final MultiValueMap<String, String> queryParams = request.getQueryParams();
        final String languageValue = queryParams.getFirst("language");

        final ServerWebExchange localizedExchange = getServerWebExchange(languageValue, exchange);
        return chain.filter(localizedExchange);
    }

    private ServerWebExchange getServerWebExchange(final String languageValue, final ServerWebExchange exchange) {
        return isEmpty(languageValue)
                ? exchange
                : getLocalizedServerWebExchange(languageValue, exchange);
    }

    private ServerWebExchange getLocalizedServerWebExchange(final String languageValue, final ServerWebExchange exchange) {
        final ServerHttpRequest httpRequest = exchange.getRequest()
                .mutate()
                .headers(httpHeaders -> httpHeaders.set("Accept-Language", languageValue))
                .build();

        return new DefaultServerWebExchange(httpRequest, exchange.getResponse(),
                httpWebHandlerAdapter.getSessionManager(), httpWebHandlerAdapter.getCodecConfigurer(),
                httpWebHandlerAdapter.getLocaleContextResolver());
    }
}

It uses @EventListener(ApplicationReadyEvent.class) in order to avoid cyclic dependencies.
Feel free to test it and provide feedback on this POC.

A: With spring-boot-starter-webflux, there are

*

*DelegatingWebFluxConfiguration

*LocaleContextResolver

For example, to use a query parameter "lang" to explicitly control the locale:

*

*Implement LocaleContextResolver, so that
resolveLocaleContext() returns a SimpleLocaleContext determined by a GET parameter of "lang". I name this implementation QueryParamLocaleContextResolver. Note that the default LocaleContextResolver is an org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver.

*Create a @Configuration class that extends DelegatingWebFluxConfiguration. Override DelegatingWebFluxConfiguration.localeContextResolver() to return QueryParamLocaleContextResolver that we just created in step 1. Name this configuration class WebConfig.

*In WebConfig, override DelegatingWebFluxConfiguration.configureViewResolvers() and add the ThymeleafReactiveViewResolver bean as a view resolver. We do this because, for some reason, DelegatingWebFluxConfiguration will miss ThymeleafReactiveViewResolver after step 2.
Also, I have to mention that, to use i18n with the reactive stack, this bean is necessary:
    @Bean
    public MessageSource messageSource() {
        final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:/messages");
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(5);
        return messageSource;
}

After creating a natural template, some properties files, and a controller, you will see that:

*

*localhost:8080/test?lang=zh gives you the Chinese version

*localhost:8080/test?lang=en gives you the English version
Just don't forget <meta charset="UTF-8"> in <head>, otherwise you may see some nasty display of Chinese characters.

A: Starting with Spring Boot 2.4.0, the WebFluxAutoConfiguration contains a bean definition for the LocaleContextResolver, which allows us to inject custom LocaleContextResolver. For reference, the following is the default bean definition in Spring Boot 2.5.4 (the implementation may be different in earlier versions):
@Bean
@Override
@ConditionalOnMissingBean(name = WebHttpHandlerBuilder.LOCALE_CONTEXT_RESOLVER_BEAN_NAME)
public LocaleContextResolver localeContextResolver() {
    if (this.webProperties.getLocaleResolver() == WebProperties.LocaleResolver.FIXED) {
        return new FixedLocaleContextResolver(this.webProperties.getLocale());
    }
    AcceptHeaderLocaleContextResolver localeContextResolver = new AcceptHeaderLocaleContextResolver();
    localeContextResolver.setDefaultLocale(this.webProperties.getLocale());
    return localeContextResolver;
}

You can provide your own LocaleContextResolver implementation to get the locale from the query parameter by providing a custom bean definition:
//@Component("localeContextResolver")
@Component(WebHttpHandlerBuilder.LOCALE_CONTEXT_RESOLVER_BEAN_NAME)
public class RequestParamLocaleContextResolver implements LocaleContextResolver {
    @Override
    public LocaleContext resolveLocaleContext(ServerWebExchange exchange) {
        List<String> lang = exchange.getRequest().getQueryParams().get("lang");
        Locale targetLocale = null;
        if (lang != null && !lang.isEmpty()) {
            targetLocale = Locale.forLanguageTag(lang.get(0));
        }
        if (targetLocale == null) {
            targetLocale = Locale.getDefault();
        }
        return new SimpleLocaleContext(targetLocale);
    }

    @Override
    public void setLocaleContext(ServerWebExchange exchange, LocaleContext localeContext) {
        throw new UnsupportedOperationException(
            "Cannot change lang query parameter - use a different locale context resolution strategy");
    }
}

Note that the framework consumes the LocaleContextResolver with a specific name localeContextResolver (WebHttpHandlerBuilder.LOCALE_CONTEXT_RESOLVER_BEAN_NAME). You need to provide the bean with the given name. See #24209.

A: Another solution with spring boot starter web flux, which is much more cleaner, is to define your own HttpHandler using WebHttpHandlerBuilder in which you can set your LocaleContextResolver.
Documentation (see 1.2.2. WebHandler API) : https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-config-customize
MyLocaleContextResolver.java
public class MyLocaleContextResolver implements LocaleContextResolver {

    @Override
    public LocaleContext resolveLocaleContext(ServerWebExchange exchange) {
        return new SimpleLocaleContext(Locale.FRENCH);
    }

    @Override
    public void setLocaleContext(ServerWebExchange exchange, LocaleContext localeContext) {
        throw new UnsupportedOperationException();
    }
}

Then in a config file (annotated with @Configuration) or in your spring boot application file, defined your own HttpHandler bean.
Application.java
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public HttpHandler httpHandler(ApplicationContext context) {

        MyLocaleContextResolver localeContextResolver = new MyLocaleContextResolver();

        return WebHttpHandlerBuilder.applicationContext(context)
                .localeContextResolver(localeContextResolver) // set your own locale resolver
                .build();

    }

}

That's it!

A: Based on Jonatan Mendoza's answer, but simpliefied and in kotlin:
/**
 * Override Accept-Language header by "lang" query parameter.
 */
@Component
class LanguageQueryParameterWebFilter : WebFilter {
  override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
    val languageValue = exchange.request.queryParams.getFirst("lang") ?: ""
    if (languageValue.isEmpty()) {
      return chain.filter(exchange)
    }
    return chain.filter(
      exchange.mutate().request(
        exchange.request
          .mutate()
          .headers {
            it[HttpHeaders.ACCEPT_LANGUAGE] = languageValue
          }
          .build(),
      ).build(),
    )
  }
}


text:
Q: Keyboard interface to wxPython listbox I'm using a wxPython listbox on Windows to get a choice from the user, and I would like them to be able to select an item using the ENTER key, as if they had double-clicked. I know how to do this in C or C++ using the Windows API directly, but can't seem to find how to do it using wxPython. Anyone know how? It seems like an obvious thing to want to do.

A: Maybe I'm missing some nuance, there wasn't much info to go on, but it sounds like you could accomplish this by catching the keydown event, matching for enter and then calling your on_doubleclick function. Unless there's an implicit double-click handling you should be good to go.

A: The simple answer is that the wx.ListBox doesn't support that. Try using a one column wx.ListCtrl (in Report mode) instead.

A: This works for me, the key is to Bind EVT_KEY_UP, rather than EVT_KEY_DOWN:
import wx

class myListBoxDemo(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent=parent, title="testing ListBox right-click")
        self.panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.myListBox = wx.ListBox(self.panel,style=wx.LB_HSCROLL|wx.LB_SINGLE)
        self.myListBox.Bind(wx.EVT_KEY_UP, self.OnKeyDownSelectedList)

        self.myListBox.Append('item 1')
        self.myListBox.Append('item 2')
        self.myListBox.Append('item 3')
        self.myListBox.Append('item 4')

        sizer.AddF(self.myListBox, wx.SizerFlags(1).Expand())
        self.panel.SetSizer(sizer)

    def OnKeyDownSelectedList(self, event):
        print "KeyCode: %d" % event.GetKeyCode()
        print "ListBox Item Index: %d" % event.GetEventObject().GetSelection()

import wx.lib.mixins.inspection as wit
class AppWInspection(wx.App, wit.InspectionMixin):
    def OnInit(self):
        self.Init()  # enable Inspection tool
        return True

if __name__ == "__main__":
    app = AppWInspection()
    f = myListBoxDemo(None)
    f.Show()
    app.MainLoop()


text:
Q: Can't understand what this text is saying I am following a tutorial and got to this point: http://rubysource.com/building-your-first-rails-application-views-and-controllers/
rails generate controller urls new

The reason we only passed in the new action (instead of new, create,
  and show) is because Rails automatically generates a dummy view for
  each action included in the generator call. In this case, we only want
  a dummy view for the new action, so we exclude the others.

So why we only need to create the controller for new? Can someone plase explain it in a little more details?

A: This will only create the new action in the controller and should skip the other ones.
EDIT:
It will generate a controller called UrlsController in app/controllers and in that controller there will only be one method called action which corresponds to a route or url called urls/new

A: The command is used to create the UrlsController with only one method: new.
This command will also automatically create a view file for you in:
app/views/urls/new.html.erb

Had you supplied more arguments like:
rails generate controller urls new create show

You would have gotten:
app/views/urls/new.html.erb
app/views/urls/create.html.erb
app/views/urls/show.html.erb

Since the tutorial only needs the new view it was unnecessary to create the additional views, hence those additional arguments were not added to the generate command.
Later in the tutorial you manually add the create and show methods, but you never add views for those methods (since those methods will not be needing specific views files in this application).
So: what you did was create the controller UrlsController with one method new, and the corresponding view for that method. The rest of the methods you will code in manually later in the tutorial so there was no need to auto-generate anything else (create or show).


text:
Q: Can I be sure the built-in hash for a given string is always the same? I am getting a string hash like this:
string content = "a very long string";
int contentHash = content.GetHashCode();

I am then storing the hash into a dictionary as key mapping to another ID. This is useful so I don't have to compare big strings during default dictionary hash computation but I can just fish the ID from the dictionary by key.
Can I be sure that the hash for a given string ("a very long string") will be always the same?
Can I be sure that two different strings won't have the same hash?
Also, if possible, how likely is it to get the same hash for different strings?

A: Just to add some detail as to where the idea of a changing hashcode may have come from.
As the other answers have rightly said the hashcode for a specific string will always be the same for a specific runtime version.  There is no guarantee that a newer runtime might use a different algorithm perhaps for performance reasons.
The String class overrides the default GetHashCode implementation in object.
The default implementation for a reference type in .NET is to allocate a sequential ID (held internally by .NET) and assign it to the object (the objects heap storage has slot for storing this hashcode, it only assigned on the first call to GetHashCode for that object).
Hence creating an instance of a class, assigning it some values then retrieving the hashcode, followed by doing the exact same sequence with the same set of values will yeild different hashcodes.  This may be the reason why some have been led to believe that hashcodes can change.  In fact though its the instance of a class which is allocated a hashcode once allocated that hashcode does not change for that instance.
Edit: I've just noticed that none of the answers directly reference each of you questions (although I think the answer to them is clear) but just to tidy up:-

Can I be sure that the hash for a given string ("a very long string") will be always the same?

In your usage,  yes.

Can I be sure that two different strings won't have the same hash?

No. Two different strings may have the same hash.

Also, if possible, how likely is it to get the same hash for different strings?

The probability is quite low, resulting hash is pretty random from a 4G domain.

A: Yes it will, that's the purpose of a hash code! It's not guaranteed to be the same between different versions of the runtime tho.  More info on MSDN

A: As others pointed out, the hash will remain constant over time. But why are you hashing a string and then put it as key on a Dictionary? Hashes are not guaranteed to be unique. So you comparisons might be incorrect. Let the Dictionary do it's job. I think the most appropriate collection to this case is a HashSet.

A: As many others have said, the implementation is dependent on the version of the framework but it also depends on the architecture.  The implementation of string.GetHashCode() is dfferent in the x86 and x64 versions of the framework even if they have the same version number.
For example, if you are writing a client/server or .net remoting type of architecture and want to use a string HashCode to stop from downloading a large resource, you can only do this if both are the same version and bitness.  Otherwise you should use a different hash -- MD5, SHA etc will work correctly.

A: The documentation for Object.GetHashCode states

If two objects compare as equal, the GetHashCode method for each object must return the same value.

So you are guaranteed that the hash code will be the same for a given string.  However, you aren't guaranteed that it will be unique (there may be other strings that have the same hash code).

A:
Can I be sure that the hash for a
  given string ("a very long string")
  will be always the same?

Yes

Can I be sure that two different
  strings won't have the same hash?

No

A: You don't have to guess about run-times or versions, just use this CaseInsensitiveStringComparer class that I made in my spare time (you can pass it to the constructor of the dictionary or if you are using .NET 3.5, a HashSet):
/// <summary>
/// StringComparer that is basically the same as StringComparer.OrdinalIgnoreCase, except that the hash code function is improved and guaranteed not to change.
/// </summary>
public class CaseInsensitiveStringComparer : StringComparer
{
    /// <summary>
    /// Compares two strings, ignoring case
    /// </summary>
    /// <param name="x">First string</param>
    /// <param name="y">Second string</param>
    /// <returns>Compare result</returns>
    public override int Compare(string x, string y)
    {
        return StringComparer.OrdinalIgnoreCase.Compare(x, y);
    }

    /// <summary>
    /// Checks if two strings are equal, ignoring case
    /// </summary>
    /// <param name="x">First string</param>
    /// <param name="y">Second string</param>
    /// <returns>True if strings are equal, false if not</returns>
    public override bool Equals(string x, string y)
    {
        return Compare(x, y) == 0;
    }

    /// <summary>
    /// Gets a hash code for a string, ignoring case
    /// </summary>
    /// <param name="obj">String to get hash code for</param>
    /// <returns>Hash code</returns>
    public override int GetHashCode(string obj)
    {
        if (obj == null)
        {
            return 0;
        }
        int hashCode = 5381;
        char c;
        for (int i = 0; i < obj.Length; i++)
        {
            c = obj[i];
            if (char.IsLower(c))
            {
                c = char.ToUpperInvariant(c);
            }
            hashCode = ((hashCode << 5) + hashCode) + c;
        }
        return hashCode;
    }
}

A: Yes, it will be consistent since strings are immutable. However, I think you're misusing the dictionary. You should let the dictionary take the hash of the string for you by using the string as the key. Hashes are not guaranteed to be unique, so you may overwrite one key with another.

A: Strings are hashed based on their content, so yes, that hash should remain the same over time if you use the default GetHashCode.

A: As has already been mentioned you can be sure that a hash for a partiular string will be the same as they are hashed based on content. However you cannot be sure that a particular string will be hashed the same for later versions of the .NET framework as is mentioned here
So I would say that this method is fine if it is being used internally to an application. If you are persisting the value to a data store then it is probably best to roll your own function to ensure that it remains consistent across versions.

A: Given that there are an infinite number of different strings its just not possible to allocate a different int (32bits which can represent up to 4 billion) number for each.
With just 8 characters tehre are 2^60 different strings. This is infinitely larger than
2^32. Naturally the hashcode of some of these strings must clash.
Two objects with the same hashcode do not have to be equal. To know for sure use the equals method. This is basically the strategy used by a hashmap to determine if keys are equal.
Map.get(String key)

*

*Calculate hashcode of key

*Use modulo to figure out which bucket key belongs too.

*Loop thru all the entries from that bucket attempting to find a matching key.

*When a key match is found return that entries' value.

As a side note as maps gain more and more elements it will recreate more buckets and place all the old entries into the new buckets. This helps present the bucket entry list from growing into really really long lists. A map wants many buckets with short lists.
The javadoc for Object.hashcode makes for interesting reading - ive pasted a snippet below.
 The equals method implements an equivalence relation:

* It is reflexive: for any reference value x, x.equals(x) should return true.
* It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
* It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
* It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
* For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

A: This is a great example for the evils of premature optimization.
Do you have the output of a profiler or benchmark that tells you String comparison between entries in the same hash bucket is actually causing a performance problem?
Didn't think so. Just use the string itself as a key in the Dictionary. That's how you're supposed to use it.
BTW, there are far, far more different strings than there are different int, so basic logic tells you that it's impossible to have a different hashcode for each different string.