text:
Q: How to align left for a text outside a table with CSS I am trying to align the text "Filter By:" lefts the table. For the margin, it may not work when the windows screen has been resized (responsive). I tried the text-align: left or center but it didn't work as my expected.
Actually, the div element can be changed to another one to make it work.
Here is the Fiddle link:
https://jsfiddle.net/a26jsLg5/
See the following screen-shot of how it should look like:

.searchType table {
        border: 1px solid #A6A6A6;
        margin: 0px auto;
    }

Filter by:

            <INPUT type=radio CHECKED value=FullMap />
            Com 1

            <INPUT type=radio value=MissingCourses />
            Com 2

            <INPUT type=radio value=NeedToLearn />
            Com 3

A: Just do a small correction in your css. Remove margin: 0 auto form your .searchType table css

.searchType table {
        border: 1px solid #A6A6A6;
    }

Filter by:

            <INPUT type=radio CHECKED value=FullMap />
            Com 1

            <INPUT type=radio value=MissingCourses />
            Com 2

            <INPUT type=radio value=NeedToLearn />
            Com 3

A: take a look at this .https://codepen.io/jayakrishnancn/pen/WjBpZa
1st method with javascript
change this line

Filter by:

to

Filter by:

and add this script to page

2nd id u know the maximum width of table in advance then use this

Filter by:

here no script is needed, also "filter by" will stay in the right place (in previous method "filter by" will be placed in left and move to right only when jquery funtion run.

A: Yes you can use the
 element for this. It goes inside your table element, you can then align it left.

.searchType table {
  border: 1px solid #A6A6A6;
  margin: 0px auto;
}

table caption {
  text-align: left;
}

Filter by:

          <INPUT type=radio CHECKED value=FullMap />
          Full learning map

          <INPUT type=radio value=MissingCourses />
          Missed courses

          <INPUT type=radio value=NeedToLearn />
          Courses need to learn

More about the caption element: https://developer.mozilla.org/en/docs/Web/HTML/Element/caption


text:
Q: How to get the Package-List of a debian/ubuntu package? It's possible to view the Package-List of a debian/ubuntu package, using the package management tools like apt, aptitude or dpkg?
I need to list the packages provided by a package, the list is visible in the dsc file:
Example:
http://archive.ubuntu.com/ubuntu/pool/main/l/lxc/lxc_1.0.0~beta3-0ubuntu1.dsc
Section Package-List.

A: You can use apt-cache showsrc and use awk (or similar tools) to get the output you want:
$ apt-cache showsrc lxc | awk '/Package-List/{a=1;next}/^[^ ]/{a=0}a{print $1}'
lxc
lxc-dbg
lxc-dev

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using regex backreference after matching n times I need to match several strings in a puppet definition:
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh1':  value => '4096' }
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh2':  value => '8192' }
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh3':  value => '16384' }
  sysctl::conf { 'net.ipv6.conf.all.disable_ipv6':     value => '0' }
  sysctl::conf { 'net.ipv6.conf.default.disable_ipv6': value => '0' }

And then using backreference add the same lines plus one more to end like this:
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh1':  value => '4096' }
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh2':  value => '8192' }
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh3':  value => '16384' }
  sysctl::conf { 'net.ipv6.conf.all.disable_ipv6':     value => '0' }
  sysctl::conf { 'net.ipv6.conf.default.disable_ipv6': value => '0' }
  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }

I've tried this match pattern (  sysctl::conf \{.*\}\n{1,}) and then replace it with \1\n  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }
The problem is that the backreference is referencing each line instead of all the grouped block to add my new line at the end. This is what I'm getting instead of the desired result:
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh1':  value => '4096' }
  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh2':  value => '8192' }
  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }
  sysctl::conf { 'net.ipv4.neigh.default.gc_thresh3':  value => '16384' }
  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }
  sysctl::conf { 'net.ipv6.conf.all.disable_ipv6':     value => '0' }
  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }
  sysctl::conf { 'net.ipv6.conf.default.disable_ipv6': value => '0' }
  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }

Should I try to match the whole block of lines as one pattern instead of a multiple match of the same pattern?
I'm doing like this because I'm using Atom to search and replace all sysctl::conf entries in several files, that are not the same, and add the new entry after already existing ones.
Thank you :)
PS: Already know that in atom backreferences are called $1 instead of \1.

A: You can try with this pattern
(?:\s*sysctl::conf \{.*\})+

After that replace with
\0\n  sysctl::conf { 'net.ipv4.tcp_mtu_probing': value       => '1' }

Note the \0, since there wasn't any capturing group.
Explanation:

*

*?: is a Non-capturing group to capture the hole block (i.e. \0).

*\s* matches any whitespace character (equal to [\r\n\t\f\v ]).

*+ at the end to capture all the matches.


text:
Q: Menu populated with database on php so I am building a menu to a site, ant the menu will be populated by the database, when I query the database I get something like this array:
Array:
Array
(
    [0] => Array
        (
            [id] => 1
            [nome] => Home
            [parent_id] => 0
        )

    [1] => Array
        (
            [id] => 2
            [nome] => Tutorials
            [parent_id] => 0
        )

    [2] => Array
        (
            [id] => 3
            [nome] => Photoshop
            [parent_id] => 2
        )

    [3] => Array
        (
            [id] => 4
            [nome] => Illustrato
            [parent_id] => 2
        )

    [4] => Array
        (
            [id] => 5
            [nome] => Web Design
            [parent_id] => 2
        )

    [5] => Array
        (
            [id] => 6
            [nome] => HTML
            [parent_id] => 5
        )

    [6] => Array
        (
            [id] => 7
            [nome] => CSS
            [parent_id] => 5
        )

)

I would like to search it and get just the child items, for instance:
function getChild($needle){
    ...
    return $array
}

where $array, is the information of the children:
print_r(getChild(2));

would output something like this:
Array ( [0] => 3 [1] => 4 [2] => 5 )

in this example it returns the ids but it could return  an array with the complete info for each one of the items...
I could query the database again and obtain the same results but I'm afraid that it is not a good practice. For example if I have a gigantic menu, the script would be querying too much the database and that would slow down the rendering of the page too much.
I am tiered of searching a way of doing this I'm already dizzy and exhausted...
I realize that in this example I have no links but it is easy to add them in the end, that's why I don't work with them for now :P

A: It might look something like this (assuming I understand your issue properly):
function getChild( $needle, $sourceArray )
{
    $ret = array();
    for( $i = $needle; $i < $sourceArray.count(); $i++ )
    {
         array_push( $ret, $sourceArray[ $i ][ 'id ' ]) ;
    }

    return $ret;
}

EDITED: the function isn't length() - it's count()

A: You will need to pass your array into the function getChild():
getChild($data, 1, 2)

Something like this:
function getChild(){
    $results = [];
    $args = func_get_args();
    $arrays = array_shift($args);

    foreach ($arrays as $subarr) {
        $curr_results = [];
        $keys = array_keys($subarr);

        foreach ($args as $index) {
            $curr_results[] = $subarr[$keys[$index]];
        }
        $results[] = $curr_results;
    }

    return $results;
}

$data = [

["id" => 1, "nome" => "Home", "parent id" => 0],
["id" => 2, "nome" => "Tutorials", "parent id" => 0],
["id" => 3, "nome" => "Photoshop", "parent id" => 0],
["id" => 4, "nome" => "Illustrato", "parent id" => 2],

];

print_r(getChild($data, 1, 2));

--output:--

Array
(
    [0] => Array
        (
            [0] => Home
            [1] => 0
        )

    [1] => Array
        (
            [0] => Tutorials
            [1] => 0
        )

    [2] => Array
        (
            [0] => Photoshop
            [1] => 0
        )

    [3] => Array
        (
            [0] => Illustrato
            [1] => 2
        )

)

I have to say, that seems like a stupid way to obfuscate your code.  It would be much clearer to write:
getChildData($data, "nome", "parent_id");

Instead, you are trying to access an associative array with numeric indexes.


text:
Q: General rule/algorithm for finding the points of a polygon, given only the lengths of the sides I have a polygon and I only know the length of its sides, how would I go about figuring out what it's points are?
Assume that the first side starts from the origin $(0,0)$ and extends along the x axis to (length of side $(a, 0)$ ).
I realize that this is trivial for, say a triangle, but is there a rule that can be used for all polygons?

