text:
Q: How can I make a click on a ListView open a new activity pertaining to that Activity? I want to have it to where I can click on an item in a ListView and it open an activity describing the thing happening that the person clicked on. I am completely new to Android Development, so constructive criticism is appreciated(Aka I know this code is ugly).
package com.example.something.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import static android.widget.AdapterView.*;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[]Planets = {"Mercury", "Venus", "Earth", "Mars" , "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};

       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Planets)

        ListView PlanetList = (ListView) findViewById(R.id.PlanetList);

        PlanetList.setAdapter(adapter);

        PlanetList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override

            public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg) {

                //What do I change to make the thing in the list open a new activity about that item on the list?

                String planetPicked = "You selected " + String.valueOf(adapterView.getItemAtPosition(position));

                                    Toast.makeText(MainActivity.this, planetPicked, Toast.LENGTH_SHORT).show();
                                }
                        });
                }

}

A: You will need an intent:
Intent itemIntent = new Intent(MainActivity.this, your_seond_activity.class);
startActivity(itemIntent);

You will probably want to pass some data to the new activity, and for this you can use InentExtra, so the code will be:
Intent itemIntent = new Intent(MainActivity.this, your_seond_activity.class);
itemIntent.putExtra("some_key", some_data);
startActivity(itemIntent);

Read about it here:
http://developer.android.com/reference/android/content/Intent.html
and here
Intent.html#putExtra

A: I would start by saying that in java, it's typical that variables start with a lowercase letter and classes start with an Uppercase letter.
Code for MainActivity.java file
PlanetList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // replace DesiredActivity with your activity class name.
        Intent intent = new Intent(MainActivity.this, DesiredActivity.class);

        // load intent.putExtra with any object you want to access in the Desired Activity class
        intent.putExtra("SOME_KEY_VALUE", apps.get(position).name);
        startActivity(intent);
    }
});

In your DesiredActivity.java file
To access your extras that you loaded onto the intent use method
getIntent().getStringExtra(getString("SOME_KEY_VALUE"));
This example is for getting a string value that you put onto the extra.  You can find other methods for intents and extras on the android developer guide.

A: Use the below code.
For reference click here to see the full code
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

// Array of strings storing country names
String[] countries = new String[] {
    "India",
    "Pakistan",
    "Sri Lanka",
    "China",
    "Bangladesh",
    "Nepal",
    "Afghanistan",
    "North Korea",
    "South Korea",
    "Japan"
};

// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[]{
    R.drawable.india,
    R.drawable.pakistan,
    R.drawable.srilanka,
    R.drawable.china,
    R.drawable.bangladesh,
    R.drawable.nepal,
    R.drawable.afghanistan,
    R.drawable.nkorea,
    R.drawable.skorea,
    R.drawable.japan
};

// Array of strings to store currencies
String[] currency = new String[]{
    "Indian Rupee",
    "Pakistani Rupee",
    "Sri Lankan Rupee",
    "Renminbi",
    "Bangladeshi Taka",
    "Nepalese Rupee",
    "Afghani",
    "North Korean Won",
    "South Korean Won",
    "Japanese Yen"
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Each row in the list stores country name, currency and flag
    List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

    for(int i=0;i<10;i++){
        HashMap<String, String> hm = new HashMap<String,String>();
        hm.put("txt", "Country : " + countries[i]);
        hm.put("cur","Currency : " + currency[i]);
        hm.put("flag", Integer.toString(flags[i]) );
        aList.add(hm);
    }

    // Keys used in Hashmap
    String[] from = { "flag","txt","cur" };

    // Ids of views in listview_layout
    int[] to = { R.id.flag,R.id.txt,R.id.cur};

    // Instantiating an adapter to store each items
    // R.layout.listview_layout defines the layout of each item
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

    // Getting a reference to listview of main.xml layout file
    ListView listView = ( ListView ) findViewById(R.id.listview);

    // Setting the adapter to the listView
    listView.setAdapter(adapter);

    // Item Click Listener for the listview
    OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
            // Getting the Container Layout of the ListView
            LinearLayout linearLayoutParent = (LinearLayout) container;

            // Getting the inner Linear Layout
            LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);

            // Getting the Country TextView
            TextView tvCountry = (TextView) linearLayoutChild.getChildAt(0);

            Toast.makeText(getBaseContext(), tvCountry.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    };

    // Setting the item click listener for the listview
    listView.setOnItemClickListener(itemClickListener);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}


text:
Q: undefined - Javascript - DOM - checkboxs Dispongo de un select con cuatro opciones, puedo elegir las que quiera, al pulsar el button "enviar" se debe enviar el texto de las opciones seleccionadas a una div.
Éste es mi código:

//Función que crea una caja con los datos del resumen. Se debe crear usando DOM.
function crearCajaResumen() {
  //Creamos el elemento/objeto que deseamos, sea
 o
 o <form>, etc.
  var div = document.createElement("div");
  //DIV tiene la propiedad style, la cual permite acceder a atributos CSS. Ejemplo: div.style.width = "280px"; ...
  div.setAttribute("style", "width: 280px; height: 170px; background-color: #FE775A; float: left;");
  //Guardamos en una variable el elemento/objeto que deseamos,
  //var variable = document.getElementsByTagName("etiqueta")[posicion];
  var body = document.getElementsByTagName("body")[0];
  //Añadimos al documento body un hijo llamado "div".
  document.body.appendChild(div);
  //Guardamos en una variable el elemento/objeto que deseamos,
  var center = document.getElementsByTagName("center")[0];
  //Insertamos el elemento "div" antes que el "center".
  body.insertBefore(div, center);
  //Creamos un nodo de texto que agregaremos al div.
  var titulo = document.createTextNode("DATOS RESUMEN FORMULARIO:\n\n");
  //Añade un nuevo nodo al final de la lista.
  div.appendChild(titulo);
  //Creamos un nodo de texto que agregamos al div.
  var contar = document.createTextNode("Has seleccionado " + contar_seleccionados() + " elementos.");
  div.appendChild(contar);
}

var texto_opciones = ["Analisis y programacion", "Hardware, redes y seguridad", "Administracion de bases de datos", "Telecomunicaciones"];
var textos_seleccionados = "";
//Función que cuenta los checkboxs seleccionados (marcados).
function contar_seleccionados() {
  //Guardamos en una variable los checkboxs (un array) del elemento <form> con la propiedad checkbox.
  var checkboxs = document.getElementById("miformulario").getElementsByName("prefe");
  var contador = 0;
  //Recorremos el array y guardamos en una variable los checkboxs seleccionados.
  for (var i = 0; i < checkboxs.length; i++) {

    if (checkboxs[i].checked) {
      contador = contador + 1;
      textos_seleccionados = textos_seleccionados + texto_opciones[i] + "
";
    }//Cerramos el for para que me acepte la correcion
  }
  console.log(textos_seleccionados);
  console.log(contador);
  return contador;
}

// **Manejo de eventos "onclick" y métodos enviar.**
miformulario.btnEnviar.addEventListener("click", function() {
  return confirmEnviar();
}, false);

function confirmEnviar() {
  var pregunta = confirm("¿Deseas enviar el formulario?");
  if (pregunta == true) {
    deshabilitar_btnEnviar();
  } else {
    //No hacer nada.
    event.preventDefault();
  }
}

function deshabilitar_btnEnviar() {
  miformulario.btnEnviar.disabled = true;
  miformulario.btnEnviar.value = "Enviando...";
  setTimeout(function() {
    miformulario.btnEnviar.disabled = false;
    miformulario.btnEnviar.value = "Enviar";
    //Llamada a la función crearCajaResumen();
    crearCajaResumen();
  }, 3000);
  return false;
}
<form id="miformulario">

         Selecciona tus Preferencias:

      <input type="checkbox" name="prefe" value="si" colspan=3>Analisis y programacion

      <input type="checkbox" name="prefe" value="si" colspan=3>Hardware, redes y seguridad

      <input type="checkbox" name="prefe" value="si" colspan=3>Administracion de bases de datos

      <input type="checkbox" name="prefe" value="si" colspan=3>Telecomunicaciones

  <input type="button" id="btnEnviar" value="Enviar" />
</form>

¿Por qué me selecciona bien las opciones marcadas pero no se muestran los textos?
Y éste el error por consola:

funciones.js:446 undefined
undefined
undefined
undefined

  funciones.js:447 4

A: Los textos que quieres rescatar, DEBEN ir en el atributo value de los inputs, como los tienes tu no tienen nada que ver con los checkbox, todos tienen el valor value="si". Si es solo Javascript puedes probar :

// **Manejo de eventos "onclick" y métodos enviar.**
miformulario.btnEnviar.addEventListener("click", function() {
  return confirmEnviar();
}, false);

//Función que crea una caja con los datos del resumen. Se debe crear usando DOM.
function crearCajaResumen() {
  //Creamos el elemento/objeto que deseamos, sea
 o
 o <form>, etc.
  var div = document.createElement("div");
  //DIV tiene la propiedad style, la cual permite acceder a atributos CSS. Ejemplo: div.style.width = "280px"; ...
  div.setAttribute("style", "width: 280px; height: 170px; background-color: #FE775A; float: left;");
  //Guardamos en una variable el elemento/objeto que deseamos,
  //var variable = document.getElementsByTagName("etiqueta")[posicion];
  var body = document.getElementsByTagName("body")[0];
  //Añadimos al documento body un hijo llamado "div".
  document.body.appendChild(div);
  //Guardamos en una variable el elemento/objeto que deseamos,
  var center = document.getElementsByTagName("center")[0];
  //Insertamos el elemento "div" antes que el "center".
  body.insertBefore(div, center);
  //Creamos un nodo de texto que agregaremos al div.
  var titulo = document.createTextNode("DATOS RESUMEN FORMULARIO:\n\n");
  //Añade un nuevo nodo al final de la lista.
  div.appendChild(titulo);
  //Creamos un nodo de texto que agregamos al div.
  //var contar = document.createTextNode("Has seleccionado " + contar_seleccionados() + " elementos.");

  var seleccionados = [];
  var inputElements = document.getElementsByName("prefe");
  for(var i=0; inputElements[i]; ++i){
      if(inputElements[i].checked){
           seleccionados.push(inputElements[i].value);
      }
  }
  var contar = document.createTextNode("Has seleccionado " + seleccionados.length + " elementos.");
  var salto = document.createElement("br")
  div.appendChild(contar);
  div.appendChild(salto);

  seleccionados.forEach(function(value, index, array) {
      var salto = document.createElement("br")
      var val = document.createTextNode(value);
      div.appendChild(salto);
      div.appendChild(val);
  });
}

function deshabilitar_btnEnviar() {
  miformulario.btnEnviar.disabled = true;
  miformulario.btnEnviar.value = "Enviando...";
  setTimeout(function() {
    miformulario.btnEnviar.disabled = false;
    miformulario.btnEnviar.value = "Enviar";
    //Llamada a la función crearCajaResumen();
    crearCajaResumen();
  }, 3000);
  return false;
}

