text:
Q: Where does VLC store Keyboard hotkeys? I just made an arduino sketch that listens for a physical foot pedal switch button that will send via  serial port a string to a python script that thanks to pyautogui will emulate a keyboard keys press.
Python will then simulate a key press, which is the same of a vlc hotkey binding I use to play/pause a video.
In this way I can play/pause a vlc video by presing the pedal switch.
I hardcoded this keyboard binding in the python script.
Now, just for fun I want to change the hotkeys combination in vlc and I would like that python could read this change in a VLC preference file configuration, so that I don't have to manually change every time the script, but I don't know where VLC saves these keyboards global hotkeys.
I am on windows, but I am a regular Linux user... and in linux everything is a file!!
Thanks in advance

A: The file that gets updated when VLC hotkeys are changed is file:
C:\Users\USER-NAME\AppData\Roaming\vlc\vlcrc
I note that by default all entries are commented out with # prefix to the line.
When a key is changed from the default, the matching entry is uncommented.
This means that the defaults are built-in to VLC, and only changes to the defaults
are noted in the file.


text:
Q: Using jQuery post function, the returned link cannot have addClass function run on it HTML

                    Click

Stuff

jQuery
                    $('#library-status-select').click(function() {
                        $(this).toggleClass('open');
                        $('.dropdown').toggleClass('open');
                    });

                    function create_library_entry(status, user_id, anime_id) {

                        jQuery('#custom_lightbox').html('');

                        jQuery.post("/wp-content/themes/phanime/custom_functions/create_single_libraryEntry.php", {user_id : user_id, anime_id : anime_id, status : status}, function(data) {
                                //this is your response data from serv
                            console.log(data);
                            jQuery('#add_to_library').html(data);

                        });

                    }

So when I click on the anchor tag with the id of library-status-select it shows the div with the class dropdown. By adding an open class and so on. Once the dropdown shows it also has a link that does a jQuery post. The jQuery post returns it's result which in the #add_to_library id, where the link is contained. That link is replaced by another link that is returned from that jQuery.post. That link looks like this...
Click me updated

It's essentially the same link with the same class / id but for some reason the jQuery.addClass / removeClass no longer works on the link that is returned from the jQuery.post. In other words the open class is not being added. If anyone knows exactly why this happens, it would be of great help.

A: Since you are replacing the contests you are dealing with dynamic contents so use event delegation
$('#add_to_library').on('click', '#library-status-select', function () {
    $(this).toggleClass('open');
    $('.dropdown').toggleClass('open');
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Cómo conseguir que no carguen ciertos elementos en la versión móvil de un sitio web? He probado con media queries y display:none, los elementos desaparecen pero revisando el Network del inspector veo que se cargan igual. La idea es ganar velocidad en los móviles quitando elementos pesados para acelerar la carga. Gracias.

A: Con css siempre aparecerá el contenido y después lo ocultara, por donde lo veas es mejor opción tener un sitio web exclusivo para móviles en este caso que solicitas para "ganar mas velocidad en los móviles"

Una solución en Javascript es detectar el ancho de la pantalla y en en base a ese ancho hacer un redireccionamiento a tu sitio exclusivo para móviles, esto puede ser una solución no muy recomendada
este es un ejemplo con Javascript obtenido de desarrollowe.com
if (BrowserDetect.browser == "Firefox") {
    document.write("<LINK REL='stylesheet' HREF='estilo_firefox.css' TYPE='text/css'>");
}
else
{
      if (BrowserDetect.browser == "Explorer"){
        if (BrowserDetect.version>=7){
          document.write("<LINK REL='stylesheet' HREF='estilo_ie7.css' TYPE='text/css'>");
        }else{
          document.write("<LINK REL='stylesheet' HREF='estilo_ie6.css' TYPE='text/css'>");
        }
      }else{
          if (BrowserDetect.browser == "Opera"){
            if (BrowserDetect.version<9){
              document.write("<LINK REL='stylesheet' HREF='estilo_opera.css' TYPE='text/css'>");
            }else{
              document.write("<LINK REL='stylesheet' HREF='estilo_opera9.css' TYPE='text/css'>");
            }
          }else{
            document.write("<LINK REL='stylesheet' HREF='estilo_otros.css' TYPE='text/css'>");
          }
      }
}

Otra forma es detectar del lado del servidor que tipo de navegador esta accediendo así evitas mandar al reenderizado de la página el contenido que no deseas ver, nunca lo he intentado.
He leído que con PHP usando la librería php-browscap para usarla con el siguiente código:
require 'vendor/autoload.php';
use phpbrowscapBrowscap;

$bc = new Browscap('cache');
/** @var stdClass $current_browser */
$current_browser = $bc->getBrowser();

ahora ya tienes un stdClass en $current_browser con toda la información disponible del browser.
Para tomar decisiones por cada navegador detectado puedes usar el siguiente código:
$curr_br = $current_browser->Browser;
$CoolBrowsers = $curr_br == 'Chrome' || $curr_br == 'Firefox';

if ($CoolBrowsers) {
  add_asset('css', 'just-for-cool-browsers.css');
  $output = renderAdvancedLayout();
}
else {
  add_asset('css', 'just-for-bad-bad-browsers.css');
  $output = renderBasicLayout();
}

También puedes detectar si están accediendo desde un móvil o una tablet, incluso saber si es Android, IOS, la versión del SO, etc.
Hay otras formas según como tengas desarrollado tu sitio.
Información obtenida de ecapy.com

A: No soy un experto pero se me ocurren dos soluciones, una es utilizando la tecnología jQuery, con esta tendrías obtener el ancho de la pantalla, muy similar como lo hacías con el query en el css, pero ahora con jQuery, luego de saber el tamaño de la pantalla usas un if o un switch como estructura de control para construir diferente tu web en los distintos tamaños.
La otra forma que te podría servir es con java script antes de cargar la pagina consultar el tamaño de la pantalla si es de móviles que lo redirija a un sub-dominio que tenga la misma pagina versión móvil, de lo contrario no redirija a ningún lado y permita cargar el contenido de la pagina actual.

A: Pues el hecho de que establezcas un display:none no quiere decir que el elemento no exista pues literalmente traducido, existe mas no es mostrado y por lo tanto, igualmente carga. Recuerda que el HTML es estático y los elementos no son creados por arte de magia, están plasmados en el código. Lo único que te puedo recomendar el usar Javascript, ya que con ellas puedes crear nuevos elementos en el DOM que antes no existían en el código, podrías hacer como una especie de condición que si el medio de visualización es movil, no crea el elemento, de otra manera, crear dicho elemento. Ademas, en vez de usar el display:none yo te recomiendo utilizar un framework CSS como materialize o bootstrap, es mucho mas facil ocultar y mostrar elementos utilizando las clases de las mismas

A: Con display:none, simplemente estas diciendo que no se muestre, pero estara ahi su presencia del elemento, una alternativa seria eliminar por completo ese elemento cuando se encuentre en determinada pantalla(ancho de pantalla) como indicas con las @media querys, te dejo un codigo que elimina elementos mediante id.

function eliminarPorId(id) {
    var elemento = document.getElementById(id);
    return elemento.parentNode.removeChild(elemento);
}

eliminarPorId("segundoDiv");
#primerDiv{
background:red;
  width:40px;
  height:40px;
}
 #segundoDiv{
background:blue;
  width:40px;
  height:40px;
}
.tercerDiv{
background:orange;
  width:40px;
  height:40px;
}

Ahora viendo en el inspector de codigo: no existe el div con id=segundoDiv(porque fue eliminado)

si bien se carga aun es por que no se utilizo algunas condiciones, una solucion seria hacer algo parecido a lo siguiente, iterar por todos los divs de la pagina.

var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
  if(divs[i].className!="divsNecesarios"){
    var elemento = document.getElementsByClassName(divs[i].className);

while(elemento[0]) {
    elemento[0].parentNode.removeChild(elemento[0]);
}

  }
}
    #primerDiv{
    background:red;
      width:40px;
      height:40px;
    }
     #segundoDiv{
    background:blue;
      width:40px;
      height:40px;
    }
    .divsNecesarios{
    background:orange;
      width:40px;
      height:40px;
    }

A: La única forma que veo de realizar lo que deseas es usando este pequeño truco (partiendo del código de @x-rw para no tener que escribir todo desde 0):

function regenerar(id) {
  var media = window.matchMedia("(min-width: 800px)");
  var elementos = document.getElementsByTagName("img");
  for (i = 0; i < elementos.length; i++) {
    if (media.matches) {
      var srcc = elementos[i].getAttribute("srcc");
      if (srcc !== null) {
        elementos[i].src = srcc;
      }
    } else {
      if (elementos[i].src == "") {
        elementos[i].src = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
      }
    }
  }
}

/* Todos los navegadores excepto IE < 9 */
document.addEventListener("DOMContentLoaded", regenerar, false);
#primerDiv {
  background-color: red;
  width: 40px;
  height: 40px;
}

#segundoDiv {
  background-color: blue;
  width: 40px;
  height: 40px;
}

.tercerDiv {
  background-color: orange;
  width: 40px;
  height: 40px;
}

Registramos una función que será llamada cuando el documento haya sido cargado. En ese momento analizamos todas las imágenes del documento e intercambiamos su atributo srcc por el src sólo si éste está definido.
No me gusta mucho la solución, pero creo que podría ayudarte a conseguir lo que deseas.

A: Mientras una etiqueta de  este en tu código esta sera cargada.
Lo que te sugiero es que cargues por defectos todas tus imagen tengan en su atributo src una misma imagen de 1x1 px y en un atributo data, por ejemplo data-src coloques la ruta la verdadera imagen.
Con esto y una vez que cargue el sitio solo cargara una imagen pequeña de 1x1 px y luego con algo de JavaScript cambiar el atributo src por el valor del atributo data-src de las imágenes que realmente quieras cargar en el móvil.
Te adjunto un ejemplo con jQuery:

$('img[data-src]:not(.hide-on-movil)').each(function () {
 var $this = $(this);
    $this.attr('src', $this.data('src'));
});
.hide-on-movil {
    display: none;
}

Espero te sirva para entender la idea y te sea de utilidad.
Suerte y Saludos!

A: El tema de las imágenes lo resolví usando la etiqueta picture con el atributo srcset. Luego con javascript para que no carguen otros elementos pesados como videos o iframes . Los elementos los metí en un div con display:none para llegar en cierta forma a la solución de la pregunta formulada.
Ejecuten el código en pantalla completa, achiquen la pantalla a menos de 500px, refresquen y se podrá apreciar en el Network del inspector que no se cargan los elementos. El iframe comienza a cargar pero se cancela de inmediato.

screen_resize()

function screen_resize() {
  var h = parseInt(window.innerHeight);
  var w = parseInt(window.innerWidth);

  if (w <= 500) {
    var iframe = document.querySelector('iframe');
    iframe.parentNode.removeChild(iframe);
    var video = document.querySelector('video');
    video.parentNode.removeChild(video);

  }

}
div {
  display: none
}
@media (min-width: 500px) {
  div {
    display: block
  }
}
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

  <picture>
    <source srcset="https://cdn.pixabay.com/photo/2016/01/10/21/06/eye-1132531_960_720.jpg" media="(min-width: 500px)" />

  </picture>

  <video width="320" height="240" controls>
    <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4">
  </video>


