text:
Q: Why do I need to apply a window function to samples when building a power spectrum of an audio signal? I have found for several times the following guidelines for getting the power spectrum of an audio signal:

*

*collect N samples, where N is a power of 2

*apply a suitable window function to the samples, e.g. Hanning

*pass the windowed samples to an FFT routine - ideally you want a real-to-complex FFT but if all you have a is complex-to-complex FFT then pass 0 for all the imaginary input parts

*calculate the squared magnitude of your FFT output bins (re * re + im * im)

*(optional) calculate 10 * log10 of each magnitude squared output bin to get a magnitude value in dB

*Now that you have your power spectrum you just need to identify the peak(s), which should be pretty straightforward if you have a reasonable S/N ratio. Note that frequency resolution improves with larger N. For the above example of 44.1 kHz sample rate and N = 32768 the frequency resolution of each bin is 44100 / 32768 = 1.35 Hz.

But... why do I need to apply a window function to the samples? What does that really means?
What about the power spectrum, is it the power of each frequency in the range of sample rate? (example: windows media player visualizer of sound?)

A: Note that a non-rectangular window has both benefits and costs.  The result of a window in the time-domain is equivalent to a convolution of the window's transform with the signal's spectrum.  A typical window, such as a von Hann window, will reduce the "leakage" from any non-periodic spectral content, which will result in a less noisy looking spectrum; but, in return, the convolution will "blur" any exactly or close to periodic spectral peaks across a few adjacent bins.  e.g. all the spectral peaks will become rounder looking which may reduce frequency estimation accuracy.  If you know, apriori, that there is no non-periodic content (e.g. data from some rotationally synchronous sampling system), a non-rectangular window could actually make the FFT look worse.
A non-rectangular window is also an informationally lossy process.  A significant amount of spectral information near the edges of the window will be thrown away, assuming finite precision arithmetic.  So non-rectangular windows are best used with overlapping window processing, and/or when one can assume that the spectrum of interest is either stationary across the entire window width, or centered in the window.

A: If you're not applying any windowing function, you're actually aplying a rectangular windowing function. Different windowing functions have different characteristics, it depends on what you want exactly.

A: Most real world audio signals are non-periodic, meaning that real audio signals do not generally repeat exactly, over any given time span.
However, the math of the Fourier transform assumes that the signal being Fourier transformed is periodic over the time span in question.
This mismatch between the Fourier assumption of periodicity, and the real world fact that audio signals are generally non-periodic, leads to errors in the transform.
These errors are called "spectral leakage", and generally manifest as a wrongful distribution of energy across the power spectrum of the signal.
The plot below shows a closeup of the power spectrum of an acoustic guitar playing the A4 note. The spectrum was calculated with the FFT (Fast Fourier Transform), but the signal was not windowed prior to the FFT.
Notice the distribution of energy above the -60 dB line, and the three distinct peaks at roughly 440 Hz, 880 Hz, and 1320 Hz.  This particular distribution of energy contains "spectral leakage" errors.

To somewhat mitigate the "spectral leakage" errors, you can pre-multiply the signal by a window function designed specifically for that purpose, like for example the Hann window function.
The plot below shows the Hann window function in the time-domain. Notice how the tails of the function go smoothly to zero, while the center portion of the function tends smoothly towards the value 1.

Now let's apply the Hann window to the guitar's audio data, and then FFT the resulting signal.
The plot below shows a closeup of the power spectrum of the same signal (an acoustic guitar playing the A4 note), but this time the signal was pre-multiplied by the Hann window function prior to the FFT.
Notice how the distribution of energy above the -60 dB line has changed significantly, and how the three distinct peaks have changed shape and height.  This particular distribution of spectral energy contains fewer "spectral leakage" errors.

The acoustic guitar's A4 note used for this analysis was sampled at 44.1 KHz with a high quality microphone under studio conditions, it contains essentially zero background noise, no other instruments or voices, and no post processing.
References:
Real audio signal data, Hann window function, plots, FFT, and spectral analysis were done here:
Fast Fourier Transform, spectral analysis, Hann window function, audio data

A: As @cyco130 says, your samples are already windowed by a rectangular function. Since a Fourier Transform assumes periodicity, any discontinuity between the last sample and the repeated first sample will cause artefacts in the spectrum (e.g. "smearing" of the peaks). This is known as spectral leakage. To reduce the effect of this we apply a tapered window function such as a Hann window which smooths out any such discontinuity and thereby reduces artefacts in the spectrum.


text:
Q: std::regex_match provokes a stack overflow The following code (win10, target plateform version = 10.0.17134.0, platform toolset = Visual Studio 2015 (v140) in latest update of visual studio 2019 pro, debug x64) :
#include <iostream>
//#define _REGEX_MAX_STACK_COUNT 0;
#include <regex>

int main()
{
    int stack_reg = _REGEX_MAX_STACK_COUNT ;

    std::string nok("FDFDFD...FDFD"); // concatenation of "FD" 298 times
    std::string ok( "FDDFFD...FD"); // concatenation of "FD" 297 times
    auto regex(std::regex("([FI]D){1,}"));

    bool res_ok = std::regex_match(ok, regex);
    bool res_nok = std::regex_match(nok, regex); // triggers the exception

    return 0;
}

triggers the following exception :

inside C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\xmemory0 when line bool res_nok = std::regex_match(nok, regex); // triggers the exception is trying to be executed.
Setting _REGEX_MAX_STACK_COUNT  to 200000 or even to 0 (no limit) keeps triggering the same exception.
I tried to apply solution from
https://stackoverflow.com/a/42913977/1581875
but I have no "regex.h" in my include paths so that I can only include <regex>.
(Context : the code is one case from thousands in a switch...case parsing a huge programming language script, so that I would ideally like to do the very same regex with the very same matching pattern in a different way. The problem is that installing boost is not an option for me.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: MaxCharLimit on the TextInput according to it's width I am using Flex 4.5 and I want to set the maximum characters limit according to the textinput width means if user enter more character then the textinput width it should not accept those extra characters.

A: unfortunately, i have no flex in front of me right now.
You should know, how many space e.g. 20 characters needed and set this value to your textinput.width.
Check out the widthInChars-property for the spark Textinput. Maybe you can work with a litte offset. When it works, you just have to synchronize this value with maxChars.
Let me know, if that work.
Frank


text:
Q: Python - Store function with parameters I'm using Tkinter for a simple trivia game. There are several buttons, one for each answer, and I'd like to run a checkAnswer function with certain parameters when one is clicked.
If I used something like the following:
self.option1 = Button(frame, text="1842", command=self.checkAnswer(question=3, answer=2))

Then it would run checkAnswer and use what it returned (nothing).
Is there a simple way to store the parameters in the button constructor?

A: You could create a higher order function to wrap your checkAnswer function. This would allow you to return a function that wouldn't require any parameters, and therefore could be used as a callback.
For example:
def makeCheckAnswer(self, **kwargs)
    return lambda: self.checkAnswer(**kwargs)

This would make your button initialization:
self.option1 = Button(frame, text="1842", command=self.makeCheckAnswer(question=3, answer=2))

A: This is exactly what functools.partial() is designed to do:
>>> import functools
>>> print_with_hello = functools.partial(print, "Hello")
>>> print_with_hello("World")
Hello World
>>> print_with_hello()
Hello

partial() returns a new function that behaves just as the old one, but with any arguments you passed in filled, so in your case:
import functools

...

self.option1 = Button(frame, text="1842", command=functools.partial(self.checkAnswer, question=3, answer=2))

A: By far easiest is just to use lambda in place
self.option1 = Button(frame, text="1842",
    command=lambda: self.checkAnswer(question=3, answer=2))

Though, in a similar but a bit more complicated cases, you really should use a function factory such as
def answerCheckerFactory(self, question, answer):
    def checker():
        return self.checkAnswer(question, answer)

    return checker

    ...
    self.option1 = Button(frame, text="1842",
        command=self.answerCheckerFactory(question=3, answer=2))

because it would make sure that you pass in correct arguments (not quetsion (sic) for example); notice the difference from functools.partial which allows you to mistype the function arguments and get an exception only when clicked on the button ;)
Also, hardcoding the questions / answers in the button code does not seem right...

A: If you have functions that have specific parameters (that dont rely on things like text.get()) you can use wrappers for it, which would be the easiest way to do this, other than lambada functions. For example:
def option1wrapper():
    ClassName.checkAnswer(question=3,answer=2)
self.option1 = Button(frame, text="1842", command=option1wrapper)

A: Only you need to use a lambda function like this
self.option1 = lambda: Button(frame, text="1842", command=self.checkAnswer(question=3, answer=2))


text:
Q: PHP no me recibe correctamente los datos Estoy realizando un programa que me muestre los pedido que se han realizado dependiendo de una fecha elegida, o dependiendo del instructor que lo elija.
Para esto, uso DOMPDF. Al enviar los datos para que se me realice la consulta a la base de datos y generar los documentos (en este caso, sólo se envía la fecha), se me envían todas las fechas que existen. Es decir, si hay 2 fechas, la consulta me mostrará todos los pedidos en esas dos fechas, en vez de la que se eligió.
Aquí el formulario:
<?php
    $fecha=mysqli_query($mysqli, "SELECT * FROM pedidos GROUP BY fecha_pedido");
    $c_f=$fecha->num_rows;
    if ($c_f>=1) {
        while ($f=mysqli_fetch_array($fecha)) {
            echo "";
            echo "";
            echo $f['fecha_pedido'];
            $fechas=$f['fecha_pedido'];
            echo "";
            echo "<form action='reporte_pdf.php' method='post' class='enviar_fechas'>";
            echo "<input type='text' class='enviar_fecha' name='fecha_pedido' value='" . $fechas . "''>";
            echo "<button></button>";
            echo "</form>";
            $instructores=mysqli_query($mysqli, "SELECT * FROM instructores, pedidos WHERE pedidos.doc_in=instructores.doc_in AND fecha_pedido='$fechas' GROUP BY nombres_in");
            while ($in=mysqli_fetch_array($instructores)) {
                echo "";
                echo "";
                echo $in['nombres_in'] . " " . $in['apellidos_in'];
                echo "";
                $producto=mysqli_query($mysqli, "SELECT * FROM instructores, pedidos, productos WHERE pedidos.doc_in=instructores.doc_in AND fecha_pedido='$fechas' AND pedidos.cod_prod=productos.cod_prod");
                while ($p=mysqli_fetch_array($producto)) {
                    echo "
";
                    echo "
";
                    echo "Nombre del producto (SIBOL).	";
                    echo "" . $p['sibol_prod'] . "	";
                    echo "
";
                    echo "
";
                    echo "Nombre comercial del producto.	";
                    echo "" . $p['nombre_prod'] . "	";
                    echo "
";
                    echo "
";
                    echo "Calidad.	";
                    echo "" . $p['calidad_prod'] . "	";
                    echo "
";
                    echo "
";
                    echo "Generalidades.	";
                    echo "" . $p['generalidades_prod'] . "	";
                    echo "
";
                    echo "
";
                    echo "Requisitos generales.	";
                    echo "" . $p['re_generales_prod'] . "	";
                    echo "
";
                    echo "
";
                    echo "Requisitos específicos.	";
                    echo "" . $p['re_espe_prod'] . "	";
                    echo "
";
                    echo "
";
                    echo "Empaque y rotulado.	";
                    echo "" . $p['empaque_prod'] . "	";
                    echo "
";
                    echo "
";
                    echo "Presentación.	";
                    echo "" . $p['presentacion_producto'] . "	";
                    echo "
";
                    echo "
";
                    echo "Imagen de referencia.	";
                    echo "	";
                    echo "
";
                    echo "
";
                    echo "
";
                }
                echo "";
            }
            echo "";
        }
    }else{
        echo "Aún no hay registros.";
    }
    ?>