A: No, you can never do this for for any polygon with more than three sides (unless it's degenerate, so that the length of one side is equal to the sum of the lengths of all the other sides -- but then you just get a straight line). For instance, if the polygon has four sides, all the same length, then it can be a square, but it can also be a rhombus with any interior angle.


text:
Q: Проблема с tkinter в PyCharm Python Всем добрый день. Работаю с Python с tkinter. Запускаю код в PyCharm, после чего выводит ошибку:
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 908, in _find_spec
AttributeError: 'TransformFinderLoader' object has no attribute 'find_spec'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/PycharmProjects/main/main.py", line 1, in <module>
    import tkinter
  File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 38, in <module>
    from tkinter.constants import *
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 910, in _find_spec
  File "<frozen importlib._bootstrap>", line 884, in _find_spec_legacy
  File "C:\Users\iljal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\source_transform\meta_path.py", line 44, in find_module
    triggered_transforms = self.get_triggered_transforms()
  File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\site-packages\source_transform\meta_path.py", line 65, in get_triggered_transforms
    prot=mmap.PROT_READ
AttributeError: module 'mmap' has no attribute 'PROT_READ'

========================================================================================
Использую Python 3.8.2
Не понимаю в чем ошибка. Библиотеку уже устанавливал: pip install tkinter. Но если сейчас попробую ввести в командной строке "pip install tkinter", то выводит ошибку:
C:\Users>pip install tkinter
Could not import runpy module
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 908, in _find_spec
AttributeError: 'TransformFinderLoader' object has no attribute 'find_spec'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 910, in _find_spec
  File "<frozen importlib._bootstrap>", line 884, in _find_spec_legacy
  File "c:\users\appdata\local\programs\python\python38-32\lib\site-packages\source_transform\meta_path.py", line 44, in find_module
    triggered_transforms = self.get_triggered_transforms()
  File "c:\users\appdata\local\programs\python\python38-32\lib\site-packages\source_transform\meta_path.py", line 65, in get_triggered_transforms
    prot=mmap.PROT_READ
AttributeError: module 'mmap' has no attribute 'PROT_READ'

================================================================================================
А вот сам код, который пытаюсь запустить:
import tkinter

master = tkinter.Tk()
canvas = tkinter.Canvas(master, bg='white', height=600, width=600)
canvas.pack()
for i in range(1, 9):
    canvas.create_line((0, 600 / 8 * i), (600, 600 / 8 * i), fill='black')
    canvas.create_line((600 / 8 * i, 0), (600 / 8 * i, 600), fill='black')
master.mainloop()

И так с любым кодом, если есть слова: import tkinter.
Подскажите пожалуйста как решить это. Заранее большое спасибо!

A: Все у вас работает. Запускается поле с клеточками. Вам нужно правильно подключить tkinter  к проекту. Для этого, вы должны убедиться, что у вас подключена библиотека, через  file-->settings.  Там в списке должен быть pip и привязана к нему нужная вам библиотека. Если вы устанавливаете библиотеку через командную строку, то не факт что указанный в Пайчарм интерпретатор её подцепит. Для установки библиотек необхоимо использовать средства Пайчарм, описанные мной выше.

A: "вы должны убедиться, что у вас подключена библиотека, через file-->settings"
file -> settings -> Project Interpreter -> + ? Так?
Но там я не могу найти ни python-tk, ни нужного мне turtle


text:
Q: Wordpress 3.9.1 installed from YUM in CentOS does not allow install plugins or themes I installed Wordpress 3.9.1 using YUM in a CentOS, however it does not allow me to install any plugins or themes (the install buttons do not appear).
I tried many things:

*

*Changed the file permissions of /usr/share/wordpress and /etc/wordpress to be writable by apache:

sudo chown -R apache:apache wordpress

*Commented lines in wp-config.php

/* define('DISALLOW_FILE_MODS', true); */
  /*define('AUTOMATIC_UPDATER_DISABLED', true); */

But it does not seem to work.
Any idea what do I need to modify>


text:
Q: Recortar imagen eliminando espacios en blanco estoy trabajando en una aplicación de escaneo, todo esto funciona bien pero un requerimiento es que si lo que se intenta escanear no ocupa todo el tamaño de la hoja se recorte en automático (el usuario no tiene acceso a manipular la imagen). Buscando en internet encontre esta respuesta a un problema similar al mio pero en mi caso no funciona. Esta es la imagen que me retorna el escaner:

Como se puede observar el objeto escaneado es pequeño pero se guarda en una hoja completa de tamaño carta, hay forma de que mediante un boton o manipulando el Bitmap que retorna el escaner se pueda extraer solo la tarjeta y eliminar todos los espacios en blanco?
Este es el codigo que estoy intentando (el resultado que me da es el mismo que la imagen de arriba):
public static System.Drawing.Image AforgeAutoCrop(Bitmap selectedImage)
{
    Bitmap autoCropImage = null;
    try
    {

        autoCropImage = selectedImage;
        // create grayscale filter (BT709)
        Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
        Bitmap grayImage = filter.Apply(autoCropImage);
        // create instance of skew checker
        DocumentSkewChecker skewChecker = new DocumentSkewChecker();
        // get documents skew angle
        double angle = 0; // skewChecker.GetSkewAngle(grayImage);
        // create rotation filter
        RotateBilinear rotationFilter = new RotateBilinear(-angle);
        rotationFilter.FillColor = Color.White;
        // rotate image applying the filter
        Bitmap rotatedImage = rotationFilter.Apply(grayImage);
        new ContrastStretch().ApplyInPlace(rotatedImage);
        new Threshold(25).ApplyInPlace(rotatedImage);
        BlobCounter bc = new BlobCounter();
        bc.FilterBlobs = true;
        // bc.MinWidth = 500;
        //bc.MinHeight = 500;
        bc.ProcessImage(rotatedImage);
        Rectangle[] rects = bc.GetObjectsRectangles();

        if (rects.Length == 0)
        {
            // CAN'T CROP
        }
        else if (rects.Length == 1)
        {
            autoCropImage = autoCropImage.Clone(rects[0], autoCropImage.PixelFormat); ;
        }
        else if (rects.Length > 1)
        {
            // get largets rect
            Console.WriteLine("Using largest rectangle found in image ");
            var r2 = rects.OrderByDescending(r => r.Height * r.Width).ToList();
            autoCropImage = autoCropImage.Clone(r2[0], autoCropImage.PixelFormat);
        }
        else
        {
            Console.WriteLine("Huh? on image ");
        }
    }
    catch (Exception ex)
    {
        //MessageBox.Show(ex.Message);
        //CAN'T CROP
    }

    return autoCropImage;
}

PD.1: El objeto escaneado puede variar su tamaño.

A: Lo primero de todo para conseguir el propósito que buscas es incrementar el contraste de la imagen original de tal forma que lo casi blanco sea blanco. Para ello nos construimos la siguiente función:
private Bitmap AplicaFiltroContrasteBrillo(Image p_ImgSource, float p_Contraste, float p_Brillo)
{
    float brilloAjustado = p_Brillo - 1.0f;
    // Creamos una matriz para aplicar contraste y brillo
    // a una imagen dada.
    float[][] matrizContraste = {
           new float[] {p_Contraste, 0, 0, 0, 0}, // aplica a RED
           new float[] {0, p_Contraste, 0, 0, 0}, // aplica a GREEN
           new float[] {0, 0, p_Contraste, 0, 0}, // aplica a BLUE
           new float[] {0, 0, 0, 1.0f, 0},        // canal alpha
           new float[] {brilloAjustado, brilloAjustado, brilloAjustado, 0, 1}};

    // Creamos los atributos en función de nuestra matriz
    // para aplicar a la imagen
    ColorMatrix cmx = new ColorMatrix(matrizContraste);
    ImageAttributes imgAttr = new ImageAttributes();
    imgAttr.SetColorMatrix(cmx);

    // Trasladamos la imagen a un bitmap ya con el efecto de contraste
    // y brillo aplicado para poder trabajar sobre eso
    Bitmap bmpCanvas = new Bitmap(p_ImgSource.Width, p_ImgSource.Height, p_ImgSource.PixelFormat);
    Graphics g = Graphics.FromImage(bmpCanvas);
    g.DrawImage(p_ImgSource, new Rectangle(Point.Empty, bmpCanvas.Size),
                0, 0,
                p_ImgSource.Width, p_ImgSource.Height,
                GraphicsUnit.Pixel, imgAttr);

    // Liberamos recursos
    g.Dispose();
    imgAttr.Dispose();

    // Retornamos la imagen con el filtro aplicado
    return bmpCanvas;
}

Ahora lo que precisamos es un algoritmo que nos recorra la imagen obtenida y nos calcule el rectángulo de recorte que andamos buscando.
Seguro se podría optimizar y mejorar, pero para el asunto la he creado de la siguiente forma:
private Rectangle ObtenerBordes(Bitmap p_Bmp)
{
    int bordeIZQ = -1;
    int bordeDER = -1;
    int bordeSUP = -1;
    int bordeINF = -1;
    // Buscamos el borde SUPERIOR e INFERIOR
    for (int y = 0; y < p_Bmp.Height; y++)
    {
        for (int x = 0; x < p_Bmp.Width; x++)
        {
            if (bordeSUP == -1)
            {
                Color pixel = p_Bmp.GetPixel(x, y);
                if (pixel.Name != "ffffffff")
                    bordeSUP = y;
            }
            if (bordeINF == -1)
            {
                Color pixel = p_Bmp.GetPixel(x, p_Bmp.Height - y-1);
                if (pixel.Name !="ffffffff")
                    bordeINF = p_Bmp.Height - y - 1;
            }
        }
        if (bordeSUP != -1 && bordeINF != -1) break;
    }
    // Buscamos el borde DERECHO e IZQUIERDO
    for (int x = 0; x < p_Bmp.Width; x++)
    {
        for (int y = 0; y < p_Bmp.Height; y++)
        {
            if (bordeIZQ == -1)
            {
                Color pixel = p_Bmp.GetPixel(x, y);
                if (pixel.Name != "ffffffff")
                    bordeIZQ = x;
            }
            if (bordeDER == -1)
            {
                Color pixel = p_Bmp.GetPixel(p_Bmp.Width - x - 1, y);
                if (pixel.Name != "ffffffff")
                    bordeDER = p_Bmp.Width - x - 1;
            }
        }
        if (bordeIZQ != -1 && bordeDER != -1) break;
    }

    return new Rectangle(bordeIZQ, bordeSUP, bordeDER - bordeIZQ, bordeINF - bordeSUP);
}

Observa que lo único que hago es ir recorriendo la imagen hasta encontrar un pixel que sea distinto de BLANCO y entonces establecer el borde en esa coordenada.
Ya casi tenemos todo el trabajo hecho, basta con aglutinarlo en una función que será la que llamaremos directamente para obtener el recorte de la imagen:
private Image RecortarImage(Image p_ImgSource)
{
    // Aplicamos un filtro a la imagen y retornamos el
    // resultado a nuestro bitmap
    // He bajado el brillo a la mitad y aumentado a 6 el contraste
    // lo que me ha permitido obtener un resultado adecuado al menos
    // con tu imagen de prueba.
    Bitmap bmpCanvas = AplicaFiltroContrasteBrillo(p_ImgSource, 6f, 0.5f);

    // Llamamos a la siguiente función que le pasaremos el Bitmap que hemos
    // creado con la imagen y que ya tiene un contraste alto para hallar los bordes
    Rectangle imgRectRecorte = ObtenerBordes(bmpCanvas);

    // Una vez calculado el rectángulo de recorte creamos un Bitmap para copiar
    // desde la imagen original a dicho bitmap la porción de imagen correspondiente
    // según el rectángulo de recorte calculado.
    Bitmap bmpCROP = new Bitmap(imgRectRecorte.Width, imgRectRecorte.Height);
    Graphics gCrop = Graphics.FromImage(bmpCROP);
    gCrop.DrawImage(p_ImgSource, new Rectangle(Point.Empty, bmpCROP.Size),
                    imgRectRecorte, GraphicsUnit.Pixel);
    // Nos aseguramos de liberar recursos
    gCrop.Dispose();

    // Retornamos la imagen recortada
    return bmpCROP;
}


text:
Q: Creating the underscore reduce function from scratch I am working on creating my own callback functions and higher order function groups.  I am stuck on replicating the underscore reduce function or ._reduce function.  Can someone help me understand how it works underneath the hood it has been a few days for me and I am stumped.  Here is what I have so far.  Please understand I am not utilizing the underscore library, I am trying to replicate it so that I can further my understanding on higher order functions.  Thanks.
var reduce = function(collection, iterator, accumulator) {

    var iterator = function(startPoint, combiner){
      for(var i = 0; i <combiner.length; i++){
        startPoint += combiner[i];
    }
    return iterator(accumulator, collection);
}

A: A simple recursive function does the trick

// arr - some array of values
// f   - the reducing function
// acc - initial value for the accumulator
function reduce(arr, f, acc) {
  if (arr.length === 0)
    return acc
  else
    return reduce(arr.slice(1), f, f(acc, arr[0]))
}

// --------------------------------------------------

// example 1:
// reduce an array of numbers using an adding function

var ex1 = reduce([1,2,3], function(acc, x) { return acc + x }, 0)

console.log(ex1)
//=> 6

// --------------------------------------------------

// example 2:
// reduce an array of pairs to a mapping object

var ex2 = reduce([['a', 1], ['b', 2], ['c', 3]], function(acc, pair) {
  var key = pair[0]
  var value = pair[1]
  acc[key] = value
  return acc
}, {})

console.log(ex2)
//=> { a: 1, b: 2, c: 3 }

As @torazaburo points out in a comment, if you can use ES6, destructuring assignment cleans up the implementation even more
// ES6
function reduce([x, ...xs], f, acc) {
  if (x === undefined)
    return acc
  else
    return reduce(xs, f, f(acc, x))
}

Or it gets super sugary sweet with arrow functions
// ES6, same as above but using arrow function and ternary expression
const reduce = ([x, ...xs], f, acc)=>
  x === undefined ? acc : reduce(xs, f, f(acc, x))

The Underscore implementation does provide some other conveniences though I'm guessing these are here to maintain compatibility with native Array.prototype.reduce. I personally wouldn't implement reduce this way, but that's beside the point.

*

*Underscore passes an iterator and arr reference to the callback function.

*Underscore allows you to change the context for the callback function

Here's a revised implementation which supports these other features
// our reduce version 2.0
function reduce(collection, iterator, memo, context) {
  function loop(memo, i) {
    if (collection.length === i)
      return memo
    else
      return loop(iterator.call(context, memo, collection[i], i, collection), i + 1)
  }
  return loop(memo, 0)
}

You can use it the same as above only now it provides more information to the callback
NOTE
I've purposefully decided not to implement a behaviour of Underscore's reduce that allows you to perform a reduction without an initial value. Supporting this behaviour results in unsafe code and should never have made it into Underscore in the first place.

A: It's something like it:
function reduce(array, combine, start) {
  for (var i = 0; i < array.length; i++)
    start = combine(start, array[i]);
  return start;
}

console.log(reduce([1, 2, 3, 4], function(a, b) {
  return a + b;
}, 0));

Link Reference: http://eloquentjavascript.net/05_higher_order.html

A: In the comments of these answers, there has been a lot of confusion between Underscore's reduce and Array.prototype.reduce. Two notes:

*

*Underscore's reduce allows for an empty collection and no seed value. In this case, it will not throw an error but rather returns undefined. naomik has convinced me that this is not safe. For example _([]).reduce(function(a, b) { return a + b}); should either throw an error or return an empty list.

*Underscore's reduce works on both objects and arrays.

Now, to my original post:

I actually did the same thing—implement the key functions from Underscore from scratch—a while back, and reduce was probably the trickiest. I think reduce is easier to grok with a non-functional reduce (credit to naomik for this):
function reduce(arr, func, seed) {
    var result = seed,
        len = arr.length,
        i = 0;
    for (; i < len; i++) {
        result = func(result, arr[i])
     }
     return result
 }

Underscore's implementation is a bit more complex, handling objects and arrays, empty collections, and an optional seed value. It also uses each instead of a for loop, since that is more functional in style. This is my implementation of Underscore's reduce:
var reduce = function(coll, func, seed) {
    // `isEmpty` (not shown) handles empty arrays, strings, and objects.
    // Underscore accepts an optional seed value and does not
    // throw an error if given an empty collection and no seed.
    if (isEmpty(coll)) {
        return coll;
    }
    var noSeed = arguments.length < 3;

    // `each` (not shown) should treat arrays and objects
    // in the same way.
    each(coll, function(item, i) {
        if (noSeed) {
            // This condition passes at most once. If it passes,
            // this means the user did not provide a seed value.
            // Default to the first item in the list.
            noSeed = false;
            seed = item;
        } else {
            seed = func(seed, item, i);
        }
    });

    return seed;
};


text:
Q: How to remove inputmask when an ajax form is submitted as FromData? It happens that my ajax form has a file upload input, and therefore I have to submit it with an FormData instead of a simple .serialize(). Then I found the autoUnmask on my jquery.inputmask no long effective.
Here is the example:
http://jsfiddle.net/btqtnumL/1/
When the form is submitted, the result from .serialize() has a value with input mask removed. But the result from FormData() still shows the mask.

Content-Disposition: form-data; name="cost"
1,000

How can we remove the mask in this case?

A: Firstly, to get unmasked value from input, use inputmask('unmaskedvalue') (here is a reference).
One way is to rename the input element to something like masked-cost and then use .append() method.
<input name="masked-cost" .... />

In javascript you can do something like this
var formData = new FormData($form[0]);
formData.append('cost', $('input[name="masked-cost"]').inputmask('unmaskedvalue'));

On the server side you can retrieve the cost variable with unmasked value.
FormData would look something like this

------WebKitFormBoundaryMHLOLWal6cTPLuBG Content-Disposition: form-data; name="masked-cost"
1,000
  ------WebKitFormBoundaryMHLOLWal6cTPLuBG Content-Disposition: form-data; name="cost"
1000

Here is the updated demo http://jsfiddle.net/dhirajbodicherla/btqtnumL/2/

A: Just found an alternative way.
We can use jquery .val() to obtain the value without its mask.
$.each($('[data-mask="integer"]'), function (idx) {
    var input = $('[data-mask="integer"]')[idx];
    var actualValue = $(input).val();
    $(input).val(actualValue);
});

Then we can have the data for ajax with $form.serialize().
In this way, we avoid the use of FormData api.

A: Its simple. In your javascript Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits. So Steps are:
get value of input mask field.
 var number = $("#your_field_id").val();

now use .replace method with a regex of \D
number =  number.replace(/\D/g,'');

Keep in mind its just a technique and above codes work only for number. According to your requirement use regular expression. more https://regexr.com

A: Just remove inputmask before FormData.
$('#form_id :input').inputmask('remove');
data = new FormData($('#form_id'));


text:
Q: Is it possible to find out the original path that was used to load the assembly in SQL SERVER CLR? I am very new to working with Assemblies CLR in SQL Server
I have a database that has many of them

Is it possible to find out the original path that was used to load the assembly ?
Considering this is the way the assemblies are created I need that "from" path
CREATE ASSEMBLY ClassLibrary1
from 'D:\DotNetTeam\SQLServer\ClassLibrary1.dll'

I'm asking this because this assembly : a798b6eb4255719355458f3749073dc1b is not found on the server list and is being reported as unsecure (I know I have to sign it, but for that I need to first find it)
I found this other question but is not what I need.
How to find the assembly registered in SQL Server?
UPDATE
Querying the sys.assembly_files table, I notice that the record exists there but not on the left side (Object Explorer: Assemblies), do I need to re-created the assembly ?
select *
from sys.assembly_files
where name like 'a79%'

The solution for this question might also help you solve any of these
errors:

System.IO.FileLoadException: Could not load file or assembly
'ASSEMBLY_NAME, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
or one of its dependencies. An error relating to security occurred.
(Exception from HRESULT: 0x8013150A)
System.IO.FileLoadException: Could not load file or assembly
'ASSEMBLY_NAME, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
or one of its dependencies. Exception from HRESULT: 0x80FC80F1

A: Yes, but only if the assembly was loaded from a DLL on the file system and not by supplying the VARBINARY literal / hex bytes. When loaded from an external DLL (a method that I strongly recommend against, btw), the original path is stored in the [name] column in sys.assembly_files.
Execute the following to show any potential paths:
-- Change this to the assembly name or path to apply filter:
DECLARE @AssemblyName NVARCHAR(260) = '';

-- The content can be used to export the DLL:
SELECT asm.[name] AS [Assembly],
       afl.[name] AS [PathOrAltName],
       asm.[permission_set_desc],
       afl.[file_id],
       afl.[content]
FROM   sys.assembly_files afl
INNER JOIN sys.assemblies asm
        ON asm.[assembly_id] = afl.[assembly_id]
WHERE asm.[name] LIKE N'%' + @AssemblyName + N'%'
OR    afl.[name] LIKE N'%' + @AssemblyName + N'%'
ORDER BY asm.[name], afl.[file_id];

If the assembly was loaded from a VARBINARY literal / hex bytes (i.e. 0x4D5A9000...), then the [name] column in sys.assembly_files should be the same as the [name] column in sys.assemblies (which is the name used in the CREATE ASSEMBLY statement).

Querying the sys.assembly_files table, I notice that the record exists there but not on the left side

To be clear, both screen shots in the question clearly show a long list of very poorly (and clearly programmatically) named assemblies. And it is not possible, in any way, for an entry to show up in sys.assembly_files (or any of the other assembly-related management views) without it existing in sys.assemblies.
ALSO: are you certain that you are in the same database in the query window that you are drilling-down into in Object Explorer?

they only provided me a database backup

Assemblies physically exist in each DB where CREATE ASSEMBLY was executed and show up in sys.assemblies, sys.asssembly_files, and a few other system catalog views. This is one of many benefits of SQLCLR: the assembly is not external to the DB as is the case with the now deprecated external stored procedure API / feature (i.e. XPs).

I know I have to sign it...

So then I assume you are restoring a pre-SQL Server 2017 DB into SQL Server 2017 or newer. In this case you do need to sign all unsigned assemblies, BUT you do not need to export them in order to do this (an extremely common misunderstanding due to Microsoft misunderstanding the issue themselves and hence providing incorrect documentation on this topic). This is rather simple to solve given that you can sign the assembly in-place in order to get past the new "CLR strict security" debacle:
SQLCLR vs. SQL Server 2017, Part 4: "Trusted Assemblies" – The Disappointment (Msg 10314)
Here is a summary of the steps:

*

*Create Certificate (using a password) in the DB containing the assembly / assemblies using CREATE CERTIFICATE ...

*Sign the Assembly using ADD SIGNATURE TO Assembly::[{assembly_name}] ...

*Copy the Certificate to [master] (but not the Private Key!)

*Create a Login from the Certificate

*Grant the signature-based Login the UNSAFE ASSEMBLY permission

*You will still need to make sure that each assembly has the correct PERMISSION_SET for what it needs to do

Here is the demo script from that article that you can copy and adjust to fit your needs:
Avoiding "Trusted Assemblies" - Demo (on PasteBin)

For more information on working with SQLCLR in general, please visit: SQLCLR Info
UPDATE (from O.P.):
The issue was that the name of the assembly was ComputeHashFuncAssmembly but the path was the one that contained a798b6eb4255719355458f3749073dc1b so an ALTER ASSEMBLY was needed. That was also the reason it was not visible on the left side because it was under ComputeHashFuncAssmembly and not as the hex code.

I exported the assembly because the original DLL was not provided to me and I wanted to have it.
These are the steps for signing the assembly
USE [yourDatabase];
GO

CREATE CERTIFICATE [AssemblyCertificate]
ENCRYPTION BY PASSWORD = 'aPasswordYouChoose'
WITH SUBJECT = 'Assembly Certificate';

ADD SIGNATURE TO Assembly::[ComputeHashFuncAssmembly]
    BY CERTIFICATE [AssemblyCertificate]
    WITH PASSWORD = 'aPasswordYouChoose';

ALTER ASSEMBLY ComputeHashFuncAssmembly
    WITH PERMISSION_SET = SAFE;

-- Copy the certificate to the master
BACKUP CERTIFICATE [AssemblyCertificate] TO FILE = 'C:\temp\certificate.cer';

USE [master];
GO

-- DROP certificate [AssemblyCertificate];
CREATE CERTIFICATE [AssemblyCertificate]
FROM FILE ='C:\temp\certificate.cer';

CREATE LOGIN [login_AssemblyCertificate]
FROM CERTIFICATE [AssemblyCertificate];

GRANT UNSAFE ASSEMBLY TO [login_AssemblyCertificate];


text:
Q: Get an interval of values possible in regression using sci-kit learn machine learning I am trying to use regression to predict a value. For a given set of independent variables, I get a fixed number as the expected value. However, is it possible to get a range of value, so as to say that the maximum possible value be say x and minimum possible value be say y.
Using
regr = linear_model.LinearRegression()

regr.fit(X_train, Y_train)

pred = regr.predict([[a, b]])

The value of pred comes out be say 10 , but i would rather want something like max = 12 and min = 8
Simply saying a range of values.
UPDATE
Tried looking into GMM, not sure if that work for this.
Tried Gausian processes but it again give a single value something like 11.137631, which really doesn't as i am looking for a range of value rather than a single value.

A: The linear regression always gives same result for a given input vector, however using a random forest regressor in iteration gives different result on each iteration and that can be used to get a Minimum and maximum possible value from a given input vector forecast.


text:
Q: Issues with seed setting in parallelised foreach loop R I have a selection of tests I want to run in parallel. When I do this using foreach(), I get the expected output of 20 test - iteration pairs:
## Without seed
require(data.table)
require(foreach)
require(iterators)
require(doParallel)
require(doRNG)

numCores = 2
registerDoParallel(numCores)

iterations = 5
num_tests = 2:5

foreach( i = 1:iterations, .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %:%
  foreach( n = num_tests, .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %dopar% {

    ## Print iteration
    print(paste('Tests =',n,'Iteration =',i))

  }

Output:
result.1 "Tests = 2 Iteration = 1"
result.2 "Tests = 3 Iteration = 1"
result.3 "Tests = 4 Iteration = 1"
result.4 "Tests = 5 Iteration = 1"
result.1 "Tests = 2 Iteration = 2"
result.2 "Tests = 3 Iteration = 2"
result.3 "Tests = 4 Iteration = 2"
result.4 "Tests = 5 Iteration = 2"
result.1 "Tests = 2 Iteration = 3"
result.2 "Tests = 3 Iteration = 3"
result.3 "Tests = 4 Iteration = 3"
result.4 "Tests = 5 Iteration = 3"
result.1 "Tests = 2 Iteration = 4"
result.2 "Tests = 3 Iteration = 4"
result.3 "Tests = 4 Iteration = 4"
result.4 "Tests = 5 Iteration = 4"
result.1 "Tests = 2 Iteration = 5"
result.2 "Tests = 3 Iteration = 5"
result.3 "Tests = 4 Iteration = 5"
result.4 "Tests = 5 Iteration = 5"

However, when I attempt to add a step to this loop that sets a random seed as described in the doRNG vignette, I get a different number of tests per iteration (14 test-iteration pairs):
## With seed
numCores = 2
registerDoParallel(numCores)

iterations = 5
num_tests = 2:5
rng <- RNGseq( iterations * (iterations+1) / 2, 1234)

foreach( i = 1:iterations, .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %:%
  foreach( n = num_tests, r = rng[(i-1)*i/2 + 1:i], .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %dopar% {

    ##Set seed
    rngtools::setRNG(r)

    ## Print iteration
    print(paste('Tests =',n,'Iteration =',i))

  }

Output:
result.1 "Tests = 2 Iteration = 1"
result.1 "Tests = 2 Iteration = 2"
result.2 "Tests = 3 Iteration = 2"
result.1 "Tests = 2 Iteration = 3"
result.2 "Tests = 3 Iteration = 3"
result.3 "Tests = 4 Iteration = 3"
result.1 "Tests = 2 Iteration = 4"
result.2 "Tests = 3 Iteration = 4"
result.3 "Tests = 4 Iteration = 4"
result.4 "Tests = 5 Iteration = 4"
result.1 "Tests = 2 Iteration = 5"
result.2 "Tests = 3 Iteration = 5"
result.3 "Tests = 4 Iteration = 5"
result.4 "Tests = 5 Iteration = 5"

I'm looking for a way to set seeds in parallel, nested foreach() loops with the correct number of iterations. Any ideas?

A: This example in the vignette is overly clever, in my opinion. It establishes r as a sublist of rng within the foreach loop as a termination condition. You used some wrong indexes/list bounds, which is what's causing your confused output.
r is given an element of the rng sublist with each iteration. It gets away with it the bizarre sublist math, but it's incredibly confusing, and that line would earn a "WTF" in a code review 11 times out of 10.
As far as an immediate fix in closest alignment to the vignette's example:
## With seed
numCores = 2
registerDoParallel(numCores)

iterations = 5
num_tests = 2:5
rng <- RNGseq( iterations * length(num_tests), 1234)

foreach( i = 1:iterations, .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %:%
  foreach( n = num_tests, r = rng[(i-1)*length(num_tests) + 1:length(num_tests)], .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %dopar% {

    ##Set seed
    rngtools::setRNG(r)

    ## Print iteration
    print(paste('Tests =',n,'Iteration =',i))

  }

This changes
rng <- RNGseq( iterations * (iterations+1) / 2, 1234)
to
rng <- RNGseq( iterations * length(num_tests), 1234)
and changes
r = rng[(i-1)*i/2 + 1:i]
to
r = rng[(i-1)*length(num_tests) + 1:length(num_tests)]
An alternate that might be more readable/understandable
rng is a list of RNGSeqs (they're just lists themselves), and all we want to do is select a new, single RNGSeq from that list for each of our parallel operations. We need an element for each of our independent, parallel iterations.
# one RNGseq for each inner+outer loop combination
iterations = 5
num_tests = 2:5
rng <- RNGseq(iterations * length(num_tests), 1234)

foreach( i = 1:iterations, .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %:%
    foreach( n = num_tests, .combine = 'rbind', .multicombine = TRUE, .inorder = FALSE ) %dopar% {

        # this is moved out of the loop termination conditions
        # and gets a new list element for each iteration
        # note the [[ ]]s to get a single element instead of a sublist!
        #         [-----------------------] conditions that change based on outer loop
        #                                     [---]  conditions that change based on inner loop
        r = rng[[ ((i-1)*length(num_tests)) + (n-1) ]]

        ##Set seed
        rngtools::setRNG(r)

        ## Print iteration
        print(paste('Tests =',n,'Iteration =',i))

    }

The assignment for r needs (n-1) because num_tests starts at 2. It would be more flexible to use the index of the current n in num_tests: r = rng[ ((i-1)*i) + (which(num_tests == n)) ]


text:
Q: Context for getting access token that needs to be passed to Graph API On my initial analysis on the fetching the access token from Azure AD using OpenID connect protocol, I came to know that there are two ways to consider

*

*Fetching access token using the signed in user's context where caching is used.

*Fetching access token using application context.
Can anyone help me to know which needs to be consider with some example code.

A: To fetch an access token to the graph API, you need to:

*

*redirect the user to the Azure authorization endpoint (https://login.microsoftonline.com/common/oauth2/v2.0/authorize),

*to get back an authorization token,

*that you need to provide Azure with, on the access token endpoint (https://login.microsoftonline.com/common/oauth2/v2.0/token), with your application credentials.

*Finally, you can provide this access token to the userinfo endpoint on the graph API: https://graph.microsoft.com/v1.0/me

with some example code

I've written a sample code, but it depends totally on the language, environment and OIDC library you are using. In case you are using Java in a servlet environment with the MIT implementation of OIDC (MITREid Connect), my example to access the Microsoft graph API by means of OIDC on Azure is available on GitHub here: https://github.com/AlexandreFenyo/mitreid-azure

A:

Fetching access token using the signed in user's context where caching is used.

OpenID Connect implements authentication as an extension to the OAuth 2.0 authorization process. It provides information about the end user in the form of an id_token that verifies the identity of the user and provides basic profile information about the user.
Please refer to code sample :Calling a web API in a web app using Azure AD and OpenID Connect ,this sample uses the OpenID Connect ASP.Net OWIN middleware and ADAL .Net. In controller , you could get access token for specific resource using the signed in user's context :
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = await authContext.AcquireTokenSilentAsync(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

Fetching access token using application context.

What do you mean by "application context" ? If you are talking about OAuth 2.0 Client Credentials Grant Flow , which permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. You could refer to this scenario explanation and code samples .


text:
Q: Categorical characterization of complete graphs In the category of (finite) simple graphs with graph homomorphisms $\mathsf{SimpGph}$, (how) can the complete graphs $K_n$ be characterized by genuinely categorical means? Are they somehow "distinguished" categorically?
Miscellaneous findings so far:

*

*$\mathsf{SimpGph}$ has only the null graph $K_0$ as its initial object (from which one cannot construct other graphs) and no terminal object at all.

*When loops are allowed the single-vertex-with-one-loop-graph is terminal, but it is not the complete graph $K_1$.

*The digraph $\circ\!\!\rightarrow\!\!\circ$ of two vertices with a single arrow between them (something like the directed version of $K_2$) gives rise to a functor category which is essentially the category of all digraphs.

A: From the definition a simple graph is a set with a symmetric-reflexive relation, and since we are considering finite graph we deal with finite sets.
Then there's a trivial functor $U \colon \mathbf{SimpGrp} \to \mathbf{FinSet}$, where $\mathbf{FinSet}$ is the category of finite sets and function between them, sending every graph in its undeliing set and every graph morphism in its underlining function. Such a functor is faithfull so gives the structure of a concrete category.
Now a $K_n$ is just a indiscrete object in the sense of the Abstract and concrete categories, i.e. is object in $\mathbf{SimpGrp}$ such that for every other graph $X$ and every function $f \colon U(X) \to U(K_n)$ there's always a (unique) lift $\tilde f \colon X \to K_n$ in $\mathbf{SimpGrp}$ such that $U(\tilde f)=f$.
Is this satisfying?


text:
Q: Transform Getting a PHP link to a PHP echo link Can someone please check what I've done, since I'm not that good at PHP yet.
<?php echo $_product->get_categories( ', ', ' ' . __( 'Posted in  ', 'jigoshop' ) . '', '.'); ?>

This line fetches the category and prints Posted in (name of category)
However I want to drop the Posted in (name of category) and make it just have a simple html link.
So I made it
<?php echo Click Me ; ?>

Is what I did correct? (I want to preserve the link inside of the  tags)

A: <?php echo 'Click Me '; ?>

If you're using echo, make sure to give it a string (in quotes).
This doesn't even need PHP.
Click Me

Is just fine.

A: To explain my comment earlier. I have my plugin that I am going to stop and add the URL.
<?php
   //MY PHP CODE
?>
Click Me
<?php
   //CONTINUE WITH PHP CODE
?>

If it is wrote like this
<?php echo $_product->get_categories( ', ', ' ' . __( 'Posted in  ', 'jigoshop' ) . '', '.'); ?>

Just replace the whole thing with the
 Click Me


text:
Q: Does PredictionIO support pyspark? PredictionIO has python SDK, but can I write my template using pyspark?
Most of the templates I have seen are in Java/Scala.

A: right now predictionio is running only on java/scala. predictonio has implemented its base version on spark now, but still needs to upgrade. -DAN


text:
Q: simulate isotropic linear diffusion smoothing I want to apply the de-noising filter I named in the title which is based on the following equations:

where d = 1 is a scalar constant diffusivity parameter, I(x, y) is the initial noisy image, and u(x, y, t) is the image obtained after a diffusion time t lets say 5, 10 and 30. However, I am quite confused about which function to use and how, in order to achieve this in OpenCV. I have the feeling that it is quite simple but for some reason I am confused. Does anyone have an idea?
Here is a sample image:

I want then to compare it with a gaussian filtering approach which according the following:

where G√2t (x, y) is the Gaussian kernel. This proves that performing isotropic linear diffusion for a time t with d = 1 is exactly equivalent to performing Gaussian smoothing with a σ = √(2t)
I have a function that applies the gaussian filtering:
void gaussian_2D_convolution(const cv::Mat& src, cv::Mat& dst, const float sigma, const int ksize_x = 0, const int ksize_y = 0)
{
    int ksize_x_ = ksize_x, ksize_y_ = ksize_y;

    // Compute an appropriate kernel size according to the specified sigma
    if (sigma > ksize_x || sigma > ksize_y || ksize_x == 0 || ksize_y == 0)
    {
        ksize_x_ = (int)ceil(2.0f*(1.0f + (sigma - 0.8f) / (0.3f)));
        ksize_y_ = ksize_x_;
    }

    // The kernel size must be and odd number
    if ((ksize_x_ % 2) == 0)
    {
        ksize_x_ += 1;
    }

    if ((ksize_y_ % 2) == 0)
    {
        ksize_y_ += 1;
    }

    // Perform the Gaussian Smoothing
    GaussianBlur(src, dst, Size(ksize_x_, ksize_y_), sigma, sigma, BORDER_DEFAULT);

    // show result
    std::ostringstream out;
    out << std::setprecision(1) << std::fixed << sigma;
    String title = "sigma: " + out.str();
    imshow(title, dst);
    imwrite("gaussian/" + title + ".png", dst);

    waitKey(260);
}

but I have difficulties implementing the first case.

A: This should work as expected. This is based on:

*

*Octave Perona & Malik smooth

*the comment on your question on answer.opencv
Code:
#include <opencv2\opencv.hpp>
using namespace cv;

void ilds(const Mat1b& src, Mat1b& dst, int iter = 10, double diffusivity = 1.0, double lambda = 0.1)
{
    Mat1f img;
    src.convertTo(img, CV_32F);
    lambda = fmax(0.001, std::fmin(lambda, 0.25)); // something in [0, 0.25] by default should be 0.25
    while (iter--)
    {
        Mat1f lap;
        Laplacian(img, lap, CV_32F);
        img += lambda * diffusivity * lap;
    }

    img.convertTo(dst, CV_8U);
}

int main() {

    Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
    Mat1b res_ilds;
    ilds(img, res_ilds);

    imshow("ILDS", res_ilds);
    waitKey();

    return 0;
}

Result:

Let me know if it works for you


text:
Q: VBA click button with no ID How can I click without class name, the link with the following element is as follows:
Add Range +

The complete element before and after it is as follows:

    Add Range +

This is the vba code i used but did not work:
doc.getElementsByTagName("Add Range +").Click

A: Try using the querySelector Method of the HTMLDocument object, which will allow you to get the desired element by the onclick attribute...
doc.querySelector("[onclick='ChooseRange()']").click


text:
Q: Hadoop - Avro : java.lang.Exception: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator I am developing a Map Reduce program to read the fixed length record and write as avro file. This is in draft form. While executing, I get the below error:
java.lang.Exception: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:406)
Caused by: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator
    at org.apache.avro.mapreduce.AvroJob.setMapOutputKeySchema(AvroJob.java:93)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.setSchema(AvroMultipleOutputs.java:511)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.getContext(AvroMultipleOutputs.java:547)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.write(AvroMultipleOutputs.java:399)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.write(AvroMultipleOutputs.java:378)
    at com.visa.edp.common.vssParser.CustomTestMapper.map(CustomTestMapper.java:98)
    at com.visa.edp.common.vssParser.CustomTestMapper.map(CustomTestMapper.java:32)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:140)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:672)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:330)
    at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:268)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: org.apache.avro.hadoop.io.AvroKeyComparator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more
17/11/10 18:13:28 INFO mapred.JobClient:  map 0% reduce 0%

I have the following dependencies in my project:
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.6.0-mr1-cdh5.8.3</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-core</artifactId>
    <version>2.6.0-mr1-cdh5.8.3</version>
</dependency>

<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro</artifactId>
    <version>1.7.6-cdh5.8.3</version>
</dependency>

<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro-mapred</artifactId>
    <version>1.7.6-cdh5.8.3</version>
</dependency>

And could not find org.apache.avro.hadoop package under the project dependency. Am I missing any dependencies?
Thank you.

A: Added the dependency to the module and worked fine.


text:
Q: How to get Shopify Shop ID inside of product/update Webhook? I'm developing a Shopify app that sets up a "product/create" Webhook through the Shopify API.
While the Webhook is sending a POST to the correct address with no problem, it seems that it is not supplying the ID of the shop that the product has been created for. This is a problem because I need to store metadata for the shop and its products. I need to ensure that the link exists in my database between the shop and its products.
Is there a way to either:

*

*Find the shop ID for the product which is being given to me through the Webhook

*Configure the Webhook with custom data that is handed back when the webhook sends its request, so that I can force it to hand back the shop ID when I create it
Thanks in advance!

A: When Shopify sends request to your webhook url. it will also send some extra details in HTTP header.
You can find X-Shopify-Shop-Domain header which will contain domain name of
store. From domain name you can extract name of store.
it also contains X-Shopify-Hmac-SHA256 to verify aunthenticity of request.

A: If you are handed a product in the products/create webhook, you are handed the domain of the incoming call. Once you authenticate the incoming domain, you can clearly query your persistance layer for the shop's token to match the domain. With that, establish the API connection you need, and voila... you can get the Shop and all it's details.
Typically you do NOT need the shop ID for anything, since the myshopify_domain is your key in almost all cases of any work done between Shopify and your App.


text:
Q: Python in vs iteration for nested list What is the fastest way to check if a list is inside of a nested list, full iteration or using in ?
Given
A = [['Yes','2009','Me'],['Yes','2009','You'],['No','2009','You']]
B = [['No','2009','Me'],['Yes','2009','You'],['No','2009','You']]

Count number of duplicates between A and B.
I see either iterating over all elements:
for i in range(len(A)):
    for j in range(len(B)):
        if A[i] == B[j]:
            count+=1

Or using in with one element iteration:
for i in range(len(A)):
    if A[i] in B:
        count+=1

With the actual lengths of A and B being over 100,000 arrays, and each contains 4 elements, are there any specific functions or strategies to do this comparison efficiently?
With my data, option 1 is green, option 2 is blue, the answer from qqvc is red, user1245262 answer is turquoise (it is at the bottom with very fast, linear complexity)  y axis is seconds, x axis is number of 4 element arrays being compared in each list.

A: You might try using sets. Consider:
>>> A = [['Yes','2009','Me'],['Yes','2009','You'],['No','2009','You']]
>>> B = [['No','2009','Me'],['Yes','2009','You'],['No','2009','You']]

sets require hashable elements, so you need to convert the lists to tuples. I'm assuming that your lists are all in some particular order, so that ['dog',2,'mouse'] will always appear that way, and not as ['mouse', 2, 'dog']. Then,
>>> AA = set(map(tuple,A))
>>> BB = set(map(tuple,B))

Then,
>>> BB.intersection(AA)
set([('No', '2009', 'You'), ('Yes', '2009', 'You')])

Since you only seem to want the size of the intersection,
>>> len(BB.intersection(AA))
2

This might be faster than your looping, but you'd have to check it.

A: option z:
sum(thing in B for thing in A)

option y:
sum(itertools.starmap(operator.eq, itertools.product(A,B)))


text:
Q: Cannot send emails with STMP Postfix on port 587? I have followed this guide line by line: https://www.linode.com/docs/email/postfix/email-with-postfix-dovecot-and-mysql
Finally got emails to be received but I cannot send them and all I get is connecting to mail.. I am using the Claws mail client and it lets me login and receive emails but just not send them. I set it to use port 587 but it just hangs on connecting when sending
Here is my master.cf:
##
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
#smtp      inet  n       -       -       -       1       postscreen
#smtpd     pass  -       -       -       -       -       smtpd
#dnsblog   unix  -       -       -       -       0       dnsblog
#tlsproxy  unix  -       -       -       -       0       tlsproxy
submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=$mua_client_restrictions
  -o smtpd_helo_restrictions=$mua_helo_restrictions
  -o smtpd_sender_restrictions=$mua_sender_restrictions
  -o smtpd_recipient_restrictions=
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=$mua_client_restrictions
  -o smtpd_helo_restrictions=$mua_helo_restrictions
  -o smtpd_sender_restrictions=$mua_sender_restrictions
  -o smtpd_recipient_restrictions=
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       -       -       -       qmqpd
pickup    unix  n       -       -       60      1       pickup

and I cannot see anything in the logs /var/log/mail.log which says what is going on. Port 587, 465 and 25 are open in the firewall as well.
Where do I go from here to debug this?
UPDATE:
I am able to connect via telnet on the server using port 587, postfix is running but I just cannot connect using the Claws Mail client when sending, it receives mail fine, even if I send an email from a Gmail account.

A: Your router or your isp is blocking outgoing connections to port 587. As you did "iptables -P OUTPUT ACCEPT", its not the local firewall for sure. I don't think disabling selinux might help as even telent returns a connection timeout.


text:
Q: Criei uma página parallax e estou tentando fixar o Menu para acompanhar na rolagem da página , mas quando coloco o nav com a opsição fixer ele some

body{
    padding: 0;
    margin:0;
    color:#242424;
    font-family: sans-serif;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

h1,h2,h3,h4,h5,h6{
    font-weight: 900;
    color: #fff;
}

.wrapper{
width: 100%;
margin: 0 auto;
}

main{
    display: block;
    background-color: #fff;
}

.container{
    width: 100%;
    max-width: 760px;
    margin:0 auto;
    padding: 0 20px;
}

section.module p{
margin-bottom: 40px;
}

section.module:last-child{
    margin-bottom: 0;
}

section.module h2{
    margin-bottom:40px;
    font-size:30px;
}

section.module.content{
    padding:40px 0 ;
    background-color: #b08968;
}

section.module.parallax{
   display: flex;
   flex-direction: column;
   justify-content: center;
   height: 100vh !important;
   width: 100%;
   position: relative;
   overflow: hidden;
   background-position: 50% 50%;
   background-repeat: no-repeat;
   background-attachment: fixed;
   background-size: cover ;
   -webkit-background-size:cover

}

section.module.parallax:after{
    content:"";
    height: 100%;
    width: 100%;
    position: absolute;
    z-index: 8;
    background: linear-gradient(to bottom, rgba(0,0,0) 0, rgba(0,0,0,0) 40%, #000 100%);
}

section.module.parallax-1{
    background-image: url("https://cdn.wallpapersafari.com/18/89/L2YNZA.jpg");
}

section.module.parallax-2{
    background-image: url("https://images.alphacoders.com/551/thumb-1920-551056.jpg");
}

section.module.parallax-3{
    background-image: url("https://images.wallpapersden.com/image/download/smite-x-aang-avatar-4k_bGZsZ2iUmZqaraWkpJRqZmdlrWdtbWU.jpg");
}

section.module.parallax h1{
    color:#fff;
    text-align: center;
    font-size: 78px;
    z-index: 50;
    text-transform: uppercase;

}

.menu{
    color: black;
    text-align: center;
    padding: 20px;
    background-color:#b08968;
    width: 100%;
    position: fixed;

}

.menu-link{
    padding:18px;
    text-decoration: none;
    background-color:#b08968;
    color: white;
    transition: 0.3s;
    font-weight: bolder;
    font-family: 'Times New Roman', Times, serif;
    font-size: 20px;

}

.menu-link:hover{
    color: bisque;
}

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device=width, initial-scale=1.0">
    <link rel="stylesheet" href="estio.css">

                Avatar Aang
                 sobre
                 overview
                 netflix

A lenda de Aang

Como foi criada ?

                        Avatar: A Lenda de Aang é uma série animada co-criada e produzida por Michael Dante DiMartino e Bryan Konietzko na Nickelodeon Animation Studios, em Burbank, Califórnia. A série possui um total de 61 episódios. Em 21 de julho de 2010, Brown Johnson, presidente da Nickelodeon,
                        anunciou que o canal começou a produzir em seus estúdios, uma continuação da série.

                        O sucessor a nova versão é A Lenda de Korra, estreou nos Estados Unidos
                         em 14 de abril de 2012 e já foi finalizada em 19 de dezembro de 2014, contando com 4 temporadas.

 Overview

Overview da animação:

                        A série conta as aventuras de Aang, o então sucessor de uma longa linhagem de avatares. Ele e seus amigos Katara, Sokka, e mais tarde Toph Beifong,
                        têm a missão de salvar o mundo dos ataques da Nação do Fogo, que tem como objetivo o domínio de todo o mundo.

                        A série encontra-se estruturada sob a forma de "livros", onde cada episódio é um "capítulo" e cada temporada um "livro" diferente. A sua estreia foi planejada para novembro de 2004, mas foi transmitida pela primeira vez no dia 21 de Fevereiro de 2005 no canal Nickelodeon dos
                        Estados Unidos da América. O último episódio da série foi exibido a 19 de julho de 2008.

 Live Action: Netflix

Anúncio do live action: Netflix

                        Há cerca de 3 anos, a Netflix anunciou que estaria trabalhando em uma adaptação live-action de Avatar: A Lenda de Aang. Na época, a produção foi descrita como uma reimaginação do desenho, e supostamente começaria a ser produzida em 2019. Desde então, a série parece ter passado por alguns momentos conturbados, principalmente dada a saída dos criadores do desenho. Foi apenas neste ano que recebemos novidades sobre a obra,
                        que finalmente conta com um elenco anunciado e parece estar novamente encaminhada para tomar forma.

A: Para resolver  o problema basta adicionar a propriedade z-index com valor 51 para a classe .menu, dessa forma:
.menu {z-index: 51;}
Com isso o menu ficará na frente de todos os elementos.


text:
Q: Java application gives random outputs of an integer I have been having an issue with my Java application where I give the user a certain amount of "points" in the database for every time they complete an action. 32 database points is equal to one ingame point. On the event that the user does an action a method is run to see if the points are a multiple of 32, then says you have  skypoints after dividing the points from the database by 32. After the user completes the action a certain amount of times it stops working and returns 0 every time the user does an action, not even when it's a multiple of 32. Here is a screenshot of the output and the code is located below to give you an understanding of what I have.
Screenshot:

Code inside my database class
public long getPoints(String uuid) {
    long points = 0;
    try {
    // Open a connection
    Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
    Statement stmt = conn.createStatement();

    // Execute a query
    stmt = conn.createStatement();

    String sql = "SELECT playerpoints FROM SkyPoints.players WHERE playerid='" + uuid + "';";
    ResultSet rs = stmt.executeQuery(sql);
    while(rs.next()) {
        points = rs.getLong("playerpoints") / 32;
    }
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return points;
}

public long getRawPoints(String uuid) {
    long points = 0;
    try {
    // Open a connection
    Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
    Statement stmt = conn.createStatement();

    // Execute a query
    stmt = conn.createStatement();

    String sql = "SELECT playerpoints FROM SkyPoints.players WHERE playerid='" + uuid + "';";
    ResultSet rs = stmt.executeQuery(sql);
    while(rs.next()) {
        points = rs.getLong("playerpoints");
    }
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return points;
}

Code inside my main class
    if(DatabaseObject.getRawPoints(uuid) % 32 == 0) {
        String newamount = String.valueOf(DatabaseObject.getPoints(uuid));
        String word = null;
        if(DatabaseObject.getPoints(uuid) == 1) {
            word = "Point";
        } else {
            word = "Points";
        }
        player.sendMessage(ChatColor.GRAY + "You have earned 1 Sky Point. New amount: " + ChatColor.BLUE + newamount + ChatColor.GRAY + " Sky " + word + ".");
    }

Note: UUID is the user id
Thanks for the help, I really appreciate it.
UPDATE: Got an sql error
[16:58:42 WARN]: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"
[16:58:42 WARN]:        at sun.reflect.GeneratedConstructorAccessor58.newInstance(Unknown Source)
[16:58:42 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[16:58:42 WARN]:        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
[16:58:42 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
[16:58:42 WARN]:        at com.mysql.jdbc.Util.getInstance(Util.java:382)
[16:58:42 WARN]:        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
[16:58:42 WARN]:        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
[16:58:42 WARN]:        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
[16:58:42 WARN]:        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1116)
[16:58:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2338)
[16:58:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2371)
[16:58:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2163)
[16:58:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:794)
[16:58:42 WARN]:        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
[16:58:42 WARN]:        at sun.reflect.GeneratedConstructorAccessor44.newInstance(Unknown Source)
[16:58:42 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[16:58:42 WARN]:        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
[16:58:42 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
[16:58:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:378)
[16:58:42 WARN]:        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
[16:58:42 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:571)
[16:58:42 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:215)
[16:58:42 WARN]:        at me.andrewyunt.SkyPoints.Database.getPoints(Database.java:159)
[16:58:42 WARN]:        at me.andrewyunt.SkyPoints.SkyPoints.onBlockBreak(SkyPoints.java:77)
[16:58:42 WARN]:        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[16:58:42 WARN]:        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
[16:58:42 WARN]:        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[16:58:42 WARN]:        at java.lang.reflect.Method.invoke(Method.java:606)
[16:58:42 WARN]:        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:296)
[16:58:42 WARN]:        at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:62)
[16:58:42 WARN]:        at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:502)
[16:58:42 WARN]:        at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:487)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.PlayerInteractManager.breakBlock(PlayerInteractManager.java:264)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.PlayerInteractManager.dig(PlayerInteractManager.java:118)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.PlayerConnection.a(PlayerConnection.java:550)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.PacketPlayInBlockDig.a(SourceFile:53)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.PacketPlayInBlockDig.handle(SourceFile:8)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.NetworkManager.a(NetworkManager.java:184)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.ServerConnection.c(ServerConnection.java:81)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.MinecraftServer.v(MinecraftServer.java:731)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.DedicatedServer.v(DedicatedServer.java:289)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.MinecraftServer.u(MinecraftServer.java:584)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.MinecraftServer.run(MinecraftServer.java:490)
[16:58:42 WARN]:        at net.minecraft.server.v1_7_R4.ThreadServerApplication.run(SourceFile:628)

Data source rejected establishment of connection,  message from server: "Too many connections"

A: You need to close your Connections and ResultSets after you are done with them, otherwise, it will be as if you're still executing queries with them, even though you aren't.
To close a Connection or ResultSet, just use variableName.close();. So, for example, you should use:
connection.close();
resultset.close();

In the case of your code, you should use:
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
//set the query, create the statement

ResultSet rs = stmt.executeQuery(sql);
//get values

conn.close();
rs.close();

//return values

The reason you're getting the error is because MySQL thinks that you're still using all of those connections, even though you aren't. To make it so MySQL doesn't think you're still using those connections, is to close them, with connection.close().


text:
Q: Unable to ignore proguard warning I'm trying to add Detox e2e testing to my project, and when I run the assembleAndroidTest I get proguard warnings that fails the build:
Warning: library class android.content.Intent depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.content.IntentFilter depends on program class org.xmlpull.v1.XmlSerializer
Warning: library class android.content.IntentFilter depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.graphics.drawable.BitmapDrawable depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.graphics.drawable.Drawable depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.graphics.drawable.Drawable depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.graphics.drawable.Drawable depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.graphics.drawable.Drawable depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.graphics.drawable.Drawable depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.graphics.drawable.Drawable depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.util.Xml depends on program class org.xmlpull.v1.XmlPullParser
Warning: library class android.util.Xml depends on program class org.xmlpull.v1.XmlSerializer
Warning: library class android.util.Xml depends on program class org.xmlpull.v1.XmlPullParser
Note: there were 13 unresolved dynamic references to classes or interfaces.
      You should check if you need to specify additional program jars.
      (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclass)
Note: there were 39 accesses to class members by means of introspection.
      You should consider explicitly keeping the mentioned class members
      (using '-keep' or '-keepclassmembers').
      (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclassmember)
Warning: there were 89 unresolved references to classes or interfaces.
         You may need to add missing library jars or update their versions.
         If your code works fine without the missing classes, you can suppress
         the warnings with '-dontwarn' options.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass)
Warning: there were 16 instances of library classes depending on program classes.
         You must avoid such dependencies, since the program classes will
         be processed, while the library classes will remain unchanged.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#dependency)
Couldn't find any dontwarn that suppressed it and allowed me to build the project, This SO thread didn't worked either.
Thanks


text:
Q: Help about in instruction of LVDT I want to instruct an LVDT with a range of 250mm, But I do not know the calculations for the winding.
How to calculate the length of the winding and the number of turns?
I think for modulate and demodulate of signal from the winding, AD698 is a suitable choice, is it true?
If there are any points in construction and design, please tell me.
Thanks,

A: Use your knowledge of inductor calculators with sleeves and stainless steel cores and follow the best-in class impedance ratios of similar LVDT's.
e.g. 280 Ohms primary at 5kHz, 1000 ohms secondary for +/-100mm, yet you only want +/-50mm.
The coil range must extend beyond the core to minimize changes on mutual inductance effects on loaded output.
Choose a frequency that is at least(!) 10x higher than the desired bandwidth for ripple rejection or define your ripple attenuation from sensitivity to small steps in position.
ref:
https://singer-instruments.com/introduction-to-lvdt/
https://singer-instruments.com/wp-content/uploads/2019/10/2_DC_LVDT_S-D_and_M-D_Series-1.pdf
Then follow their construction advice and but I don't know how to estimate the mutual coupling effects of a transformer using a (non magnetic stainless steel core. An aluminum core is non-magnetic, yet has mutual coupling from the eddy currents at 50kHz might be an option. (or not)
It all depends on your goal for source and load impedance as well with changes in mutual coupling, complex permeability, skin effects and eddy current effects. .
For lower mass sleeve cores might be possible or just smaller diameter and the same for inner stainless steel coil sleeves. The steel sleeve and centre core must be smooth and co-linear as possible with perhaps some lubricant (?) and must be precise with the smallest air gap yet have to prevent friction at all costs so that temperature effects does not warp it or enlarge it more than the coil form.


text:
Q: How can I validate my REFERER URL with glob? I'm trying to check if my referrer String is coming from any URL with the format https://www.google.com/{{anything}}:
    String referrer = req.getHeader("REFERER");

    if (!(referrer.equals("https://www.google.com")) + createRegexFromGlob("*")) {
        System.out.println("The referrer is valid.");
    } else {
        System.out.println("The referrer is not valid.");
    }

Here is the glob:
public static String createRegexFromGlob(String glob)
{
    String out = "^";
    for(int i = 0; i < glob.length(); ++i)
    {
        final char c = glob.charAt(i);
        switch(c)
        {
        case '*': out += ".*"; break;
        case '?': out += '.'; break;
        case '.': out += "\\."; break;
        case '\\': out += "\\\\"; break;
        default: out += c;
        }
    }
    out += '$';
    return out;
}

Does the referrer URL have to be a direct hit or will it automatically know if it's coming from the base URL, https://www.google.com?
I suppose I can just use .contains instead of making sure the string is equal to something plus a regular expression? Is there anything wrong with this?

A: Why not use .startsWith instead?
Try
if (referrer.startsWith("https://www.google.com"))

Also, what on earth are are you doing with createRegexFromGlob? Simply match the URL with the following regex
^https:\/\/www\.google\.com.*$

Java code:
String pattern = "^https:\\/\\/www\\.google\\.com.*$";
if(referrer.matches(pattern))

.contains can be used but it'll also accept URLs like
http://example.com/https://www.google.com


text:
Q: MongoDB not installable from 10gen's Debian repository I added the official 10gen Debian repo to my Wheezy installation but MongoDB remains uninstallable:
Setting up mongodb-10gen (2.4.4) ...
[FAIL] Starting database: mongodb failed!
invoke-rc.d: initscript mongodb, action "start" failed.
dpkg: error processing mongodb-10gen (--configure):
 subprocess installed post-installation script returned error exit status 1
Setting up mmv (1.01b-15) ...
Errors were encountered while processing:
 mongodb-10gen
E: Sub-process /usr/bin/dpkg returned an error code (1)
A package failed to install.  Trying to recover:
Setting up mongodb-10gen (2.4.4) ...
[FAIL] Starting database: mongodb failed!
invoke-rc.d: initscript mongodb, action "start" failed.
dpkg: error processing mongodb-10gen (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 mongodb-10gen

Did anyone install MongoDB successfully as .deb?

A: I had the same problem. I followed the instructions here:
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian/
After downgrading with
 apt-get install mongodb-10gen=2.2.3

It started
[ ok ] Starting database: mongodb.

If you want to make this change permanent to subsequent updates, mark this package to hold state use:
apt-mark hold mongodb-10gen

A: If you are on a VM and started it with a relatively small size, it could just be due to a lack of free space. At this stage, MongoDB create the journal files and you need at least 3379MB available for that.
Otherwise check the log which should be at :
/var/log/mongodb/mongod.log


text:
Q: How to fix this error, next js + firebase + Zeit I am using firebase in Nextjs app, it works perfectly fine on production but
while deploying to Zeit I am getting this error!
 ./node_modules/@firebase/database/dist/index.node.cjs.js
                          Module not found: Can't resolve 'request' in '/tmp/6d82ffed/node_modules/@firebase/database/dist'
2019-07-08T17:56:01.203Z  > Build error occurred
2019-07-08T17:56:01.203Z  Error: > Build failed because of webpack errors
                              at Object.build [as default] (/tmp/6d82ffed/node_modules/next/dist/build/index.js:192:15)
                              at <anonymous>
                              at process._tickCallback (internal/process/next_tick.js:188:7)

How can I resolve this.
I checked the github issues and I found its an open issue with no solution provided yet
https://github.com/zeit/now-cli/issues/1830
is the issue link!


text:
Q: Will NEST project in elasticsearch or in the client? If I have a complex document indexed in elasticsearch and query it using a DTO, will a projection for the fields required by the DTO be applied in elasticsearch, before sending the data to the C# client or will the full source be sent, and C# will use that to hydrate the DTO?
var response = await elasticClient.SearchAsync<TDto>(searchRequest);
Basically, I need to know if I can simply ask for a TDto and not worry about data volume of the larger ComplexDocument that was indexed, or if I have to specify Source inclusion/exclusion in the searchRequest to get the best performance.

A: By default, Elasticsearch will send back the full _source document for each search hit. You can specify which fields of _source to include/exclude with source filtering
var client = new ElasticClient();

var searchResponse = client.Search<ComplexDocument>(s => s
    .Source(sf => sf
        .Includes(i => i
            .Field(f => f.Path)
            .Field(f => f.Content)
        )
        .ExcludeAll()
    )
);

foreach(var source in searchResponse.Documents)
{
    var path = source.Path;
}

which sends
{
    "_source": {
        "excludes": ["*"],
        "includes": ["path", "content"]
    }
}

Or you can ask not to return _source at all
var searchResponse = client.Search<ComplexDocument>(s => s
    .Source(false)
);

With source filtering, the storage field for _source is read completely on the Elasticsearch side, and filtering applied. This is usually fine, but if _source is a huge document, and you only ever want to return a subset of fields in response to a search, you might decide to use stored fields instead.
As the name implies, stored fields are fields stored separately to _source (by specifying store:true in their mapping) and can be returned in a search response
var searchResponse = client.Search<ComplexDocument>(s => s
    .StoredFields(f => f
        .Field(ff => ff.Path)
    )
);

foreach(var fields in searchResponse.Fields)
{
    var path = fields.ValueOf<ComplexDocument, string>(f => f.Path);
}

Stored fields are returned in a "fields" property on each hit.

If I have a complex document indexed in elasticsearch and query it
  using a DTO, will a projection for the fields required by the DTO be
  applied in elasticsearch, before sending the data to the C# client or
  will the full source be sent, and C# will use that to hydrate the DTO?

In summary, Elasticsearch will return the full _source and NEST will map matching properties in the _source to properties of the DTO. NEST maps camel case properties in JSON to the POCO properties by default. If you want to transmit less across the wire, take a look at source filtering. You could probably wrap up the functionality to include only fields in the DTO in the request as an extension method to SearchDescriptor<TInferDocument>
public class ComplexDocument
{
    public int Id { get; set; }
    public string Path { get; set; }
    public string Content { get; set; }
    public Attachment Attachment { get; set; }
}

public class SimpleDTO
{
    public string Path { get; set; }
}

public static class SearchDescriptorExtensions
{
    public static SearchDescriptor<TInferDocument> SourceIncludesDto<TInferDocument, TDocument>(this SearchDescriptor<TInferDocument> descriptor)
        where TInferDocument : class
        where TDocument : class
        {
            // TODO: cache this :)
            Fields fields = typeof(TDocument).GetProperties();

            return descriptor.Source(s => s
                .Includes(f => f
                    .Fields(fields)
                )
            );
        }
}

ISearchResponse<SimpleDTO> searchResponse =
    client.Search<ComplexDocument, SimpleDTO>(s => s
        .SourceIncludesDto<ComplexDocument, SimpleDTO>()
    );

sends
{
    "_source": {
        "includes": ["path"]
    }
}


text:
Q: sending bulk email in laravel from select options Am trying to send bulk email from my laravel project sing PHPMailer, I get the emails from the select option in blade:
<form action="{{url('send/bulk/email')}}" method="post">
   @csrf
   <select name="recipient[]"   multiple data-mdb-filter="true" >
      <option value="glemar0@amazon.co.uk" >glemar0@amazon.co.uk</option>
      <option value="xfacey2@dion.ne.jp" >xfacey2@dion.ne.jp</option>
      <option value="lsenten3@tripod.com" >lsenten3@tripod.com</option>
      <option value="gchamperlen4@zimbio.com">gchamperlen4@zimbio.com</option>
      <option value="dgracey5@simplemachines.org" >dgracey5@simplemachines.org</option>
      <option value="mwildman6@amazon.co.jp" >mwildman6@amazon.co.jp</option>
   </select>
</form>

In Controller
public function sendBulkEmail(Request $request){
    try {
        $recipients = explode(',', $request->recipient);
        $mail = new PHPMailer(true);

        //Server settings
        $mail->setFrom('sender@example.com', 'Sender');

        foreach ($recipients as $recipient) {
           $mail->addAddress($recipient);
     }

    $mail->addReplyTo('sender@example.com', 'Information');

    $mail->isHTML(true);
    $mail->Subject = 'Request';
    $mail->Body    = 'this test message';
   }
}

My error
explode(): Argument #2 ($string) must be of type string, array given

A: The recipient parameter in request is an array itself. You don't need to explode it.
$recipients = $request->recipient ;


text:
Q: Is their any way to find device is a mobile or a Tab in android ? how to remove Recent app button alone? Is there any way to either remove the recent apps button in android 3.0 (I have a xoom) or clear the list? Is their any way to find device is, Mobile or Tab using java code.
Bcoz it breaks my policy app and allows people to switch device administrator if default Settings in that list. i am displaying my own launcher with out settings application.
So is their any way to disable Recent app button or to clear app thumbnail.
Please help me with any code sample or doc.Thanks in advance.

A: You've asked multiple questions. Here, I'm trying to answer your second question;

Is their any way to find device is, Mobile or Tab using java code.

You can use the screen size to determine whether your code is running on a tablet or mobile phone, see the code below;
public boolean isTablet() {
    try {
        // Compute screen size
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        float screenWidth  = dm.widthPixels / dm.xdpi;
        float screenHeight = dm.heightPixels / dm.ydpi;
        double size = Math.sqrt(Math.pow(screenWidth, 2) + Math.pow(screenHeight, 2));
        // Tablet devices should have a screen size greater than 6 inches
        return size >= 6;
    } catch(Throwable t) {
        Log.error(TAG_LOG, "Failed to compute screen size", t);
        return false;
    }
}

Source: http://groups.google.com/group/android-developers/browse_thread/thread/d6323d81f226f93f


text:
Q: What is the error reported for AH01757, "generating secret for digest authentication ..."? I'm working through our web server's error log for an Open Source project. I see repeated entries for:
$ cat /var/log/httpd/error_log-20160522 | grep "digest"
[Mon May 16 08:11:29.004792 2016] [auth_digest:notice] [pid 20628] AH01757: generating secret for digest authentication ...
[Thu May 19 09:45:18.519977 2016] [auth_digest:notice] [pid 12588] AH01757: generating secret for digest authentication ...
[Thu May 19 09:47:10.331913 2016] [auth_digest:notice] [pid 128] AH01757: generating secret for digest authentication ...
[Thu May 19 14:59:26.211893 2016] [auth_digest:notice] [pid 7102] AH01757: generating secret for digest authentication ...
...

The configuration file is /etc/httpd/conf/httpd.conf. LogLevel is set to LogLevel warn. ErrorLog is set to "logs/error_log".
What, exactly, is the error Apache is reporting? How do I fix it?

$ hostnamectl
  ...
    Virtualization: openvz
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 2.6.32-042stab113.17
      Architecture: x86-64

$ apachectl -V
Server version: Apache/2.4.6 (CentOS)
Server built:   May 12 2016 10:27:23
...

A: Ignore it, it's informational and reporting no error. It has already been dropped to DEBUG level in 2.5.x (trunk) which means you will not see it in a later release.
I will see about getting the change in log level backported to 2.4.x


text:
Q: Choosing which sound to play in Pygame In Pygame how would I define which sound I want to play in certain "if" events? I've been able to load them both in I just hit the issue of not playing either on demand. Thanks for helping me in advance.

A: You need to use a sound object to play sounds.
if condition_one_true:
    sound_one = Sound('sound1.mp3')
    sound_one.play()

if condition_two_true:
    sound_two= Sound('sound2.mp3')
    sound_two.play()


text:
Q: Can not receive SessionSwitch event in Windows Service As I mentioned in title I have a problem with receiving SessionSwitch events of SystemEvents class.
There is a sample code (Example 2) at the end of SystemEvents class documentation page which shows how to receive TimeChanged and UserPreferencesChanged events and it works good.
I have added another event handler for SessionSwitch by myself. As I figured out only applications with window can receive this message from OS (because only they have message loop). That is why there is hidden window in this example. I have tried to create WinForms app and it works okay so the code is correct. But I need a Windows Service which will be running under Local System Account. I have no ideas what is the problem.
I am using Visual Studio 2012 Ultimate and Windows 7 Enterprise Edition.
Code:
using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Drawing;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;

namespace SimpleServiceCs
{
    public class SimpleService : ServiceBase
    {
        private static void Main(string[] args)
        {
            Run(new SimpleService());
        }

        protected override void OnStart(string[] args)
        {
            EventLog.WriteEntry("SimpleService", "Starting SimpleService");
            new Thread(RunMessagePump).Start();
        }

        private void RunMessagePump()
        {
            EventLog.WriteEntry("SimpleService.MessagePump", "Starting SimpleService Message Pump");
            Application.Run(new HiddenForm());
        }

        protected override void OnStop()
        {
            Application.Exit();
        }
    }

    public partial class HiddenForm : Form
    {
        public HiddenForm()
        {
            InitializeComponent();
        }

        private void HiddenForm_Load(object sender, EventArgs e)
        {
            SystemEvents.TimeChanged += SystemEvents_TimeChanged;
            SystemEvents.UserPreferenceChanged += SystemEvents_UPCChanged;
            SystemEvents.SessionSwitch +=SystemEvents_SessionSwitch;
        }

        private void HiddenForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
            SystemEvents.UserPreferenceChanged -= SystemEvents_UPCChanged;
            SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
        }

        private void SystemEvents_TimeChanged(object sender, EventArgs e)
        {
            EventLog.WriteEntry("SimpleService.TimeChanged", "Time changed; it is now " +
                                                             DateTime.Now.ToLongTimeString());
        }

        private void SystemEvents_UPCChanged(object sender, UserPreferenceChangedEventArgs e)
        {
            EventLog.WriteEntry("SimpleService.UserPreferenceChanged", e.Category.ToString());
        }

        private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
        {
            switch (e.Reason)
            {
                case SessionSwitchReason.ConsoleConnect:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Connected from console at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.ConsoleDisconnect:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Disconnected from console at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.RemoteConnect:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Connected from remote at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.RemoteDisconnect:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Disconnected from remote at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.SessionLock:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Locked at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.SessionLogoff:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Logoff at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.SessionLogon:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Logon at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.SessionRemoteControl:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Remote control at " + DateTime.Now.ToLongTimeString());
                    break;
                case SessionSwitchReason.SessionUnlock:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Unlocked at " + DateTime.Now.ToLongTimeString());
                    break;
                default:
                    EventLog.WriteEntry("SimpleService.SessionSwitch",
                        "Default case: something is wrong. " + DateTime.Now.ToLongTimeString(),
                        EventLogEntryType.Error);
                    break;
            }
        }
    }

    partial class HiddenForm
    {
        private readonly IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            SuspendLayout();
            AutoScaleDimensions = new SizeF(6F, 13F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(0, 0);
            FormBorderStyle = FormBorderStyle.None;
            Name = "HiddenForm";
            Text = "HiddenForm";
            WindowState = FormWindowState.Minimized;
            Load += HiddenForm_Load;
            FormClosing += HiddenForm_FormClosing;
            ResumeLayout(false);
        }
    }

    [RunInstaller(true)]
    public class SimpleInstaller : Installer
    {
        private ServiceProcessInstaller processInstaller;
        private ServiceInstaller serviceInstaller;

        public SimpleInstaller()
        {
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller = new ServiceInstaller();

            // Service will run under system account
            processInstaller.Account = ServiceAccount.LocalSystem;

            // Service will have Start Type of Manual
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            serviceInstaller.ServiceName = "Simple Service";

            Installers.Add(serviceInstaller);
            Installers.Add(processInstaller);
        }
    }
}