function confirmEnviar() {
  var pregunta = confirm("¿Deseas enviar el formulario?");
  if (pregunta == true) {
    deshabilitar_btnEnviar();
  } else {
    //No hacer nada.
    event.preventDefault();
  }
}
<form id="miformulario">

                 Selecciona tus Preferencias:

              <input type="checkbox" name="prefe" value="Analisis y programacion" colspan=3>Analisis y programacion

              <input type="checkbox" name="prefe" value="Hardware, redes y seguridad" colspan=3>Hardware, redes y seguridad

              <input type="checkbox" name="prefe" value="Administracion de bases de datos" colspan=3>Administracion de bases de datos

              <input type="checkbox" name="prefe" value="Telecomunicaciones" colspan=3>Telecomunicaciones

          <input type="button" id="btnEnviar" value="Enviar" />
        </form>

A: Deberías reiniciar la variable nada mas entrar en el método, si no se te van a ir acoplando los resultados nuevos con los del anterior cada vez que le des al botón. Me faltaría ver como llamas a los métodos, lo he pegado en un jsfiddle y me funciona perfectamente.
Añade el código del botón y su onClick
EDICION
En la linea document.getElementById("miformulario").getElementsByTagName("input") estas sacando todos los inputs del formulario, y aunque compruebes que tenga name='prefe' la variable i se va incrementando, de tal manera que cuando llega a los checkbox, la variable i alcanza un valor superior al tamaño del Array y al pasarse te saca undefined
La linea debería quedar document.getElementById("miformulario").getElementsByName("prefe")

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET MVC: Redirecting back to page when no parameter is given to URL http://localhost:50034/Admin/Delete/723
Always needs this parameter to perform the action, however, if you go to the URL without the parameter, an exception occurs. How do you handle this and redirect back to the main page without doing anything?
Thanks.

A: I am not sure what you mean, do you mean that the url http://localhost:50034/Admin/Delete/ is generating an exception?
Try setting the id parameter as nullable, like this:
public class MyController : Controller
{
  public void Delete(int? id)
  {
    if (!id.HasValue)
    {
      return RedirectToAction("Index", "Home");
    }

    ///
  }
}

A: public ActionResult Details(int? Id)
{
     if (Id == null)
           return RedirectToAction("Index");
     return View();
}

A: Assuming that you are using the default routing rules:
  routes.MapRoute(
     "Default",  // Route name
     "{controller}/{action}/{id}",  // URL with parameters
     new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
   );

then create your Delete method with a nullable int (int?) for the id parameter similar to
public ActionResult Delete(int? id)
{
   if (id.HasValue)
   {
      // do your normal stuff
      // to delete
      return View("afterDeleteView");
    }
    else
    {
      // no id value passed
      return View("noParameterView");
    }

}


text:
Q: boost.variant derived type: cannot use copy constructor I have a type that derives from boost::variant<T, E>. I do the following, and I cannot use the copy constructor, I cannot figure out why, some SFINAE seems to fail. Looks that the boost::variant<T, E> construction is swallowing a T as ExpectedResult<T, E> in the inherited constructor.
How could I fix it to make it work and with the simplest solution?
template <class T, class E>
class ExpectedResult : boost::variant<T, E> {
public:
    using boost::variant<T, E>::variant;
};

ExpectedResult<int,float> er;
ExpectedResult<int, float> er2 = er;

error: no type named 'type' in 'boost::enable_if<boost::mpl::and_<boost::mpl::not_<boost::is_same<Emotiv::Cortex::Utilities::ExpectedResult<int, float>, boost::variant<int, float> > >, boost::detail::variant::is_variant_constructible_from<const Emotiv::Cortex::Utilities::ExpectedResult<int, float> &, boost::mpl::l_item<mpl_::long_<2>, int, boost::mpl::l_item<mpl_::long_<1>, float, boost::mpl::l_end> > >, mpl_::bool_<true>, mpl_::bool_<true>, mpl_::bool_<true> >, void>'; 'enable_if' cannot be used to disable this declaration
        typename boost::enable_if<mpl::and_<
                                  ^~~~~~~~~~
note: in instantiation of member function 'boost::variant<int, float>::variant' requested here
    using boost::variant<T, E>::variant;
    while substituting deduced template arguments into function template 'ExpectedResult' [with T = Emotiv::Cortex::Utilities::ExpectedResult<int, float>]
    ExpectedResult<int, float> er2 = er;

A: Boost variant has a perfect forwarding constructor.
You are importing it into your class.
It guards against consuming self& by checking if self is exactly a boost::variant.  You are passing it an ExpectedResult&.
This confuses it.
template <class T, class E>
struct ExpectedResult : boost::variant<T, E> {
  using boost::variant<T, E>::variant;
  ExpectedResult()=default;
  ExpectedResult(ExpectedResult const&)=default;
  ExpectedResult(ExpectedResult &&)=default;
  ExpectedResult(ExpectedResult & o):
    ExpectedResult( const_cast<ExpectedResult const&>(o) )
  {}
  ExpectedResult(ExpectedResult &&)=default;
  ExpectedResult(ExpectedResult const&& o):
    ExpectedResult( o ) // calls const& ctor
  {}
  ExpectedResult& operator=(ExpectedResult const&)=default;
  ExpectedResult& operator=(ExpectedResult &&)=default;
  ExpectedResult& operator=(ExpectedResult &) {
    return *this=const_cast<ExpectedResult const&>(o);
  }
  ExpectedResult& operator=(ExpectedResult const&& o){
    return *this = o; // const& assign
  }
};

I suspect the above defaulted and manually written special member functions may help.
To be complete, you'd also have to include volatile, exploding it by another bunch.
I would be careful about adding my own perfect forwarding constructor as well as a using parent constructor, as the rules for how these change change in C++17 in a possibly breaking way.  I am currently very leery of using inherited constructors due to the breaking changes in C++17 I do not fully understand as yet.
Another approach would be to avoid inheriting construction and instead forward to the variant.
template <class T, class E>
struct ExpectedResult : boost::variant<T, E> {
  using base=boost::variant<T, E>;
  ExpectedResult()=default;
  ExpectedResult(ExpectedResult const&)=default;
  ExpectedResult(ExpectedResult &&)=default;
  ExpectedResult(ExpectedResult &&)=default;
  ExpectedResult& operator=(ExpectedResult const&)=default;
  ExpectedResult& operator=(ExpectedResult &&)=default;

  template<class T0, class...Ts,
    class=std::enable_if_t<
      std::is_constructible<base, T0, Ts...>::value
      && (
        (sizeof...(ts)!=0)
        || !std::is_same<std::decay_t<T0>, ExpectedResult>::value
      )
    >
  >
  ExpectedResult(T0&&t0, Ts&&...ts):
    base(std::forward<T0>(t0), std::forward<Ts>(ts)...)
  {}
};

which is perfect forwarding with all of its imperfections, but close enough for most use.
An initializer_list<T>, Ts&&... constructor may make the perfect forwarding more perfect, so ExpectedResult<std::vector<int>, bool> er{ {1,2,3,4} } works.


text:
Q: Python writing two dictionaries with different value types into a single csv file using writerow I have two dictionaries similar to samples below:
# First dictionary
dict_names = {}
dict_names[1] = 'Jane'
dict_names[2] = 'Alex'
dict_names[3] = 'Max'

# Second dictionary
dict_numList = {}
dict_numList[1] = [i for i in range(50)]
dict_numList[2] = [2*i for i in range(50)]
dict_numList[3] = [i*i for i in range(50)]

I would like to write to csv file where each row includes common key (in its first column, when opened using excel), string value from the first dictionary (in its second column), each element of the list value from the second dictionary (in its third column all the way to 52nd column).
I have attempted the code below, but it will write the entire number list into third column.
with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter = ',')
    for key, val in dict_names.iteritems():
        csvwriter.writerow([key, val, [dict_numList[key][i] for i in range(0,50)]])

Any help would be greatly appreciated!
Thanks
SOLUTION: given the answers, I have used the code below
with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter = ',')
    for key, val in dict_names.iteritems():
        csvwriter.writerow([key, val] + dict_numList[key])

A: If your comprehension is redundant, but keeping it for now, the following approach will suffice:
for key, val in dict_names.iteritems():
    row = [key, val]
    row.extend(dict_numList[key][i] for i in range(0,50))
    csvwriter.writerow(row)

Really, I believe you simply need:
for key, val in dict_names.iteritems():
    row = [key, val]
    row.extend(dict_numList[key])
    csvwriter.writerow(row)

A: I think the problem is you're including a list in a list:
[key, val, [array of things]]

Instead of:
[key, val, thing 1, thing 2...]

You can simply append the two lists together with the + operator:
csvwriter.writerow([key, val] + [dict_numList[key][i] for i in range(0,50)])


text:
Q: Hiding URL parameters with .htaccess while still making them available to $_GET I have a script on my site ('write-review.php') that takes an optional url parameter 'site'. So server-side requests could be:
/reviews/write-review.php

or
/reviews/write-review.php?site=foo

I'm using .htaccess to create search engine friendly URLs and hide my php extensions, so that requests to this script are respectively rewritten as
/reviews/write-a-review/

or
/reviews/write-a-review/foo

I think having 'foo' in the URL may cause confusion for my users, so I'm trying to write an htaccess rewrite rule that removes 'foo' while still passing this variable to my script. Thus, a request to /reviews/write-a-review/foo would be rewritten as /reviews/write-a-review/ but write-review.php would be passed 'foo'.
The rewrite rule I currently have in place is:
RewriteRule ^reviews/write-a-review/?$ reviews/write-review.php
RewriteRule ^reviews/write-a-review/([a-zA-Z0-9_-]+)/?$ reviews/write-review.php?site=$1

Is it even possible to do what I've described above? There are MANY questions on Stack Overflow that are similar to this, and I've read through at least a dozen, but I haven't found a way to do this specifically.
Any help is really appreciated.
Thanks,
Chris

A:
Is it even possible to do what I've described above?

No. To alter the actual URL the user inputs, you'd have to do a header redirect, during which you would lose foo.
This is not possible, except maybe by using ridiculous technical tricks like storing foo in a session variable or something. I would not recommend going that route.


text:
Q: Neo4j Path sampling I have CALL apoc.algo.allSimplePaths(A, B, '', 3) result that look like this:

*

*[A –>relation1 –>B]

*[A –>relation2 –>B]

*[A –>relation2->C->relation 1–>B]

*[A –>relation5->D->relation 3–>B]

*[A –>relation2->Y->relation 1–>B]

*[A –>relation2->E->relation 1–>B]

*[A –>relation2->D–>relation2->F->relation 1–>B]

*[A –>relation2->F–>relation4->Y->relation 2–>B]