Y aquí se recibe y se genera el PDF:
<?php
# Cargamos la librería dompdf.
require_once './dompdf/dompdf_config.inc.php';
include('conexion.php');
$fecha_pedido=$_GET['fecha_pedido'];
# Contenido HTML del documento que queremos generar en PDF.
$html='

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ejemplo de Documento en PDF.</title>

';
$ver_pedidos=mysqli_query($mysqli, "SELECT * FROM pedidos");
while ($vp=mysqli_fetch_array($ver_pedidos)) {
    if (isset($vp['doc_in'])) {
        $pedidos_in=mysqli_query($mysqli, "SELECT * FROM pedidos, instructores, productos WHERE pedidos.doc_in=instructores.doc_in AND pedidos.cod_prod=productos.cod_prod AND pedidos.fecha_pedido='$fecha_pedido'");
        while ($pi=mysqli_fetch_array($pedidos_in)) {
            $html.='

' . $pi["nombres_in"] . ' ' . $pi["apellidos_in"] . '

            ' . $fecha_pedido . '

            Nombre del producto (SIBOL).
            ' . $pi["sibol_prod"] . '

            Nombre comercial del producto.
            ' . $pi["nombre_prod"] . '

            Calidad.
            ' . $pi["calidad_prod"] . '

            Generalidades.
            ' . $pi["generalidades_prod"] . '

            Requisitos generales.
            ' . $pi["re_generales_prod"] . '

            Requisitos específicos.
            ' . $pi["re_espe_prod"] . '

            Empaque y rotulado.
            ' . $pi["empaque_prod"] . '

            Presentación.
            ' . $pi["presentacion_prod"] . '

            Imagen de referencia.

';
        }
    }elseif(isset($vp['doc_fun'])){
       //Aún no hay código aquí.
    }
}
$html.='

';

# Instanciamos un objeto de la clase DOMPDF.
$mipdf = new DOMPDF();

# Definimos el tamaño y orientación del papel que queremos.
# O por defecto cogerá el que está en el fichero de configuración.
$mipdf ->set_paper("A4", "portrait");

# Cargamos el contenido HTML.
$mipdf ->load_html(utf8_decode($html));

# Renderizamos el documento PDF.
$mipdf ->render();

# Enviamos el fichero PDF al navegador.
$mipdf ->stream('' . $fecha_pedido . '.pdf');
?>

Y cuando el .php está normal, sin DOMPDF, sí me realiza la consulta correctamente:
    <?php
include('conexion.php');
$fecha_pedido=$_GET['fecha_pedido'];
$ver_pedidos=mysqli_query($mysqli, "SELECT * FROM pedidos");
while ($vp=mysqli_fetch_array($ver_pedidos)) {
    if (isset($vp['doc_in'])) {
        $pedidos_in=mysqli_query($mysqli, "SELECT * FROM pedidos, instructores, productos WHERE pedidos.doc_in=instructores.doc_in AND pedidos.cod_prod=productos.cod_prod AND pedidos.fecha_pedido='$fecha_pedido'");
        while ($pi=mysqli_fetch_array($pedidos_in)) {
            echo "
";
                echo "
";
                echo "Nombre del producto (SIBOL).	";
                echo "" . $i['sibol_prod'] . "	";
                echo "
";
                echo "
";
                echo "Nombre comercial del producto.	";
                echo "" . $i['nombre_prod'] . "	";
                echo "
";
                echo "
";
                echo "Calidad.	";
                echo "" . $i['calidad_prod'] . "	";
                echo "
";
                echo "
";
                echo "Generalidades.	";
                echo "" . $i['generalidades_prod'] . "	";
                echo "
";
                echo "
";
                echo "Requisitos generales.	";
                echo "" . $i['re_generales_prod'] . "	";
                echo "
";
                echo "
";
                echo "Requisitos específicos.	";
                echo "" . $i['re_espe_prod'] . "	";
                echo "
";
                echo "
";
                echo "Empaque y rotulado.	";
                echo "" . $i['empaque_prod'] . "	";
                echo "
";
                echo "
";
                echo "Presentación.	";
                echo "" . $i['presentacion_prod'] . "	";
                echo "
";
                echo "
";
                echo "Imagen de referencia.	";
                echo "	";
                echo "
";
                echo "
";
        }
    }elseif(isset($vp['doc_fun'])){

    }
}

¿Alguién sabe cómo hago para que me haga una correcta recepción de datos?
--
-- Estructura de tabla para la tabla `instructores`
--