text:
Q: Turn iOS Device into AirPlay Speaker I'm fiddling with an app, and I'm also aware that apps made by developers that allow an iOS Device to receive an audio stream from another iOS Device or iTunes.  So I'd like to implement it and possibly find a method within Apple's guidelines, allowing audio to be streamed.  I've tried looking for everything, but I can't find where to start.  Any ideas, a place to start, maybe even a point of direction would be great.

A: chekout the airspeaker project on github.
https://github.com/chenkaigithub/AirSpeaker
I was able to run it on iOS simulator 6.0 and then use my iphone to stream audio.
However if I try to stream from iTunes 11 it does not work ( iTunes lists the device in airplay list but , on selection , prompts with error "airplay device is not compatible with this version of iTunes." )


text:
Q: Is there a point in creating a conda package from an PyPI package? If one has a pure Python package already on pypi.org, is there any advantage of providing a conda package?
My assumption was that conda is really useful, if you have dependencies outside of the Python eco system. It then helps to have reliable builds. But is there something else? Is it in the end just personal preference?
The tutorial didn't even mention the question when a conda package is (not) necessary.


text:
Q: How do I find an installed nuget package at the console? I have tried
Get-Package -filter json

But this shows No packages installed.
I want to find packages containing "json" not starting with  "json" is this possible?
The GUI package manager search works how I want, but how do I do this on the console?

A: This is currently not possible. The code specifically looks for StartWith.
        foreach (var project in projects)
        {
            var packageRefs = await project.GetInstalledPackagesAsync(token);
            // Filter the results by string
            if (!string.IsNullOrEmpty(filter))
            {
                packageRefs = packageRefs.Where(p => p.PackageIdentity.Id.StartsWith(filter, StringComparison.OrdinalIgnoreCase));
            }

            ...

Since scripts rely on these cmdlets behavior, we can't just change it to IndexOf or something like that because that would be a breaking change.
We will take a look at the issue you opened and come up with a suggestion.

A: Currently the -Filter parameter is applied when you use -ListAvailable, which goes to the remote repositories instead of searching specifically in the project.
You can still use Get-Package in a similar fashion you posted in your question, though:
Get-Package | Where-Object { $_.Id -like '*json*' }


text:
Q: orderBy subcategories till exists in laravel i want to order category as per below.
level-1
   level-11
       level-111
            level-1111
            level-1112
            level-1113
       level-112
       level-113
            level-1131
       level-114
       level-115
             level-1151
             level-1152
  level-12
       level-121
            level-1211
            level-1212
            level-1213
       level-122
       level-123
            level-1231
       level-124
       level-125
             level-1251
             level-1252
level-2
    .....<same as above if have nestied category than show in below line till have nested category>
level-3

in sort, I want category data till the existence of the child category. if a category has a child then shown in below line and child have child category then shown in below child till category doesn't have child.
how to order like that. I also want pagination of 10 rows .in the above example, the first page has data till   level-114    child.
hope my question is clear and understandable.


text:
Q: How to convert the following optimization problem to SDP format? I want to convert the optimization problem $x \in \mathbb R^n$ to SDP format to further solve it using the famous solvers like sdpt3 and sedumi.
$$\text{minimize} \quad \| A(x) - B \|_* + \lambda \| D x \|_1$$
where $A$ is a linear mapping, and $B$ and $D$ are matrices.


text:
Q: Clarification of an integral inequality used in proof of Chebyshev's inequality Casella and Berger's proof of Chebyshev's inequality relies on the statement that for random variable $X$, non-negative function $g(x)$, and $r > 0$,
$$
\int_{x: g(x)\geq r}^{\infty} g(x)f_X(x)dx \geq r\int_{x:g(x)\geq r}^{\infty}f_X(x)dx
$$
I am struggling to understand the general validity of this. Can someone provide an explanation?

A: Perhaps it is more suggestive to rewrite the inequality in the form
$$ \int_{x:g(x)-r\geq 0} (g(x)-r)f_X(x) \, dx \geq 0. $$
Then this says we want to show that if we integrate a function over the set of points where it is nonnegative, the result is nonnegative ($f_X(x) \geq 0$ since it is a the probability density, of course). This is one of those basic facts about integrals (usually going by the name of nonnegativity or monotonicity), and should be proved in any reasonable textbook.


text:
Q: Секундомер на Си (Linux) Разработать программу, имитирующую работу цифрового секундомера, который позволяет измерять временные интервалы с точностью до миллисекунды. Временной интервал должен измеряться от момента запуска программы до момента интерактивного прерывания ее работы по сигналу от клавиатуры. Изменение времени в пределах измеряемого интервала должно отображаться в одной строке потока стандартного вывода (stdout). Формат вывода должен содержать поля для отображения часов, минут и секунд, разделенные символом двоеточия, а также поле для отображения миллисекунд, которое отделяется от поля секунд символом точки. Обновление информации в полях указанного формата должно происходить с периодичностью одна миллисекунда. При этом модифицироваться должны только те цифры строки вывода, значения которых изменились относительно предыдущего отображаемого момента времени.
1)Как сделать модификацию только изменившейся цифры ? Да и вообще строки в целом (\r не вариант, обновляет всю строку)
2)Как в этом случае сделать остановку по нажатию на клавишу (Не ctrl+C желательно)
#include <stdio.h>
#include <time.h>

int main()
{
    int start, end;
    int ms= 0;
    int ns= 0;
    int sec=0 , min=0 , hrs=0;
    start = clock ();
    while (1)
    {
        end = clock ();
        ns= end - start;
        ms = ns / 10;
        if (ms>100)
        {
            sec = sec + 1;
            ms= ms - 100;
            start= end;
        }
        if (sec > 59)
        {
            min = min+1;
            sec= 0;
        }
        if (min > 59)
        {
            hrs = hrs + 1;
            min=0;
        }
        printf ("%d:%d:%d.%d\n",hrs, min, sec, ms );
    }
}

A: Есть вариант - либо использовать \r и выводить новую строку поверх старой (тем самым выглядеть цифры будут как не измененные...), либо (раз вам этот вариант не подходит)
использовать "забой" на нужное количество символов и выводить только изменившиеся цифры.
Я бы записывал все в строку, которую хранил. После этого сравнивал бы две строки, и смотрел, где начинается отличие.
С клавишами - если у вас в системе есть тот же <conio.h>, то проверять в том же цикле, не была ли нажата клавиша, и если была - то какая...


text:
Q: Binomial logistic regression in SPSS using survey weights I am running a logistic regression in SPSS with a sample that uses survey weights. The sample size is 1000 and the weights are along the lines of .86 or 1.23 depending on the case. I am using the weights option in the Data command to weight my sample before I run my logistic regression but then I get the unweighted frequencies in the Categorical Variables Coding part of the output.
At the beginning my output gives me a Case Processing Summary, which says Unweighted cases with a superscript "a" which then says "If weight is in effect see classification table for the total number of cases."  My classification tables all are properly saying 1000 cases which is right.  I have 7 predictor variables (all categorical) and one outcome variable (dichotomous).  My output seems to make sense, but I am troubled that the frequencies are all the unweighted frequencies.  Are my results still legitimate?  I am afraid that I may not understand the weighting quite properly.


text:
Q: IEEE Access LaTeX: using \textbf{ } in table with multicolumn generates error: Argument \bf has an extra } Same code is generating table with bold option in other temples
\usepackage{multirow}
\begin{table*}[h!]
\centering
\caption{table1}
\begin{tabular}{|c|c|c|c|c|}
\hline
\textbf{Dataset}    & \textbf{Total News}    & \textbf{Fake}         &

Error is shown here: Argument \bf has an extra }
\multicolumn{2}{c|}{\textbf{Real}}       \\ \hline
\textbf{PolitiFact} & 72                     & 36                    &
\multicolumn{2}{c|}{36}                  \\ \hline
\textbf{GossipCop}  & 100                    & 50                    &
\multicolumn{2}{c|}{50}                  \\ \hline
\multicolumn{1}{|l|}{\textbf{}} & \textbf{Total Tweets} & \textbf{Fake Tweets} & \multicolumn{2}{c|}{\textbf{Real Tweets}} \\ \hline
\textbf{PolitiFact} & 5045                   & 3371                  &
\multicolumn{2}{c|}{1674}                \\ \hline
\textbf{GossipCop}  & 3636                   & 2489                  &
\multicolumn{2}{c|}{1147}                \\ \hline
\textbf{}           & \textbf{Total ML Rows} & \textbf{Fake Rows}    &
\multicolumn{2}{c|}{\textbf{Real Rows}}  \\ \hline
\textbf{PolitiFact} & 4085                   & 2972                  &
\multicolumn{2}{c|}{1113}                \\ \hline
\textbf{GossipCop}  & 3342                   & 2245                  &
\multicolumn{2}{c|}{1097}                \\ \hline
\textbf{}           & \textbf{Total Users}   & \textbf{In Fake Only} &
\textbf{In Real Only} & \textbf{In Both} \\ \hline
\textbf{PolitiFact} & 3865                   & 2763                  & 1081                  & 10               \\ \hline
\textbf{GossipCop}  & 2564                   & 1706                  & 858                   & 8                \\ \hline
\textbf{}           & \begin{tabular}[c]{@{}c@{}} \textbf{1st Degree}\\\textbf{Fake Followers}\end{tabular}   & \begin{tabular}[c]{@{}c@{}}
\textbf{1st Degree}\\\textbf{Fake Followings}\end{tabular} & \begin{tabular}[c]{@{}c@{}} \textbf{1st Degree} \\\textbf{Real Followers}\end{tabular} &
\begin{tabular}[c]{@{}c@{}}\textbf{1st Degree}\\\textbf{ Real Followings}\end{tabular} \\ \hline
\textbf{PolitiFact} & 312M                    & 27M                  & 534M                  & 19M               \\ \hline
\textbf{GossipCop}  & 209M                   & 19M                  & 378M                   & 12M                \\ \hline
\end{tabular}
\end{table}

A: The newer version of ieeeaccess.cls does a very bad set of definitions.
Let's see what happens. The class is based on IEEEtran.cls that enables the old font commands such as \bf. Such (silly) idea allows users to do something like ${\bf x}$, which has been deprecated for more than 25 years.
So the developer of ieeeaccess.cls decided that this is not good, but starts with doing
\def\textbf#1{{\bf #1}}

for no apparent reason than making a robust command fragile and introducing the usage of a deprecated command. Oh, no, says the developer, we redefine \bf.
Here it is! In all its glory!
\AtBeginDocument{%
\gdef\operator@encoding{T1}
\gdef\encodingdefault{T1}
%\def\it{\fontencoding{T1}\selectfont}
\long\def\bf#1{\ifmmode\mathbf{#1}\message{Please use mathbf in math mode instead of bf.}\else\fontencoding{T1}\fontseries{b}\selectfont{#1}\fi}
\long\def\rm#1{\ifmmode\mathrm{#1}\message{Please use mathrm in math mode instead of rm.}\else\fontencoding{T1}\selectfont{#1}\fi}
}

Now your error can be easily replicated with a very minimal example, namely
\documentclass{ieeeaccess}
\begin{document}
\textbf{}
\end{document}

If the developers (rightly) don't want authors to use \bf they should simply disable it, not relying on faulty heuristics to "fix" the input.
What's the problem? \textbf{} is translated into {\bf} and \bf wants to find an argument, but the next token is }. So TeX is forced to issue the error message
! Argument of \bf has an extra }.