Desired result: FOREACH pathlength, randomly return 1 row

*

*[A –>relation2 –>B]

*[A –>relation2->Y->relation 1–>B]

*[A –>relation2->D–>relation2->F->relation 1–>B]
The result is representative of all pathlengths:
The first row:
[A –>relation2 –>B]     is a sample from path length 1
The second row:
[A –>relation2->Y->relation 1–>B   is a sample from path length 2
 the third row:
[A –>relation2->D–>relation2->F->relation 1–>B].   is a sample from path length 3

A: To solve this, we'll need to collect the paths according to their length, so we have a row and list per length, then shuffle the collected paths and take one.
...
CALL apoc.algo.allSimplePaths(A, B, '', 3) YIELD path
WITH length(path) as length, collect(path) as paths
WITH length, apoc.coll.shuffle(paths)[0] as randomPath
ORDER BY length ASC
RETURN randomPath


text:
Q: Rotate image and adjust space I want to rotate a picture (90 degrees) that is between two boxes. The problem is that the picture overlaps the two boxes in this case.
Example 1: Wrong formatting
CSS:
.box{
    height:50px;
    width:200px;
    background-color:blue;
}

HTML:

Top

Bottom

Example 2: Desired formatting
There is a solution, but I can not use it because "image-orientation" is not recognized by all browsers (especially mobile devices):

Top

Bottom

Is there any other solution that a rotated image does not overlap other elements? Or is there any alternative for image-orientation that works with all browsers?

A: If you are looking to keep the image in a relative space such as a restricted width then I would suggest the following which adds a div tag around the image, uses the before pseudo selector to create an aspect ratio based off of the boxes max with of 1:1 width & height, then absolute positioning the image within that to rotate around a center access point. See code below:


text: Q: persistant cookies using nodejs I want to save some cookies in my browser using node.js. Any one knows how I can achieve this behavior? My purpose is when the user has checked the checkbox("keep me logged in") then the checkbox state and the cookies should be stored.


text:
Q: Bootstrap's popover only working on buttons - not anchors or spans I am including tooltip.js and popover.js.
When my markup looks like so:
<button class="popover-dismiss" data-toggle="popover" title="sheen"
data-content="<a href="sheen60">60</a>, <a href="sheen80">80</a>">
PDS
</button>

with JS
$('.popover-dismiss').popover({
  trigger: 'focus',
  html: 'true'
})

Then everything works fine. However, when I change my button to an a, it breaks. There are no errors in the console. It just simply does not give the popup.

PDS

The exact same attributes. Just an anchor instead of a button. I have also tried using a span and that does not appear to work either.

A: Ok so it turns out there is a bug in Twitter Bootstrap. It has been opened and closed a couple times.
There is currently a work around:
1) Do not use trigger: focus when initializing bootstrap popovers
2) Instead use data-trigger="focus" as an attribute to the items which will trigger the popover
3) Items which have a popover will need to have tabindex="-1" explicitly declared.
Cross-browser working example here: http://jsfiddle.net/v5L7m/3/
I have also confirmed this in a real-world use case scenario.
Edit: @xanderiel noted that tabindex=0 now appears to cause a browser native focus border which is what my original answer called for. They say a tabindex of -1 eliminates this border.

A: Well, I guess that if you want to use "focus" as a trigger your element must be focusable.  Setting tabindex forces the element to be focusable, that's why trigger "focus" starts working when tabindex is set.
Consider using a tabindex of -1 if you do not expect users to actually stop on the element hitting the tab key.
That's all there is to it. Trigger: focus can be used in JS initialization.

A: There's no need for a workaround or anything. It works just fine if you set the info via JS, here's an example:
HTML:
Dismissible popover

JS:
$(function() {
    $(document).popover({
        selector: '[data-toggle=popover]',
        trigger: 'focus'
    });
});

JSFiddle: https://jsfiddle.net/s02ykLo2/

A: Try setting container: 'body' option for popover() call.


text:
Q: Detect all columns in an oracle table which have the same value in each row Every day, the requests get weirder and weirder.
I have been asked to put together a query to detect which columns in a table contain the same value for all rows.   I said "That needs to be done by program, so that we can do it in one pass of the table instead of N passes."
I have been overruled.
So long story short.  I have this very simple query which demonstrates the problem. It makes 4 passes over the test set.  I am looking for ideas for SQL Magery which do not involve adding indexes on every column, or writing a program, or taking a full human lifetime to run.
And sigh   It needs to be able to work on any table.
Thanks in advance for your suggestions.
WITH TEST_CASE AS
(
    SELECT 'X' A, 5 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 3 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 7 B, 'TUE' C, NULL D FROM DUAL
),
KOUNTS AS
(
    SELECT SQRT(COUNT(*)) S, 'Column A' COLUMNS_WITH_SINGLE_VALUES
    FROM TEST_CASE P, TEST_CASE Q
    WHERE P.A = Q.A OR (P.A IS NULL AND Q.A IS NULL)

    UNION ALL

    SELECT SQRT(COUNT(*)) S, 'Column B' COLUMNS_WITH_SINGLE_VALUES
    FROM TEST_CASE P, TEST_CASE Q
    WHERE P.B = Q.B OR (P.B IS NULL AND Q.B IS NULL)

    UNION ALL

    SELECT SQRT(COUNT(*)) S, 'Column C' COLUMNS_WITH_SINGLE_VALUES
    FROM TEST_CASE P, TEST_CASE Q
    WHERE P.C = Q.C OR (P.C IS NULL AND Q.C IS NULL)

    UNION ALL

    SELECT SQRT(COUNT(*)) S, 'Column D' COLUMNS_WITH_SINGLE_VALUES
    FROM TEST_CASE P, TEST_CASE Q
    WHERE P.D = Q.D OR (P.D IS NULL AND Q.D IS NULL)
)
SELECT COLUMNS_WITH_SINGLE_VALUES
FROM KOUNTS
WHERE S = (SELECT COUNT(*) FROM TEST_CASE)

A: Optimizer statistics can easily identify columns with more than one distinct value.  After statistics are gathered a simple query against the data dictionary will return the results almost instantly.
The results will only be accurate on 10g if you use ESTIMATE_PERCENT = 100.  The results will be accurate on 11g+ if you use ESTIMATE_PERCENT = 100 or AUTO_SAMPLE_SIZE.
Code
create table test_case(a varchar2(1), b number, c varchar2(3),d number,e number);

--I added a new test case, E.  E has null and not-null values.
--This is a useful test because null and not-null values are counted separately.
insert into test_case
SELECT 'X' A, 5 B, 'FRI' C, NULL D, NULL E FROM DUAL UNION ALL
SELECT 'X' A, 3 B, 'FRI' C, NULL D, NULL E FROM DUAL UNION ALL
SELECT 'X' A, 7 B, 'TUE' C, NULL D, 1    E FROM DUAL;

--Gather stats with default settings, which uses AUTO_SAMPLE_SIZE.
--One advantage of this method is that you can quickly get information for many
--tables at one time.
begin
    dbms_stats.gather_schema_stats(user);
end;
/

--All columns with more than one distinct value.
--Note that nulls and not-nulls are counted differently.
--Not-nulls are counted distinctly, nulls are counted total.
select owner, table_name, column_name
from dba_tab_columns
where owner = user
    and num_distinct + least(num_nulls, 1) <= 1
order by column_name;

OWNER     TABLE_NAME   COLUMN_NAME
-------   ----------   -----------
JHELLER   TEST_CASE    A
JHELLER   TEST_CASE    D

Performance
On 11g, this method might be about as fast as mucio's SQL statement.  Options like cascade => false would improve performance by not analyzing indexes.
But the great thing about this method is that it also produces useful statistics.  If the system is already gathering statistics at regular intervals the hard work may already be done.
Details about AUTO_SAMPLE_SIZE algorithm
AUTO_SAMPLE_SIZE was completely changed in 11g.  It does not use sampling for estimating number of distinct values (NDV).  Instead it scans the whole table and uses a hash-based distinct algorithm.  This algorithm does not require large amounts of memory or temporary tablespace.   It's much faster to read the whole table than to sort even a small part of it.  The Oracle Optimizer blog has a good description of the algorithm here.  For even more details, see this presentation by Amit Podder.  (You'll want to scan through that PDF if you want to verify the details in my next section.)
Possibility of a wrong result
Although the new algorithm does not use a simple sampling algorithm it still does not count the number of distinct values 100% correctly.  It's easy to find cases where the estimated number of distinct values is not the same as the actual.  But if the number of distinct values are clearly inaccurate, how can they be trusted in this solution?
The potential inaccuracy comes from two sources - hash collisions and synopsis splitting.  Synopsis splitting is the main source of inaccuracy but does not apply here.  It only happens when there are 13864 distinct values.  And it never throws out all of the values, the final estimate will certainly be much larger than 1.
The only real concern is what are the chances of there being 2 distinct values with a hash collision.  With a 64-bit hash the chance could be as low as 1 in 18,446,744,073,709,551,616.  Unfortunately I don't know the details of their hashing algorithm and don't know the real probability.  I was unable to produce any collisions from some simple testing and from previous real-life tests.  (One of my tests was to use large values, since some statistics operations only use the first N bytes of data.)
Now also consider that this will only happen if all of the distinct values in the table collide.  What are the chances of there being a table with only two values that just happen to collide?  Probably much less than the chance of winning the lottery and getting struck by a meteorite at the same time.

A: If you can live with the result on a single line, this should only scan once;
WITH TEST_CASE AS
(
    SELECT 'X' A, 5 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 3 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 7 B, 'TUE' C, NULL D FROM DUAL
)
SELECT
  CASE WHEN COUNT(DISTINCT A) +
            COUNT(DISTINCT CASE WHEN A IS NULL THEN 1 END) = 1
       THEN 1 ELSE 0 END SAME_A,
  CASE WHEN COUNT(DISTINCT B) +
            COUNT(DISTINCT CASE WHEN B IS NULL THEN 1 END) = 1
       THEN 1 ELSE 0 END SAME_B,
  CASE WHEN COUNT(DISTINCT C) +
            COUNT(DISTINCT CASE WHEN C IS NULL THEN 1 END) = 1
       THEN 1 ELSE 0 END SAME_C,
  CASE WHEN COUNT(DISTINCT D) +
            COUNT(DISTINCT CASE WHEN D IS NULL THEN 1 END) = 1
       THEN 1 ELSE 0 END SAME_D
FROM TEST_CASE

An SQLfiddle to test with.

A: this will be done in a single scan
WITH
    TEST_CASE AS
    (
        SELECT 'X' A, 5 B, 'FRI' C, NULL D FROM DUAL UNION ALL
        SELECT 'X' A, 3 B, 'FRI' C, NULL D FROM DUAL UNION ALL
        SELECT 'X' A, 7 B, 'TUE' C, NULL D FROM DUAL
    )
    select decode(count(distinct nvl(A,0)),1,'SINGLE','MULTP') COL_A,
           decode(count(distinct nvl(B,0)),1,'SINGLE','MULTP') COL_B,
           decode(count(distinct nvl(C,0)),1,'SINGLE','MULTP') COL_C,
           decode(count(distinct nvl(D,0)),1,'SINGLE','MULTP') COL_D
    from TEST_CASE