CREATE TABLE `instructores` (
  `doc_in` bigint(10) NOT NULL,
  `nombres_in` varchar(255) NOT NULL,
  `apellidos_in` varchar(255) NOT NULL,
  `contrasena_in` varchar(255) NOT NULL,
  `id_prog` bigint(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `instructores`
--

INSERT INTO `instructores` (`doc_in`, `nombres_in`, `apellidos_in`, `contrasena_in`, `id_prog`) VALUES
(0, '', '', 'siga', 0),
(123456, 'Instructor', 'Prueba', 'siga', 1);

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `pedidos`
--

CREATE TABLE `pedidos` (
  `id_pedido` int(11) NOT NULL,
  `fecha_pedido` date NOT NULL,
  `estado_pedido` varchar(255) NOT NULL,
  `presentacion_producto` varchar(255) NOT NULL,
  `doc_in` bigint(10) DEFAULT NULL,
  `doc_fun` bigint(10) DEFAULT NULL,
  `cod_prod` bigint(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `pedidos`
--

INSERT INTO `pedidos` (`id_pedido`, `fecha_pedido`, `estado_pedido`, `presentacion_producto`, `doc_in`, `doc_fun`, `cod_prod`) VALUES
(1, '2019-03-12', 'Sin observar', '1000 CC', 123456, NULL, 1),
(2, '2019-03-12', 'Sin Observar', 'Frasco de 1000 CC', 123456, NULL, 3),
(3, '2019-03-05', 'Sin Observar', '1000 CC', 123456, NULL, 5);

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `productos`
--

CREATE TABLE `productos` (
  `cod_prod` bigint(100) NOT NULL,
  `sibol_prod` longtext NOT NULL,
  `nombre_prod` longtext NOT NULL,
  `categoria_prod` longtext NOT NULL,
  `sub_categoria_prod` longtext NOT NULL,
  `calidad_prod` longtext NOT NULL,
  `generalidades_prod` longtext NOT NULL,
  `re_generales_prod` longtext NOT NULL,
  `re_espe_prod` longtext NOT NULL,
  `empaque_prod` longtext NOT NULL,
  `presentacion_prod` longtext NOT NULL,
  `imagen_prod` longtext NOT NULL,
  `id_prog` bigint(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `productos`
--

INSERT INTO `productos` (`cod_prod`, `sibol_prod`, `nombre_prod`, `categoria_prod`, `sub_categoria_prod`, `calidad_prod`, `generalidades_prod`, `re_generales_prod`, `re_espe_prod`, `empaque_prod`, `presentacion_prod`, `imagen_prod`, `id_prog`) VALUES
(1, 'Aceite Crudo de Oliva', 'Aceite de oliva', 'Ingredientes', 'Aceites', 'NTC 258', 'Aceite crudo de oliva, obtenido únicamente del fruto del olivo (olea europaea l.), obtenidos por procedimientos mecánicos de extracción o por otros medios físicos, en condiciones especiales de temperatura que no alteran su composición y separados de los residuos de materia prima e impurezas y que no han sido sometido a ningún proceso químico o físico diferente a los mencionados. Los aceites crudos de oliva, obtenidos por presión en frío o primer prensado, son aptos para el consumo humano directo, previa depuración.', 'El aceite de oliva debe tener un aspecto limpio a 25 o c, tener sabor y olor característico y estar libre de rancidez. No deben contener sustancias extrañas. No presentar mezcla con otros aceites y grasas.', 'El producto debe contener: Acidez libre (% ácido oléico), 1% Máximo índice de Yodo 94, Máximo índice de Bellier 17, Máximo índice de saponificación 196 Máximo. El aceite crudo de oliva debe cumplir con los requisitos fisicoquímicos y perfil de ácidos grasos establecidos en la NTC 258. Los residuos de plaguicidas no de beben exceder los límites máximos establecidos en la Resolución 2906 de 2007, el Ministerio de la Protección Social.', 'El producto se empacará en recipientes impermeables, suficientemente inertes al producto que aseguren su conservación. Los envases utilizados deben ser de primer uso. El rotulado debe cumplir con los requisitos establecidos en la Resolución 5109 de 2005 del Ministerio de Protección Social.', 'FRASCO * 1000 CC', 'null', 1),
 (3, 'Aceitunas de Mesa', 'Aceitunas', 'Ingredientes', 'Frutas', 'Cumplir con los requisitos establecidos en: Norma Técnica Colombiana NTC 4842 – Aceitunas de mesa Norma Técnica Colombiana NTC 5121 – Industrias Alimentarias. Rotulado o etiquetado. Parte 1. Norma General. Norma Técnica Colombiana NTC 5122 – Industrias Alimentarias. Rotulado o etiquetado. Parte 1. Rotulado nutricional de alimentos envasado', 'La aceituna es el fruto del olivo. El fruto es una drupa comestible, de tamaño variable, con una sola semilla, hueso o corazón en su interior. El fruto del olivo puede cortarse en cualquiera de sus etapas, las aceitunas verdes son cortadas cuando el fruto no ha madurado y las aceitunas negras son cortadas cuando están maduras. Conforme el fruto del olivo madura, se vuelve de verde a rojo, a purpura, volviéndose finalmente negro.', 'Las aceitunas pueden adquirirse en las siguientes presentaciones: Enteras, deshuesadas, rellenas (con pimiento, cebolla, atún, anchoa, salmón, etc), saladas (cortadas en lonjas o gajos) Las aceitunas generalmente provienen de las variedades: Manzanilla Sevillana, Manzanilla Cacereña, Hojiblanca, Aloreña, Gordal Sevillana, Verdial, Lechin y Picual. Las aceitunas podrán estar en un medio de cobertura liquido como salmuera, vinagre o aceite.', 'La aceituna de mesa deberá cumplir con la totalidad de los requisitos establecidos en la NTC4842', 'El producto se deberá empacar en envases o empaques de material inocuo que asegure su conservación o higiene durante su almacenamiento, transporte, expendio y uso. El rotulado deberá cumplir en su totalidad con lo establecido en las NTC5121 y NTC 5122', 'FRASCO * 450 GRAMOS ENCURTIDAS', 'null', 1),
(5, 'Vegetales Encurtidos', 'Alcaparras en Conserva', 'Ingredientes', 'Vegetales', 'NTC 4107. Resolución 14712 del Ministerio de Salud.', 'Producto obtenido a partir de una o varias frutas, hortalizas o verduras enteras, en trozos o molidos, previamente curadas en salmuera o que hayan sufrido o no una transformación láctica, conservadas en un medio de cobertura adecuado. Los vegetales sanos y limpios cortados o enteros son envasados herméticamente en un medio de cobertura apropiado (solución a base de sal o ácido acético o vinagre de origen vínico) y sometidos a tratamientos físicos permitidos que garanticen su conservación. En el proceso de conserva los vegetales son sumergidos (marinados) en una solución de Sal, que fermenta por si solo o con la ayuda de un inoculo (microorganismo como Lactobacillusplantarum), el cual baja el pH y aumenta la acidez del mismo, con el objeto de poder extender su conservación. La característica que permite la conservación es el medio ácido del vinagre que posee un pH menor que 4.6 y es suficiente para eliminar la mayor parte de las necrobacterias. El este proceso permite conservar los alimentos durante dos meses en promedio. Se suele añadir a la marinada hierbas y sustancias antimicrobianas.', 'La alcaparra (Capparisspinosa) son los frutos (Alcaparrones) y las yemas o capullos florales que no se han abierto (Alcaparras) comestibles. En el proceso de conserva las alcaparras son sumergidas en una solución de sal, que fermenta por si solo o con la ayuda de un inoculo, el cual baja el pH y aumenta la acidez del mismo, con el objeto de poder extender su conservación. La característica que permite la conservación es el medio ácido del vinagre que posee un pH menor que 4.6 y es suficiente para eliminar la mayor parte de las necrobacterias. Conserva en salmuera.', 'Por 100 gramos de alcaparras en conserva: Calorías: 23 kilocal, Grasas monoins 0,1 gr., Proteínas: 2,4 gr., Grasas poliinsat.: 0,3 gr., Colesterol: 0,0, Mg Calcio: 40 Mg., Grasas sats: 0,2 gr., Magnesio: 33 Mg., Fósforo: 10 Mg., Vitamina C: 4,3 Mg., Potasio: 40 Mg., Vitamina E: 0,9 Mg., Sodio: 2964, Mg., Vitamina A: 139 IU.', 'En envase de vidrio que conserve las características organolépticas del producto. Rotulado con el nombre del producto, nombre del productor o empacador (marca comercial), fecha de empaque, fecha de vencimiento, lote de producción, peso neto El producto en su rótulo debe cumplir con lo establecido en la Resolución 5109 de 2005 del ministerio de la Protección Social.', 'FRASCO * 200 GRAMOS ENCURTIDAS', 'null', 1);

Lo que necesito que me muestre en el PDF, es justo lo que aparece dentro del primer  que son las fechas.


text:
Q: Query JSON String using Jackson API with good performance I am working on a use case where I need to parse different JSON strings and query for specific fields basing on the "type" of the JSON. The "type" is a field in the JSON string.
I am using Jackson API to perform this task after going through the blogs and benchmarks, as it is the fastest.
I am able to parse the JSON and achieve what I want but the issue is with the performance.
public String generate(String inputJson, List<String> idParams,final String seperator) throws Exception {
        JsonNode node;
        StringBuilder sb = new StringBuilder();
        try {
            node = new ObjectMapper().readTree(new StringReader(inputJson));
            idParams.forEach(e -> {
                String value = node.findValue(e).asText();
                sb.append(value).append(seperator);
            });
        } catch (Exception e) {
            throw e;
        }

        return sb.toString();
    }

In the above method, I am getting the field details as a List. With the help of forEach(), i am able to fetch the values by finding using the fields.
The culprit is the list iterator as I have to search the whole json tree to find the value for each element. Is there a better approach to optimize. I would also like to get the inputs on other JSON parsing libraries which can improve the performance here.
I am also thinking of parsing the whole json once and writing the Keys and Values to a HashMap. But, I have very few fields which i really care about the remaining fields are not needed.

A: take a look at JsonPath . It offers xpath-like rich query language that allows for search and retrieval of individual or few elements from the JSON tree.

A: Consider using Jackson Streaming API -
https://github.com/FasterXML/jackson-docs/wiki/JacksonStreamingApi
Take a look at this example -
http://www.baeldung.com/jackson-streaming-api


text:
Q: change socket address mariadb_config I can't understand what follows, can someone explain me and help me solve the problem?
I have a mariadb-server a front-end application in C.
I have 2 make files and i'd like that i can use both of them.
The first one is this
all:
    gcc -g src/*.c -o applicazione `mysql_config --cflags --include --libs`
clean:
    -rm applicazione

and it works. If i compile with this, my application runs without any trouble.
The second one is this
all:
    gcc -g src/*.c -o applicazione `mariadb_config --cflags --include --libs`
clean:
    -rm applicazione

The difference is that in the first I used mysql_config, while in the second I used mariadb_config.
My problem is that with the second makefile, (after some problems) I can successfully compile, but as soon as I try to connect to the server I get this error
fabiano@fabiano-HP-15-Notebook-PC:~/Scrivania/BackupProgetto/0226198$   ./applicazione
Inserisci Matricola: g1
Inserisci Password: *
Connection error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Reading on the net i understand that the problem is that the socket is not where my application try to find it.
Indeed if i execute sudo mariadb and after that \system i can read this
UNIX socket:        /var/run/mysqld/mysqld.sock

Now my questions:

*

*why my application run successfully with the first make file but it doesn't with the second one ?

*what can i do for let my application works with both make files ?

My OS is Ubuntu 18.04.3 LTS.

A: If you compare output from mysql_config --libs with output from mariadb_config --libs you will probably notice that different libraries from different locations will be used.
mariadb_config is part of MariaDB Connector/C, the default build uses /tmp/mysql.sock for the socket file:
IF(NOT MARIADB_UNIX_ADDR)
  SET(MARIADB_UNIX_ADDR "/tmp/mysql.sock")
ENDIF()

The libraries from mysql_config output were compiled with default socket located at /var/run/mysqld while the libraries from mariadb_config where compiled with socket located in the tmp directory.
There are several options to fix that:
1) Change the socket in your my.cnf file. This needs to be done in [mysqld] section, but also in [mysql] section to make sure that the client tools will work properly.
2) Set the environment variable MYSQL_UNIX_PORT to /var/run/mysqld/mysql.sock before running your application
3) If you build MariaDB Connector/C on your own:
cd mariadb-connector-c
mkdir bld
cd bld
cmake .. -DMARIADB_UNIX_ADDR=/var/run/mysqld/mysql.sock
cmake --build .

4) Before connecting you can specify the location of the socket in your application:
mysql= nysql_init(NULL);
rc= mysql_options(mysql, MARIADB_OPT_UNIXSOCKET, "/var/run/mysqld/mysql.sock");


text:
Q: R - Verifying That A Column Only Has Certain Values I am trying to figure out how to verify that that columns of a spreadsheet only contain a predetermined set of values.  Any thoughts on the best way to do this?
To provide an example, I am using the following method to determine that the number of columns is correct.
if(!ncol(data_read) == 9){
    print("There are not 9 columns in this file")
    return(FALSE)
} else if{
  OTHER PARAMETERS HERE (such as the one I'm trying to figure out)
  }

   return(TRUE}
 }

A: valid_values <- c(1, 2, 3)
df <- data.frame(a = c(2, 3, 2), b = c(2, 3, 4))

all(df$a %in% valid_values)
[1] TRUE
all(df$b %in% valid_values)
[1] FALSE


text:
Q: Configurar margens e tamanho do papel com PrintDocument Preciso fazer a impressão de etiquetas e estou usando o PrintDocument, só que tem um problema eu não sei como eu crio a página para a impressão.
Ex. minha etiqueta tem 4cm de altura e 10cm de largura com margens de 0,2cm. Como posso configurar essas
private void btnImprimir_Click(object sender, EventArgs e)
    {
       for (int i = 0; i < iQuantidadeVolumes; i++)
        {
            var volumeUnico = (i + 1).ToString();

            for (int ii = 0; ii < ListaConteudoImpressao.Count; ii++)
            {
                if (ListaConteudoImpressao[ii].Contains("VOLUME : "))
                {
                    ListaConteudoImpressao[ii] = sTextoNF +  "VOLUME : " + volumeUnico + "/" + iQuantidadeVolumes.ToString();
                    Documento.PrinterSettings.PrinterName = sNomeImpressora;
                    Documento.DefaultPageSettings.Landscape = true;
                    Documento.Print();

                }
            }
        }
    }

    private void Documeto_PrintPage(object sender, PrintPageEventArgs e)
    {
        string texto = "";
        Font letra = new Font("Aerial", 23, FontStyle.Bold, GraphicsUnit.Pixel);
        SolidBrush cor = new SolidBrush(Color.Black);
        Rectangle retangulo = new Rectangle(0, 100, largura, 30);
        StringFormat alinhamento = new StringFormat();
        alinhamento.Alignment = StringAlignment.Center;
        alinhamento.LineAlignment = StringAlignment.Center;
        e.Graphics.DrawString(texto.ToUpper(), letra, cor, retangulo, alinhamento);

        int y = 170;
        foreach (string frase in ListaConteudoImpressao)
        {
            e.Graphics.DrawString(frase, letra, cor, new Point(20, y));
            y += 40;
        }

    }
  }
}

A: Pode fazê-lo da seguinte forma:
private void btnImprimir_Click(object sender, EventArgs e)
{
    // ...

    Documento.DefaultPageSettings.Landscape = true;

    // Para configurar as margens
    int margemIn = CentimetrosParaCentesimasPolegada(0.2); // https://msdn.microsoft.com/pt-br/library/system.drawing.printing.pagesettings.margins(v=vs.110).aspx
    Documento.DefaultPageSettings.Margins = new Margins(margemIn, margemIn, margemIn, margemIn);

    // Para configurar o tamanho do papel a ser usado
    int larguraIn = CentimetrosParaCentesimasPolegada(10);
    int alturaIn = CentimetrosParaCentesimasPolegada(4);
    PaperSize paperSize = new PaperSize("MeuTipo", larguraIn, alturaIn);
    Documento.DefaultPageSettings.PaperSize = paperSize;
    Documento.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;

    // ...
}

Note que as medidas usadas pelo PrintDocument são centésimas de polegadas, por isso e necessário um método que converta os seus valores em centímetros:
private static int CentimetrosParaCentesimasPolegada(double cm)
{
    return (int) Math.Round(cm / 0.393701 * 100, MidpointRounding.AwayFromZero);
}


text:
Q: shr raid drives with crashed nas OS (synology) I have two disks which I used as SHR (synology hybrid raid) in synology NAS. After an update the OS crashed without ability to use reset option. apparently this is known as white screen of death.
I'm looking for a way to access the data to transfer it to a back-up disk. Unfortunately I have no back-up now.
Synology posted a solution to mount the disks on a PC under Ubuntu.
I followed all the steps, except the "postfix configuration - no configuration" option as it did not appear during installation.
I have the following disk info when plugged in via USB (have no desktop available so USB is my only option for now)
Both disks are visible under gparted (sdb and sdc)
Both disks are symmetrical, so info below for sdb counts also for sdc
partitioning:

*

*/dev/sdb1 (2,37 GiB)

*/dev/sdb2 (2,00 GiB)
127,12 MB unallocated

*Extended partition: /dev/sdb3 (927,01 GiB)
7,80 MB Unallocated

*/dev/sdb5 926,91 GiB)
94,12 MB unallocated
6,91 unallocated

sdb 1,2,3, and 5 are all linux raid as file configuration
Extended partition is LBA
There is no sdb 4
sdb5 has mount point /dev/md2
When I ran mdadm -Asf && vgchange -ay the disks responded physically both at the same time (as expected when both disk should mount)
After inspection gparted showed a extra disk /dev/md2 with only one 926,91 GiB partion of lvm pv2 files system. Exactly as the drive size under in the synology NAS. So it seems that it all should've worked, but no extra drive under nautilus or in the mnt folder. also a little key with /dev/md2 under gparted and no option to mount (probably as it is already mounted).
Is there another way to excess this (mounted?) md2 partition?
Is the SHR (synology hybrid raid) file system an issue here? It is probably different then common raid. They don't mention anything about this though, not as far as I know.
Hoping for tips or help on how to access the data.
sudo lvs:
  LV     VG        Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  root   ubuntu-vg -wi-ao---- 114,84g
  swap_1 ubuntu-vg -wi-ao----   3,90g
  lv     vg1000    -wi-a----- 926,90g

sudo vgs:
LV     VG        Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  root   ubuntu-vg -wi-ao---- 114,84g
  swap_1 ubuntu-vg -wi-ao----   3,90g
  lv     vg1000    -wi-a----- 926,90g

sudo pvs:
  LV     VG        Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  root   ubuntu-vg -wi-ao---- 114,84g
  swap_1 ubuntu-vg -wi-ao----   3,90g
  lv     vg1000    -wi-a----- 926,90g

sudo pvdisplay:
  --- Physical volume ---
  PV Name               /dev/md2
  VG Name               vg1000
  PV Size               926,91 GiB / not usable 3,81 MiB
  Allocatable           yes (but full)
  PE Size               4,00 MiB
  Total PE              237287
  Free PE               0
  Allocated PE          237287
  PV UUID               BgEiR6-dOhF-POyb-0nVE-GMc1-WW8c-QxWXpc

  --- Physical volume ---
  PV Name               /dev/mapper/sda5_crypt
  VG Name               ubuntu-vg
  PV Size               118,76 GiB / not usable 0
  Allocatable           yes
  PE Size               4,00 MiB
  Total PE              30403
  Free PE               5
  Allocated PE          30398
  PV UUID               hQ16w8-eBos-edQ5-sF1s-CV0q-UB2x-nIIHKf

sudo lvdisplay
  --- Logical volume ---
  LV Path                /dev/vg1000/lv
  LV Name                lv
  VG Name                vg1000
  LV UUID                G40w9j-sqL1-6e7e-1i9g-PcPA-7mo6-9W69Mr
  LV Write Access        read/write
  LV Creation host, time ,
  LV Status              available
  # open                 0
  LV Size                926,90 GiB
  Current LE             237287
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:4

  --- Logical volume ---
  LV Path                /dev/ubuntu-vg/root
  LV Name                root
  VG Name                ubuntu-vg
  LV UUID                iODJJk-iDeM-5eiy-mGGK-Z2Wj-aJsJ-b9nPNL
  LV Write Access        read/write
  LV Creation host, time ubuntu, 2017-02-03 22:35:31 +0100
  LV Status              available
  # open                 1
  LV Size                114,84 GiB
  Current LE             29400
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:1

  --- Logical volume ---
  LV Path                /dev/ubuntu-vg/swap_1
  LV Name                swap_1
  VG Name                ubuntu-vg
  LV UUID                xHrGFf-GHaB-W4jc-VYJm-e3WT-gkhF-lXigfM
  LV Write Access        read/write
  LV Creation host, time ubuntu, 2017-02-03 22:35:31 +0100
  LV Status              available
  # open                 1
  LV Size                3,90 GiB
  Current LE             998
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:2

sudo vgdisplay:
  --- Volume group ---
  VG Name               vg1000
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  2
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                1
  Open LV               0
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               926,90 GiB
  PE Size               4,00 MiB
  Total PE              237287
  Alloc PE / Size       237287 / 926,90 GiB
  Free  PE / Size       0 / 0
  VG UUID               owLxtE-2AEt-yTQX-VyGf-gdkz-u5E8-afGETg

  --- Volume group ---
  VG Name               ubuntu-vg
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               118,76 GiB
  PE Size               4,00 MiB
  Total PE              30403
  Alloc PE / Size       30398 / 118,74 GiB
  Free  PE / Size       5 / 20,00 MiB
  VG UUID               xUCkb6-bk95-bacK-HlIc-IAIv-6rC5-43ymwu

Hope this is a bit informative

A: steeldrivers suggestion worked perfectly!
sudo mount /dev/mapper/vg1000-lv /mnt

still unmounting never got fixed, but got it all copied over the network and disks were formatted so, that got that solved.

A: I am not an expert on LVM or mdadm but here's what I did to solve a related problem on Ubuntu 18.
A single hard drive SHR attached trough USB-SATA adapter. The system tries to automatically set the RAID volume, but something goes wrong:
If I try to assemble:
mdadm -Asf && vgchange -ay

mdadm: Found some drive for an array that is already active: /dev/md/DiskStation:2
mdadm: giving up.
mdadm: No arrays found in config file or automatically

or mount:
mount /dev/mapper/vg1000-lv /mnt/
mount: /mnt: can't read superblock on /dev/mapper/vg1000-lv.

I have checked and the system already mapped a /dev/mdXXX to the SHR drive. So:
dmsetup remove /dev/mapper/vg1000-lv

mdadm --stop /dev/mdXXX

And after it's possible to retry to assemble with mdadm:
mdadm -Asf && vgchange -ay

The mount reference is under /media/xxxxx/volumeToMount


text:
Q: Parsing a list nested within a dictionary for words with similar characters in Python As my first personal project I am building a Wordle "solver" that comes up with a first guess word then takes an input of the letters that were correct in the word then searches the word list for words with similar characters. To do this I stored each word in a dictionary with the key being the word and the value being each character in the word i.e dodge: [d, o, d, g, e]. I am currently experimenting to get code running that parses through the values of the dictionary to match the characters to the inputted letters but am stumped on how to search through the lists within the dictionary as a loop.
Here's my code for inputting the correct letters:
correct_letters_1 = list(letters for letters in input("Input corrects letters: ").strip().split())
Here's one of my attempts at parsing the dictionary:
for letters in correct_letters_1:
    if letters in word_dictionary.values():
       print("yes")

I'm pretty sure this problem has something to do with my code parsing the entire lists within the dictionary rather than each individual character but even when I try inputting the whole word, i.e Input Correct Letters: d o d g e; I still don't have any output.
If someone could put a beginner on the right track it would be much appreciated.

A: You might be looking to compare the whole list, rather than the letters:
correct_letters_1 = list(input("Enter correct letters: ").strip())

# correct_letters_1 is a whole list
if correct_letters_1 in word_dictionary.values():
    print("yes")

# Inputting "abc"
>>> correct_letters_1
['a', 'b', 'c']
>>> word_dictionary
{'abc': ['a', 'b', 'c']}
>>> correct_letters_1 in word_dictionary.values()
True

To check if the user's guess is a subset of any of the words:
correct_letters_1 = list(input("Enter correct letters: ").strip())
let_set = set(correct_letters_1)

word_dictionary = {'abc': ['a', 'b', 'c'],
                   'abcde': ['a', 'b', 'c', 'd', 'e'],
                   'ab': ['a', 'b'],
                   'test': ['t', 'e', 's', 't']}

# Check to see if correct_letters_1 is a subset of any word in the dictionary
close_words = ["".join(x) for x in word_dictionary.values() if let_set <= set(x)]

Which can be simplified to:
correct_letters_1 = input("Enter correct letters: ").strip()
let_set = set(correct_letters_1)

words = ["abc", "test", "ab"]

# Check to see if correct_letters_1 is a subset of any word in the list words
close_words = [x for x in words if let_set <= set(x)]


text:
Q: How to create function with input is 2D array in C++ I have a 2D array that defined as
int P[5][10];
for (int i=0;i<N;i++)
{
    for(int j=0;j<L;j++)
    {
        if(random()>0.5)
            P[i][j]=1;
        else
            P[i][j]=0;
    }
}

I want to make a function with input is P. The function allows us show the value of P. How to defined that function. I tried such as
void show_P(int P[][], int numcols,int numrows)

However, it is wrong. Could you help me fix it? Thanks

A: If you want to restrict the arguments to 5 by 10 2D arrays, you can pass by reference like this:
void show_P(int (&P)[5][10])

This will fail for any other type of array. If you want the function to work for other sizes, you can make it a template.
template <size_t N, size_t M>
void show_P(int (&P)[N][M])

A: You could just change it to:
void show_P(int** P, int numcols, int numrows)

Passing 2D array always using the pointer.
Hope this will help.

A: Or using the std::array
void printArray(array<array<int,2>,3>& arr)
{
  for (auto x : arr)
  {
    for (auto y : x)
    {
      cout << y << endl;
    }
  }
}

int main()
{
  array<array<int,2>,3> arr{{{1, 2}, {2, 3}, {3, 4}}};
  arr[0][1] = 5;
  printArray(arr);
}

would give you:
1
5
2
3
3
4

A: void print( int (&ref)[5][10]) {

for( auto &lm: ref) // get the first array from the multidimensional array and initialize lm with it
    for( auto &elem: lm) // get the first element from lm
        std::cout << elem << " "; // print the element

}

This only works with an array with dimensions as P i.e,   [5][10]

A: N=5;
L=10;
void show_P( int ( &P )[N][L] )


text:
Q: Find a string in a string - Python I am trying to implement a function that find a text in a string recursively.
I tried this, but I don't know why it's not working. Please note that I am new to coding.
def find(text, substring):
  if len(text) == 0:
     return 0
  while substring[0] in text:
     return find(text, substring[1:])

Thanks! :)
Example:
find("mississippi", "sip")
True
find("to be or not to be", "be")
True
find("mississippi", "sup")
False

A: There are much simpler ways to do this. For example, you can loop over the indices of the string and check if the substring is at that location, as mentioned here:
[i for i in range(len(string)) if s.startswith(substr,i)]

This will evaluate to a list of indices of all of the occurrences of substr in string.

A: You need a base case for your recursive function that will eventually return without recursing. Your base case len(text)==0 is never executed unless text=='' the first time through.

A: If I understand your question correctly, you want to implement a recursive function where find(text, substring), given two strings, returns the same result as the simple Python expression substring in text.  A recursive breakdown of this problem would be:

*

*Does text begin with substring? If so, return True. (Base case 1)

*Is text empty?  If so, return False. (Base case 2).

*Otherwise, return the result of find(text[1:], substring) – the recursive case where we call the same function on a smaller problem.

See if you can implement that!  For base case one, you'll have good use of Python's String method startswith (google it!).


text:
Q: Continuity of f Is the statement below true.If it is could someone provide a proof of this.If its not provide a counter example
$ f(x)$ is continuous at $x_0$
$\implies  \exists \delta>0:$
(if   $|x-x_0|<\delta \implies  f(x) $  is continuous).

A: Outline: This is not true. Let $f(x)=x$ if $x$ is irrational, and let $f(x)=0$ if $x$ is rational. Show that the only point of continuity of $f$ is at $x=0$.


text:
Q: Undefined method 'merge' for "test":String - Rails 3.1 I have a collection_select:
<%= form_for(@feedback) do |f| %>

<%= f.label :poster_id %>

<%= f.collection_select :feedback, :poster_id, @users, :id, @user.username, :prompt => "Select your username" %>

<%= f.number_field :poster_id %>

<% end %>

This is the error message:
ActionView::Template::Error (undefined method `merge' for "test":String):
    15:
    16:

    17:     <%= f.label :poster_id %>

    18:     <%= f.collection_select :feedback, :poster_id, @users, :id, @user.username %>

    19:     <%= f.number_field :poster_id %>
    20:

    21:

  app/views/feedbacks/_form.html.erb:18:in `block in _app_views_feedbacks__form_html_erb__3181571289116259961_2154876620'
  app/views/feedbacks/_form.html.erb:3:in `_app_views_feedbacks__form_html_erb__3181571289116259961_2154876620'

"test" is the username that was returned by @user.username.
How do I fix that?

A: the signature for collection_select is:
def collection_select method, collection, value_method, text_method, options = {}, html_options = {}

i'm not sure what you're trying to do, maybe this is what you want:
<%= f.collection_select :poster_id, @users, :id, :username, :prompt => "Select your username" %>

A: I had to think of the inputs this way to get it to make sense in my head...
collection_select 'model field', 'collection of options in the dropdown menu', 'model field for values', 'model field to show in the menu'
This helped me understand


text:
Q: Code works for java but doesn't works for Android Below code runs perfectly as java code in eclipse but it does not runs in Android Activity(MainActivity.java) results in application force closed
        try
    {
        Socket s=new Socket("192.168.0.6",9321);
        OutputStream d=s.getOutputStream();
        DataOutputStream dos=new DataOutputStream(d);
        dos.writeUTF("hii");
        s.close();
    }
    catch (IOException e)
    {}

A: My best guess is you're trying to do network communication on the main thread.
You can't do that in Android.
Otherwise, the entire UI would completely freeze whenever you made a network request.
Try finding some examples of using the AsyncTask class to do network requests. That will handle the network request on another thread (so the UI doesn't freeze), and then deliver the response back.


text:
Q: Count elements with int < 5 in List I have a List<int> and need to count how many elements with (value < 5) it has - how do I do this?

A: int count = list.Count(i => i < 5);

A: Count() has an overload accepting Predicate<T>:
int count = list.Count(x => x < 5);

See MSDN

A: List<int> list = ...
int count = list.Where(x => x < 5).Count();

A: Try -
var test = new List<int>();
test.Add(1);
test.Add(6);
var result =  test.Count(i => i < 5);

A: Something like this:
var count = myList.Where(x => x < 5).Count();

A: list.Where(x => x < 5).Count()

A: Unlike other answers, this does it in one method call using this overload of the count extension method:
using System.Linq;

...

var count = list.Count(x => x < 5);

Note that since linq extension methods are defined in the System.Linq namespace you might need to add a using statement, and reference to System.Core if it's not already there (it should be).

See also: Extension methods defined by the Enumerable class.

A: Try this:
int c = myList.Where(x=>x<5).Count();

A: int c = 0;
for (i = 0; i > list.Count; i++)
{
    // The "for" is check all elements that in list.
    if (list[i] < 5)
    {
        c = c + 1; // If the element is smaller than 5
    }
}

A: The shortest option:
myList.Count(v => v < 5);

This would also do:
myList.Where(v => v < 5).Count();


text:
Q: Copy specific range I have one sheet that contains data and I want to copy a specific range if a condition is met.
I have the following code which works fine, but I need to copy only a specific range.
Sub cautare_copiere()

'1. declar si setez variabilele
'2. sterg rezultatele vechi
'3. cauta si lipeste intr-un nou tab

Dim datasheet As Worksheet 'de unde este informatia copiata
Dim raportsheet As Worksheet 'unde este copiata informatia
Dim familie As String
Dim ultimulrand As Integer
Dim i As Integer 'numaram randurile

'setez variable

Set datasheet = Sheet1
Set raportsheet = Sheet2
familie = raportsheet.Range("B2").Value
valoare = raportsheet.Range("D2").Value
cantitate = raportsheet.Range("F2").Value

'sterge datele din tab-ul Raport
raportsheet.Range("A6:L200").ClearContents 'ajustez range-ul de unde sterg datele - daca am informatie multa, il maresc
raportsheet.Range("A6:L200").ClearFormats

'se duce in tab-ul Copy, cauta si copiaza
datasheet.Select
ultimulrand = Cells(Rows.Count, 1).End(xlUp).Row

'cauta printre randuri si selecteaza informatia pe care o cautam

For i = 2 To ultimulrand
        If Cells(i, 5) = familie And Cells(i, 8) <= valoare And Cells(i, 7) <= cantitate Then 'daca numele din coloana E se potriveste, copiaza intregul rand
            Range(Cells(i, 1), Cells(i, 8)).Copy 'copiaza range-ul setat de la 1 la 8 (A la H)
            raportsheet.Select 'selecteaza tab-ul raport
            'Range("A200").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats 'cauta primul rand fara informatii
            Range("A200").End(xlUp).Offset(1, 0).PasteSpecial xlPasteAll 'deseneaza margini
            Range("A6:L200").Sort Key1:=Range("H5"), Order1:=xlAscending
            datasheet.Select 'se intoarce in tab-ul Copy si continua sa cauta informatia
            End If

Next i

raportsheet.Select 'selecteaza tab-ul Raport cand cautarea a fost terminata

Range("B2").Select

End Sub

I need to copy only data from columns 1, 3, 5, 6, 7 and 8 when condition is met.
Thank you!

A: No need to select sheets - you can copy-paste directly between them.
'...
'cauta printre randuri si selecteaza informatia pe care o cautam
With datasheet
    For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
        If .Cells(i, 5) = familie And .Cells(i, 8) <= valoare And _
                                      .Cells(i, 7) <= cantitate Then
            'copy range is *relative to the row*
            .Rows(i).Range("A1,C1,E1:H1").Copy _
                    raportsheet.Range("A200").End(xlUp).Offset(1, 0)

        End If
    Next i
End With

With raportsheet
    .Range("A6:L200").Sort Key1:=.Range("H5"), Order1:=xlAscending
    .Select
    .Range("B2").Select
End With


text:
Q: Customize meta info based on the query string values My website sells stuff and I would like to customize the page title and meta description in certain pages when certain items are viewed. I would want these custom titles and descripts to be listed when shared on other websites. E.g.: Twitter, FB, etc...
Basically I want to customize the title and description based on the query string values. How is this possible? I've looked a js based plugin or similar on github as well but had no luck.

A: The issue with JavaScript rendered pages is that there's no guarantee a scraper will pick up the meta tags. The headers are read before scripts are run - meaning to lower overhead they likely won't even bother executing it. Better if you write a script that writes customised meta tags to the HTML file.


text:
Q: select even column is null oracle the command below is my sql select command;
sqlcommand = "SELECT * FROM INVENTORY WHERE LOWER(SAPNO) LIKE LOWER('" + sapNo + "%') AND LOWER(PARTDESC) LIKE LOWER('" + partDesc + "%') AND LOWER(PARTNO) LIKE LOWER('" + partNo + "%') AND MINQTY = '" + minQty + "' AND QOH = '" + QOH + "' AND LOWER(CATEGORY) LIKE LOWER('" + category + "%') AND LOWER(EQUIPMENT) LIKE LOWER('" + equipment + "%')";

example like category and equipment is confirm null. and the rest have the value. How can I select the row even though category and equipment is null?? because I using this comment whenever equipment and category is null, the data wont be shown!
your comment is much appreciated!!
TQ

A: You can add some OR conditions in order to return rows that can have specific values null.
AND (LOWER(CATEGORY) LIKE LOWER('" + category + "%') OR CATEGORY IS NULL) AND (LOWER(EQUIPMENT) LIKE LOWER('" + equipment + "%') OR EQUIPMENT IS NULL)


text:
Q: How do I plot time series data by week and year? I have a simple time series dataframe('cats'). Transactions by year and week. I just want a line chart with the year and week in the axis.
    year    week    transactions
0   2013    25      1824
1   2013    26      1876392
2   2013    27      2048913
3   2013    28      2060043
4   2013    29      1864779
5   2013    30      1844886
6   2013    31      2089084
7   2013    32      2017478
8   2013    33      1927819
9   2013    34      1965046

I can get the line to work here doing this, but it only plots vs the index
plt.plot(cats['total_sales'])

But when I try to add an axis something like this happens
plt.plot(cats['year'],cats['total_sales'])

A: You could create a column of proper datetimes from your year and week number:
# %U assumes Monday as first day of the week. Use %W for Sunday
cats['week_yr'] = pd.to_datetime(cats['year'].astype(str) + ' ' + cats['week'].astype(str) + ' 1',
                                format='%Y %U %w')

Then you can do:
cats.plot.line(x='week_yr', y='transactions')

And get:

A: use plt.xticks
x = range(len(cats['total_sales']))
plt.plot(x, cats['total_sales'])
plt.xticks(x, zip(cats['year'], cats['week']))


text:
Q: Existence of function with zero positive and negative-integer moments I am trying to find the existence of a continuous function defined on $(0,\infty)$ such that
\begin{align*}
\int_0^\infty x^n f(x)\ dx = \begin{cases} 1, &\mbox{ $n = 0$, }\\ 0, &\mbox { $n \neq 0$, } \end{cases}
\end{align*}
where $n \in \mathbf{Z}$.
If restricted only for $n \ge 0$, Stieltjes gave an example of such a function with zero moments. Let
\begin{align*}
f(x) = \exp\left(-x^{\frac{1}{4}}\right)\sin\left(x^{\frac{1}{4}}\right)\mathbf{1}_{(0,\infty)}(x)
\end{align*}
and we can show that
\begin{align*}
\int_0^\infty x^n f(x)\ dx = 0
\end{align*}
for all $n \ge 0$. I think I can modify this function slightly such that when $n = 0$ the integral is not zero.
However, if we extend $n$ to take negative values, I see no way out. I am not aware of an existing example. Any idea would be appreciated.


text:
Q: Mapbox how to dissolve cluster on click of it I am using Mapbox sdk in my project. https://www.mapbox.com/mapbox-ios-sdk/
I have got the basic clustering working but my question is how to i dissolve a cluster further on click of it.
eg. I have a cluster with 8 markers. On click it should further zoom in, not just one level but to a point where all 8 markers are on screen with maximum zoom possible.(some markers out of these 8 can be clustered)
I tried
[mapView zoomWithLatitudeLongitudeBoundsSouthWest: CLLocationCoordinate2DMake(south, west)
                                                northEast: CLLocationCoordinate2DMake(north, east) animated:YES];
but no success.

A: This is how ended up doing it:
- (void)tapOnAnnotation:(RMAnnotation *)annotation onMap:(RMMapView *)map {

    if (annotation.isClusterAnnotation) {

        CLLocationCoordinate2D southwestCoordinate = annotation.coordinate;
        CLLocationCoordinate2D northeastCoordinate = annotation.coordinate;

        for (RMAnnotation *plot in annotation.clusteredAnnotations) {

            CGFloat latititude = plot.coordinate.latitude;
            CGFloat longitude = plot.coordinate.longitude;

            if (southwestCoordinate.latitude > fabsf(latititude)) southwestCoordinate.latitude = latititude;
            if (southwestCoordinate.longitude > fabsf(longitude)) southwestCoordinate.longitude = longitude;

            if (northeastCoordinate.latitude < fabsf(latititude)) northeastCoordinate.latitude = latititude;
            if (northeastCoordinate.longitude < fabsf(longitude)) northeastCoordinate.longitude = longitude;

        }

        [self.mapView zoomWithLatitudeLongitudeBoundsSouthWest:southwestCoordinate northEast:northeastCoordinate animated:YES];

   }
}

Basically, what's happening here is that I'm storing the outermost region's bounding coordinates southwestCoordinate and northeastCoordinate to the tapped annotation (in this case, the cluster). Then, for each annotation within the cluster, we're checking to see if it's absolute distance from that "center" coordinate is the greatest in the group.
Seems to work pretty well for me.

A: The following snippet will do a better job of zooming in on your cluster points, expanding to a level where some or all points are unclustered:
    // 1. Start with a maximum (world-wide) bounding box
    CLLocationCoordinate2D topRight = CLLocationCoordinate2DMake(180, -90);
    CLLocationCoordinate2D bottomLeft = CLLocationCoordinate2DMake(-180, 90);

    // 2. Derive the minimum bounding box coordinates that contains all cluster points, by "squeezing in" on their coordinates
    for (RMAnnotation *a in annotation.clusteredAnnotations) {

        if (a.coordinate.latitude < topRight.latitude) {
            topRight.latitude = a.coordinate.latitude;
        }
        if (a.coordinate.longitude > topRight.longitude) {
            topRight.longitude = a.coordinate.longitude;
        }

        if (a.coordinate.latitude > bottomLeft.latitude) {
            bottomLeft.latitude = a.coordinate.latitude;
        }
        if (a.coordinate.longitude < bottomLeft.longitude) {
            bottomLeft.longitude = a.coordinate.longitude;
        }
    }

    CLLocation *sw = [[CLLocation alloc] initWithLatitude:topRight.latitude longitude:topRight.longitude];
    CLLocation *ne = [[CLLocation alloc] initWithLatitude:bottomLeft.latitude longitude:bottomLeft.longitude];

    // 3. Calculate the distance in meters across the calculated bounding box
    CLLocationDistance distanceInMeters = [ne distanceFromLocation:sw];
    // 4. Adjust the map view's meters per pixel setting so that the bounding box fits nicely within the map views bounds (which is equivalent to zooming)
    [self.mapView setMetersPerPixel:(distanceInMeters / (self.mapView.frame.size.width * 0.7)) animated:YES];
    // 5. Center on the midpoint of the bounding box
    [self.mapView setCenterCoordinate:[self midPointBetween:topRight and:bottomLeft] animated:YES];

A: GoogleMaps
Used: https://github.com/googlemaps/google-maps-ios-utils for clustering
"Uncluster cluster" :D
Swift 3
if let cluster = marker.userData as? GMUCluster {
let boxConstant = 0.01
    var southwestCoordinate = cluster.position
    var northeastCoordinate = cluster.position

    for clusterItem in cluster.items {

      let latitude = clusterItem.position.latitude
      let longitude = clusterItem.position.longitude

      if southwestCoordinate.latitude > latitude {
        southwestCoordinate.latitude = latitude
      }
      if southwestCoordinate.longitude > longitude {
        southwestCoordinate.longitude = longitude
      }
      if northeastCoordinate.latitude < latitude {
        northeastCoordinate.latitude = latitude
      }
      if northeastCoordinate.longitude < longitude {
        northeastCoordinate.longitude = longitude
      }

    }

    // Create Box
    southwestCoordinate.longitude += boxConstant
    southwestCoordinate.latitude -= boxConstant
    northeastCoordinate.longitude -= boxConstant
    northeastCoordinate.latitude += boxConstant
    let bounds = GMSCoordinateBounds(coordinate: southwestCoordinate, coordinate: northeastCoordinate)
    self.mapView.moveCamera(GMSCameraUpdate.fit(bounds))
}

A: i would add this as a comment of the metatheoric answer but i have not enough rep.
I think that with that fasbf it makes a bad calculation for negative coordinates and it works better without it. Am i right?
- (void)tapOnAnnotation:(RMAnnotation *)annotation onMap:(RMMapView *)map {
    if (annotation.isClusterAnnotation) {

        CLLocationCoordinate2D southwestCoordinate = annotation.coordinate;
        CLLocationCoordinate2D northeastCoordinate = annotation.coordinate;

        for (RMAnnotation *plot in annotation.clusteredAnnotations) {

            CGFloat latitude = plot.coordinate.latitude;
            CGFloat longitude = plot.coordinate.longitude;

            if (southwestCoordinate.latitude > latitude) southwestCoordinate.latitude = latitude;
            if (southwestCoordinate.longitude > longitude) southwestCoordinate.longitude = longitude;

            if (northeastCoordinate.latitude < latitude) northeastCoordinate.latitude = latitude;
            if (northeastCoordinate.longitude < longitude) northeastCoordinate.longitude = longitude;

        }

        [map zoomWithLatitudeLongitudeBoundsSouthWest:southwestCoordinate northEast:northeastCoordinate animated:YES];
    }
}


text:
Q: How to obtain the correct physical size of the monitor? How can I get the size of the display in centimeters or inches?
This code does not always works correctly:
HDC hdc = CreateDC(_T("DISPLAY"),dd.DeviceName,NULL,NULL);
int width = GetDeviceCaps(hdc, HORZSIZE);
int height = GetDeviceCaps(hdc, VERTSIZE);
ReleaseDC(0, hdc)

Especially for multi-monitor configuration.
Update: I need to get the size just for ordinary monitors, which have a constant physical size.

A: Navigating the registry directly is not only unsupported, but actually fails for devices different than yours. (e.g., the one on which I tested your code).
Unlike what some here say, there is an official way of accessing the EDID key path: by use of the Setup API, and specifically SetupDiOpenDevRegKey.
There's some tedious setup involved - Sample code is here.

EDIT: multiple monitors are handled here.

A: It is not possible to determine the exact physical size of a video device on windows as this depends on quite a lot of variables (e.g. active monitor profile, horizontal/vertical resolution, pixel size, etc.), some of which are not under the control of the computer.
Think for example of projector devices, where the physical size depends on the distance to the projection area which cannot be determined programmatically, as the video projector could be moved manually anytime.

A: You can't get the real exact size - you can get an approximation that depends on the DPI setting in windows, and the resolution of the screen, but you can't guarantee that this is the real size.
Especially in a multimonitor situation with different displays (say a 19" CRT and 24" LCD).  Further, if the display is CRT then the measurement is the tube measurement, and not the display area.
When programs have needed this information exactly in the past, they've shown a gauge onscreen, and had the user hold a piece of paper up to the screen and measure the paper width with the gauge.  Given the paper is 8.5" or A4 then you know the width, and you can use the number that they input to figure out the real DPI for a given display.  You may need to have them do that for each monitor in a multimonitor setup.
-Adam

A: Windows Vista and upper support new function GetMonitorDisplayAreaSize()
http://msdn.microsoft.com/en-us/library/ms775210%28VS.85%29.aspx
Update: It doesn't work properly

A: I found another way. The physical size of the monitor are stored in the EDID, and Windows are almost always copies of its value in the registry. If you can parse EDID, you can read the width and height of the monitor in centimeters.
Update: Added code
BOOL GetMonitorDevice( TCHAR* adapterName, DISPLAY_DEVICE &ddMon )
{
    DWORD devMon = 0;

    while (EnumDisplayDevices(adapterName, devMon, &ddMon, 0))
    {
        if (ddMon.StateFlags & DISPLAY_DEVICE_ACTIVE &&
            ddMon.StateFlags & DISPLAY_DEVICE_ATTACHED) // for ATI, Windows XP
            break;

        devMon++;
    }

    if (ddMon.DeviceString[0] == '\0')
    {
        EnumDisplayDevices(adapterName, 0, &ddMon, 0);
        if (ddMon.DeviceString[0] == '\0')
            _tcscpy_s(ddMon.DeviceString, _T("Default Monitor"));
    }
    return ddMon.DeviceID[0] != '\0';
}

BOOL GetMonitorSizeFromEDID(TCHAR* adapterName, DWORD& Width, DWORD& Height)
{
    DISPLAY_DEVICE ddMon;
    ZeroMemory(&ddMon, sizeof(ddMon));
    ddMon.cb = sizeof(ddMon);

    //read edid
    bool result = false;
    Width = 0;
    Height = 0;
    if (GetMonitorDevice(adapterName, ddMon))
    {
        TCHAR model[8];
        TCHAR* s = _tcschr(ddMon.DeviceID, '\\') + 1;
        size_t len = _tcschr(s, '\\') - s;
        if (len >= _countof(model))
            len = _countof(model) - 1;
        _tcsncpy_s(model, s, len);

        TCHAR *path = _tcschr(ddMon.DeviceID, '\\') + 1;
        TCHAR str[MAX_PATH] = _T("SYSTEM\\CurrentControlSet\\Enum\\DISPLAY\\");
        _tcsncat_s(str, path, _tcschr(path, '\\')-path);
        path = _tcschr(path, '\\') + 1;
        HKEY hKey;
        if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, str, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
        {
            DWORD i = 0;
            DWORD size = MAX_PATH;
            FILETIME ft;
            while(RegEnumKeyEx(hKey, i, str, &size, NULL, NULL, NULL, &ft) == ERROR_SUCCESS)
            {
                HKEY hKey2;
                if(RegOpenKeyEx(hKey, str, 0, KEY_READ, &hKey2) == ERROR_SUCCESS)
                {
                    size = MAX_PATH;
                    if(RegQueryValueEx(hKey2, _T("Driver"), NULL, NULL, (LPBYTE)&str, &size) == ERROR_SUCCESS)
                    {
                        if (_tcscmp(str, path) == 0)
                        {
                            HKEY hKey3;
                            if(RegOpenKeyEx(hKey2, _T("Device Parameters"), 0, KEY_READ, &hKey3) == ERROR_SUCCESS)
                            {
                                BYTE EDID[256];
                                size = 256;
                                if(RegQueryValueEx(hKey3, _T("EDID"), NULL, NULL, (LPBYTE)&EDID, &size) == ERROR_SUCCESS)
                                {
                                    DWORD p = 8;
                                    TCHAR model2[9];

                                    char byte1 = EDID[p];
                                    char byte2 = EDID[p+1];
                                    model2[0]=((byte1 & 0x7C) >> 2) + 64;
                                    model2[1]=((byte1 & 3) << 3) + ((byte2 & 0xE0) >> 5) + 64;
                                    model2[2]=(byte2 & 0x1F) + 64;
                                    _stprintf(model2 + 3, _T("%X%X%X%X"), (EDID[p+3] & 0xf0) >> 4, EDID[p+3] & 0xf, (EDID[p+2] & 0xf0) >> 4, EDID[p+2] & 0x0f);
                                    if (_tcscmp(model, model2) == 0)
                                    {
                                        Width = EDID[22];
                                        Height = EDID[21];
                                        result = true;
                                    }
                                    else
                                    {
                                        // EDID incorrect
                                    }
                                }
                                RegCloseKey(hKey3);
                            }
                        }
                    }
                    RegCloseKey(hKey2);
                }
                i++;
            }
            RegCloseKey(hKey);
        }
    }

    return result;
}

A: You can request LOGPIXELSX from GetDeviceCaps to get the DPI for the display, though it will generally return 96. See also this MSDN article on writing DPI-aware apps.

A: You can obtain EDID from the registry.


text:
Q: Retrieving data in recycler view not working -query correction I have a problem retrieving data from Firebase. I am attaching the structure of my database in the figure.enter image description here
Here I have the parent node as "Reply", inside that I have replykey, inside push key parent for each node have its children. I like to fetch data based on particular "teacherID" that matches the current teacher. The query I wrote is shown below
RootRef = FirebaseDatabase.getInstance().getReference();
  query=RootRef.child("Reply").orderByChild("teacherID").equalTo(CurrentTeacherrId);
       FirebaseRecyclerOptions<StudentModelClass> options =
               new FirebaseRecyclerOptions.Builder<StudentModelClass>()
                       .setQuery(InstRef,StudentModelClass.class)
                       .build();

Using this code recycleView is not fetching the data. How I can rewrite the query to fetch data correctly


text:
Q: EXCEL: Combining SUMIFS with multiple VLOOKUPs due to small variances in names Ok, this is going to be a difficult question to ask, but I'm gonna give it a try.
I have three sheets (Sheet1, Sheet2, Sheet3) in one worksheet (Worksheet).
Sheet1 contains ~100,000 rows with columns Company (A), Holding (B), Product (C), Year (D), Spend (E).
Sheet2 contains 100 rows with columns Company (A), Holding (B), Product Spend in certain Year (C).
Sheet3 contains 100 rows with columns Company (A), ID (B), Variant1 (C), Variant2 (D), Variant3 (E).
What I want, is in Sheet2 to calculate the Product Spend in certain Year. I've been able to do this as a test in Sheet1 by using the function SUMIFS. So in Sheet1 I used:
=SUMIFS(E:E,A:A,"Fake Ltd",B:B,"Fake Holding",C:C,"Dog Food",D:D,"2011")

The problem is that the company names aren't the same in all sheets. I tried to solve it via a FuzzyFind, but that is not working perfectly enough. So I decided to change my methods, and that's why Sheet3 exists. This sheet contains all different name variants of one company in one row (similar to a relational database).
Now I need to use this SUMIFS function in Sheet2 where the company name relates to all possible other company names in Sheet3 so it can sum the company names that appear in Sheet1 as if it were one company name. The column Company in Sheet3 is the 'chosen' company name and also the one used in Sheet2. It's Sheet1 that gives the problem.
So somehow I need to combine SUMIFS with VLOOKUP in Sheet2, but I am not sure how. Anyone any clues? I'll do my best to improve my question, I can imagine if I didn't do the best job explaining.

A: Unless Sheet1 is read-only, just add another column to Sheet1 in which you look up the proper company name from Sheet3. Then build your SUMIFS in Sheet2 based on this column.
If you're using Excel 2010/13, consider installing Powerpivot as an alternative. Here you only need to link the table from Sheet1 with the table from Sheet3 via the Company name column - and then produce a pivot that gives you all the aggregations you need!

A: I think what you're after is excel's array functionality.
http://office.microsoft.com/en-au/excel-help/introducing-array-formulas-in-excel-HA001087290.aspx
For Sheet C, I'd suggest repeating the pattern:
  Company, Variant
That way, you can cross reference any and all companies that match in C without trying to compare against offset 1, 2, 3 ... n
You can then combine the results and use that to match against multiple criteria:
http://blog.contextures.com/archives/2012/07/12/check-multiple-criteria-with-excel-index-and-match/
(the criteria is essentially the union of all rows that match both a company name and a year).
Once you've got the array of the rows that match, you can then apply your sumif over the top.


text:
Q: Sending SMS with SMSLib and Web Services I have made a REST Web Service to send SMSs using a HSDPA USB modem. I am using SMSLib in Java to send SMSs. Every time the web service is invoked, I create the gateway start the service, send message, stop service and remove gateway. This takes about 20 seconds for each message. I found that starting the service takes a lot of time.
This is the part of code I use to send SMSs
        Service.getInstance().addGateway(gateway);
        Service.getInstance().startService();

        OutboundMessage msg = new OutboundMessage(phoneNumber, message);

        if (Service.getInstance().sendMessage(msg)) {
            result = "Message sent successfully!!";
        } else {
            result = "Could not send message.";
        }
        Service.getInstance().stopService();
        Service.getInstance().removeGateway(gateway);//remove the gateway

Is there a way I can start the service once if it is not started and use it to send a message when ever the web service is invoked?

A: Why dont you group the messages and send all in one go?
Service.getInstance().sendMessages(messageList, gateway.getGatewayId());


text:
Q: Run gradle Project in Eclipse I am working with the Gradle build system in the Eclipse IDE. Whenever I create Gradle project in Java I always need to go to command prompt and then to specific project directory and build it first through command gradle build followed with the my corporate proxy settings. I am not able to build it directly from the IDE. can anyone suggest Where I can add my proxy setting to make it build and run my Gradle project from the Eclipse IDE directly rather than going to command prompt always.
Thanks in advance :-)

A: You can define the proxy settings in gradle.properties in your root project directory if it is the same for anyone using that repository, or in ~/.gradle/gradle.properties to set it for any Gradle project on your machine but not affecting other users of the repository.
See here for further information about the proper syntax.


text:
Q: Non Decimal Numbers on Math.ceil or Math.round in JavaScript? I want to use Javascript to round up a number.
For example like this,
15 => 20
345 => 400
201 => 300
180 => 200
93 => 100
22 => 30

How to achieve this using Javascript? I know i can use Math.ceil or Math.round but this is not decimal numbers.

A: Solution for your first example:
var n = 15;
n /= 10; //n = 1.5
n = Math.ceil(n); //n = 2
n *= 10; //n = 20

The other examples work the same way.

A: To round to the nearest multiple of 100, you can write
100*Math.ceil(x/100)

Similarly for other factors.
Choosing a "nice" factor might be a different problem. You could take the base-10 logarithm of your numbers, multiply that by three and round. Then you could apply the following map:
3*round(log10(x))  factor
               0    1
               1    2
               2    5
               3   10
               4   20
               5   50

You don't have to store that table: using modulo operations, you can compute the leading digit of the factor, and using the floor of the third part you get the number of trailing zeros.
Whether this is appropriate depends on your application. The code in your question appears to only use factors which are a power of 10. In that case, don't do the multiplication by 3 in the above approach, but instead simply use the floor of the base 10 log directly:
factor = Math.pow(10, Math.floor(Math.log(x)/Math.log(10)));
rounded = Math.ceil(x/factor)*factor;

A: The answer you want depends on the precision.
A basic solution would be
function round(num, precision) {
  var div = Math.pow(10, precision);
  return Math.ceil(num/div)*div;
}

A: What about you divide your numbers by 10/100/1000 to have decimals, then ceil/round. Then multiply again.
This is the first solution that comes to my mind.


text:
Q: How to get PortalId into sql script for 2sxc visual query I need to run a sql script in a 2sxc visual query.
I can do "where portalid = 709"
But, to use this in any portal, how do I automatically the the PortalId into the script?

A: Use the token [Portal:PortalId] in your sql ;)
For other token examples, like [QueryString:xyz] see https://docs.2sxc.org/api/dot-net/ToSic.Eav.DataSources.Sql.html


text:
Q: Advanced search with mysql OR statement - Magento I want to search with the advanced form, but with an mysql OR statement instead of AND statement.
For example I search for product 'Nokia' in Productname field and 'N97' in keywords field. The search results has to be Nokia OR N97.
Is there a way to fix this?

A: There is a way to configure it from search settings in admin page
System > Configuration > Catalog > Catalog > Catalog Search > Search Type


text:
Q: Como salvar arquivo JSON com Node.js Quero fazer um site para testar algumas coisas. O site esta rodando em meu servidor em casa feito com o Wamp. Me disseram que eu poderia fazer um pequeno banco de dados usando arquivos JSON. Eu tenho um arquivo JSON na pasta do site que contem o seguinte:
[
        {
            "titulo":"Filme A",
            "titulo original":"Movie A",
            "duracao":"120 min",
            "genero":"Genero 1",
            "Atores":"Nome 1, Nome 2",
            "Rate":"1",
            "Visto":"sim"
        },
        {
            "titulo":"Filme B",
            "titulo original":"Movie B",
            "duracao":"160 min",
            "genero":"Genero 2",
            "Atores":"Nome 1, Nome 2",
            "Rate":"2",
             "Visto":"sim"
        },
        {
            "titulo":"Filme C",
            "titulo original":"Movie C",
            "duracao":"140 min",
            "genero":"Genero 3",
            "Atores":"Nome 1, Nome 2",
            "Rate":"",
             "Visto":"nao"
        }
]

Com a ajuda de vocês eu consegui listar as propriedades desses objetos do array JSON.
Agora estou tentando salvar um novo objeto dentro desse array JSON através de informações que o usuário coloca quando são feitas as perguntas e pra isso eu preciso de um scripting no lado do servidor, eu escolhi o Node.js por estar um pouco mais familiarizado com o JavaScript. Tenho poucos conhecimentos e quase nenhum de Node.js. Mas mesmo assim gostaria de qualquer ajuda de vocês para eu tentar aprender alguma coisa. Tenho lido na internet sobre o node.js e JSON mas ainda não entendi como salvar o JSON no servidor usando o node. Qualquer explicação será de muita ajuda.
Veja no JSFiddle

A: O mais indicado, que foi citado pelo Joel é sim de fato utilizar o Mongo, mas caso tenha interesse em utilizar uma API de manipulação de arquivos no Node.JS, você pode utilizar a Filesystem API, veja um exemplo abaixo
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

Ou então como o exemplo abaixo, pode ser a utilização do Node.JS com conexão com o MongoDB
var MongoClient = require('mongodb').MongoClient,
Grid = mongo.Grid;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
    if(err) return console.dir(err);

    var grid = new Grid(db, 'fs');
    var buffer = new Buffer("Hello world");
    grid.put(buffer, {metadata:{category:'text'}, content_type: 'text'}, function(err, fileInfo) {
        if(!err) {
             console.log("Finished writing file to Mongo");
        }
    });
});

A: Recomendo usares uma base de dados JSON MongoDB em Node.js.
http://nodebr.com/nodejs-e-mongodb-introducao-ao-mongoose/
Recomendo em aprender e ler mais em como usar MongoDB:
http://net.tutsplus.com/tutorials/databases/getting-started-with-mongodb/
https://education.mongodb.com/


text:
Q: php header Location not working on iframe I've been searching here, and it seems that it's just that it doesn't work. But I had this working perfectly in WAMP Server 2.5, and when I uploaded to actual client's server, it stopped working.
Here's my code:
remSoc($_POST['sid'], $db, $_POST['f_baja']);
header("Location: ../files/bSoc.php?e=0&soc=".$_POST['sid']);

And its working inside an iframe on the main page. I think I might replace it with some <script></script> but does anyone have a clue about why is it working with my test-server and not with remote server? What is the minimum version required for this to work properly?
Thanks a lot!


text:
Q: PHP codeigniter SQL Injection(MSSQL) I was receiving the the report show my query has SQL injection, would need your help to verify some problem:

*

*I was using this as the insert statement

  function insert($table_name, $insert_data)
    {
        $this->db->set($insert_data);
        if ($this->db->insert($table_name)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

for exmaple:
$name = 'iamklll';
$status = 1;

  $insert_data =
                array(
                'name' => $name,
                'status' => $status,
                );
  $this->model->insert('table', $insert_data);

This kind of method cannot prevent the SQL injection? If this cannot prevent I think best way is query bindings?

*How do I prevent the SQL injection if the $POST['column'] is array?

*How to store the data as if the person insert test">
eee
? Should I use htmlspecialchars to store in database?

A: You are referring to Active Record class. It has own query builder and it suppose to protect you from SQL injections from the box.
How to store the data as if the person insert test">
eee

I think you are referring to XSS attack. I believe that the best practice it to strip out all the tags except allowable tags. I don't think htmlspecialchars will make much sense here while you are going to make backward converting on the output.

A: In your case you're using the query builder $this->db->insert() this generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. All values are escaped automatically producing safer queries.
This is actually the best option in my opinion. Better than using the query bindings, specially because in the long run you might need to change from MSSQL to mySQL or any other engine and you wont need to change anything in your code.
Since you're using codeigniter 3 be sure to validate your data before inserting it.
Use the form validation for that: https://codeigniter.com/userguide3/libraries/form_validation.html?highlight=form%20validation
From your example I think you're also referring to xxs attacks. If so, you have two options, you can do this while validating your data with form validation using the XSS rule. Or you can activate this globally in your application/config/config.php
$config['global_xss_filtering'] = true;

Since we're talking about protecting your app you might also want to consider using the csrf settings in codeigniter. This can also be done in your config.php file.
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
 */
$config['csrf_protection'] = true;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = true;
$config['csrf_exclude_uris'] = array();

So, in your case, using the query builder is fine to prevent SQL injection of that's what you're actually looking for.


text:
Q: getter/setter Class from $variable w/out switch/if in Symfony? I am using a table edit switch, which I want to integrate to Symfony.
This is the script I am talking about: LINK
Now this script sends requests that I am able to receive in symfony.
Sender
superuser

Receiver (/post)
if($table == "table1"){
    $repo = "AppBundle:Table1";
}
...
/* Get correct repo/entry */
$repo = $em->getRepository($repo)->find($request->get('pk'));

That is somehow untested but should work I guess.
Now I want to update the according column, which is sent by id="Username"
What I'd like to achieve now is something like this: (I know this won't work)
$repo->set.$request->get('id')('blabla')
I could use a switch, but that needs to be quite large then.
Any other approach to this?
PS: I know it is not very safe to send values like this, but it's only for personal use.

A: If you want call a setter from your request value, the following code will work :
$setter = 'set'.$request->request->get('id'); // is now equal to 'setUsername'
$repo->$setter('blabla'); // Assuming $repo is the entity retrieved by find();

Also, there is a clean way to do that is symfony called PropertyAccess, you just need the name of the property you want set/get .
Example :
use Symfony\Component\PropertyAccess\PropertyAccessor;
// ...
$accessor = PropertyAccess::createPropertyAccessor();

// If the property 'username' is writable, set it
if ($accessor->isWritable($repo, 'username') {
    $accessor->setValue($repo, $request->request->get('id'), 'blabla');
}

See Symfony PropertyAccess


text:
Q: mysql dynamic sql using IN I would like to create a sp with the next code:
select *
from document
where cod_emp='AAA'
and cod_situation in ('01','02','03');

But I would like ('01','02','03') to be a parameter, so I thought something like this would work:
-- sp's call

call sp('"01","02","03"');

-- sp's parameter

in param_txt_cod_situation text;

-- sp's code

set @cons1=
'select *
from document
where cod_emp="AAA" ';

if length(param_txt_cod_situation)>0 then
set @param_txt_cod_situation=param_txt_cod_situation;
set @cons2='and cod_situacion in concat("(",?,")") '
else
set @param_txt_cod_situation=true;
set @cons2='and ?';
end if;

set @cons=concat(
@cons1,
@cons2);

prepare cons from @cons;
execute cons using
@param_txt_cod_situation;
deallocate prepare cons;

But it didn't work.
Hope you guys can help me.
Thanks very much.

A: The concat function returns a string in whatever query it is in. You do not want to see if something is in a string but rather a list.
Replace
set @cons2='and cod_situacion in concat("(",?,")") '

with
set @cons2=concat('and cod_situacion in (',?,') ')

and see if that works


text:
Q: Launching an application at start-up I want my application to be automatically launched when the system is started. Can anyone tell me how to do that?
Thanks in advance for the time you will spend trying to help me.

A: First, you need the permission in your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Also, in your manifest, define your service and listen for the boot-completed action:
<service android:name=".MyService" android:label="My Service">
    <intent-filter>
        <action android:name="com.myapp.MyService" />
    </intent-filter>
</service>

<receiver
    android:name=".receiver.StartMyServiceAtBootReceiver"
    android:enabled="true"
    android:exported="true"
    android:label="StartMyServiceAtBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

Then you need to define the receiver that will get the BOOT_COMPLETED action and start your service.
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent serviceIntent = new Intent("com.myapp.MySystemService");
            context.startService(serviceIntent);
        }
    }
}

And now your service should be running when the phone starts up.

A: Here is Complete working Example Code,
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.practice" android:versionCode="1" android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AutoStartExampleActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="AutoStart"></receiver>

        <receiver android:name=".AutoStart">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

AutoStartExampleActivity File
package com.practice;

import android.app.Activity;
import android.os.Bundle;

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

BroadcastReceiver Code,
package com.practice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AutoStart extends BroadcastReceiver
{

    public void onReceive(Context context, Intent intent)
    {
        System.out.println ( "Application Started" );
        // put your TimerTask calling class here

        try
        {
            Intent myIntent = new Intent ( context, AutoStartExampleActivity.class );
            myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(myIntent);
        }
        catch ( Exception e )
        {
            System.out.println ( " Error while Starting Activity " + e.toString() );
        }
    }
}


text:
Q: Search set of characters inside a string irrespective of its position in PHP Hi I would like to get find the set of characters inside a string and then would like to remove it from another string. For eg
$start_state = 'BCFSW|';

$possible_combinations = array('BF','BCF','BFS','BFW');

I would like the function to search each array element from possible_combinations irrespective of its position. So for eg 'BF' should return true as both the characters are present in BCFSW|
I would further want to remove those characters and generate a new array string from it and add it to another array which would look something like this.
$possible_states = array ('CSW|BF', 'SW|BCF', 'CW|BFS' ,'CS|BFW')

Can you guys please help me with this? It would be of a great help. Thanks

A: What you are looking for is the "array_diff" . "array_intersect".
Array_diff finds what is not in matching between the arrays, and array_intersect finds what is matching.
$str = 'BCFSW|';

$arr = array('BF','BCF','BFS','BFW');

$str = str_split($str);
foreach($arr as $item){
    $temp = str_split($item);
    $new[] = implode("",array_diff($str, $temp)) . implode("",array_intersect($temp, $str));
}

var_dump($new);

Output:
array(4) {
  [0]=>
  string(6) "CSW|BF"
  [1]=>
  string(6) "SW|BCF"
  [2]=>
  string(6) "CW|BFS"
  [3]=>
  string(6) "CS|BFW"
}

https://3v4l.org/8RvL2

A: You can use regular expressions with the functions preg_match and preg_replace
Example with BF:

$found = preg_match('#B.*F#', $text);

Will return true if $text is BF, BAF, BZZF, ...
You can search all combination in one time if you want by using | (see regex documentation for more details)
If order if irrelevant, the regex might be '#[BF].*[BF]#
Then, you can use parenthesis to catch characters and change the string with preg_replace()


text:
Q: If others permission is writable of a directory, other users can modify a file even the file is not writable
user1@server1:/locdisk/data/a$ touch test
user1@server1:/locdisk/data/a$ ll
rwxrwxrwx 1 user1 user1 1 AUG 30 11:11 ./
rwx------ 1 user1 user1 1 AUG 30 11:11 test
user2@server2:~$ ssh server1
user2@server1:~$ vi /locdisk/data/a/test

and then modify test by 'w!'

user2@server1:~$ ll /locdisk/data/a/
rwxrwxrwx 1 user1 user1 1 AUG 30 11:11 ./
rwx------ 1 user2 user2 3 AUG 30 11:11 test

How could it be??
My ubuntu has a bug? How should I fix it?

A: Your Ubuntu does not have a bug. This is how Unix file systems work. There are a number of issues here.
First, you should read the link provided by Mark Plotnick in his comment. You will see that you are not writing to the file, but merely changing the directory. And because you have write-permissions on the directory, that is allowed.
Second: this is why, in Unix/Linux, you should never ever have world writable directories.
Third, are you sure your vi /locdisk/data/a/test does not complain about the file not being readable? So you cannot modify the file, you can overwrite it however.


text:
Q: crudrepository findBy method signature with multiple in operators? I have an Entity Class like this:
@Entity
@Table(name = "EMAIL")
class Email{
    @Id
    @Column(name = "Id")
    Long id;
    @Column(name = "EMAIL_ID")
    String emailId;
    @Column(name = "PIN_CODE")
    String pincode;
}

How to write findBy method for the below query using crudrepository spring data jpa?
select email_id,name from email_details where eamil_id in('mike@gmail.com','ram@gmail.com') and pin_code in('633677','733877')

I am expecting the spring data jpa method like the below but how to construct it?
List<Email> findBy.....(List<String> emails, List<String> pinCodes);

I want to get list of Emails in a single database hit.

A: The following signature will do:
List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.


text:
Q: Session does not redirect I have a login page that when checking the database if the user exists, does not redirect to the panel
The problem is in the session because without it it works correctly
if($sql->RowCount()>0){

    $entrou = $_SESSION['entrou'];
    header('location: painel.php');

And here we have the check, if the session was not created, it is automatically because the login was not made, and if there is no session, redirects to the login
    if (!isset($_SESSION['entrou']) == true ) {
  unset($_SESSION['entrou']);
  header('location: index.php');
}

A: As already mentioned you have to start your session at the beginning of every file you want to use sessions.
If you want to set a session use this:
session_start();
$_SESSION[NAME] = VALUE;

and to redirect after you checked if the session is set you can do like that:
session_start();
if (isset($_SESSION[NAME]){
   header('Location: index.php';
}

A: Give this a shot.
// ensure to add session_start at the beginning of
// all scripts that require use of $_SESSION[]
session_start();

if($sql->rowCount()){
    $entrou = $_SESSION['entrou'];
    header('location: panel.php');
}

if(isset($_SESSION['entrou'])){
    unset($_SESSION['entrou']);
    header('location: index.php');
}

A: Here try this

<?php

session_start();

...

if($sql->RowCount()>0){

   $_SESSION['entrou'] = true;
   header('location: panel.php');
}
else {
    header('location: index.php'); // "no user in the db!"
}

...

if (!isset($_SESSION['entrou']) {
    header('location: index.php');
}

?>

But of course if you want to check if the user exists in the database you sould do something like this
<?php

$data = $sql->query('SELECT * WHERE username=$_SESSION["username"]') // where "username" is the username column

if ($data == "") {
    header('location: index.php'); // user is non-existent
}
else {
    header('location: panel.php'); // the user is in the database
}
// note this only applies if you're using SQLite