You can fix the problem in two ways: first one, simple, never use \textbf{}, but always have something between the braces. After all,
 \multicolumn{1}{|l|}{\textbf{}}

is a complicated way to say
 \multicolumn{1}{|l|}{}

which can actually be removed altogether.
Second way: reinstate the right definition of \textbf by saying
\DeclareTextFontCommand{\textbf}{\bfseries}
\DeclareTextFontCommand{\textit}{\itshape}

in the document preamble. I also added \textit, which is treated similarly in the class. You might also want to do
\AtBeginDocument{%
  \let\bf\undefined
  \let\it\undefined
  \let\rm\undefined
}

so you will get a better error message in case you use code sent to you by a coauthor who's not aware that the command have been deprecated for a quarter of a century.

Note: one could find that the initial statement in this answer is too harsh. Actually, I find it even too gentle.

A: The class ieeeaccess redefines \textbf by:
\def\textbf#1{{\bf #1}}
That's strange since \bf is deprecated in LaTeX. One should use \bfseries.
You can put the following line at the end of your preamble.
\def\textbf#1{{\bfseries #1}}
With that line, there is no error.
\documentclass{ieeeaccess}
\usepackage{graphicx} %<<<<<<<<<<<<<<< needed for ieeeaccess
\usepackage{multirow}

\def\textbf#1{{\bfseries #1}}

\begin{document}

    \begin{table}[h!]
        \centering
        \caption{table1}
        \begin{tabular}{|c|c|c|c|c|}
            \hline
    \textbf{Dataset}    & \textbf{Total News}    & \textbf{Fake}         &
    \multicolumn{2}{c|}{\textbf{Real}}       \\ \hline
    \textbf{PolitiFact} & 72                     & 36                    &
    \multicolumn{2}{c|}{36}                  \\ \hline
    \textbf{GossipCop}  & 100                    & 50                    &
    \multicolumn{2}{c|}{50}                  \\ \hline
    \multicolumn{1}{|l|}{\textbf{}} & \textbf{Total Tweets} & \textbf{Fake Tweets} & \multicolumn{2}{c|}{\textbf{Real Tweets}} \\ \hline
    \textbf{PolitiFact} & 5045                   & 3371                  &
    \multicolumn{2}{c|}{1674}                \\ \hline
    \textbf{GossipCop}  & 3636                   & 2489                  &
    \multicolumn{2}{c|}{1147}                \\ \hline
    \textbf{}           & \textbf{Total ML Rows} & \textbf{Fake Rows}    &
    \multicolumn{2}{c|}{\textbf{Real Rows}}  \\ \hline
    \textbf{PolitiFact} & 4085                   & 2972                  &
    \multicolumn{2}{c|}{1113}                \\ \hline
    \textbf{GossipCop}  & 3342                   & 2245                  &
    \multicolumn{2}{c|}{1097}                \\ \hline
    \textbf{}           & \textbf{Total Users}   & \textbf{In Fake Only} &
    \textbf{In Real Only} & \textbf{In Both} \\ \hline
    \textbf{PolitiFact} & 3865                   & 2763                  & 1081                  & 10               \\ \hline
    \textbf{GossipCop}  & 2564                   & 1706                  & 858                   & 8                \\ \hline
    \textbf{}           & \begin{tabular}[c]{@{}c@{}} \textbf{1st Degree}\\\textbf{Fake Followers}\end{tabular}   & \begin{tabular}[c]{@{}c@{}}
        \textbf{1st Degree}\\\textbf{Fake Followings}\end{tabular} & \begin{tabular}[c]{@{}c@{}} \textbf{1st Degree} \\\textbf{Real Followers}\end{tabular} &
    \begin{tabular}[c]{@{}c@{}}\textbf{1st Degree}\\\textbf{ Real Followings}\end{tabular} \\ \hline
    \textbf{PolitiFact} & 312M                   & 27M                  & 534M                   & 19M               \\ \hline
    \textbf{GossipCop}  & 209M                   & 19M                  & 378M                   & 12M                \\ \hline
\end{tabular}
\end{table}

\EOD  %<<<<<<<<<<<<<<< needed for ieeeaccess

\end{document}

However, a table in the spirit of booktabs would probably be more legible...

A: Your posted table compiles fine using the ieeeaccess class, as long as you remember to add  \EOD before \end {document}
The following four files should be in the working directory:
ieeeaccess.cls
IEEEtran.cls
bullet.png
notaglinelogo.png

% !TeX TS-program = pdflatex

\documentclass{ieeeaccess}
\usepackage{graphicx} %<<<<<<<<<<<<<<< needed for ieeeaccess
\usepackage{multirow}

\begin{document}
    \begin{table}[h!]
        \centering
        \caption{table1}
        \begin{tabular}{|c|c|c|c|c|}
            \hline
    \textbf{Dataset}    & \textbf{Total News}    & \textbf{Fake}         &
    \multicolumn{2}{c|}{\textbf{Real}}       \\ \hline
    \textbf{PolitiFact} & 72                     & 36                    &
    \multicolumn{2}{c|}{36}                  \\ \hline
    \textbf{GossipCop}  & 100                    & 50                    &
    \multicolumn{2}{c|}{50}                  \\ \hline
    \multicolumn{1}{|l|}{\textbf{}} & \textbf{Total Tweets} & \textbf{Fake Tweets} & \multicolumn{2}{c|}{\textbf{Real Tweets}} \\ \hline
    \textbf{PolitiFact} & 5045                   & 3371                  &
    \multicolumn{2}{c|}{1674}                \\ \hline
    \textbf{GossipCop}  & 3636                   & 2489                  &
    \multicolumn{2}{c|}{1147}                \\ \hline
    \textbf{}           & \textbf{Total ML Rows} & \textbf{Fake Rows}    &
    \multicolumn{2}{c|}{\textbf{Real Rows}}  \\ \hline
    \textbf{PolitiFact} & 4085                   & 2972                  &
    \multicolumn{2}{c|}{1113}                \\ \hline
    \textbf{GossipCop}  & 3342                   & 2245                  &
    \multicolumn{2}{c|}{1097}                \\ \hline
    \textbf{}           & \textbf{Total Users}   & \textbf{In Fake Only} &
    \textbf{In Real Only} & \textbf{In Both} \\ \hline
    \textbf{PolitiFact} & 3865                   & 2763                  & 1081                  & 10               \\ \hline
    \textbf{GossipCop}  & 2564                   & 1706                  & 858                   & 8                \\ \hline
    \textbf{}           & \begin{tabular}[c]{@{}c@{}} \textbf{1st Degree}\\\textbf{Fake Followers}\end{tabular}   & \begin{tabular}[c]{@{}c@{}}
        \textbf{1st Degree}\\\textbf{Fake Followings}\end{tabular} & \begin{tabular}[c]{@{}c@{}} \textbf{1st Degree} \\\textbf{Real Followers}\end{tabular} &
    \begin{tabular}[c]{@{}c@{}}\textbf{1st Degree}\\\textbf{ Real Followings}\end{tabular} \\ \hline
    \textbf{PolitiFact} & 312M                   & 27M                  & 534M                   & 19M               \\ \hline
    \textbf{GossipCop}  & 209M                   & 19M                  & 378M                   & 12M                \\ \hline
\end{tabular}
\end{table}

\EOD  %<<<<<<<<<<<<<<< needed for ieeeaccess

\end{document}

Using  \filelist
*File List*

ieeeaccess.cls
IEEEtran.cls    2015/08/26 V1.8b by Michael Shell
  ot1ptm.fd    2001/06/04 font definitions for OT1/ptm.
   ifpdf.sty    2019/10/25 v3.4 ifpdf legacy package. Use iftex instead.
   iftex.sty    2020/03/06 v1.0d TeX engine tests
 xkeyval.sty    2020/11/20 v2.8 package option processing (HA)
 xkeyval.tex    2014/12/03 v2.7a key=value parser (HA)
   color.sty    2020/02/24 v1.2b Standard LaTeX Color (DPC)
   color.cfg    2016/01/02 v1.6 sample color configuration
  pdftex.def    2020/10/05 v1.2a Graphics/color driver for pdftex
spotcolor.sty    2006/11/15 v1.2 Package for adding Spot Color support to pdfLa
TeX.
graphics.sty    2020/08/30 v1.4c Standard LaTeX Graphics (DPC,SPQR)
    trig.sty    2016/01/03 v1.10 sin cos tan (DPC)
graphics.cfg    2016/06/04 v1.11 sample graphics configuration
graphicx.sty    2020/09/09 v1.2b Enhanced LaTeX Graphics (DPC,SPQR)
multirow.sty    2021/03/15 v2.8 Span multiple rows of a table
l3backend-pdftex.def    2021-03-18 L3 backend support: PDF output (pdfTeX)
   t1ptm.fd    2001/06/04 font definitions for T1/ptm.
supp-pdf.mkii
epstopdf-base.sty    2020-01-24 v2.11 Base part for package epstopdf
epstopdf-sys.cfg    2021/03/18 v2.0 Configuration of epstopdf for MiKTeX
   t1phv.fd    2020/03/25 scalable font definitions for T1/phv.
  bullet.png    Graphic file (type png)
notaglineLogo.png    Graphic file (type png)
 ***********