A: do you mean something like this?
WITH
TEST_CASE AS
(
    SELECT 'X' A, 5 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 3 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 7 B, 'TUE' C, NULL D FROM DUAL
)
select case when min(A) = max(A) THEN 'A'
            when min(B) = max(B) THEN 'B'
            when min(C) = max(C) THEN 'C'
            when min(D) = max(D) THEN 'D'
            else 'No one'
       end
from TEST_CASE

Edit
this works:
WITH
TEST_CASE AS
(
    SELECT 'X' A, 5 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 3 B, 'FRI' C, NULL D FROM DUAL UNION ALL
    SELECT 'X' A, 7 B, 'TUE' C, NULL D FROM DUAL
)
select case when min(nvl(A,0)) = max(nvl(A,0)) THEN 'A ' end ||
       case when min(nvl(B,0)) = max(nvl(B,0)) THEN 'B ' end ||
       case when min(nvl(C,0)) = max(nvl(C,0)) THEN 'C ' end ||
       case when min(nvl(D,0)) = max(nvl(D,0)) THEN 'D ' end c

from TEST_CASE

Bonus: I have also added the check for the null values, so the result now is: A and D
And the SQLFiddle demo for you.


text:
Q: Error loading WebappClassLoader I am trying a basic servlet application. I created a dynamic web project and add HelloWorld.java to src folder and edit web.xml as below. Then I run the project on server but i get error as follows. I checked for solution online but its not solving my problem..any help?
HelloWorld.java
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;

     public class HelloWorld extends HttpServlet{
      public void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException,IOException{
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("");
      pw.println("<title>Hello World</title></title>");
      pw.println("");
      pw.println("
Hello World
");
      pw.println("");
      }
    }

Web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>

    <web-app>
     <servlet>
      <servlet-name>Hello</servlet-name>
      <servlet-class>HelloWorld</servlet-class>
     </servlet>
     <servlet-mapping>
     <servlet-name>Hello</servlet-name>
     <url-pattern>/HelloWorld</url-pattern>
     </servlet-mapping>
    </web-app>

and the error is,
Sep 23, 2013 2:38:37 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:testasu' did not find a matching property.
Sep 23, 2013 2:38:37 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorld' did not find a matching property.
Sep 23, 2013 2:38:37 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /opt/jdk1.6.0_21/jre/lib/i386/server:/opt/jdk1.6.0_21/jre/lib/i386:/opt/jdk1.6.0_21/jre/../lib/i386:/usr/lib/jvm/java-6-openjdk/jre/lib/i386/client:/usr/lib/jvm/java-6-openjdk/jre/lib/i386:/usr/lib/xulrunner-addons:/usr/lib/xulrunner-addons:/usr/java/packages/lib/i386:/lib:/usr/lib
Sep 23, 2013 2:38:37 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Sep 23, 2013 2:38:37 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 694 ms
Sep 23, 2013 2:38:38 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Sep 23, 2013 2:38:38 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.18
Sep 23, 2013 2:38:38 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Sep 23, 2013 2:38:38 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Sep 23, 2013 2:38:38 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/24  config=null
Sep 23, 2013 2:38:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 586 ms
Sep 23, 2013 2:40:01 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet Hello as unavailable
Sep 23, 2013 2:40:01 PM org.apache.catalina.core.ApplicationContext log
SEVERE: Error loading WebappClassLoader
  delegate: false
  repositories:
    /WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@176c74b
 HelloWorld
java.lang.ClassNotFoundException: HelloWorld
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1094)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:808)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:619)
Sep 23, 2013 2:40:01 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet Hello
java.lang.ClassNotFoundException: HelloWorld
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1094)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:808)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:619)

The classes are not getting generated under WEB-INF I searched alot about this problem but no satisfactory answer to solve my problem. I m trying lot of application using servelets and jsp and html but bcoz of this problem none seems to work..Any help?

A: Refresh your project after cleaning it and try to deploy it again..

A:    <servlet-class>HelloWorld</servlet-class>

That is wrong.
You have to give fully qualified name (package) name.
like
<servlet-class>com.some.something.HelloWorld</servlet-class>

Docs


text:
Q: How can I win big at the casino in Dragon Quest VII? Casinos are a Dragon Quest tradition. In fact, they're pretty much the best way to make money.
In Dragon Quest VII, there's a casino available as soon as you reach Alltrades Abbey. There are several games here - a matching game (which randomizes the tiles each time), slots for either 1 or 10 tokens, and a variant of poker.
How can I win big? None of these games seem particularly lucrative from my testing.

A: Like with many games of chance, in RPGs, your best best is going to end up being save-scumming.  Meaning: Keep playing the games of chance and saving when you win, then reloading when you lose.  This can take a lot of times, however, so it's up to you as to how long you wish to keep this up, for.
A guide written by David Fisher at gameskinny.com has some other information that could prove beneficial in the casino, of this particular game.
Note that a key point of this guide is to select Pilgrim's Rest [Past] as it allows for closer access to a priest (for saving) and several advantages over the [Present] version, which are discussed at length in the guide.
The main point of the guide describes buying a nominal amount of coins and using those to play Lucky Panel over and over until the coins run out, and then selling the proceeds.  (Lather, rinse, repeat.)  He also suggests that if you do wish to play the slots, make sure to use the machine on the far right as it has, inherently, better win chances due to having 2 chances to win, instead of the 1 that other machines have.
The strategy suggested for the Lucky Panel game involves simply using your first six free selections to clear up the top of the board, and writing down what you see, so that you can more easily solve the rest of the board.  The main point of this is to select those cards consecutively, so that it's easier to divide the board in half, in your head.
If you didn't run into matches in those, then it assumes that the lower half of the board will have your match.  Like all card match-up games, however, it's purely chance, and you'll have just as much luck selecting anything, as long as you write down what you found.  By revealing the tiles in order, you simply help to avoid revealing the same tile, multiple times, wasting your limited number of card picks.  (Watch someone play these games, randomly, sometimes, and you'll see that revealing the same card once, twice, three times, or even more, is common.)
Note that if you do end up, by chance, finding several matches in the first two rows, then you're back to pure chance on the lower rows, since you don't know where their pairs are.
He does emphasize to avoid finding the match for the shuffle card, however, since it will ruin all of your notes.


text:
Q: Angular 7 - how to make initial input value visible for JSON? I have problem with my Angular 7 project. I have
<form [formGroup]="myFormGroup">
  <mat-form-field>
    <input value="some text" matInput placeholder="sometext" formControlName="aName" #myName>
  </mat-form-field>
</form>

and

{{myName.value}}

and also

form value: {{myFormGroup.value | json}}

The problem is, that in first-paragraph I can see the initial value of input - "some text" but in second-paragraph it does not show until I make any change in input. For example if I type manually "abcdef", that I have "abcdef" in both paragraphs. Is there any way to fix it?

A: When defining your form group in your component just do this:
this.myFormGroup = new FormGroup({
    aName: new FormControl('some text'),
});

That way you would leave the initialization of values to the components logic, where it belongs.
I also recommend defining a method like this:
get myvalue(): string {
    return this.myFormGroup.get('aName').value;
}

By doing so you should be able to access your value in your template via

{{myvalue}}

Also remove the value="some text" from your template and you are good to go.
I hope that helps!

A: I think you can just use two-way binding with  [(ngModel)]="name" and initialize "name" from the component and use it {{name | json}}
<input value="some text" matInput placeholder="sometext" formControlName="aName" [(ngModel)]="name" #myName>
Hope it helps!


text:
Q: How to get non Angular Service Worker running in Angular I've been trying to implement a Service Worker into a brand new Angular app. It is not angular's SW, it is just the out of the box api. I'm wanting to purposefully use this one instead of Angular's (just in case that was asked). After reading, it seems like the issue I'm having relates to path issues, but I believe I have the path right. The other issue I've seen is that we can't use ng serve and have the SW successfully register, so I've began doing ng build --prod and then deploying it using http-server, but still I get the following error:
Service worker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

What steps do I need to get this SW successfully registered?
Also, my file structure is:
- main.ts
- index.html
- service-worker.js