Using MiKTex
This is pdfTeX, Version 3.141592653-2.6-1.40.22 (MiKTeX 21.3) (preloaded format=pdflatex 2021.4.2)  1 MAY 2021 11:37
entering extended mode
**./ieee_v3.tex
(ieee_v3.tex
LaTeX2e <2020-10-01> patch level 4
L3 programming layer <2021-02-18> (ieeeaccess.cls (IEEEtran.cls
Document Class: IEEEtran 2015/08/26 V1.8b by Michael Shell


text:
Q: basic structure question code not working I don't understand what is wrong with this code, a very basic doubt. Plz help
#include<stdio.h>
#include<stdlib.h>
typedef struct student{
    char name[20];
    int marks;
}student;
int main(){
    student s1;
    scanf("%s\n",s1->name);
    scanf("%d",&s1->marks);
    printf("%s",s1->name[0]);
    printf("%d",s1->marks);

return 0;
}

A: there is problem with structure object initialization
solution
typedef struct student{
    char name[20];
    int marks;
}student;
int main(){

    student *s1 = (student*)malloc(sizeof(student));

    //check is not null
    if(s1 == NULL)
    {
        printf("memory failed!.. \n");
    }

    printf("enter your name \n");

    //now read the user input as name
    scanf("%s", s1->name);

    printf("user input %s \n", s1->name);

      //now read the user input as name

    printf("enter your mask \n");

    scanf("%d", &s1->marks);

    printf("the mask %d \n", s1->marks);

return 0;
}

A: You need to use . not ->. The -> operator is for pointers.
There are a few other things to mention as well.
When reading strings with scanf("%s"), you should always provide the maximum length (which is 20-1=19 in this case) that should be read, otherwise you can get buffer overflow (scanf would write past the end of the array).
Also, please note that scanf("%s") only reads one word (it finishes when it finds whitespace). Therefore, you shouldn't tell scanf to read a \n, because if it doesn't find one after the string, it will be bad. The \n was probably meant for the call to printf instead.
When writing strings, you don't pass name[0], but just name. You pass name[0] only when printing characters, with %c.
#include<stdio.h>
#include<stdlib.h>
typedef struct student{
    char name[20];
    int marks;
}student;
int main(){
    student s1;
    scanf("%19s", s1.name);
    scanf("%d", &s1.marks);
    printf("%s\n", s1.name);
    printf("%d", s1.marks);
}


text:
Q: How can I solve the equation $x^3-x-1 = 0$? Can someone give me a hint on how can I solve the equation
$$x^3 - x - 1 =0?$$
Thank you!

A: I like to apply Cardano's method.
It can be used immediately (without a change of variable) because you have to find the roots of a depressed cubic.
Let $x=u+v$, where $u$ and $v$ are two complex variables that I'll define later.
Then your equation can be written
$$(u+v)^3-(u+v)-1=0\;.$$
By expanding, you find
$$u^3+3u^2v+3uv^2+v^3-u-v-1=0\;,$$
which can be written
$$u^3+v^3-1+(u+v)(3uv-1)=0\;.$$
Let's try to find $u$ and $v$ by imposing these two conditions:
$$u^3+v^3=1$$
$$uv=\dfrac 13$$
Then $x=u+v$ would clearly be a solution of your equation.
The second condition implies that $u^3v^3=\dfrac 1{27}$.
We know the sum $S$ and the product $P$ of the two numbers $U=u^3$ and $V=v^3$.
It's a well-known fact that $U$ and $V$ are the roots of the quadratic equation $X^2-SX+P=0$.
You can simply expand $(X-U)(X-V)$ if you're not convinced.
In our case, we have to solve for
$$X^2-X+\dfrac 1{27}=0\;.$$
When the real numbers $U$ and $V$ are found ($U$ can be either of the two roots), you can then find three possible complex values for $u$. If you want the real solution of your initial equation, then you simply take the real cubic root of $U$, and then $v$ is uniquely defined by $v=\dfrac 1{3u}$ (or you can also take the real cubic root of $V$ for $v$).
I found:
$$x=\sqrt[3]{\dfrac{9+\sqrt{69}}{18}}+\sqrt[3]{\dfrac{9-\sqrt{69}}{18}}\approx 1.325$$
The other cubic roots of $U$ are $ju$ and $j^2u$, where $j=e^{2i\pi/3}$ and $u$ is the real cubic root of $U$.

A: HINT:
Let $z=a\cos y, z^3-z=a^3\cos^3y-a\cos y$ where $a>0$
Comparing with $\cos3y=4\cos^3y-3\cos y$
$$\dfrac43=\dfrac{a^3}a\implies a=\dfrac2{\sqrt3}=\dfrac1{\cos30^\circ}$$
Now $\cos3x=\cos3A\implies3x=m360^\circ\pm3A$ where $m$ is any integer
$x=A,A+120^\circ,A+240^\circ$


text:
Q: Let $\mathcal C^{n}([a,b])$ be a space of functions on the interval Let $\mathcal C^{n}([a,b])$ be a space of functions on the interval $[a,b]$with the property that all derivatives up to n are continuous.
Define norm in which convergence of a sequence $(f_k)$ will be an uniform convergence for itself and for its all derivatives up to n.
As I recall metric defined as $d(f_k,f) = \sup_{t\in [a,b]}|f_k(t)-f(t)|$ is an uniform convergence metric. But what should we do with these n derivatives.
Is the norm $\Vert f \Vert = \sum_{i=0}^n(\sup_{t\in [a,b]}|f^{(i)}(t)|)$
an answer for that?


text:
Q: Use of "Coefficient of variation" to investigate cause and effect correlation? Thank you for looking in to my question.
I have 8 reactors in duplicate, I am measuring voltage (my result), call it "V", as well as a number of parameters (e.g. pH) call it "P" which may affect the result.
What is a proper method for statistically showing the correlation between "V" and "P" ?
I was thinking that the coefficient of variation, could be a valid way of showing a correlation between a deviation in parameters, and a deviation in results..
I could then use this to try and disprove that my results are significant ?
Other suggestions to statistical analysis are most welcome
thank you for your time

A: I guess you want quantify the association between variables $V$ and $P.$
By eight 'reactors', I suppose you mean you have eight values of $V$ and
eight matching values of $P.$
First, I would make a plot of the eight $V_i$ against their corresponding
$P_i.$ If the relationship is 'mainly' linear, then you should use the
coefficient of correlation $r$ to assess the association. (See the link.) By "linear"
I don't mean the points all need to lie exactly on a straight line; I mean
that a straight line should 'fit' the data better than some kind of simple curve.
The coefficient of correlation $r$ measures linear association.
If $r > 0,$ then $V$ increases as $P$ increases. If $r < 0$ then $V,$ decreases as $P$ increases. If $r \approx 0,$  then there is no linear association.
Always, $-1 \le r \le 1,$ where $r = \pm 1$ indicates perfect fit of the points
to a line. There is a statistical test to check whether the data are
consistent with $r = 0.$
If the relationship is steadily increasing or decreasing, but not mainly
linear, then Spearman's rank correlation may be more useful. (See the link.)
Here is a plot to illustrate these ideas. In the nearly linear plot at left
$r = .995.$ In the curved plot at right the coefficient of correlation $r = .964,$ but Spearman's rank coefficient $r_s = 1.$

Regression methods might allow you to find the best equation for expressing
$V$ in terms of $R$ (or $R$ in terms of $V$), or to predict the value of
one variable given the value of the other.
These are only vague statements for orientation. Without seeing your data and knowing what your objective is, it is very difficult to give specific advice.
If you have data, please post them with $V$ on one line, separated by commas,
and corresponding values of $R$ (same order) on another line, separated by
commas. Also say what you mean by a 'significant' finding. Then maybe I or
someone else on this site can give your further guidance.


text:
Q: Fill Consecutive NANs in a column of a dataframe I have a dataframe having a column C, I want to fill consecutive blanks by the same number because later I need to group that row.
eg
A B C
 1 2 Nan
 1 2 Nan
 1 2 3
 1 2 Nan
 1 2 Nan

the output I want is something like this
A B C
1 2 1
1 2 1
1 2 3
1 2 2
1 2 2

I tried using shift() to compare but didn't come to the desired output.

A: You can use fillna by new Series created by cumsum by boolean mask:
df['C'] = df['C'].fillna(df['C'].notnull().cumsum() + 1)

print (df)
   A  B    C
0  1  2  1.0
1  1  2  1.0
2  1  2  3.0
3  1  2  2.0
4  1  2  2.0

Detail:
print (df['C'].notnull().cumsum())
0    0
1    0
2    1
3    1
4    1
Name: C, dtype: int32

A: The function fillna is your solution:
dataframe['yourColumn'] = dataframe['yourColumn'] .fillna( 1 , inplace=True)

Moreover you can put whatever value you want to substitute the nan values.
For instance, you coul set the mean:
dataframe['yourColumn']= dataframe['yourColumn'].fillna(dataset['yourColumn'] .mean(), inplace=True)


text:
Q: How embedded CSS in transactional email works? I have a very frustrating issue with the Magento 2 sales order emails.  Through experimentation, I worked out the locations of the many files that are used to comprise these emails.
At some point, I edited what I believe was
/app/design/frontend/themefolders/web/source/_email-extend.less

to alter the CSS there to check if that makes a difference to the resulting sales emails.
The confusion I have is that sometimes editing this seems to influence the resulting emails, sometimes not.
My question is, how do I clarify for sure what .less / .css files are being used as the source for the CSS that I believe is embedded into emails.  I'm not sure if the normal css that is in the pub/static folders of magento comes into this or not.   Clarification about the exact source files for email css would be great.

A: Confusingly looks like a mixture of places
Have you tried viewing the source of one of your emails
A forgotten password email I generated using Luma US theme from the admin pulled this via import statement
@import url("http://magento2.docker/static/version1571346637/frontend/Magento/luma/en_US/css/email-fonts.css");

So pub/static
But then I spotted blockquote cite{font-style:normal} which is a bit unusual and easy to search for.
I found this inside
var/view_preprocessed/pub/static/frontend/Magento/luma/en_US/css/email-inline.css
which is built from
vendor/magento/theme-frontend-blank/web/css/email-inline.less
I've read you can override these
Add your custom styles here for common emails:
app/design/frontend/Vendor/Theme/web/css/source/_email-extend.less

Add your custom less variables here for common emails :
app/design/frontend/Vendor/Theme/web/css/source/_email-variables.less

Add your custom styles here for sales emails :
app/design/frontend/Vendor/Theme/Magento_Sales/web/css/source/_email.less

Note: I'm a backend dev.  I won't be able to confirm this for you but logically makes sense.

A: Found this in Magento Documentation this might be a good read. This explains at least How to Style Email Templates and how email styles are organized.

A: You need to override below two css files from Magento default blank theme to you custom theme and editing those files.

Magento_Blank_theme_dir/web/css/source/_email-extend.less
Magento_Blank_theme_dir/web/css/source/_email-variables.less

Your custom theme css path will be below

app/design/frontend/Vendor/Theme/web/css/source/_email-extend.less

and

app/design/frontend/Vendor/Theme/web/css/source/_email-variables.less

and for sales email

app/design/frontend/Vendor/Theme/Magento_Sales/web/css/source/_email.less

you can check this magento devdoc link for reference.
https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/templates/template-email.html


text:
Q: Populate a Dropdown in a Dynamic Form in Angular 2 I have this scenario :
This is my FieldDefinition
 export interface FieldDefinition {
    key: string,
    type: string,
    isId: boolean,
    label: string,
    required: boolean
 }

This is the Dynamic Field definition

  {{ field.label }}
  <textarea class="form-control" [formControlName]="field.key" [id]="field.key"
          [readonly]="operation == 'details' || field.isId"></textarea>

  {{ field.label }}
  <input class="form-control" [formControlName]="field.key" [id]="field.key"
          [readonly]="operation == 'details' || field.isId"
          type="number">

  {{ field.label }}
  <select [id]="field.key"
          [formControlName]="field.key">
    <option *ngFor="let opt of field.options"
            [value]="opt.key">
      {{opt.value}}
    </option>
  </select>

  {{ field.label }} is required.

The ts file :
 import { Component, Input, OnInit } from '@angular/core';
 import { FormGroup } from '@angular/forms';
 import { FieldDefinition } from '../field-definition';

 @Component({
    selector: 'fw-dynamic-field',
    templateUrl: './dynamic-field.component.html',
    styleUrls: ['./dynamic-field.component.css']
})
export class DynamicFieldComponent {
   @Input() field: FieldDefinition;
   @Input() form: FormGroup;
   @Input() operation: string;
   @Input() submitted: boolean;

   get isValid() { return this.form.controls[this.field.key].valid; }

   constructor() { }
 }

The Dynamic Form html
  <form (ngSubmit)="onSubmit()" [formGroup]="form">

  <fw-dynamic-field [field]="field"
                    [form]="form"
                    [operation]="operation"
                    [submitted]="submitted">
  </fw-dynamic-field>

  {{ errorMessage }}

    <button type="button" class="btn" (click)="onBack()" >Back</button>
    <button type="button" class="btn btn-primary" (click)="onEdit()" >Edit</button>

    <button type="button" class="btn" (click)="onCancel()" >Cancel</button>
    <button type="button" class="btn btn-primary" (click)="onSave()" >Save</button>

    <button type="button" class="btn" (click)="onBack()" >Back</button>
    <button type="button" class="btn btn-primary" (click)="onCreate()" >Create</button>

</form>

And the ts file :
 export class DynamicFormComponent implements OnChanges, OnInit {

 @Input() vm: any;
 @Input() vmDefinition: Array<FieldDefinition>;
 @Input() operation: string;
 @Input() errorMessage: string;
 @Output() update: EventEmitter<any> = new EventEmitter();
 @Output() create: EventEmitter<any> = new EventEmitter();

 form: FormGroup;
 status: string;
 submitted = false;
 vmCopy: any;

  constructor(private router: Router,
          private route: ActivatedRoute,
          private location: Location) { }

  clearForm() {
    const group = {};
    this.vmCopy = Object.assign({}, this.vm);
    this.vmDefinition.forEach(field => {
      group[field.key] = field.required ? new FormControl(this.vmCopy[field.key], Validators.required)
    : new FormControl(this.vmCopy[field.key]);
   });
   this.form = new FormGroup(group);
 }

 ngOnChanges(changes: SimpleChanges) {
     if (changes['errorMessage'].currentValue && this.status === 'waiting') {
      this.status = '';
     }
 }

 ngOnInit() {
    this.clearForm();

    this.route.params.subscribe(params => {
       this.operation = params['operation'];
       this.clearForm();
     });
 }

I'm trying to use this dynamic form in my book-detail page but I'm having problems with populating the dropdown
 export class BookDetailComponent implements OnInit {
  book: Book;
  books: IBook[];
  authors: IAuthor[];
  categories: ICategory[];
  errorMessage: string;

  bookDefinition: Array<FieldDefinition> = [
   {
      key: 'bookId',
      type: 'number',
      isId: true,
      label: 'BookId',
      required: true
   },
  {
      key: 'title',
      type: 'string',
      isId: false,
     label: 'Title',
     required: true
  },
  {
     key: 'authors',
     type: '[]',
     isId: false,
     label: 'Authors',
     required: false
  },
  {
     key: 'categories',
     type: '[]',
     isId: false,
     label: 'Categories',
     required: false
  }
];
operation: string;

constructor(private route: ActivatedRoute,
  private router: Router,
  private bookService: BookService,
  private authorService: AuthorService,
  private categoryService: CategoryService) { }

 ngOnInit(): void {

   this.operation = this.route.snapshot.params['operation'];
   this.authorService.getAuthors()
  .subscribe((authors: IAuthor[]) => { this.authors = authors });

   this.categoryService.getCategories()
  .subscribe((categories: ICategory[]) => { this.categories = categories });

  if (this.operation === 'create') {
    this.book = { bookId: 0, title: '', authors: this.authors, categories:
   this.categories };
  } else {
   this.bookService.getBook(this.route.snapshot.params['id'])
    .subscribe((book: Book) => { this.book = book });
 }
}

And in the book-detail-component.html I have this

Book

<fw-dynamic-form *ngIf='book' [vm]="book" [vmDefinition]="bookDefinition"
[operation]="operation"
[errorMessage]="errorMessage"
(update)="updateBook($event)"
(create)="createBook($event)">

It works fine with the other fields but I have problems with the dropdowns for authors and categories. First of all how can I make the getAuthors and getCategories calls in one subscribe ? And then how can I append the values to the dropdowns ? I should create a dropdownField and set it to the field type ? Because I don't have the options property on the field now..
Thanks a lot !
UPDATE :
I created this :
import { FieldDefinition } from './field-definition';

export class DropdownField extends FieldDefinition {
 type: 'dropdown';
 options: { key: number, value: string }[] = [];

constructor(options: {} = {}) {
  super();
 this.options = options['options'] || [];
 }
 }

And I tried to use it in the book-detail-component to populate the dropdown for Authors and the dropdown for Categories
ngOnInit(): void {

this.operation = this.route.snapshot.params['operation'];

this.authorService.getAuthors()
  .subscribe((authors: IAuthor[]) => {
    this.authors = authors,
      authors.forEach(function (author) {
      this.authorDropdown.options = [{ key: this.author.authorId, value: this.author.authorName }]
      });
  });

this.categoryService.getCategories()
  .subscribe((categories: ICategory[]) => { this.categories = categories, console.log(this.categories) });

if (this.operation === 'create') {
  this.book = { bookId: 0, title: '', authors: this.authorDropdown, categories: this.categories };
} else {
  this.bookService.getBook(this.route.snapshot.params['id'])
    .subscribe((book: Book) => { this.book = book });
}
}

Still doesn't work..
Update 2
export class BookDetailComponent implements OnInit {
  book: Book;
  author: Author;
  books: IBook[];
  authors: IAuthor[];
  categories: ICategory[];
  errorMessage: string;

  bookDefinition: Array<FieldDefinition> = [
     {
       key: 'bookId',
       type: 'number',
       isId: true,
       label: 'BookId',
       required: true
     },
     {
       key: 'title',
       type: 'string',
       isId: false,
       label: 'Title',
       required: true
     },
     {
       key: 'authors',
       type: '[]',
       isId: false,
       label: 'Authors',
       required: false
     },
     {
       key: 'categories',
       type: '[]',
       isId: false,
       label: 'Categories',
       required: false
     }
    ];
  operation: string;
  authorDropdown: DropdownField;
  categoryDropdown: DropdownField;

 constructor(private route: ActivatedRoute,
     private router: Router,
     private bookService: BookService,
     private authorService: AuthorService,
     private categoryService: CategoryService) { }

 ngOnInit(): void {
    this.operation = this.route.snapshot.params['operation'];
    this.authorService.getAuthors()
      .subscribe((authors: IAuthor[]) => {
      this.authors = authors,
      authors.forEach(function (author) {
      this.authorDropdown.options.push({ key: this.author.authorId, value: this.author.authorName });
      });
      console.log(this.authorDropdown);
   });

if (this.operation === 'create') {
  this.book = { bookId: 0, title: '', authors: this.authorDropdown, categories: [] };
} else {
  this.bookService.getBook(this.route.snapshot.params['id'])
    .subscribe((book: Book) => { this.book = book });;
}
}

A: That's the correct way to do it, your code just add the last element when you are iterating authors array now  you are going to have appended every element from authors here this.authorDropdown.options by using push.
this.authorService.getAuthors()
  .subscribe((authors: IAuthor[]) => {
    this.authors = authors,
      authors.forEach(function (author) {

      this.authorDropdown.options
      .push({ key: this.author.authorId, value: this.author.authorName });

      });

  });


text:
Q: How to execute a correct cleanup of GPIO and SPI on Raspberry Pi using Python I'm experimenting with wireless communication using NRF24L01+ between Arduino and Raspberry Pi. I'm able to establish the connection and send the data to RPi but when I stop and start my program no data are received. No error or warning message is displayed. After reboot works everything fine so I think there is something wrong with my cleanup code.
Here is my code:
import RPi.GPIO as GPIO
import time
import spidev
from libs.lib_nrf24 import NRF24

try:

    GPIO.setmode(GPIO.BCM)

    pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]
    radio = NRF24(GPIO, spidev.SpiDev())
    radio.begin(0, 25)
    radio.setPayloadSize(32)
    radio.setChannel(0x76)
    radio.setDataRate(NRF24.BR_250KBPS)
    radio.setPALevel(NRF24.PA_MIN)
    radio.setAutoAck(True)
    radio.enableDynamicPayloads()
    radio.enableAckPayload()
    radio.openReadingPipe(1, pipes[1])
    radio.printDetails()
    radio.startListening()

    while True:

        while not radio.available(0):
            time.sleep(1/100)

        receivedMessage = []
        radio.read(receivedMessage, radio.getDynamicPayloadSize())
        print("Received: {}".format(receivedMessage))

        print("Translating our received Message into unicode characters...")
        string = ""

        for n in receivedMessage:
            if (n >= 32 and n <= 126):
                string += chr(n)
        print("Our received message decodes to: {}".format(string))

finally:
    print("Performing cleanup...")
    radio.end()
    GPIO.cleanup()
    print("Cleanup done...")

The library lib_nrf24 I'm using is this one: https://github.com/BLavery/lib_nrf24
Output from radio.printDetails() is displayed correctly in both cases.
I'm stopping the program using Ctrl+C and both messages are printed - Performing cleanup... and also Cleanup done...
How should I perform the cleanup to be able to run my program multiple times without rebooting the RPi? Or is there some other error in my code?
Thanks for your help


text:
Q: How can I solve $(y+2)^2 y' + (x + 2y + 3)^2 = 0 $? I'm stuck trying to solve this ODE and I wonder if someone can help, thanks in advance. The ODE is the following:
$$(y+2)^2 y' + (x + 2y + 3)^2 = 0 $$
I first tried expanding the squared terms and trying to separate the variables but it was not very helpful. Then I noticed that the equation is homogenious but trying to make a substitution got me nowhere. Thanks for your help.

A: As given, it is not homogeneous, but you can make a substitution to make it homogeneous: $Y = y+2$, $X = x - 1$

A: Hint :
Substitute $y=Y+k$, $x=X+h$ to do away with the constant terms. Then this will reduce to homogeneous form when the substitution $Y=VX\Rightarrow Y'=V+XV'$ works.
On first substituion, you will find $k=-2, h=1$.


text:
Q: Maximize $x^\intercal\,A\,x$ Let $A \in \mathbb{R}^{n \times n}$ be a symmetric matrix. I'm trying to find the $x \in \mathbb{R}^n$ with $\lVert x \rVert = 1$ so that $x^\intercal\,A\,x$ is maximized. Intuitively, I'd say that this is the case if $x$ is the normalized eigenvector corresponding to the largest eigenvalue of $A$.
Is this correct? If so, how would I prove it?
EDIT: What about the following:
$x^\intercal\,A\,x = x^\intercal\,(\frac12 A + \frac12 A) x = \frac12x^\intercal\,A + \frac12\,A\,x = \frac12\,A\,x + \frac12\,A\,x = A\,x$
Then the claim is obvious knowing that $A$ has real eigenvalues?

A: Yes, you are correct. Use the following hint to prove it.
Hint: Use the eigenvalue decomposition of $A=U^T\Lambda U$ and define $y=Ux$, so that $||y||=||x||=1$

A: You are indeed correct that the maximized value of $x^\intercal\,A\,x$ would be the largest eigenvalue of A and the normalized eigenvector that corresponds to it.
Have you studied quadratic forms? And how diagonal matrices will relate to them?


text:
Q: mqtt mosca pahojs WebSocket connection to 'ws://localhost:1884/mqtt' failed/timeout Broker
var mosca = require('mosca')

var settings = {
  port: 1884
};

//here we start mosca
var server = new mosca.Server(settings);
server.on('ready', setup);

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running')
}

// fired whena  client is connected
server.on('clientConnected', function(client) {
  console.log('client connected', client.id);
});

// fired when a message is received
server.on('published', function(packet, client) {
  if (packet.cmd === 'publish') {
    //Qui uso mongo DB
    console.log('Published: ', packet.payload.toString('utf8'));
  }
});

// fired when a client subscribes to a topic
server.on('subscribed', function(topic, client) {
  console.log('subscribed : ', topic);
});

// fired when a client subscribes to a topic
server.on('unsubscribed', function(topic, client) {
  console.log('unsubscribed : ', topic);
});

// fired when a client is disconnecting
server.on('clientDisconnecting', function(client) {
  console.log('clientDisconnecting : ', client.id);
});

// fired when a client is disconnected
server.on('clientDisconnected', function(client) {
  console.log('clientDisconnected : ', client.id);
});

client.html
<html>
  <head>
        <meta charset="utf-8" />
  </head>
  <body>
    <script src="./mqttws3.1.js"></script>
      <script>
  var client = new Paho.MQTT.Client( 'localhost', 1884, 'clientId');

  client.onConnectionLost = onConnectionLost;
  client.onMessageArrived = onMessageArrived;
  client.connect({onSuccess:onConnect});

  function onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  client.subscribe("/World");
  message = new Paho.MQTT.Message("Hello");
  message.destinationName = "/World";
  client.send(message);
};
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0)
  console.log("onConnectionLost:"+responseObject.errorMessage);
};
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
  client.disconnect();
};
      </script>
    </body>
</html>

I run the broker
node broker

than I call the client.html by a web server
like
http://localhost/client.html

I get after a while

Firefox can't establish a connection to the server at
  ws://localhost:1884/mqtt. this.socket = new WebSocket(wsurl,
  ["mqtt"]);
Chrome : WebSocket connection to 'ws://localhost:1884/mqtt' failed:
  WebSocket opening handshake timed out

I don't know which way to turn :(
Can you help me please ?

A: Have a look at this:
https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets
It looks like you have just started a normal MQTT listener not a WS listener.
You need to add a http block to the settings:
var settings = {
  http: {
    port: 1884,
    bundle: true,
    static: './'
  }
};


text:
Q: How to Automock for existing mock object? In my existing project, I am using xunit. Currently, it's very irritating to mock each instant in service. So I decided to use AutoMock but my project is very vast and I have already done a lot of code and assigned a lot of values. So is this any way that without changing existing mock object I can use AutoMock?
Below is my existing code sample.
I am planning to use AutoFac
Currently, if I want to set up any value I am doing
bordereauFormatsRepositoryMock
    .Setup(x => x.GetBordereauFormats(It.IsAny<List<string>>()))
    .Returns(botFormatsVMList);*

In AutoMock -
mock.Mock<IBordereauFormatsRepository>()
    .Setup(x => x.GetBordereauFormats(It.IsAny<List<string>>()))
    .Returns(botFormatsVMList)*;