The service-worker.js file is empty and my main.ts file is where the registration is contained:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./service-worker.js')
  .then(registration => console.log('Service worker registration succeeded:', registration)
  , error => console.log('Service worker registration failed:', error));
} else {
  console.log('Service workers are not supported.');
}
platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));```

A: So I've ended up coming up with a solution, that I would love to get feedback on because of my lack of understanding.
Since I'm running the angular build command, I looked into the angular.json file and checked out the build command. I've added the service-worker.js to the assets array (in the form of src/service-worker.js) and also my manifest.json file to the array as well because I was having similar issues to the above question, and that fixed everything.
The SW successfully registers after doing the above. I'm guessing because the angular compiler compiles everything into the one output file since it is in the same structure as the index.html and specifying those as an asset will make it not be included in the "bundling"?
NOTE
Doing this solution also allows me to use ng-serve (so no need to build and use http-server)


text:
Q: jquery datatable : get selected check box rows I have the following datatable. Its got a list of columns. Last column is a checkbox.
I want to get list of all rows which has the checkbox ticked? is it possible to get all datatable rows with the checkbox checked? my datatable is like below
    $.fn.dataTable.moment('DD.MM.YYYY');
    $('#bankReconDataListing tbody').off('click');
   RECON_DATATABLE = $('#bankReconDataListing').DataTable({
    "language": __DT,
    "select": true,
    "order": [
        [1, "desc"]
    ],
    "searchable": true,
    "destroy": true,
    "sAjaxSource": '/bankReconciliationGetData?coa=' + coa + '&toDate=' + toDate + '&fromDate=' + fromDate,
    "sAjaxDataProp": "",
    "bLengthChange": false,
    "pageLength": 20,
    "aoColumns": [{ //document date : 0
    "mDataProp": null,
    { //Document type  //5
        //balance
        "mDataProp": null,
        render: function(data, type, row) {
            return data.doctype;
        }
    },
    render: function(data, type, row) {
        return "<input type='checkbox' name='" + checkBoxName + "' data-tableinput='checkbox'  " +
            "id='checkBox" + reconJrnlId + "' value='" + reconJrnlId + "' checked='checked' />";

    }
}],
    "columnDefs": [],
    "initComplete": function() {}
});

A: Give a class name to your checkbox column, say checkboxclass.
Then,
  $('.checkboxclass:checked',table.fnGetNodes()).each(function(){
        //what you want to do
   }

A: You could attach an event handler to the checkboxes in the table. Whenever a checkbox is clicked, that row gets added to an array. If it's unchecked, you remove it from the array.
This is untested but something like this should work:
let arr = [];

$("#tableDiv tbody").on("click", "input[type='checkbox']", function(e) {

    let row = $(this).closest('tr');

    // Get row data
    let data = table.row(row).data();

    if (this.checked) {

        // Add to array
        arr.push(data);

    } else {

        arr.splice(arr.indexOf(data), 1);

    }

});

#tableDiv is just the table's container. You could use whatever other selector is appropriate depending on your application.


text:
Q: Graphics Viewport coordinates after scrolling Here is a class i use for the viewport to zoom in/out.
zoom.cpp
#include "zoom.h"
#include <QMouseEvent>
#include <QApplication>
#include <QScrollBar>
#include <qmath.h>

Graphics_view_zoom::Graphics_view_zoom(QGraphicsView* view)
  : QObject(view), _view(view)
{
  _view->viewport()->installEventFilter(this);
  _view->setMouseTracking(true);
  _modifiers = Qt::ControlModifier;
  _zoom_factor_base = 1.001;
  initfactor=1;

}

QList<int> Graphics_view_zoom::gentle_zoom(double factor) {

  _view->scale(factor, factor);
  _view->centerOn(target_scene_pos);
  QPointF delta_viewport_pos = target_viewport_pos - QPointF(_view->viewport()->width() / 2.0,
                                                             _view->viewport()->height() / 2.0);
  QPointF viewport_center = _view->mapFromScene(target_scene_pos) - delta_viewport_pos;
  zpoint=_view->mapToScene(viewport_center.toPoint()); //zpoint is public QPointF
  _view->centerOn(_view->mapToScene(viewport_center.toPoint()));

  emit zoomed();
  zooms.append(viewport_center.x());
  zooms.append(viewport_center.y());
  zooms.append(_view->viewport()->x());
  zooms.append(_view->viewport()->y());
  return zooms;

}

void Graphics_view_zoom::set_modifiers(Qt::KeyboardModifiers modifiers) {
  _modifiers = modifiers;

}

void Graphics_view_zoom::set_zoom_factor_base(double value) {
  _zoom_factor_base = value;
}

bool Graphics_view_zoom::eventFilter(QObject *object, QEvent *event) {

  if (event->type() == QEvent::MouseMove || event->type()==QEvent::Scroll) {
    QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event);
    QPointF delta = target_viewport_pos - mouse_event->pos();
    if (qAbs(delta.x()) > 5 || qAbs(delta.y()) > 5) {
      target_viewport_pos = mouse_event->pos();
      target_scene_pos = _view->mapToScene(mouse_event->pos());

    }
  } else if (event->type() == QEvent::Wheel) {
    QWheelEvent* wheel_event = static_cast<QWheelEvent*>(event);
    if (QApplication::keyboardModifiers() == _modifiers) {
      if (wheel_event->orientation() == Qt::Vertical) {
        angle = wheel_event->angleDelta().y();
        steps=steps+angle;
        factor = qPow(_zoom_factor_base, angle);
        initfactor=qPow(_zoom_factor_base,0-steps);

        gentle_zoom(factor);
        return true;
      }
    }
  }
  Q_UNUSED(object)
  return false;
}

zoom.h
#ifndef ZOOM_H
#define ZOOM_H

#include <QObject>
#include <QGraphicsView>

class Graphics_view_zoom : public QObject {
  Q_OBJECT
public:
  Graphics_view_zoom(QGraphicsView* view);
  QList<int> gentle_zoom(double factor);
  void set_modifiers(Qt::KeyboardModifiers modifiers);
  void set_zoom_factor_base(double value);
  double _zoom_factor_base;
  double angle;
  double factor;
  double initfactor;
  int steps=0;
  QList<int> zooms;

  QPointF target_scene_pos;
  QPointF zpoint;
  int slposx;

  QGraphicsView* _view;
  Qt::KeyboardModifiers _modifiers;

  QPointF target_viewport_pos;

  bool eventFilter(QObject* object, QEvent* event);

private:

signals:
  void zoomed();
};

#endif // ZOOM_H

I need to add a GraphicsItem (which is also sub-classed to either the center of the viewport or ideally at its top-left corner. What i managed to get from this class is the center of the view (see zpoint variable in gentle_zoom(). However, it only works if mouse wheel is used to zoom. If i then move the scrollbar of the Graphics view (which is in a Ui HLayout and auto-adjusts), the item is added to the previous position and doesn't follow the scrolling i did with mouse.
How can i get that ? I assume i have to add some event to the eventFilter(), but unsure of what is that. Thanks

A: Perhaps add the _view-horizontalScrollBar()->value() (or vertical) to the zpoint. So keep track of the last scrollbar position when you zoom, then when you add an item after scrolling you add (newScrollPosition - lastScrollPosition) to your center point.

A: You seem to want to have a view-bound item that ignores transformations (i.e. zoom). One approach is to have an item with QGraphicsItem::ItemIgnoresTransformations flag set. It'd make sense when the untransformed "UI" items are shared among all views.
Another is to overlay a second, transparent graphics view on top of the primary one, and show the "static" (un-zoomable) UI there, from a dedicated scene. This makes sense when each view needs its own custom UI that's not shared between the views. You may refer to this, albeit not fully fleshed out yet working, answer.
As a colossal hack, you can use the first approach for the UI items for all views, but instead have dedicated untransformed item(s) for each view, and do nothing if paint(..., widget) is not the items desired view.

A: Well, it was much easier than i thought. After studying the zoom class, i realized that i was storing the initial zoom factor (initfactor variable), so all i had to do for my new GraphicsItem was ..
item->setX(ceil(ui->graphicsView->horizontalScrollBar()->value()*z->initfactor));
item->setY(ceil(ui->graphicsView->verticalScrollBar()->value()*z->initfactor));

... and the item was added at the top-left position of my zoomed view.
@Noah Whitehouse Thanks for the heads up, the horizontalScrollBar()->value() was actually the one that lead me to the solution


text:
Q: How to properly cache Bridj JNI objects in Java/Scala I'm looking for some guidelines on caching and reusing Bridj JNI objects between multiple JNI calls. I found that caching JNI objects vastly speeds up calling C functions over JNI but it also causes some numerical stability issues. Basically, sometimes the same C function with the same arguments produces different results.
I found this page discussing how to cache JNI objects. http://www.latkin.org/blog/2016/02/01/jni-object-lifetimes-quick-reference/
Does anyone do it in BridJ, any hints on how to cache primitives, structs, pointers, etc.?

A: Generally it is enough to know that java references to all Bridj pointers should be kept, so that they are not collected by JVM Garbage collector. Once it happens, Bridj/JNI will release the memory allocated for these pointers.
One particular situation to take care of is this:
Imagine you create a Java instance of auto generated(with JNAerator) class:
@Library("libtarget.so")
public class SomeStruct extends StructObject {
  public SomeStruct() {
    super();
  }

  @Field(0)
  public Pointer<Byte > p0() {
    return this.io.getPointerField(this, 0);
  }

  @Field(0)
  public SomeStruct p0(Pointer<Byte > p0) {
    this.io.setPointerField(this, 0, p0);
    return this;
  }
...
}

and then
val struct = new SomeStruct()
struct.p0(pointerToCString("a"))

It is not enough to keep a reference to the struct object, also a reference to pointerToCString("a") should be maintained separately. If not, Bridj/JNI will release allocated memory once this pointer is collected by garbage collector. It is not obvious from the code above as it suggests that SomeStruct() object should keep a reference to the pointerToCString("a") pointer anyway.


text:
Q: Create Folder and Insert if Not Present I wonder whether someone may be able to help me please.
I'm using Aurigma's Image uploader software to allow users to upload images for locations they visit. The information is saved via the script shown below:
<?php

//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget about the slash in the end of the folder name.
$galleryPath = 'UploadedFiles/';

require_once 'Includes/gallery_helper.php';

require_once 'ImageUploaderPHP/UploadHandler.class.php';

/**
 * FileUploaded callback function
 * @param $uploadedFile UploadedFile
 */
function onFileUploaded($uploadedFile) {

  $packageFields = $uploadedFile->getPackage()->getPackageFields();
  $username=$packageFields["username"];
  $locationid=$packageFields["locationid"];

  global $galleryPath;

  $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
  $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR;

  if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) {
    initGallery($absGalleryPath, $absThumbnailsPath, FALSE);
  }

  $locationfolder = $_POST['locationid'];
  $locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
  if (!is_dir($absGalleryPath . $locationfolder)) {
    mkdir($absGalleryPath . $locationfolder, 0777);
  }

  $dirName = $_POST['folder'];
  $dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName);
  if (!is_dir($absGalleryPath . $dirName)) {
    mkdir($absGalleryPath . $dirName, 0777);
  }

  $path = rtrim($dirName, '/\\') . '/';

  $originalFileName = $uploadedFile->getSourceName();

  $files = $uploadedFile->getConvertedFiles();

  // save converter 1

  $sourceFileName = getSafeFileName($absGalleryPath, $originalFileName);
  $sourceFile = $files[0];
  /* @var $sourceFile ConvertedFile */
  if ($sourceFile) {
    $sourceFile->moveTo($absGalleryPath . $sourceFileName);
  }

  // save converter 2

  $thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName);
  $thumbnailFile = $files[1];
  /* @var $thumbnailFile ConvertedFile */
  if ($thumbnailFile) {
    $thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName);
  }

  //Load XML file which will keep information about files (image dimensions, description, etc).
  //XML is used solely for brevity. In real-life application most likely you will use database instead.
  $descriptions = new DOMDocument('1.0', 'utf-8');
  $descriptions->load($absGalleryPath . 'files.xml');

  //Save file info.
  $xmlFile = $descriptions->createElement('file');
  $xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName);
  $xmlFile->setAttribute('source', $sourceFileName);
  $xmlFile->setAttribute('size', $uploadedFile->getSourceSize());
  $xmlFile->setAttribute('originalname', $originalFileName);
  $xmlFile->setAttribute('thumbnail', $thumbnailFileName);
  $xmlFile->setAttribute('description', $uploadedFile->getDescription());
  //Add additional fields
  $xmlFile->setAttribute('username', $username);
  $xmlFile->setAttribute('locationid', $locationid);
  $xmlFile->setAttribute('folder', $dirName);
  $descriptions->documentElement->appendChild($xmlFile);
  $descriptions->save($absGalleryPath . 'files.xml');
}

$uh = new UploadHandler();
$uh->setFileUploadedCallback('onFileUploaded');
$uh->processRequest();
?>

In additon to the original script I've added code that creates a folder, with it's name based on the current 'locationid'. This is shown below.
  $locationfolder = $_POST['locationid'];
  $locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
  if (!is_dir($absGalleryPath . $locationfolder)) {
    mkdir($absGalleryPath . $locationfolder, 0777);
  }

What I like to incorporate, is a check that looks to see whether there is a folder already setup with the current 'locationid' value, if not create the folder. I'm ceratianly no expert in PHP, but I know that to check to see whether a file exists, the if(file exists....) can be used, but I just wondered whether someone could tell me please how I can implement this check for the folder name?
Many thanks
Chris

A: I think is_dir() is what you are looking for.
UPDATE:
The code you have:
if (!is_dir($absGalleryPath . $locationfolder)) {
   mkdir($absGalleryPath . $locationfolder, 0777);
}

Does exactly what you want. It checks for the folder and if it does not exist then it creates one for you (with CHMOD 777). Don't see what your question is then...


text:
Q: Why is the current thread's CultureInfo not being used when parsing a DateTime parameter on a 'WebMethod' call in ASP .NET? I have an ASP .NET Web Forms application that makes use of the 'WebMethod' attribute for making AJAX calls from jQuery. I'm dealing with trying to localize the application so I recently created a web method that looks something like this for testing purposes:
[WebMethod]
public static string HandleDate(DateTime dateValue)
{
    return dateValue.ToString("f");
}

The point of this method is to verify that if I set the CultureInfo properly the web method will parse the provided date correctly using the date formatting rules for that culture. Unfortunately, this code is never being reached. Instead, I'm seeing an error getting raised by the helper classes that allow these WebMethods to be called.
I have an HttpModule that is setting the 'CurrentCulture' and 'CurrentUICulture' properties of the current thread to 'pt-BR' (Brazilian Portuguese) at the 'BeginRequest' event.
Client side, I have a jQuery AJAX call to this 'HandleDate' web method that is providing the dateValue parameter as '18/10/2010'. In the 'pt-BR' culture this should evaluate to October 18, 2010 (day/month/year date format).
When I execute this I'm getting back an error indicating that the 'System.Web.Script.Serialization.ObjectConverter' is blowing up stating that '18/11/2010' is not a valid value for DateTime. The stack trace included with the error indicates that this was thrown by the 'System.ComponentModel.DateTimeCoverter.ConvertFrom' method, which accepts the object to be converted in addition to a CultureInfo object representing the culture that should be applied during the conversion.
I fired up Reflector and it appears that the 'ObjectConverter' is invoking the 'DateTimeConverter' using CultureInfo.InvariantCulture instance, which I think is the problem.
How can I force this logic to use the CultureInfo attached to the current thread instead of the InvariantCulture?

A: I would recommend you change the parameter type to string and then do the parsing yourself using DateTime.Parse or TryParse.


text:
Q: Mysql : How to find non duplicate rows with left join? I got a problem in Mysql sine a few days and i can't solve it (i'm pretty bad with DB) and I hope you can help me :)
I'm going to simplify the problem so you can see where I'm stuck !
I got two tables :
current_stock (article_id, ...)
stock_record (id, article_id)

Current_stock describes the actual stock and stock_record the articles which have already been inventoried.
The problem comes when I want to get the articles left to inventory (thoses in current_stock but not in stock_record), and when i got multiples sames articles_id
I tried :
SELECT *
FROM current_stock
WHERE NOT EXISTS (
SELECT * FROM stock_record)

And others forms like :
SELECT *
FROM current_stock
LEFT JOIN (SELECT * FROM stock_record) second
WHERE second.article_id IS NULL

BUT, when there a multiple lines with the same article_id in current_stock, AND there is one line with this article_id in stock_record, i'm not getting the good result !
For exemple:
current_stock (article_id)
8315
8315
8315

stock_record (id, article_id)
15, 8315

I want the result to have two rows with the article_id 8315 !
(Sorry for my bad english, hope you guys understand me !)
EDIT :
With theses forms i'm getting nothing in the result, because the "NOT EXISTS" or the "LEFT JOIN" is excluding ALL the lines from current_stock with this article_id.
I would like to exclude only the amount of lines in stock_record
For exemple :
I have 10 articles in my current_stock(with the article_id = 8315)
I have 3 articles already scanned in my stock_record(with the article_id = 8315)
I want the result to have 7 lines of this article_id.

A: Your correct exists() query:
SELECT *
FROM current_stock t
WHERE NOT EXISTS (SELECT * FROM stock_record s
                   where t.article_id = s.article_id)

The problem in your query, that you need to check if a specific id not exists in stock_record, and not if any id not exists there.
And your correct left join query:
SELECT *
FROM current_stock s
LEFT JOIN stock_record t on( t.article_id = s.article_id)
WHERE t.id IS NULL

The problem with your left join query is that you didn't specify a relation condition (see the ON()) so, it didn't know which row to join to which row.
You can also use NOT IN like this:
SELECT *
FROM current_stock t
WHERE article_id NOT IN(SELECT article_id FROM stock_record)

A: You can use variables to enumerate records. Then join on row number and ignore rows having a match in stock_record:
SELECT t1.*
FROM (
  SELECT *,
         @rn1 := IF(@aid = article_id, @rn1 + 1,
                    IF(@aid := article_id, 1, 1)) AS rn1
  FROM current_stock
  CROSS JOIN (SELECT @rn1 := 0, @aid := 0) AS vars
  ORDER BY article_id) AS t1
LEFT JOIN (
  SELECT article_id,
         @rn2 := IF(@aid = article_id, @rn2 + 1,
                    IF(@aid := article_id, 1, 1)) AS rn2
  FROM stock_record
  CROSS JOIN (SELECT @rn2 := 0, @aid := 0) AS vars
  ORDER BY article_id
) AS t2 ON t1.article_id = t2.article_id AND t1.rn1 = t2.rn2
WHERE t2.article_id IS NULL

A: try to group by current_stock
This link will help you


text:
Q: react-scripts build error code-134, not creating build When i try to create build in react app and run:
 `npm run build`

it give me this is error and before that it was working fine don't what is happened today after creating some UI components.
Below is the error which i am getting when i try to run npm run build:
`E:\client\paytify>npm run build

 > paytify@0.1.0 build E:\client\paytify
 > react-scripts build

 Creating an optimized production build...

 <--- Last few GCs --->

 [11012:0000025D9D438DE0]   274773 ms: Scavenge 1353.8 (1424.5) -> 1353.1 (1425.0) MB, 5.6 / 0.0 ms
 (average mu = 0.163, current mu = 0.106) allocation failure
 [11012:0000025D9D438DE0]   274782 ms: Scavenge 1353.9 (1425.0) -> 1353.3 (1425.5) MB, 5.4 / 0.0 ms
 (average mu = 0.163, current mu = 0.106) allocation failure
 [11012:0000025D9D438DE0]   274792 ms: Scavenge 1354.1 (1425.5) -> 1353.5 (1426.5) MB, 4.9 / 0.0 ms
 (average mu = 0.163, current mu = 0.106) allocation failure

 <--- JS stacktrace --->

 ==== JS stack trace =========================================