So How can I assign bordereauFormatsRepositoryMock to mock.Mock<IBordereauFormatsRepository>()?
public BotMockTest()
{
    #region Object initialization
    botFormatsVMList = new List<BotFormatsVM>();
    botFormatsVM = new BotFormatsVM();
    botService = new BotService(bordereauFormatsRepositoryMock.Object, bordereauFormatColumnRepositoryMock.Object, contractRepository.Object, bordereauxRepositoryMock.Object, exceptionLogServiceMock.Object);
    #endregion
}

[FactWithAutomaticDisplayName]
public void GetBordereauFormats()
{
    //Arrange
    List<string> sheetList = new List<string>() { { "sheet" } };
    botFormatsVM.BordereauFormatId = Guid.Parse("847AE6BD-C20E-4377-8F56-36D58674C961");
    botFormatsVMList.Add(botFormatsVM);
    bordereauFormatsRepositoryMock.Setup(x => x.GetBordereauFormats(It.IsAny<List<string>>())).Returns(botFormatsVMList);

    //Act
    botService.GetBordereauFormats(sheetList);

    //Assert
    Assert.True(botFormatsVM.BordereauFormatName == "UpdatedVal");
}


text:
Q: How to clear form after submit in vuejs I am trying to empty the form after it submits form but I am unable to do this. Here is the code
<form class="form-horizontal" @submit.prevent="addtodirectory" id="form-directory">

                Name

                 <input v-model="form.name" type="text" name="name"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
                     <has-error :form="form" field="name"></has-error>

                Address

                 <textarea v-model="form.address" type="text" name="address"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('address') }"></textarea>
                     <has-error :form="form" field="address"></has-error>

                Profession

                 <input v-model="form.profession" type="text" name="profession"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('profession') }">
                     <has-error :form="form" field="profession"></has-error>

                Contact Number

                 <input v-model="form.contact_number" type="text" name="contact_number"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('contact_number') }">
                     <has-error :form="form" field="contact_number"></has-error>

                City

                 <input v-model="form.city" type="text" name="city"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('city') }">
                     <has-error :form="form" field="city"></has-error>

                State

                 <select v-model="form.state" type="text" name="state"
                      class="form-control" :class="{ 'is-invalid': form.errors.has('state') }">
                     <has-error :form="form" field="state"></has-error>
                 <option value="Rajasthan">Rajasthan</option>
                 <option value="Gujrat">Gujrat</option>

                 </select>

              <button type="submit" class="btn btn-success">Submit</button>
              <button type="submit" class="btn btn-default float-right">Cancel</button>

          </form>


text:
Q: 0 1 matrix balancing On wikipedia http://en.wikipedia.org/wiki/Dynamic_programming#A_type_of_balanced_0.E2.80.931_matrix, counting the number of 0 1 balanced matrices is given as an example of dynamic programming. But I found it really hard to implement the algorithm given there. Is there a better algorithm?
If not, then can anyone kindly explain the algorithm presented there in a way that makes it easier to implement. Like what would be the recurrence relation in this algorithm? Because once I have found it, it would be easy to do memoization.
Also can any one tell that why this particular problem seems so much harder than all the other problems given on that page.

A: Dynamic programming would be faster, but here is a simple way for enumeration.
Balanced matrix: bicolorable 0-1 matrix. Here s is the dimension of the 0-1 balanced square matrix, L[p][q] is an entry of the matrix. Initially call enumerate(s,1,1).
int enumerate(int s, int p,int q){

    if(p>s) {
             printmatrix(L);
             return 0;
    }

    if(p>=3 && q>=3){
            int min = p;if(p>q){min=q;}
            if L[1...min][1...min] is not a balanced matrix, then return 0;
    }
    if(q<=s) {
            L[p][q] = 1;
            enumerate(s,p,q+1);
            if(p!=q){
                     L[p][q] = 0;
                     enumerate(s,p,q+1);
            }
    }
    if(q>s) {
            enumerate(s,p+1,1);
    }
    return 0;
}

A: Dynamic programming solution
import java.util.HashMap;
import java.util.Map;

public class Balanced01Matrix {

    //Variable to hold all possible row permutation
    private int[][] rowPerms;

    //Mapping function f((n/2,n/2),(n/2,n/2)......(n/2,n/2))
    Map<String, Integer> arrangeFunction;

    int rowCounter = 0;

    /**
     * @param args
     */
    public static void main(String[] args) {
        Balanced01Matrix bm = new Balanced01Matrix();
        int n = 4;
        int rows = bm.combination(n, n/2);
        bm.rowPerms = new int[rows][n];
        //Getting all the row permuation with n/2 '0' and n/2 '1'
        bm.getAllCombination(n/2, n/2, n, new int[n]);
        //bm.printAllCombination();
        bm.arrangeFunction = new HashMap<String, Integer>();
        //Variable to hold vector ((n/2,n/2),(n/2,n/2),......(n/2,n/2))
        int[][] digitsRemaining = new int[n][2];
        for(int i=0;i<n;i++){
            digitsRemaining[i][0]=n/2;
            digitsRemaining[i][1]=n/2;
        }
        //Printing total number of combination possible for nxn balanced matrix
        System.out.println(bm.possibleCombinations(digitsRemaining, n));
    }

    /**
     * Method to get all permutation of a row with n/2 zero and n/2 one
     * @param oneCount
     * @param zeroCount
     * @param totalCount
     * @param tmpArr
     */
    private void getAllCombination(int oneCount, int zeroCount, int totalCount, int[] tmpArr){
        if(totalCount>0){
            if(oneCount > 0){
                tmpArr[totalCount-1] = 1;
                getAllCombination(oneCount-1, zeroCount, totalCount-1, tmpArr);
            }
            if(zeroCount > 0){
                tmpArr[totalCount-1] = 0;
                getAllCombination(oneCount, zeroCount-1, totalCount-1, tmpArr);
            }
        }else{
            rowPerms[rowCounter++] = tmpArr.clone();
        }

    }

    /**
     * Recursive function to calculate all combination possible for a given vector and level
     * @param digitsRemaining
     * @param level
     * @return
     */
    private int possibleCombinations(int[][] digitsRemaining, int level){
        //Using memoization
        if(arrangeFunction.containsKey(getStringForDigitsRemaining(digitsRemaining))){
            return arrangeFunction.get(getStringForDigitsRemaining(digitsRemaining));
        }
        int totalCombination = 0;
        for(int[] row: rowPerms){
            int i=0;
            int[][] tmpArr = createCopy(digitsRemaining);
            for(;i<row.length;i++){
                if(row[i]==0){
                    if(tmpArr[i][0] - 1 >= 0){
                        tmpArr[i][0] -= 1;
                    }else
                        break;
                }else{
                    if(tmpArr[i][1] - 1 >= 0){
                        tmpArr[i][1] -= 1;
                    }else
                        break;
                }
            }
            //If row permutation is successfully used for this level
            //else try next permuation
            if(i==row.length){
                //If last row of matrix return 1
                if(level == 1){
                    return 1;
                }else{
                    int combinations = possibleCombinations(tmpArr, level-1);
                    arrangeFunction.put(getStringForDigitsRemaining(tmpArr), combinations);
                    totalCombination += combinations;
                }
            }
        }
        return totalCombination;
    }

    /**
     * Creating deep copy of 2 dimensional array
     * @param arr
     * @return
     */
    private int[][] createCopy(int[][] arr){
        int[][] newArr = new int[arr.length][arr[0].length];
        for(int i=0;i<arr.length;i++){
            for(int j=0;j<arr[0].length;j++){
                newArr[i][j] = arr[i][j];
            }
        }
        return newArr;
    }

    private void printRow(int[] row){
        for(int i: row)
            System.out.print(i);
    }

    private String getStringForDigitsRemaining(int[][] digitsRemaining){
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<digitsRemaining.length;i++){
            sb.append(digitsRemaining[i][0]);
            sb.append(digitsRemaining[i][1]);
        }
        return sb.toString();
    }

    /**
     * Calculates x choose y
     * @param x
     * @param y
     */
    private int combination(int x, int y){
        if(x>0 && y>0 && x>y)
            return factorial(x)/(factorial(y)*factorial(x-y));
        else
            return 0;
    }

    private int factorial(int x){
        if(x==0)
            return 1;
        return x*factorial(x-1);

    }

    private void printAllCombination(){
        for(int[] arr: rowPerms){
            for(int i: arr)
                System.out.print(i);
            System.out.println();
        }

    }

}