0: ExitFrame [pc: 0000003AD395C5C1]
Security context: 0x03b1e301e6e9 <JSObject>
1: /* anonymous */ [000000FF19B291E1] [E:\client\monaia\node_modules\source-map\lib\source-
node.js:~342] [pc=0000003AD58A0C59](this=0x01d803b0d481 <JSGlobal Object>,chunk=0x010e6094a299
<String[9]: prototype>,original=0x021da8f29cd1 <Object map = 000001EC1636A009>)
2: SourceNode_walk [0000010FBDDA0F91] [E:\client\monaia\node_modules\source-map\lib\...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of
memory
1: 00007FF645EEDD8A v8::internal::GCIdleTimeHandler::GCIdleTimeHandler+4506
2: 00007FF645EC8886 node::MakeCallback+4534
3: 00007FF645EC9200 node_module_register+2032
4: 00007FF6461E30DE v8::internal::FatalProcessOutOfMemory+846
5: 00007FF6461E300F v8::internal::FatalProcessOutOfMemory+639
6: 00007FF6463C9804 v8::internal::Heap::MaxHeapGrowingFactor+9620
7: 00007FF6463C07E6 v8::internal::ScavengeJob::operator=+24550
8: 00007FF6463BEE3C v8::internal::ScavengeJob::operator=+17980
9: 00007FF6463C7B87 v8::internal::Heap::MaxHeapGrowingFactor+2327
10: 00007FF6463C7C06 v8::internal::Heap::MaxHeapGrowingFactor+2454
11: 00007FF6464F1EA7 v8::internal::Factory::NewFillerObject+55
12: 00007FF64656F096 v8::internal::operator<<+73494
13: 0000003AD395C5C1
npm ERR! code ELIFECYCLE
npm ERR! errno 134
npm ERR! paytify@0.1.0 build: `react-scripts build`
npm ERR! Exit status 134
npm ERR!
npm ERR! Failed at the paytify@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\haroon traders\AppData\Roaming\npm-cache\_logs\2020-11-07T22_11_58_325Z-
debug.log`

These are my dependencies:
`"dependencies": {
"@khanacademy/react-multi-select": "^0.3.3",
"@material-ui/core": "^4.8.0",
"@material-ui/icons": "^4.5.1",
"@material-ui/lab": "^4.0.0-alpha.44",
"@material-ui/styles": "^4.7.1",
"@stripe/react-stripe-js": "^1.1.2",
"@stripe/stripe-js": "^1.8.0",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"browser-image-compression": "^1.0.11",
"chart.js": "^2.9.3",
"dotenv": "^8.2.0",
"emoji-mart": "^3.0.0",
"firebase": "^7.6.1",
"i18next": "^19.3.3",
"jquery": "^3.4.1",
"lodash": "^4.17.15",
"mic-recorder-to-mp3": "^2.2.2",
"moment": "^2.24.0",
"react": "^16.12.0",
"react-charts": "^2.0.0-beta.6",
"react-contenteditable": "^3.3.5",
"react-day-picker": "^7.4.8",
"react-dom": "^16.12.0",
"react-export-excel": "^0.5.3",
"react-geocode": "^0.2.1",
"react-google-autocomplete": "^1.1.2",
"react-google-maps": "^9.4.5",
"react-i18next": "^11.3.4",
"react-idle-timer": "^4.2.12",
"react-image-crop": "^8.5.0",
"react-phone-number-input": "^3.0.24",
"react-qr-reader": "^2.2.1",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-scripts": "^3.4.1",
"react-scroll": "^1.8.1",
"react-simple-timefield": "^3.0.0",
"react-to-print": "^2.7.0",
"react-toastify": "^6.0.8",
"redux": "^4.0.4",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.3.0"
},`

Note:
I try all solutions like npm cache clean --force, delete node_modules, npm install/yarn install even update the react-scripts versions.

A: I got my issue resolve by adding below one line of code in package.json "scripts" section.
"scripts": {"build": "react-scripts --expose-gc --max-old-space-size=8192 build",... ...}
https://stackoverflow.com/a/59983758/13129244


text:
Q: Grouping or Clustering Algorithm Similar questions in the database seem to be much more complicated than my example. I want to cluster 100'ish points on a line. Number of groups is irrelevant; the closeness of points is more important.
What is a term, method or algorithm to deal with this grouping problem? K-means, Hamming distance, hierarchical agglomeration, clique or complete linkage??
I've reduced two examples to bare minimum for clarification:
Simple example:
Set A = {600, 610, 620, 630} and the set of differences between its elements is diff_A = {10, 20, 30, 10, 20, 10}. I can then group as follows: {10, 10, 10}, {20, 20}, and {30}. Done.
Problematic example:
Set B = {600, 609, 619, 630} and the set of differences is diff_B = {9, 10, 11, 19, 21, 30}. I try to group with a tolerance of 1, i.e. differences that are 1 (or less) are 'similar enough' to be grouped but I get a paradox: {9, 10} AND/OR {10, 11}, {19}, {21}, and {30}.
Issue:
9 and 10 are close enough, 10 and 11 are close enough, but 9 and 11 are not, so how should I handle these overlapping groups? Perhaps this small example is unsolvable because it is symmetrical?

A: Why do you work on the pairwise differences? Consider the values 1, 2, 101, 102, 201, 202. Pairwise differences are 1,100,101,200,201,99,100,199,200,1,100,101,99,100,1
The values of ~200 bear no information. There is a different "cluster" inbetween. You shouldn't use them for your analysis.
Instead, grab a statistics textbook and look up Kernel Density Estimation. Don't bother to look for clustering - these methods are usually designed for the multivariate case. Your data is 1 dimensional. It can be sorted (it probably already is), and this can be exploited for better results.
There are well-established heuristics for density estimation on such data, and you can split your data on local minimum density (or simply at a low density threshold). This is much simpler, yet robust and reliable. You don't need to set a paramter such as k for k-means. There are cases where k-means is a good choice - it has origins in signal detection, where it was known that there are k=10 different signal frequencies. Today, it is mostly used for multidimensional data.
See also:

*

*Cluster one-dimensional data optimally?

*1D Number Array Clustering

*partitioning an float array into similar segments (clustering)

*What clustering algorithm to use on 1-d data?


text:
Q: IONIC: Shared Container Folder for DocumentProvider Extension like Swift I want to make a Document Provider extension for an app originally developed in IONIC.I understand that I can use .xcodeproj file to open the project in XCode and then add new target for intended extension.However, I'm confused about shared storage between my AppGroup (App & Extension).According to NSFileManager (now FileManager), you need to store files in a shared container with group identifier.The method to achieve this is following:-
func containerURL(forSecurityApplicationGroupIdentifier groupIdentifier: String) -> URL?

However according to IONIC guide the files can be saved in one of these locations:-

According to IONIC Developer, the files currently reside in Document Directory of App where we need to have those files in a shared container as mentioned above. How can we achieve that?
FYI: I couldn't find any help on IONIC forums regarding this, and I'm following this tutorial for Extension development.


text:
Q: No route found for "GET /demo/koco/create" : 404 Not Found - NotFoundHttpException Why I am getting errors for the route?
Other APIs for the CRUD operation are working fine.
I have added a new controller code for my new API and I am getting a route error.
What could be the mistake?
While I have already written my route in routing.yml
creat:
  path: /create
  defaults: { _controller: AcmeDemoBundle:DemoController:create }
  methods: [GET]

Products:
  path: /recentProducts/{id}
  defaults: { _controller: AcmeDemoBundle:DemoController:recentProducts }
  methods: [GET]

Update:
  path: /updateProduct/{id}
  defaults: { _controller: AcmeDemoBundle:DemoController:update }
  methods: [POST]

Delete:
  path: /deleteProduct/{id}
  defaults: { _controller: AcmeDemoBundle:DemoController:delete }
  methods: [DELETE]

referenceCreation:
  path: /koco/create
  defaults: { _controller: AcmeDemoBundle:DemoController:createReference }
  methods: [GET]

My api is
http://localhost/koco1/web/app_dev.php/demo/koco/create
My Controller is
/**
     * @Route("/koco/create", name="referenceCreation")
     * @Template()
     */
    public function createReferenceAction()
    {

        $organization = new Organization();
        $organization->setName('Sensio Lab');

        $user = new User();
        $user->setName("Jonathan H. Wage");
        $user->setOrganization($organization);

        $dm = $this->get('doctrine_mongodb')->getManager();
        $dm->persist($organization);
        $dm->persist($user);
        $dm->flush();

        return new Response('Created product id ');

        // $response = new Response('Hello Huzaifa ');
        // return $response;
    }

What is wrong here?
Kindly let me know.
Thanks

A: Your routing is off.
Also you are creating routes through yaml and through annotations. Should stick to one.
Also server setup looks off too, http://localhost/koco1/web/app_dev.php/demo/koco/create should be more like http://localhost/koco1/web/koco/create, you can try running php server. Going to /public and running php -S localhost:8000 you can read more here: https://www.php.net/manual/en/features.commandline.webserver.php
or symfony cli server https://symfony.com/download
Your routes does not match /demo/koco/create is not equal to /koco/create, you should first of all set up correctly, then it will be easier to debug.


text:
Q: Best Frameworks for Jetson For Computer Vision/Streaming TV/IoT Huupe would like your recommendations on platforms to best exploit Nvidia Jetsons for our intelligent basketball backboard.
OS: JetPack vs Yocto

*

*Yocto: We are considering using Yocto instead of Jetpack because we believe that it will be easier to make changes in Yocto when we build production systems.

Application Frameworks being considered:

*

*ReactJS in GTK WebKit with GJS/Typescript

*GTK/C++/Boost

*Electron/ReactJS/Chromium/Typescript

Our current net:

*

*We will choose GJS/ReactJS if we can display our app over hardware accelerated video with an acceptable level of effort for updating packages and level of UI processing overhead.

*We will use GTK/C++/Boost if we can overcome build issues.

*Else we will stick with Electron/ReactJS/Chromium if we can hardware accelerate video.

Background: Huupe.com is building an intelligent basketball backboard supporting games, training, and casting content. The entire backboard is a TV screen. Cameras and computer vision detect from where shots are taken and if the shots are made or missed. Huupes stream video from the cloud, to other Huupes, and from casting mobile devices. We will stress the Nvidia Jetson that is controlling the Huupe by running AI, video processing, and generating and displaying graphics and animations on the Huupe screen. Note that Huupes are controlled by mobile devices via BLE/wifi and will not require on screen UI controls. Huupe prototypes are using Jetson Xaviers, but we are planning to upgrade to Jetson Orins.
Alternatives being considered:

*

*ReactJS in GTK WebKit with GJS/Typescript

*

*Pros:

*

*ReactJS has higher app developer efficiency than GTK/Boost.

*ReactJS has a larger app developer community than GTK/Boost.

*Typescript use is growing more than C++.

*More efficient than Electron/Chromium.

*Concerns:

*

*IPC between GTK and ReactJS hard to debug.

*Updating packages can require significant effort.

*GTK/C++/Boost

*

*Pros:

*

*HW acceleration of UI

*More efficient processing than ReactJS….

*Electron/ReactJS/Chromium is used in our current prototype.

*

*Concerns:

*

*Overhead of Electron/Chromium in the long run as we add capabilities.

*Chromium doesn't support hardware acceleration for video.

Note: We are using React Native for our iOS and Android mobile app which is used to control the Huupe backboard.
We tried:

*

*ReactJS in GTK WebKit with GJS/Typescript: We are having challenges getting our app to display with a transparent background over video and with interprocess communication between rendering logic and our CV, BLE, and API code.

*GTK/C++/Boost: haven't successfully built the app yet.

*Electron/ReactJS/Chromium/Typescript: It is running without hardware accelerated video and we have concerns about resource usage.


text:
Q: XAML/C# - Binding Property does not get called Not sure why it does this...
I'm simplifying my problem for the sake of clarity. I have two variables that participate in data-binding. One variable is fetched fine, but the other one does not get fetched.
Example.xaml.cs:
public partial class Example : UserControl
{
    private string _name;
    private string _area;
    private AppClass _app;

    public Example(string name, AppClass app)
    {
        InitializeComponent();
        _name = name;
        _app = app;
        this.DataContext = this;
        InitializeData();
    }

    private void InitializeData()
    {
        if (_app != null)
        {
            _area = _app.GetArea();
        }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public string Area
    {
        get { return _area; }
        set { _area = value; }
    }
}

And my Example.xaml (just the lines of interest):
<TextBlock Grid.Row='0' Grid.Column ='0' Padding='5,0,0,0' Background='LightBlue' Text='Exchanger'/>
<TextBlock Grid.Row='0' Grid.Column ='1' Background='LightBlue' Text="{Binding Name}" TextAlignment='Center'/>

<TextBlock Grid.Row='2' Grid.Column ='0' Padding='5,0,0,0' Background='LightCyan' Text='Area'/>
<TextBlock Grid.Row='2' Grid.Column ='1' Background='LightCyan' Text="{Binding Area}" TextAlignment='Center'/>

Interestingly enough, Area gets called fine, but Name doesn't. I put a breakpoint on the getter of Name and Area and it breaks on Area but not Name. I'm perplexed...

A: the Name property is defined in FrameworkElement. Change the property name to something else.
Also, The UI is not the right place to store your data. Instead of doing that, create a proper ViewModel to hold your data and make sure your usercontrol is bound to that ViewModel.


text:
Q: Freezing Previous Years Data I have a database that tracks employee's data for the current year and previous years.
In examples below I will use calendar years (years start in Jan and end in Dec)- this is not always the case, some users have their year running from July to June- or April to March, etc.
There are many tables that, with a few heavy calculations, make a view of the employee's data at this point in time.
This current year's data is what users look at mostly. But data from previous years impact on this year (so, a change made to the 2008 data- will have a knock on effect on 2009, and then into 2010 and so onto this year).
Obviously, this has a negative impact on performance when viewing reports as viewing this year's data will mean trudging through all the previous years- calculating and creating views until the end result is found. As the application ages, this problem will get worse and worse- say in 2015, anybody using the system from its inception (2008) will be waiting for a long time to get their data.
We plan to freeze previous years data so instead of having data from 2008, 2009, 2010 and this year's data- we would have one block with the previous year's data (with all calculations done for those previous years) and this year's data.
In this way, we would have the end results data for all the previous year's already calculated and we would only need to add to this year to get the final result.
Obviously, we would have to prevent users from entering/updating data in previous years.
My question is what is the best way to achieve this? I presume you would need some process that waits until the new year and does some calculations.
Thanks in advance,
ViperMAN.

A: the approach you describe is normally referred as data archiving, you can have some queries a DBA runs manually every year the first working day after the new year party so the calculated data is prepared and stored.
Also, your application needs to deny users to modify previous years data, if I have got it right.

A: One approach I was thinking works as follows:

*

*Create a table that holds the result of the previous years calculations.

*Prevent all addtions/deletions/updates to previous years from the app tier.

*Change reporting so that queries would consult this table instead of trudging along, calculating everything out each time.

*Have a daily process that would:
Check if today was the first day of an employees year-
If yes, get all of the elapsed year's data and add them to all the previous years.

Obviously, this is a simlified version- but one that I think could work.
Thoughts?

A: If you have data that should not be edited, and you can define what that data is, then I would use a combination of stored procedures and security settings to ensure the old data stays accurate.
If you used stored procedures as a filter, you can have logic in your stored procedure that checks the record against the current DateTime and only allows the update if everything fits your requirements.


text:
Q: Ways to check positive definiteness of bilinear form For each real number $\alpha$, we define the bilinear form $F_{\alpha}:\mathbb{R}^3 \times \mathbb{R}^3 \rightarrow \mathbb{R} $ by
$\displaystyle F_{\alpha}(((x_1, x_2, x_3), (y_1, y_2, y_3))
= 2x_1y_1 + (\alpha + 5)x_1y_2 + x_1y_3 + (\alpha + 5)x_2y_1
-(2\alpha + 4)x_2y_2 + 2x_2y_3 + x_3y_1 + 2x_3y_2 + 2x_3y_3.$
Find the set of $\alpha \in \mathbb{R}$ such that $F_{\alpha}$ is positive definite.
Is there any other way to check positive definiteness instead of extracting the underlying symmetric matrix and the eigenvalues  ? Can the same be applied for quadratic forms ?


text:
Q: Can I get a callback / do I know when SQLite has created write-ahead log files? I want to chmod them I have an elevated process and I want to make sure the SQLite files that it creates are readable by other processes. For some reason umask doesn't seem to do what I want (set permissions of sqlite file created by process).
I'm using write-ahead logging, so -wal and -shm files are created in addition to the database file. I want all 3 to be chmodded correctly.
I wonder if it's possible to get in after the SQLite file is created and chmod it.
Possible approaches:

*

*touch all 3 files before SQLite tries to create them, then chmod and hope the mask stays the same

*Intercept when the files are created and chmod them.

*Work out how to get umask to work for the process.

*Mystery option four.

What's the best way to go?
Questions for approaches:

*

*Will SQLite be OK with this?

*Do we know when all 3 files are created? Is there some kind of callback I can give a function pointer to? Do we know if the same wal and shm files are around forever? Or are they deleted and re-created?

A: You can touch the database file before opening it. (When you use the sqlite3 command-line tool to open a new file, but do nothing but begin; and commit;, SQLite itself will create a zero-sized file.)
If you want to intercept file operations, you can register your own VFS.
The -wal and -shm files are created dynamically, but SQLite will give them the same permission bits as the main database file. The comments for robust_open() in os_unix.c say:

If the file creation mode "m" is 0 then set it to the default for
  SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  0644) as modified by the system umask.  If m is not 0, then
  make the file creation mode be exactly m ignoring the umask.
The m parameter will be non-zero only when creating -wal, -journal,
  and -shm files.  We want those files to have exactly the same
  permissions as their original database, unadulterated by the umask.
  In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  transaction crashes and leaves behind hot journals, then any
  process that is able to write to the database will also be able to
  recover the hot journals.


text:
Q: Linux KVM guest hanging after several weeks I've got a Linux KVM guest that hangs after several weeks.  Looking at the virt-manager window shows 100% CPU usage.  virsh reboot guest doesn't take any effect, the guest needs to be forced off.  On the guest I can see no indication of what went wrong.  I've scanned /var/log/messages and just about any other log file that can might tell me something.  After rebooting the system is stable for several weeks and then hangs again.
I've tried the following things:

*

*Add clocksource=acpi_pm to the kernel boot options

*Changing the disk bus from Virtio to IDE

*Changing the NIC to e1000

All to no avail.  Right now I'm at a point where I reboot the server on a weekly basis.
Are there any other ways to diagnose what is going wrong here?  Or any other changes that might be made?

A: try to get something from qemu log from /var/log/libvirt/qemu/<domain-id>.log.
If your VM hangs, try to use guestfs to inspect VM disk file and check /var/log/messages and/or /var/log/dmesg to see what happens inside the VM.

A: I was unable to determine the cause of these crashes.  I resolved this by reinstalling the guest in a new virtual disk.  For the crashing VM, I had converted it from a VirtualBox image that an employee had created.  I suspect that was the cause of the problem.


text:
Q: Cache tableView cell data In my application, I want to cache the displayed data in tableview so that whenever the application starts or if the internet connection isn't there, my tableview should be able to display the cached old data [not completely but say 10 old cached cells].
What I'm displaying in individual cells is an object of one of the 8 classes I'm defining. So in my case I'll have to create 8 tables in order to store these objects.
Can anybody suggest any efficient way of achieving this?
Thanx in advance.

A: Here is a little hint: Maintain plist(XML) file with NSDictionary as item; just like a info.plist file

A: Write data to SQLite database and read on start. It is quick, easy and efficient. This might help you: http://www.mobileorchard.com/iphone-sqlite-tutorials-and-libraries/


text:
Q: dynamic data driven UI I would like to build a webpage of whose the UI would be data driven. As in, the meta-data (layout, structure, components, content etc) of the UI would be stored in a database, which would be fetched at realtime, from which the UI will be generated accordingly. Any pointer or suggestions as to how I could go about it will be greatly appreciated.

A: Do you also store the entity data in this database or do you only want to configure the presentation of "static" (strange to use that word here) pages?
If you also store data, you need to make an important decisions about how closely you want to tie the data model with the view model, since your view definitions is also data.
Define tables for Entity, Property and populate them with some example data.
For defining the views, it might be a better option to look for an XML structure that you can store in a database, because page layouts are very hierarchical in nature.

A: This
is probably close to what you are looking for. Just store the HTML code in your database and pull it out with whatever web serivce works best for you. I would also suggest using an associative model of data. MongoDB and others like it handle small amounts of complex data more efficiently than a standard SQL database*. They also allow you to read/write to the database from JavaScript. You could possibly develop an administration system for your front end meta using the same technique.


text:
Q: Memory layout of JavaScript objects in V8 I'm looking to writing some C bindings to V8, and so I'll need to figure out the memory layout of the various primitive JavaScript types. Is there any documentation on these details anywhere?

A: You don't need to know data types layout to write C bindings for V8. Object's are never really accessed directly when you work with V8 but through an API - only V8 implementation knows how they are laid out. For example getting a property foo from an object o looks like this in C++:
v8::Handle<v8::Object> o;
v8::Handle<v8::Object> v =
  o->Get(v8::String::NewFromUtf8(isolate, "foo"));

Now to wrap this into C you only need to know how to represent and pass around v8::Handle<T>, then you can write wrappers like:
template<typename T> Handle<T> FromC(v8_handle_t h) { /* ... */ }
template<typename T> v8_handle_t ToC(Handle<T> h) { /* ... */ }

extern "C" v8_handle_t v8_object_get(v8_handle_t self,
                                     v8_handle_t key) {
  return ToC(FromC<Object>(self)->Get(FromC<Value>(key)));
}

So what's inside v8::Handle<T>? In reality it's just a pointer to some slot which in turn contains an actual pointer to an underlying V8 object. This double indirection exists to enable V8 GC to precisely track which objects are in use in C++ code and to allow it moving this objects.
So theoretically you can define v8_handle_t as an opaque pointer and marshall it like this:
typedef struct v8_object_pointer_t* v8_handle_t;  // Opaque pointer
static_assert(sizeof(v8_handle_t) == sizeof(Handle<Object>))
template<typename T> Handle<T> FromC(v8_handle_t h) {
  return *(Handle<T>*)&h;
}
template<typename T> v8_handle_t ToC(const Handle<T>& h) {
  return *(v8_handle_t*)&h;
}

A minor complication comes from managing the structure called HandleScope that manages Handles. In C++ API it relies on RAII-pattern to manage some backing storage. The simplest way to deal with it probably is:
typedef struct {
  void* a[3];
} v8_handle_scope_t;
static_assert(sizeof(v8_handle_scope_t) == sizeof(HandleScope))
void v8_handle_scope_enter(v8_handle_scope_t* scope) {
  new(scope) HandleScope;
}
void v8_handle_scope_leave(v8_handle_scope_t* scope) {
  delete (HandleScope*)scope;
}

With carefully balanced usage in code that needs handle scopes:
for (i = 0; i < N; i++) {
  v8_handle_scope_t scope;
  v8_handle_scope_enter(&scope);
  // action
  v8_handle_scope_leave(&scope);
}

A: As your question is about how to write V8 C++ addons for Node.js you should just refer to the manual for nodeJs which has a reasonably simple guide for writing addons;
If you question is about how to make background threads then there are nodejs plugins which helps you with that, but also read this for how to write it directly.
You should never try to access the memory for V8 directly, as the memory and object may move --always use the APIs


text:
Q: How can I know whether a file is being used by other process by using c++ under Linux? I want to copy a file to another file. But it always failed. I checked my code carefully, but I still can not know what's wrong with it. So I guess may be one of the two files is being used by other process. So firstly, I want to check whether they are being used by other process.
If so, is there any solution to stop the procedure by using c++??

A: If your code always fails, I would assume that it's because there is a problem with the code, because that's where the problem is in approximately 99.999%1 of the cases.
That said, there isn't much point in checking if you can open a file before you try, since some other process might open (or lock, or remove, ...) the file between your checking and your opening it.
The reliable method is to just go ahead and try to open the file, and then handle failure gracefully (which you need to do anyway).

Footnotes:
1 Scientific fact that I just made up.


text:
Q: SharePoint - Adding a user to a person or group field that allows multiple values I have searched everywhere for a solution but I am not having any luck. What I am trying to do is, in a form append a variable value (username) to a person or group field that already has values in it. I want to achieve this through jquery or javascript. Please see below for an example
Person Field : usera, userb, userc
UserVar = userd
after code executes UserVar is appended to Person Field
Person Field : usera, userb, userc, userd
Any help would be appreciated


text:
Q: Remove Event Listener from React Hooks Element I have a question regarding Event Listeners inside React Components. For window events I always use the return function inside the useEffect, but for the project I'm currently working on, I introduced an event listener to the component.
For window events I totally understand the perspective, but for component related event, in my mind it does not make a lot of sense, because why should I remove an event listener from a component that no longer exists in the DOM?
useEffect(() => {
  function cancelAutoPlay() {
    setIsAutoScrollOn(false)
  }

  carouselContainerRef.current.addEventListener('touchstart', cancelAutoPlay)
  return () => {
    if (carouselContainerRef?.current) {
      carouselContainerRef.current.removeEventListener('touchstart', cancelAutoPlay)
    }
  }
}, [])

Is this the right way? There is another way for doing it? Should I not care about removing it?