text:
Q: Hacer un modificar y eliminar desde android estudio una base de datos en SQL Server? Estoy creando una app, que haga un registro de productos y lo hace a la perfección, luego lo busque los productos y también lo hace el problema empieza al momento de querer modificar ya que lo intente, pero el código que hice no hace nada solo me dice que fue modificado pero no lo fue y no he podido hacer tampoco el eliminar, y el código es el siguiente, necesito que el método modificar y eliminar...
Estoy creando una app, que haga un registro de productos y lo hace a la perfección, luego lo busque los productos y también lo hace el problema empieza al momento de querer modificar ya que lo intente, pero el código que hice no hace nada solo me dice que fue modificado pero no lo fue y no he podido hacer tampoco el eliminar, y el código es el siguiente, necesito que el método modificar y eliminar...
   package com.example.e_foot;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class registro extends AppCompatActivity {

    private EditText txt_id,txt_nombre,txt_descripcion,txt_precio;
    private Button agregar,modificar,buscar,eliminar;

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

        txt_id = (EditText)findViewById(R.id.txt_idAg);
        txt_nombre = (EditText)findViewById(R.id.txt_nombreAg);
        txt_descripcion = (EditText)findViewById(R.id.txt_descripcion);
        txt_precio = (EditText)findViewById(R.id.txt_precioAg);

        agregar = (Button)findViewById(R.id.button_agregar);
        agregar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                agregarComida();
            }
        });

        buscar = (Button)findViewById(R.id.button_buscar);
        buscar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Buscar();
            }
        });

        modificar = (Button)findViewById(R.id.button_moficar);
        modificar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Modificar();

            }
        });

    }

    //Conexion a la base de datos
    public Connection connection(){

        Connection connection = null;
        try{

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection("jdbc:jtds:sqlserver://DESKTOP-6G1JRJF:1433;databaseName=EfootDataBase;user=adminEFOOT;password=321");

        }catch (Exception e){

            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        return connection;
    }

    //agregar
    public void agregarComida() {

        String codigo = txt_id.getText().toString();
        String nombreP = txt_nombre.getText().toString();
        String ingredientes = txt_descripcion.getText().toString();
        String precioP = txt_precio.getText().toString();

        if(!codigo.isEmpty() && !nombreP.isEmpty() && !ingredientes.isEmpty() && !precioP.isEmpty()){

            try{

                PreparedStatement pst = connection().prepareStatement("insert into Productos values(?,?,?,?)");

                int precio = Integer.parseInt(txt_precio.getText().toString());
                int codigoP = Integer.parseInt(txt_id.getText().toString());
                pst.setInt(1,codigoP);
                pst.setString(2,txt_nombre.getText().toString());
                pst.setString(3,txt_descripcion.getText().toString());
                pst.setInt(4,precio);
                pst.executeUpdate();

                txt_id.setText("");
                txt_nombre.setText("");
                txt_descripcion.setText("");
                txt_precio.setText("");

                Toast.makeText(this, "Registro Exitoso", Toast.LENGTH_SHORT).show();

            }catch (Exception e){

                Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();

            }
        }else{

            Toast.makeText(this, "Llene todos los campos", Toast.LENGTH_SHORT).show();

        }
    }

    //Buscar
    public void Buscar(){

        int save_id = Integer.parseInt(txt_id.getText().toString());

        try{

            Statement stm = connection().createStatement();
            ResultSet rs = stm.executeQuery("SELECT * FROM Productos WHERE ID LIKE " + save_id);
            while (rs.next()){

                txt_nombre.setText(rs.getString("Nombre"));
                txt_descripcion.setText(rs.getString("descripcion"));
                txt_precio.setText(rs.getString("precio"));

            }

        }catch (Exception e){

            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();

        }
    }

    //Modificar
    public void  Modificar(){

        int save_id = Integer.parseInt(txt_id.getText().toString());

        try{

            Statement stm = connection().createStatement();
            ResultSet rs = stm.executeQuery("SELECT * FROM Productos WHERE ID LIKE " + save_id);

            while (rs.next()){

                    txt_nombre.setText(rs.getString("Nombre"));
                    txt_descripcion.setText(rs.getString("descripcion"));
                    txt_precio.setText(rs.getString("precio"));

                    Toast.makeText(this, "Modificado corrctamente", Toast.LENGTH_SHORT).show();

                }

            }catch (Exception e){

                Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();

            }

        }

    }

A: fijate en tu funcion Modificar(), estas haciendo un select y lo que tienes que hacer es:
update "UPDATE "NOMBRE DE TABLA" SET "NOMBRE COLUMNA"= "NUEVO VALOR" WHERE "COLUMNA" = "CONDICION PARA ACTUALIZAR"".


text:
Q: Definite integral evaluation of $\frac{\sin^2 x}{2^x + 1}$
Compute
$$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \frac{\sin^2 x}{2^x + 1} \ dx.$$

So looking at the limits I first checked whether the function is even or odd by substituting $x = -x$ but this gave me:
$$\frac{\sin^2 x}{2^x + 1} \cdot 2^x$$
so the function is clearly neither odd or even and I don't know what to infer from this. I can't think of a good substitution either.
Any help would be appreciated!

A: You did the right thing. Using your substitution, you have
$$
I = \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \frac{\sin^2 x}{2^x + 1} \ dx = \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \frac{\sin^2 x}{2^x + 1} 2^x \ dx.
$$
Adding the two equivalent formulations you have
$$
2 I = \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \frac{\sin^2 x}{2^x + 1} (2^x +1) \ dx
= \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}{\sin^2 x} \ dx = \int_0^{\frac{\pi}{2}} (1-\cos(2x))\ dx=\frac{\pi}{2}$$
which gives $I = \frac{\pi}{4}$ as the answer.

A: This video provides a formula that is very useful in your case, check the video for a proof: https://www.youtube.com/watch?v=xiIsPEqyTqU
$$\int_{-a}^{a} \frac{E(x)}{t^{O(x)} + 1} \ dx = \int_{0}^{a} E(x) \ dx$$
where $E(x)$ and $t$ are even functions, and $O(x)$ is an odd function. In your case: $\sin^2(x)=E(x); x = O(x)$, and so your integral simplifies to:
$$\int_{0}^{\pi/2} \sin^2(x) \ dx = \pi/4$$

A: Let $$\;I=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \dfrac{\sin^2 x}{2^x+1} dx\;.$$
By substituting $\;x\to -x\;$ we get that $$I=-\int_{\frac{\pi}{2}}^{-\frac{\pi}{2}} \dfrac{\sin^2 x}{2^{-x}+1} dx=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \dfrac{2^x\sin^2 x}{2^x+1} dx=\\=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\left(\sin^2 x -\dfrac{\sin^2 x}{2^x+1}\right)dx=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\sin^2 x\ dx-I\;.$$
Since
$$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\sin^2 x\ dx=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\dfrac{1-\cos(2x)}{2}dx=\\=\frac{x}{2}-\dfrac{\sin(2x)}{4}\bigg|_{-\frac{\pi}{2}}^{\frac{\pi}{2}}=\cfrac{\pi}{2}\;,$$
we get that $\;I=\cfrac{\pi}{2}-I\;,\;$ hence
$I=\cfrac{\pi}{4}\;.$


text:
Q: panda loc with mulitple boolean conditions to create subset I want to create a subset dataframe containing all the rows when the row 'Name' is Sam or Frank. I run the following code but it returns no data:
df.loc[(df["Name"] == 'Sam') & (df["Name"] =='Frank'), :]

How can I change the code to work?


text:
Q: If $J$ is the ideal generated by all idempotents in a prime ideal, then $R/J$ has only trivial idempotents Let $R$ be a commutative ring with identity, $P$ be a prime ideal in $R$ and define
$$X := \lbrace t \in P \mid t^2=t \rbrace. $$
Also let $J$ denote the smallest ideal of $R$ that contains $X$.
Prove that if $$a^2+J=a+J$$ in $R/J$, then $$a+J=J$$ or $$a+J=1+J$$
I am trying to solve this but I am new to algebra (aprox. 3 months), so I generally don't know how to start such questions. So any help is appreciated.

A: First note that $J$ is the ideal generated by all idempotents in $P$, so $J\subset P$.
Since $a^2-a\in J$ we have $a^2-a=a_1t_1+\cdots+a_nt_n$ with $t_i\in P$, $t_i^2=t_i$. Then $(1-t_1)\cdots(1-t_n)(a^2-a)=0$, so $(1-t)(a^2-a)=0$ for some $t\in P$, $t^2=t$. (In particular, $t\in J$.)
Since $a^2-a\in P$ we have two possibilities:
$(i)$ $a\in P$; from $(1-t)(a^2-a)=0$ we get $a-ta=(a-ta)^2$, so $a-ta\in J$, and thus $a\in J$;
$(ii)$  $1-a\in P$; similarly $(1-a)-t(1-a)$ is idempotent, so $1-a\in J$.


text:
Q: I have a JS script in my php file, and it does not seem to be executing This started after I converted this same script which was previously laid out in PHP to JS (I tried to change all the syntax.)
I have tried running it how it is within the php file and it didn't work :

<title>Learn | A Level Scientist</title>
<link rel="shortcut icon" href="http://www.iconj.com/ico/f/0/f0ghi1ksdc.ico" type="image/x-icon" />

<?php
    include 'C:\xampp\htdocs\ALevelScientistTesting\menubar.php' ;
?>

 Working out Relative Formula/Molecular Masses

 Go to the Next Exercise =>

    <?php
     //echo 'The '.$CoMo.' : '.$SubName[$FormNo].' Has a Relative '.$FoMo.' Mass of : '.$x;
    //echo '
 Work out the Relative '.$FoMo.' Mass of the '.$CoMo.' : '.$SubName[$FormNo] ;
    ?>

    <form id="useranswer">
        Enter Your Answer Here

        <input type="text" id="useranswer">

        <input type="submit" id="usersubmit" value="Check Answer">

    </form>

    Not sure what Relative Formula mass is?

    Click Here.

    Not sure what Relative Molecular mass is?

    Click Here.

    Haven't learned how to work this out yet?

    Click Here.

 Copyright A Level Scientist 2014 | All rights reserved.

When I run this code at the moment, the result looks like this :
http://postimg.org/image/6993cuaqb/
Can someone please explain to me what is wrong with the code at the moment ! Thank you :)
---EDIT /
This is my new script, it kind of works, but does not. If someone would kindly test it you may get an insight into what i'm talking about (NAN, Long decimals.). When you're testing it, refresh multiple times and look at what happens.
New Script :

can someone please point me in the right direction as to why this is happening. Thank you.

A: You have an error on your JS code. On line 125 you have close a bracket too "while (l < Form.length)) {". Fix it by deleting one and try the code


text:
Q: Multiple faults on Joomla installation I have previously installed several different Joomla installation at the same hosting company without any major faults that couldn't be corrected quickly. Though I must say that I now find myself lost and don't know where to turn.. So here I am.
I have mulitple issues that I believe is all connected somehow.

*

*Can't upload Images using the Media Uploader (Image size too large) though everything is set up correctly (max_file_size etc.) in PHP configurations and Joomla config.

*Can't upload any other files in the Extension Manager either, since it says my PHP temp folder is not set. Though it is set, and writeble, have permissions etc. Also more than triplechecked the path, by FTP upload PHP-files to write out and verify the absolute path.

*When I save something in the Global Configuration, it says my "Configuration.php" file is not writable. Permission is set to 777 even! If I go back and check, my settings is saved though it just said it couldn't save to the file?

*Even tried to change to FTP-upload to see if I could bypass the fault somehow, tried both by setting it in Global Settings and by downloading the config file, change it manually and then re-upload it via FTP. No luck there either, seemed to just ignore my settings..
Updating Joomla seems to go just fine though, just updated to 3.4.1 to see if it made any difference but no. Running on PHP 5.6 right now though my hostingcompany just said they will downgrade to 5.4 to see if can make something change.
Otherwise, the website is fully functional! You can browse as usual, and write blogs etc. Though, not upload anything. Saving other settings work fine though. Should also mention that the website worked locally 100% before uploaded to the current server.
Any ideas where to start looking? Been Googling for the last 8 hours!

A: My webhost downgraded my PHP service to 5.4 instead, which solved all problems. Weird.


text:
Q: Not being allowed to use some terms in Add New Site in Wordpress The following words are reserved for use by WordPress functions and cannot be used as blog names: page, comments, blog, files, feed
This is the error message that I'm getting. I wanted to use /blog as a sub-site in the network. What I require is that my site has the following structure:
Home (only contains links to the other parts)
Part 1
Part 2
Blog

Would using permalinks solve my problem? I want all my blogs to appear in only the 'Blog' part of the site and nowhere else.
Another follow-up query is that, since I'm working on this site on my localhost, I'm using sub-folders. But when I eventually transfer the site on a web host, I want to use sub-domains. I'm mentioning this as I fear that any solution to the above problem can influence this.

A: http://codex.wordpress.org/Create_A_Network#Permalinks
/blog cannot be used as a new site name. It is relied on heavily by WP for the main site. Everything added to it automatically has /blog as part of the permalink from my understanding
You can check out this discussion
http://wordpress.org/support/topic/root-directory-blog-for-wordpress-30-main-multisite
to see if it helps you out, gives some further options.
The main issue with the /blog is to prevent collisions. I'm not sure of the repercussions of not using it, when using subdomains
I'm not sure if you can easily switch from subfolders to subdomains..... I would think that would cause some issues. I think when you transfer over, the existing subsites are not switched.... so if you set it up one way, and try to change, there may be some headaches


text:
Q: How to prevent from value substitution for variables in angular 6 buil files I'm using angular 6 in my application, I just want to know is there any angular build config property to prevent the value substitution instead of using variable and also for minifing the variable names in the final build file.
For Example:
If my code in component.ts look like this
let func = sampleFunct(firstname,lastname);

I want my code to look like this in build file
let a = b(c,d);

Existing, how its working is in build file is
let func = sampleFunct('abc','def');

It is substituting the value of the variables instead of using the minified variables.
My angular.json configuraion look like this
"configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            },
}

Kindly provide a way to prevent this to happen. Thanks in advance.

A: have you tried 'ng build --prod'? This --prod option should uglify (i.e. obfuscate) your code.


text:
Q: Sql strictly more than query I'm in PostgreSQL.
I need to print all mailing with creation date strictly more that 2015-04-04. I tried the following queries:
SELECT *
FROM mailing.mailing
WHERE creation_date > '2015-04-04';

and
SELECT *
FROM mailing.mailing
WHERE creation_date >= '2015-04-04';

But they produced the same result set(including '2015-04-04'). Is it possible to write such a query without explicitly saying     WHERE creation_date >= '2015-04-05';
UPD: The column's type is timestamp without time zone.

A: If your creation_date field is of type datetimetry comparing it to '2015-04-04 23:59:59' instead, as '2015-04-04 08:30:00' seems to be greater than '2015-04-04'.

A: Assuming your default date format for your database is 'YYYY-MM-DD' and creation_date field is a date type, your query will actually be converted automatically to something like:
SELECT *
FROM mailing.mailing
WHERE creation_date > to_date('2015-04-04', 'YYYY-MM-DD');

The date value you have provided represents the first second of that day, that's why you see no difference between your queries. (Your first query would exclude the first second of the day though.)
What you could do to avoid this is:
where creation_date >= to_date('2015-04-05 00:00:00', 'YYYY-MM-DD HH24:MI:SS')

or
where date_trunc(creation_date-1) = '2015-04-04'


text:
Q: Restricted Lie algebras with a $p$-nilpotent basis Let $L$ be a finite-dimensional restricted Lie algebra over a field of characteristic $p>0$. An element $x$ of $L$ is called $p$-nilpotent if $x^{[p]^k}=0$ for some positive integer $k$. If $L$ is nilpotent as an ordinary Lie algebra and it has a basis consisting of $p$-nilpotent elements, can one conclude that every element of $L$ is $p$-nilpotent?

A: In general the answer is NO. For instance, let $F$ be a field of characteristic $2$ and consider the 3-dimensional Heisenberg algebra $H=Fx \oplus Fy \oplus Fz$ with $[x,y]=z$ and $[x,z]=[y,z]=0$ and power map defined by the conditions $x^{[2]}=y^{[2]}=0$ and $z^{[2]}=z$. Then $\mathcal{B}=\{x, y, x+y+z\}$ is a basis of $H$ consisting of $2$-nilpotent elements, however the element $z$ is not $2$-nilpotent.
On the other hand, it is easy to see that the question has positive answer when the nilpotency class of $L$ is less than $p$.


text:
Q: How do I check an input against prohibited words in MySQL database? Hypothetically, if I didn't want to allow the word "douche" anywhere in a username and I have a table in my database with all of the prohibited words...
$q = "SELECT * FROM restrictions WHERE prohibited LIKE '%username%'";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

if (mysqli_num_rows($r) !== 0)
{
//username is prohibited
echo "invalid";
}
else
{
...etc

The problem is that I don't know how to execute a query that would pick up partial matches (ie. Jdoucher, or douchebag4).  The %username% part is obviously wrong, I know.  Does anyone know how to do this?  Is it even possible?  Thanks.

A: select *
    from restrictions
    where locate(prohibited, @username) <> 0

A: You'd do the opposite of the example you gave.  Get all of the prohibited keywords first then look for each word in the username:
if (stripos($username, $word) !== FALSE) {
   // uhoh
}

A: Using a regex match based on simshaun's answer would probably be the faster answer.
Of course if your database of words is too long you're looking at time to process and large memory requirements.

A: You can accomplish this with regex.


text:
Q: Kentico V9 CSS List Menu webpart for 2nd and 3rd level pages I thought i had my left rail section nav working, untill i added some 3rd level pages. Here's a rough break down of the IA.

*

*sub 1.1

*sub 1.2

*sub 1.3

*

*sub 1.3.1

*sub 1.3.2

*sub 1.3.3

My initial path was set to ../% and nav items for pages 1.1, 1.2, 1.3 works as expected. When i navigate to 1.3.1, i loose the parent node pages.
Here's a screen grab showing the full left nav.

Here is how the nav looks when I'm on a 3rd level page (1.3.1):

I came across this post, but it doesn't seem to work for me: http://devnet.kentico.com/questions/how-to-display-child-documents-if-they-exist-and-display-siblings-if-they-don%E2%80%99t

A: Use /% for a path. ../% is a relative path.
See more details in documentation.

A: I changed my path to this: /{0}/%
{0} is a wildcard for the first child node. I re-re-re-read of the Writing path expressions (https://docs.kentico.com/display/K81/Writing+page+path+expressions), with some aid and trial and error helped.


text:
Q: Large bulk capacitance after LDO for linear power supply I understand that modern L's need output capacitors with very low ESR and ESL for stability (or data sheet recommended values.) Is there any issue with putting a large amount (>=10000 uF) of bulk electrolytic capacitance in addition to the usual tantalum/ceramic capacitors post-LDO (about 10 LDOs in parallel?)
This would be to feed the output of a 250W 10A linear power supply, with potentials for large amounts of load transients.  My thought is that putting more bulk capacitance after would undoubtably smooth the response and ensure stability during heavy peak loads. Low-frequency DC noise is going to ruin the entire supply so I need absolute low-frequency voltage stability <100 kHz.


text:
Q: Laravel translate boolean values for validation (required_if) Using this code inside my validation.php, I was able to translate the translate the values of the edit_type-field:
'values' => [
    'edit_type' => [
        '1' => 'Intern',
        '2' => 'Kunde'
    ],
    'every_day' => [
        'true' => 'ausgewählt',
        'false' => 'nicht ausgewählt'
    ]
],

But for some reason, the same logic does not work for the every_day field. I assume it has something to do with the values being booleans.
This is usually used with required_if inside the validation, in the case of every_day I use required_unless which should not make a difference.
Any idea how I can accomplish this?

A: As explained here

... in PHP, the boolean value true is displayed as 1 and the boolean value false is displayed as the empty string (i.e. nothing is displayed)

So, you can map boolean values like this
'values' => [
    'every_day' => [
        '1' => 'ausgewählt',
        '' => 'nicht ausgewählt',
    ],
],

A: Try this. I think this will help
'values' => [
'edit_type' => [
    '1' => 'Intern',
    '2' => 'Kunde'
],
'every_day' => [
    true => 'ausgewählt',
    false => 'nicht ausgewählt'
]
],


text:
Q: How can I disable save password popup in Selenium? I am using Selenium version 3.141.59 for Java and I would like to disable password popup while initializing the driver for Chrome and Firefox.
I am using the Options syntax since the DesiredCapabilities alternative is now deprecated. My code look like this, but it is not working:

*

*Firefox

FirefoxOptions options = new FirefoxOptions();
options.addPreference("signon.rememberSignons", false);
webDriver = new FirefoxDriver(options);

*

*Chrome

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("credentials_enable_service", false);
chromeOptions.setExperimentalOption("profile.password_manager_enabled", false);
webDriver = new ChromeDriver(chromeOptions);

How can I add that option to the options object before creating the driver?

A: Below are java code, which worked for me. I am using selenium 3.3.1 with selenium-chrome-driver 3.3.1 and Java 8.
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--disable-web-security");
options.addArguments("--no-proxy-server");

Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);

options.setExperimentalOption("prefs", prefs);


text:
Q: clarification on when does ajax call within document.ready gets triggered If I've a page which contains below:
1. HTML with text and images.
2. Lots of reference to CSS and Large JS Files.
3. Within HTML a call similar to one below:

$(document).ready(function () {
     $.ajax({
      url: "http://fiddle.jshell.net/favicon.png",
      beforeSend: function( xhr ) {
        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
      }
    })
      .done(function( data ) {
        if ( console && console.log ) {
          console.log( "Sample of data:", data.slice( 0, 100 ) );
        }
      });
      }

Could someone please clarify if my understanding below is correct, in terms of which one gets loaded first?

*

*Load all HTML and Images.

*Load CSS and apply CSS Styles

*Then, invoke $.ajax call.

*Render whole page.

A: ready is guaranteed to be invoked after the DOM is ready, nothing more. This definitely will not have loaded "all HTML and images", specifically images may or may not have been loaded.


text:
Q: pass a tibble row to a named function as unlisted named vectors, including list-columns I'd like to pass a one-row tibble/dataframe, foo_tibble, to foo_func and have each column of foo_tibble, including list-columns, be an unlisted vector when referenced inside of foo_func by the name of the column.
The closest I've gotten is with the following:
library(tidyverse)

foo_tibble <- tibble(varr = list(c("A", "B")),
                     var2 = list(c(1, 2, 3)))
# actual case has many more variables which need to be referenced by name in foo_func()

foo_func <- function(...) {
  with(..., {
    print(varr)
    is.list(varr)
    # various arbitrary operations involving different columns here
    })
}

foo_tibble %>%
  foo_func()
#> [[1]]
#> [1] "A" "B"
#> [1] TRUE

But here varr is recognized as a list (length 1) instead of a plain vector. I don't want to have to put unlist() around every column name when I use it.
I know one way to accomplish what I want is with an anonymous function inside pmap() like so:
foo_tibble %>%
  pmap(., ~with(list(...), {
    print(varr)
    is.list(varr)
  }))
#> [1] "A" "B"
#> [[1]]
#> [1] FALSE

I use this type of construction often, such as when I need to iterate over many rows. But in my present situation I only need to do this with one row at a given time and I'm looking for something simpler. I don't think pmap() should be necessary in this situation since I am not iterating.
I suspect I am missing something very simple.