text:
Q: objects not visible after re-login in spring boot application I have simple spring boot app, which have a page to add some notes.
enter image description here
As long as I am login I can see it but when I log out and login again I don't until I add the new note.
How to make those objects visible directly after re-login?
I am using H2 DB and my SpringSecurtity config looks like this:
    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/signup","/css/**", "/js/**").permitAll().
    anyRequest().authenticated();

    http.formLogin().loginPage("/login").permitAll();

    http.formLogin().defaultSuccessUrl("/home", true);
    http.logout().logoutUrl("/logout").logoutSuccessUrl("/login");

    http.csrf().disable(); // in order to log into h2 console in browser
    http.headers().frameOptions().disable(); // in order to log into h2 console in browser
}

HTML file for Notes handling:

                    <button id="add-new-note-button" style="margin: 0.25em;" type="button" class="btn btn-info float-right" onclick="showNoteModal()">
                        + Add a New Note
                    </button>

                                    Title
                                    Description

                                        <button type="button" class="btn btn-success">Edit</button>
                                        Delete

                                    Example Note Title
                                    Example Note Description

Note

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

                                    <form action="#" th:object="${noteForm}" th:action="@{/home}" method="POST">
                                        <input type="hidden" name="noteId" id="note-id">

                                            Title
                                            <input type="text" field="*{noteTitle}" name= "noteTitle" class="form-control" id="note-title" maxlength="20" required>

                                            Description
                                            <textarea class="form-control" field="*{noteDescription}" name="noteDescription" id="note-description" rows="5" maxlength="1000" required></textarea>

                                        <button id="noteSubmit" type="submit" class="d-none"></button>
                                    </form>

                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button id="note-save-changes" type="button" class="btn btn-primary" onclick="$('#noteSubmit').click();">Save changes</button>

A: Problem solved. The reason for not dispplaying objects after re-login was the controller class - it didn't load needed data:
missing part in Controller class was loading data from the model:
model.addAttribute("notes", noteService.getUserNotes(userId));


text:
Q: Failing backup, Ubuntu 12.04 after I installed Ubuntu 12.04, my automatic backup hasn't been working. I get that it failed with an unknown error, and the following output:
Traceback (most recent call last):

      File "/usr/bin/duplicity", line 1411, in <module>
        with_tempdir(main)

    File "/usr/bin/duplicity", line 1404, in with_tempdir
        fn()

    File "/usr/bin/duplicity", line 1255, in main
        action = commandline.ProcessCommandLine(sys.argv[1:])

    File "/usr/lib/python2.7/dist-packages/duplicity/commandline.py", line 999, in ProcessCommandLine
        globals.backend = backend.get_backend(args[0])

    File "/usr/lib/python2.7/dist-packages/duplicity/backend.py", line 158, in get_backend
        return _backends[pu.scheme](pu)

    File "/usr/lib/python2.7/dist-packages/duplicity/backends/_boto_single.py", line 49, in __init__
        import boto

    ImportError: No module named boto

I haven't changed anything from 10.10. The specified backup location is my Amazon S3 account. I have tried to google this, but couldn't find anything helpful.
Thanks!

A: You need to install the boto package:
sudo apt-get install python-boto

redpajama_set_name: RedPajamaStackExchange


text:
Q: question about the forms of prime numbers I was thinking about primes earlier and I thought of a hypothesis that I have been unable to prove. I was wondering whether it was a known theorem and whether anyone knows a proof or can prove (or disprove) it.
here it is:
there are an infinite number of primes that satisfy the equation:
$p \equiv a \bmod n$
for all A and N where A and N are relatively prime.

A: This is Dirichlet's theorem on arithmetic progressions of primes. A brief sketch of the proof is given in the article, along with a reference to Jürgen Neukirch's Algebraic number theory $(1999)$.


text:
Q: How to create rotating magnetic field using four electromagnets How would you create a rotating magnetic field using 4 big electromagnets located equal distance around the DUT. The magnets are configured in pairs of two (magnets opposite each other), controlled by bipolar PSUs (2) in Constant current mode (the value which is changing).

Excuse the horrific picture but it should help visualize the problem. My question is what mathematical formulas would i need to create a rotating magnetic field using these, or what documents could i read to help get me there?
This will be software defined so formulas/mathematical solution is needed.
Any clarification, ask, and i will edit the question with it.

A: This is exactly the configuration used in a capacitor start single phase induction motor. The motor has two sets of windings configured at right angles to each other. The main winding is fed with a sine wave from the line supply and a capacitor is used in series with the other winding to phase shift the supply by 90 degrees-making it a cosine wave.
In this type of motor the start winding is usually switched out as the motor comes up to speed,in order to protect the capacitor. In your case you either need to make psu1 supply a sine wave and psu2 supply a cosine wave or use a capacitor that is rated for continuous use at your supply current.
If you assume that you are using a cosine wave on one winding and a sine wave on the other winding then the resultant magnetic field is the vector sum of the individual fields produced in each winding set. This will effectively look like a rotating magnet.


text:
Q: jQuery Autocomplete not working properly I am using multiple autocomplete boxes on my site. The boxes are filled with dynamic string arrays, so I am not using a server. All of the information is local. Here is some of my code:
<script>
var availableMaps = new Array();
var availableLayers = new Array();
var availablePlaces = new Array();
</script>

The above is at the top of my index page
<div class="ui-widget">
    <label for="mapTags">Search: </label>
    <input id="mapTags">
</div>

The above is in the body of my index page
for(var i = 0; i < mapContainer.length; i++)
{
    availableMaps[i] = mapContainer[i].name;
}
$( "#mapTags" ).autocomplete({
        source: availableMaps
});

This piece of code is found in a js function that runs right as the page loads. It does not run in a $(document).ready function. And I know that the availableMaps array fills up with string values.
The autocomplete does work slightly, because if I enter in a letter or word in the input field, I can press the down arrow and items show up in the field just as if the autocomplete was working. The only problem is that I do not get the little drop down menu with values to choose from. So all I need is to get the drop down menu to show up. There is other content below the input field so could the drop down menu be hiding behind the other content? Doesn't seem likely. Do I need to have this in a $(document).ready function?

A: Yes, you need to put the $("#mapTags").autocomplete... part inside of a $(document).ready function to make sure jQuery has loaded, otherwise $ will be undefined and your autocomplete will not get set up.

A: For anyone that still cares, I had to increase the z-index to something like 100000000000. The guy who wrote part of the system before me had apparently set something to have a very very large z-index. At least now I know you can have a z-index larger than 100.
Mikeshiny


text:
Q: Getting python file to return different values based on the input arguments using argparse Let's say I have a function f1()
def f1(input1, input2):
     # does some magic
     return p1, p2

if __name__ == "__main__":

    parser = ArgumentParser(description='Help function description')
    parser.add_argument('t1', help='Token')
    parser.add_argument('t2', help='Another token')
    args = parser.parse_args()

    p1, p2 = f1(args.t1, args.t2)

Let's say this file is called street.py. I want to use the same file to return p1 when the argument arg1 is an input and p2 when argument arg2 is an input.
Outside the file :
variable1 = (python3 ../street.py t1 t2 -arg1)
variable2 = (python3 ../street.py t1 t2 -arg2)

I'm a bit confused over the argparse argument style from the documentation, what's the easiest way to do this?

A: You can solve your problem by using:
parser.add_argument('-arg1', '--argument1', action='store_true')
args = parser.parse_args()

this will store True in the variable args.argument1 if you call python3 ../street.py t1 t2 -arg1, so that you can later use a simple if/elif statement to separate the different cases, i.e.:
if args.argument1 is True:
    print(p1)

A: TL;DR
Make the call in the terminal like this (linux)
variable=$(python3 streep.py t1 'foo' t2 'bar')

you should associate each param t1 and t2 with their respective values.
Also only return a single value from f1 which you will print to stdout

You should consider what you want the behaviour to be. If you want to use the output of f1 then be explicit in its arguments what is mandatory and what is an optional input.
Also consider what you want the output to be, since this is a script passing values will be through stdout you kinda only have the one line to print.
def f1(input1, input2):
     # does some magic
     return p1 or p2

Then simply print the result to stdout with python print() statement
An example based on your code could look like
from argparse import ArgumentParser
import sys
def f1(input1, input2):
     # does some magic
    return input1 or input2

if __name__ == "__main__":

    parser = ArgumentParser(description='Help function description')
    parser.add_argument('--t1', help='Token')
    parser.add_argument('--t2', help='Another token')
    args = parser.parse_args()

    try:
        result = f1(args.t1, args.t2)
        print(result)
    except Exception as e:
        print(e, file=sys.stderr)
        exit(1)

I can then use this script as
variable=$(python3 streep.py --t2 'bar')

A: With this file:
import argparse, sys

def f1(input1, input2):
     # does some magic
     print('inside f1')
     return input1, input2

if __name__ == "__main__":

    print(sys.argv)
    parser = argparse.ArgumentParser(description='Help function description')
    parser.add_argument('t1', help='Token')
    parser.add_argument('t2', help='Another token')
    args = parser.parse_args()
    print(args)

    p1, p2 = f1(args.t1, args.t2)
    print(p1, p2)

Asking for help (in a shell window):
201:~/mypy$ python3 stack64684099.py -h foo bar
['stack64684099.py', '-h', 'foo', 'bar']
usage: stack64684099.py [-h] t1 t2

Help function description

positional arguments:
  t1          Token
  t2          Another token

optional arguments:
  -h, --help  show this help message and exit

running with 2 arguments as specified in the help:
1201:~/mypy$ python3 stack64684099.py foo bar
['stack64684099.py', 'foo', 'bar']
Namespace(t1='foo', t2='bar')
inside f1
foo bar

I added prints to show sys.argv the list of strings that argparse gets from the shell.  And the namespace that parsing produced, and the results of running f1.
===
I don't know where you are doing:
variable1 = (python3 ../street.py t1 t2 -arg1)
variable2 = (python3 ../street.py t1 t2 -arg2)

There's nothing in your parser set up that looks for or pays attention to those '-arg1','-arg2' strings.  And what they are supposed to do is not clear in your question.
I could redirect stdout to file:
1202:~/mypy$ python3 stack64684099.py foo bar > test.txt
1208:~/mypy$ cat test.txt
['stack64684099.py', 'foo', 'bar']
Namespace(t1='foo', t2='bar')
inside f1
foo bar

Omitting all but the last print give just the foo bar line.
The primary purpose of the parser is to read and understand/parse the user input.  If you are happy with the results in the args namespace, the rest is up to your own code.  As defined your arguments are simple strings, which you can use as is or test for certain values.  You can also produce numbers, and with the correct action, boolean values.  You can also define optionals, arguments that expect a flag string like --arg1.


text:
Q: How to change Document Root with Docker I'm new to Docker. I'm trying to change Document Root for my app.
my-app directory has my php codes.
Tree
Project
 - docker-compose.yml
 - html
    - my-app
 - php
    - 000-default.conf
    - Dockerfile

docker-compose.yml
version: "3"

services:
  php:
    build: ./php/
    # image: php:7.2-apache
    volumes:
      - ./html:/var/www/html
    ports:
      - 8080:80
    container_name: php7.2
    restart: always

Dockerfile
FROM php:7.2-apache

RUN apt-get -y update && apt-get -y install vim
COPY 000-default.conf /etc/apache2/sites-available/

000-default.conf
<VirtualHost *:8080>

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/my-app

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    EnableSendfile off
</VirtualHost>

I command docker-compose up -d --build, however document root never change to my-app where I expect. I confirmed 000-default.conf has changed by COPY inside of container.
Please give me same advice.
Thanks.

A: You appear to have your ports back-to-front. In your docker-compose.yml file, you've set host port 8080 and container port 80 () but your v-host is listening on container port 8080.
I'm not actually seeing any reason for you to override the default site config nor for you to have a Dockerfile at all. The default site serves content from /var/www/html over container port 80 so you don't need to change that.
Try this config instead
version: "3"

services:
  php:
    image: php:7.2-apache
    volumes:
      - "./html:/var/www/html"
    ports:
      - "8080:80"

Run the stack using
docker-compose up -d

then open http://localhost:8080/my-app/ in your browser.


text:
Q: Possible to access low level touchpad input at user-level (esp. in Windows) to provide better gestures/palm rejection? I have a laptop whose touchpad is very sensitive to spurious light, grazing touches of anything other than the finger being used, causing unwanted gesture input--even with the sensitivity set to low in the control panel. I can (and will) probably learn over time to hold my wrists in a manner to minimize the problem--but as someone interested in algorithms in things like signal processing, vision, etc., I thought it might be a fun project to try and write a more intelligent filtering algorithm for touch input.
I'm not scared by the math/algorithmic aspect--but what I have zero knowledge of is how the software stack for input devices works, on what level in the stack such code would need to run, and how privileged/close to the kernel I would need to get to have access to that (and whether such a level is even sufficiently documented and accessible to make this possible). Most of the stack presumably handles touch data at "mouse level" abstraction, i.e. as a pointer x/y pair, whereas filtering to eliminate spurious touches would presumably need to act on a sort of "pixel map" of the pad with the areas registering touch "bright", before some sort of "blob detection" on this computes the pointer coordinates.
Where is this transformation ("pad image" to "pointer") performed--in the driver for the touchpad, in the OS kernel, in some userspace code, etc.? Is it even performed at all, or does the capacitive sensing circuitry directly detect only the centroid of the points of contact to begin with? (I can't find a good description of even how multi-touch with capacitive sensing works, fundamentally on a physics level) Is this the sort of thing that's only possible to modify in something like Linux where every line of code in the whole system is modifiable, or is there a good way to "hook" this process even in OSes that are otherwise proprietary?


text:
Q: mysql - sum number of occurrence of values in all rows and columns I am new to mysql and stuck with a problem.
table A looks like this:
-------
A|B|C|D
-------
5|4|3|2
-------
1|2|3|2
-------
5|1|3|2
-------
2|4|3|5
-------

I want to sum all occurence of each value i.e 5 came 3 times, 3 came 4 times etc.
Please help. Thanks.

A: SELECT A,COUNT(*) FROM (select A from tre UNION ALL
   select B from tre UNION ALL
   select C from tre UNION ALL
  select D from tre) X group by A;
+------+----------+
| A    | COUNT(*) |
+------+----------+
|    1 |        2 |
|    2 |        5 |
|    3 |        4 |
|    4 |        2 |
|    5 |        3 |
+------+----------+
5 rows in set (0.00 sec)


text:
Q: Comparação de atributos de objetos dentro de um laço for Como comparar um único item de um objeto que tem 3 espaços ou mais?
Quero fazer um sistema que, todas as vezes que o login digitado for igual a algum que já esteja armazenado em algum objeto, apareça um alerta informando que o login já esta cadastrado.

//objeto
function User(login, senha) {
    this.login = login;
    this.senha = senha;
}

lista = new User(3);

//laço para comparação (NÃO SEI SE ESTA CORRETO)
for (var i = 0; i < n; i++) {
    lista[i] = new User();
    lista[i].login = prompt("Digite o " + (i + 1) + "º usuário para cadastro");
    lista[i].senha = prompt("Digite a senha do " + (i + 1) + "º usuário para cadastro");
    for (var j = i+1; j < n; j++) {
        if (lista[i].login == lista[j].login)) {
            alert("Login já cadastrado!");
        }
    }
}

CÓDIGO COMPLETO COM A PARTE QUE ESTA DANDO ERRO EM COMPARAR. SEGUE ABAIXO:

/*ENUNCIADO:
Crie Uma lista de usuários(Login e Senha); Mostrar um alerta todas as vezes que o usuários digitar um login igual.*/

function User(login, senha) {
    this.login = login;
    this.senha = senha;
}

//ENTRADA DA QUANTIDADE DE CADASTROS QUE DESEJA FAZER
    var n = prompt("Entre com quanto usuários você gostaria de cadastrar");

//LAÇOS PARA POSSIVEIS ERROS DE DIGITAÇÃO
if (n >= 'a' && n <= 'z' || n >= 'A' && n <= 'Z') {
    alert("ERRO!\nEntre com um número inteiro para o cadastro dos usuários.");
    n = 0;
    var n = prompt("Entre com quanto usuários você gostaria de cadastrar");
} else if (n == "" || n == " ") {
    alert("ERRO!\nO Espaço não pode estar em branco");
    n = 0;
    var n = prompt("Entre com quanto usuários você gostaria de cadastrar");
}

//CRIAÇÃO DE UM ARRAY PARA UTULIZAR COM O ARMAZENAMENTO DE VALORES
lista = new User(n);

//LAÇO PARA ENTRADA DO LOGIN E SENHA DO CADASTRO
for (var i = 0; i < n; i++) {
    lista[i] = new User();
    lista[i].login = prompt("Digite o " + (i + 1) + "º usuário para cadastro");
    while(lista[i]login ==lista[i].login) {
      alert("Login já cadastrado!");
      lista[i].login = null;
    }
    lista[i].senha = prompt("Digite a senha do " + (i + 1) + "º usuário para cadastro");
    }
}

A: Em relação a sua pergunta, uma forma geral para verificar a presença de um valor x nos atributos de objetos armazenados em um vetor, podemos usar a seguinte expressão:
vetor.some(elemento => elemento.atributo === x);

A aplicação desta expressão no caso específico segue no código abaixo. No entanto, antes gostaria de mencionar o que considero alguns problemas com o código apresentado:

*

*A expressão lista = new User(3) está incorreta, deve-se criar a lista usando lista = [] e criar os objetos usando new User(login, senha).

*O valor da variável n não está definido.

*Não há verificação de retorno da função prompt(), a qual pode retornar null caso clique-se em Cancelar. É interessante também evitar a
entrada de strings vazias.

*No laço for (var j = i+1; j < n; j++), são realizadas iterações da posição atual do vetor para frente, quando deveria-se fazer o contrário.

Por fim, aplicando a fórmula e efetuando as correções dos problemas apresentados, incluindo verificações de consistência, obtive o código abaixo:
function User(login, senha) {
    this.login = login;
    this.senha = senha;
}

let lista = [];
let login, senha;
let n = prompt("Quantos usuários deseja cadastrar?");;

for (var i = 0; i < n; i++)
{
    login = null;
    while(login == null || login == "")
    {
      login = prompt("Digite o " + (i + 1) + "º usuário para cadastro");

      if(lista.some(usuario => usuario.login === login)) {
        alert("Login já cadastrado!");
        login = null;
      }
    }

    do {
      senha = prompt("Digite a senha do " + (i + 1) + "º usuário para cadastro");
    }
    while (senha == null || senha == "");

    lista.push(new User(login, senha));
}


text:
Q: wordpress custom admin page - checkbox I'mt trying to create a plugin which adds a custom page in the admin panel. I have a checkbox with name "deposit_sandbox" if check true it should update the option in the database to true, if not selected it should update the option in the database to false.
how do I check if a checkbox was selected and then update the database with update_option() function?
It works if I leave the action blank and then use $_POST, but I would need to do this for each item in my form. if there is a workaround please let me know :)

A: If your options have the same name as the checkboxes, you can write the following:
$options_names = array("deposit_sandbox", "name2", "name3");
foreach($options_names as $option_name){
    $checked = isset($_POST[$option_name]);
    update_option($option_name, $checked);
}

I don't remember if update_option accepts boolean values (like $checked in my example). If it doesn't, change the $checked line for $checked = isset($_POST["deposit_sandbox"]) ? 1 : 0;.
I'm supposing you create default values to all your options when you activate the plugin.


text:
Q: Are complements of generalized eigenspaces $T$-invariant? Let $T$ be a linear operator of a finite-dimensional vector space $V$ over the field $F$. Let's assume that $T$ has an eigenvalue $\lambda$. Let $K_\lambda$ be the generalized eigenspace of $T$ associated to $\lambda$ and let $W$ be the complement of $K_\lambda$ in $V$ obtained by extending any basis of $K_\lambda$ to a basis of $V$, that is, $V=K_\lambda\oplus W$.
Is $W$ $T$-invariant?


text:
Q: Default code from Cocos2d-V3 isn't working at all? I ran the default code provided with the cocos2d template
but doesn't seems to work.
But a tutorial at Ray Wenderlich says it should be working.
I Couldn't get any far from boilerplate code.
when I ran the initial code provided by default. got crashed
with the following out put :-
cocos2d: cocos2d-iphone version 3.0.alpha
cocos2d: compiled with Profiling Support: NO
cocos2d: OS version: 6.1 (0x06010000)
cocos2d: GL_VENDOR: Apple Computer, Inc.
cocos2d: GL_RENDERER: Apple Software Renderer
cocos2d: GL_VERSION: OpenGL ES 2.0 APPLE
cocos2d: GL_MAX_TEXTURE_SIZE: 4096
cocos2d: GL_MAX_TEXTURE_UNITS: 8
cocos2d: GL_MAX_SAMPLES: 4
cocos2d: GL supports PVRTC: YES
cocos2d: GL supports BGRA8888 textures: YES
cocos2d: GL supports NPOT textures: YES
cocos2d: GL supports discard_framebuffer: YES
cocos2d: GL supports shareable VAO: NO
AudioStreamBasicDescription: 2 ch, 44100 Hz, 'lpcm' (0x00000029) 32-bit little-endian float, deinterleaved
2014-02-10 18:12:19.669 Cocos2DSimpleGame[2532:16103] Error '!obj' trying to fetch default input device's sample rate
2014-02-10 18:12:19.670 Cocos2DSimpleGame[2532:16103] Error getting audio input device sample rate: '!obj'
2014-02-10 18:12:19.671 Cocos2DSimpleGame[2532:16103] AQMEIOManager::FindIOUnit: error 'NoHW'
2014-02-10 18:12:19.672 Cocos2DSimpleGame[2532:12203] AURemoteIO::Initialize failed: -10851 (enable 2, outf< 2 ch, 44100 Hz, Float32, non-inter> inf< 2 ch, 0 Hz, Int16, inter>)
2014-02-10 18:12:19.673 Cocos2DSimpleGame[2532:13e03] <0xb0197000> AQMEIOManager::FindIOUnit: error 'NoHW'
(lldb)

What am i missing here ?
PS:- I am using Xcode 4.6.2


text:
Q: php regexp for get images
Possible Duplicate:
Regex to change format of all img src attributes

Hi,
I want to replace the image path in my content db field.
I have the following
preg_replace("/src='(?:[^'\/]*\/)*([^']+)'/g","src='newPath/$2'",$content);

which is working fine for
src="/path/path/image.jpg"

BUT fails ON
src="http://www.mydomain.com/path/path/image.jpg"

Any help to bypass this problem?

A: Don't use regular expressions for this. Use a HTML parser like Simple HTML DOM.
$html = file_get_html('http://www.example.com/sourcepage.html');

foreach($html->find('img') as $element)
 {
    $new_src = "Do stuff with new src here";
    $element->src = $new_src;
 }

 echo $html; // Output new code


text:
Q: What is the number of ways of distributing '$n$' identical items among '$r$' identical baskets? I have  seen explanations for distribution among '$r$' groups as opposed to '$r$' identical groups(example: if $12$ eggs are to be distributed among $4$ baskets such that the baskets are not numbered). I know that it cannot be done by finding the number of possible whole number solutions for these $4$ baskets$[(12+4-1)C(4-1)]$, which gives the answer when the baskets are numbered, and then dividing by 4! to "adjust" for the "identical" baskets(as there would also be distributions such as $2,2,3,5; 2,3,2,5; 2,2,2,6$). All this leads me to wonder if there is a single working formula(without the need of step-by-step calculation) for the same.

A: Using the Polya Enumeration Theorem the closed form is given by
$$[z^n] Z(S_r)\left(\frac{1}{1-z}\right)$$
where $Z(S_r)$ is  the cycle index of the symmetric  group. This cycle
index  is   known  in   species  theory   as  the   multiset  operator
$\mathfrak{M}_{=r}.$
Recall the  recurrence by Lovasz for  the cycle index $Z(S_r)$  of the
set operator $\mathfrak{M}_{=r}$ on $r$ slots, which is
$$Z(S_r) = \frac{1}{r} \sum_{l=1}^r a_l Z(S_{r-l})
\quad\text{where}\quad
Z(S_0) = 1.$$
This recurrence lets us calculate the cycle index $Z(S_r)$ very easily.

For example when $r=5$ the cycle index is
$$Z(S_5) =
{\frac {{a_{{1}}}^{5}}{120}}+1/12\,a_{{2}}{a_{{1}}}^{3}+1/6\,a_{{3}}
{a_{{1}}}^{2}+1/8\,a_{{1}}{a_{{2}}}^{2}
\\+1/4\,a_{{4}}a_{{1}}+1/6\,a_{{2}}a_{{3}}+1/5\,a_{{5}}$$
and the generating function becomes
$${\frac {1}{120\, \left( 1-z \right) ^{5}}}
+1/12\,{\frac {1}{ \left(-{z}^{2}+1 \right)  \left( 1-z \right) ^{3}}}
+1/6\,{\frac {1}{ \left( -{z}^{3}+1 \right)  \left( 1-z \right) ^{2}}}
\\+1/8\,{\frac {1}{ \left( 1-z \right)  \left( -{z}^{2}+1 \right) ^{2}}}
+1/4\,{\frac {1}{ \left( -{z}^{4}+1 \right)  \left( 1-z \right) }}
+1/6\,{\frac {1}{ \left( -{z}^{2}+1 \right)  \left( -{z}^{3}+1 \right) }}
\\+1/5\, \left( -{z}^{5}+1 \right) ^{-1}.$$
which gives the sequence
$$1, 1, 2, 3, 5, 7, 10, 13, 18, 23, 30, 37, 47, 57, 70, 84, 101,
\\ 119, 141, 164, 192, \ldots$$
that points to OEIS A001401 which looks to
be a match. Here we have assumed that empty bins are admissible.

This   MSE   link
shows how  one might go about  producing a closed form  expression for
the coefficients of this type of generating function. Furthermore this
MSE       link II
presents an algorithm for computing these closed forms.
There is some Maple code to help explore these data.

pet_varinto_cind :=
proc(poly, ind)
local subs1, subs2, polyvars, indvars, v, pot, res;

    res := ind;

    polyvars := indets(poly);
    indvars := indets(ind);

    for v in indvars do
        pot := op(1, v);

        subs1 :=
        [seq(polyvars[k]=polyvars[k]^pot,
             k=1..nops(polyvars))];

        subs2 := [v=subs(subs1, poly)];

        res := subs(subs2, res);
    od;

    res;
end;

pet_cycleind_symm :=
proc(n)
option remember;

    if n=0 then return 1; fi;

    expand(1/n*add(a[l]*pet_cycleind_symm(n-l), l=1..n));
end;


text:
Q: Delphi 10 Seattle missing libsqlib.a I can't compile my multi-device iOS application, because there is an error:
[DCC Error] E2597 ld: file not found: libsqlib.a
I use Delphi 10 Seattle.
I didn'd find solution for this, only for the Delphi XE8 and XE5 libsqlib.a can be downloaded. But it doesn't work with these.
Can you help me?
Zoltán

A: The libsqlib.a files for iOS are installed on my D10Seattle system in following directories:
C:\Program Files (x86)\Embarcadero\Studio\17.0\lib\iosDevice32\release
C:\Program Files (x86)\Embarcadero\Studio\17.0\lib\iosDevice32\debug
C:\Program Files (x86)\Embarcadero\Studio\17.0\lib\iosDevice64\release
C:\Program Files (x86)\Embarcadero\Studio\17.0\lib\iosDevice64\debug

There could be something wrong with your installation or missing/wrong search paths.
A reinstallation might resolve your problem.


text:
Q: Poor accuracy at mnist csv data in tensorflow I'm trying to mnist for beginners, using csv data.
I got the csv data from here and made each label one-hot vector.
Each row has 794dims(colum1~10 as a label and 11~794 as pixels).
Here is the code I wrote that results in the awful accuracy.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys

import tensorflow as tf
import numpy      as np

FLAGS = None

def main(_):
  # Import data
  def csv_to_numpy_array(filepath, delimiter):
      return np.genfromtxt(filepath,delimiter=delimiter, dtype=None)

  def import_data():
      print("loading training data")
      traindata = csv_to_numpy_array("data/mnist_train_onehot.csv",delimiter=",")
      [trainY, trainX] = np.hsplit(traindata,[10]);
      print("loading test data")
      [testY, testX] = np.hsplit(testdata,[10]);
      return trainX, trainY, testX, testY

  x_train, y_train, x_test, y_test = import_data()

  numX = x_train.shape[1] #784
  numY = y_train.shape[1] #10

  # Prepare the placeholder
  x = tf.placeholder(tf.float32, [None, numX]) #input box
  y_ = tf.placeholder(tf.float32, [None, numY]) #output box

  #define weight and biases
  w = tf.Variable(tf.zeros([numX,numY]))
  b = tf.Variable(tf.zeros([numY]))

  #create the model
  def model(X, w, b):
      pyx = tf.nn.softmax(tf.matmul(X, w) + b)
      return pyx

  y = model(x, w, b)

  #cost function
  loss = -tf.reduce_sum(y_*tf.log(y))
  # the loss and acc
  cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
  train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
  init = tf.initialize_all_variables()
  correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()

  # Train
  for i in range(1000):
      ind = np.random.choice(100,100)
      x_train_batch = x_train[ind]
      y_train_batch = y_train[ind]
        #run optimization op (backprop) and cost op (to get loss value)
      _,c = sess.run([train_step, loss], feed_dict={x: x_train_batch, y_: y_train_batch})
      if i % 50 == 0:
          train_acc = accuracy.eval({x: x_train_batch, y_: y_train_batch})
          print('step: %d, acc: %6.3f' % (i, train_acc) )

  # Test trained model
  print(sess.run(accuracy, feed_dict={x: x_test,
                                      y_: y_test}))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

The accuracy is 0.098pt.
Could someone please try this code and tell me what is wrong on this code?
Thank you very much in advance.

A: There are possible problems:
1- Initialize your variables randomly and not zero
2- You may misunderstand the .csv file format, where you got .csv file, said the format is label, pix-11, pix-12, pix-13, ...
3- Try to use tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits( logits , llabels )) the method you use to compute loss is numerically unstable. Update: in this case dont use tf.nn.softmax because tf.nn.softmax_cross_entropy_with_logits internally have softmax normalizer and cross entropy.(thanks for @ml4294 comment)

A: Here is you code with the needed changes.  Specifically, you can use tf.nn.softmax_cross_entropy_with_logits to do the heavy lifting of calculating cross entropy for you.  Another improvement is to use loss = tf.reduce_mean... instead of loss = tf.reduce_sum...*.  This will make your training correction be the average of all the errors that were made instead of the sum.  You'll get wild and uncontrolled training swings if you use sum and you'll have to compensate by using a really small gradient descent factor.  If you find you have to use something in gradient descent higher than 1 or lower than .1 you could probably fix the problem by using reduce_mean for the loss.
Here is your code.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys

import tensorflow as tf
import numpy      as np

FLAGS = None

def main(_):
  # Import data
  def csv_to_numpy_array(filepath, delimiter):
      return np.genfromtxt(filepath,delimiter=delimiter, dtype=None)

  def import_data():
      print("loading training data")
      traindata = csv_to_numpy_array("data/mnist_train_onehot.csv",delimiter=",")
      [trainY, trainX] = np.hsplit(traindata,[10]);
      print("loading test data")
      [testY, testX] = np.hsplit(testdata,[10]);
      return trainX, trainY, testX, testY

  x_train, y_train, x_test, y_test = import_data()

  numX = x_train.shape[1] #784
  numY = y_train.shape[1] #10

  # Prepare the placeholder
  x = tf.placeholder(tf.float32, [None, numX]) #input box
  y_ = tf.placeholder(tf.float32, [None, numY]) #output box

  #define weight and biases
  w = tf.Variable(tf.zeros([numX,numY]))
  b = tf.Variable(tf.zeros([numY]))

  y = tf.matmul(x, w) + b

  # unused for this model
  keep_prob = tf.placeholder(tf.float32)

  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_))
  train = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Test trained model
  correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  percent_correct = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

  init = tf.initialize_all_variables()

  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()

  # Train
  for i in range(1000):
      ind = np.random.choice(x_train.shape[0],100)
      x_train_batch = x_train[ind]
      y_train_batch = y_train[ind]
        #run optimization op (backprop) and cost op (to get loss value)
      _,c = sess.run([train_step, loss], feed_dict={x: x_train_batch, y_: y_train_batch})
      if i % 50 == 0:
          train_acc = percent_correct.eval({x: x_train_batch, y_: y_train_batch})
          print('step: %d, acc: %6.3f' % (i, train_acc) )

  # Test trained model
  print(sess.run(percent_correct, feed_dict={x: x_test,
                                      y_: y_test}))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

Here is a link to a few different mnist tensorflow architectures https://github.com/panchishin/learn-to-tensorflow/blob/master/examples/mnist_model_comparison.py all in one script


text:
Q: Android - Remove permission programmatically in the last days I try to make a simple Android app that can run adb command , more specific this command pm revoke com.example.app android.permission.ACCESS_NETWORK_STATE.
I try to run this from pc and say me that I can't because this permission isn't changeable.
With root is possible? or there are other method to block the internet connection to one app?


text:
Q: Record allowing members implementing any interface which extends another This is my current code:

interface hasFoo {
  foo: string;
}

interface hasBar extends hasFoo {
  bar: string;
}

interface hasBaz extends hasFoo {
  baz: string;
}

const myRecord: Record<string, hasFoo> = {
  "a": {
    foo: "hello",
    bar: "world",
  },
  "b": {
    foo: "goodbye",
    baz: "my lover",
  },
  "c": {
    foo: "periwinkle",
  },
}

However, this doesn't work ('bar' does not exist in type 'hasFoo'). I could do Record<string, hasFoo | hasBar | hasBaz>, but that would quickly get unwieldy if I add more interfaces which extend hasFoo. Instead, I want something like Record<string, extends hasFoo>. Can this be done?

A: You are trying to create hasFoo and compiler gives error as bar or baz is not defined in hasFoo. But, as you can see type casting actually works as expected.
const myRecord: Record<string, hasFoo> = {
  "a": {
    foo: "hello",
    bar: "world",
  } as hasBar,
  "b": {
    foo: "goodbye",
    baz: "my lover",
  } as hasBaz,
  "c": {
    foo: "periwinkle",
  },
}

or
const myRecord: Record<string, hasFoo> = {
  "a": {
    foo: "hello",
    bar: "world",
  } ,
  "b": {
    foo: "goodbye",
    baz: "my lover",
  } ,
  "c": {
    foo: "periwinkle",
  },
} as Record<string, hasFoo>

A: You could use
const myRecord: Record<string, Record<string,string> & hasFoo> = {
  "a": {
    foo: "hello",
    bar: "world",
  },
  "b": {
    foo: "goodbye",
    baz: "my lover",
  },
  "c": {
    foo: "periwinkle",
  },
}

which will be less maintenance than
const myRecord2: Record<string, hasBar | hasBaz | hasFoo> = {
  "a": {
    foo: "hello",
    bar: "world",
  },
  "b": {
    foo: "goodbye",
    baz: "my lover",
  },
  "c": {
    foo: "periwinkle",
  },
}

Playground Link


text:
Q: Open a page over another page bootstrap jQuery I'm using spring and jsp for my web-app.
I'm trying to create a component like this:

When I click on a button inside the "master" page, I want open a second page over the first one.
Is there a component using bootstrap or jQuery to do this?
Otherwise how can I do that?

A: What about using modal? Example here

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

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

Modal Header

Some text in the modal.

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

A: it looks like you require to open a popup window
you can easily do this by installing any free popup overlay jquery pluging like- ( http://www.jqueryscript.net/lightbox/Responsive-Accessible-jQuery-Modal-Plugin-Popup-Overlay.html )
install only if you want to create many popup overlay items


text:
Q: Alternative to java.util.BitSet for small sizes? java.util.BitSet is backed by a long[] so the minimum size is 64 bits. I require to cache lots (~2M) of objects that each require a BitSet of size 23. Is there an alternative to BitSet that is more space efficient for small sizes? For example is there a BitSet type data structure that is backed by a byte[] instead of a long[]? This would allow me to store my 23 bits in 3 bytes instead of 8.

A: The java.util.BitSet class is designed for larger bit sets. When you need bit sets of size 23, even a bit set based ob 3 bytes would use too much memory, because an array of any size uses an additional reference for the array itself, which is most likely four to eight bytes.
The most economical solution in terms of memory is using ints instead of bit sets, and writing your own implementations of the bit set operations that you need. Since operations on bit sets are for the most part copied from bitwise operations, you should have no problem implementing them:
boolean get(int mySet, int index) {
    return (mySet & (1<<index)) != 0;
}
int set(int mySet, int index) {
    return mySet | (1<<index);
}
int clear(int mySet, int index) {
    return mySet & (1<<index);
}

...and so on.

A: First, byte array of length 3 takes much more than 3 bytes. Any object instance in Java has memory overhead, including BitSet.
To keep memory consumption low, try to use elements of int array for bit set. Such element cannot be represented as an object, so you have to develop procedure interface rather than object-oriented. Tell us what operations on bitsets you need and we'll make more detailed advice.


text:
Q: PHP Variables & Optimsation This may well be a very basic PHP 101 question, but I was wondering if there is any real benefit in collecting data in variables in one query (when possible), rather than throughout a page effectively on the fly.
For example;
<?php

    $title = get_field('title');
    $paragraph = get_field('paragraph');
    $url = get_field('url');

?>

<?php echo $title; ?>

<?php echo $paragraph; ?>

    <a href="<?php echo $url; ?>">

vs;

<?php the_field('title'); ?>

<?php the_field('paragraph'); ?>

    <a href="<?php the_field('url'); ?>">Read More

Does either method have an impact on performance?


text:
Q: Problems with null(?) Date criteria in a Process Builder flow. We've got different statuses for a record where we want to back fill date markers that an event happened. If I "Held Interview" then obviously I also "Contacted" a given person. Sometimes the Process Builder works, other times it flat out fails and so far I'm at a loss as to why. The criteria for the action seems correct as does the action. But we're getting close to just switching over to using Apex instead to do a field evaluation.
I've tried enabling Recursion, that didn't seem to help either, but I could look at again.
Not necessarily looking for a silver bullet just looking for ideas of things to check. Attaching a screenshot of the criteria. All of the fields are different date fields. The end action is simply setting some of those date fields with the current date value if the particular event permutation happens.


text:
Q: Using VB.Net code to create a barcode in SSRS I am attempting to design a barcode to implement into my report. I am using this guide to do this Code 128 Barcode in SSRS . I have little experience in VB.Net, I'm receiving an error in my custom code on line 7 that says Name 'objGraphic' is not declared. I'm also open to other alternatives to implementing a barcode in my report preferably free.
Function PaintBox(ByVal level As String) As System.Drawing.Bitmap
    Dim objBitmap As System.Drawing.Bitmap

objBitmap = New System.Drawing.Bitmap(3,3)

GenCode128.Code128Rendering.MakeBarcodeImage(level, 1, True)

objGraphic.DrawLine(System.Drawing.Pens.Gray,0,0,width,height)

Return objBitmap End Function

Function PaintBoxBmp(ByVal level As String) As Byte()

Dim bmpImage As System.Drawing.Bitmap

bmpImage = PaintBox(level)

Dim stream As System.IO.MemoryStream = New IO.MemoryStream

Dim bitmapBytes As Byte() bmpImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp)

bitmapBytes = stream.ToArray

stream.Close()

bmpImage.Dispose()

Return bitmapBytes

End Function

A:     Function PaintBox(ByVal level As String) As System.Drawing.Bitmap

Dim objBitmap As System.Drawing.Bitmap

objBitmap = GenCode128.Code128Rendering.MakeBarcodeImage(level, 1, True)

 Return objBitmap

End Function

Function PaintBoxBmp(ByVal level As String) As Byte()

Dim bmpImage As System.Drawing.Bitmap

 bmpImage = PaintBox(level)

 Dim stream As System.IO.MemoryStream = New IO.MemoryStream
Dim bitmapBytes As Byte()
bmpImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp)

 bitmapBytes = stream.ToArray
stream.Close()
 bmpImage.Dispose()
Return bitmapBytes

End Function


text:
Q: Common lisp Error: the value is not of the expected type number i am new to lisp, and have some troubles with my function:
(setf (symbol-function 'reduce-our)
    #'(lambda(new-expression)
            (setf expression nil)
              (loop while (not (equal new-expression expression)) do
                        (setf expression new-expression)
                        (setf new-expression (reduce-once-our expression))
                        (if (not (equal 'new-expression 'expression))
                            (format t " ==> ~A Further reductions are impossible.~%"
                             new-expression)
            new-expression))))

(reduce-our '(^ x => x))

This thows next error:
Error: The value ^ is not of the expected type NUMBER.

I thought that lisp is trying to evaluate  my input list in while loop, but
(not (equal nil '(^ x => x)))

works just fine, and i am sure that my function does the same check. So. i don't understand where and why happens this error.

A: Are you sure that the error happens in this function? You should look at the backtrace.
Additionally:
(setf (symbol-function 'reduce-our)
   #'(lambda (new-expression)
      ...))

is typically written as
(defun reduce-our (new-expression)
   ...)

Then:
(setf (symbol-function 'reduce-our)
  #'(lambda(new-expression)
      (setf expression nil) ...

Where is the variable expression introduced? It is undeclared. Setting the value does not declare a variable.
Then:
while (not (foo ...))

is just
until (foo ...)

And
(if (not (foo)) a b)

is
(if (foo) b a)

Also: improve the indentation. The editor in Lisp will do that for you. It increases readability for you and others.


text:
Q: how to convert blob to arraybuffer or string to blob Imagine I have a file with this data:
lastModified: 1543877513859
lastModifiedDate: Tue Dec 04 2018 02:21:53 GMT+0330 (Iran Standard Time) {}
name: "ali.jpg"
objectURL: SafeUrlImpl
changingThisBreaksApplicationSecurity: "blob:http://localhost:4200/b45412e9-69ad-433f-b24d-b3833d705da4"
__proto__: SafeValueImpl
size: 16196
type: "image/jpeg"
webkitRelativePath: ""

So I want to get the binary data of this image. I read some info of how to get the content of image here.  so I try to get the binary data with this:
const expecteadBinaryData= file.objectURL.
        changingThisBreaksApplicationSecurity.arrayBuffer();
        reader.onload = (e) => e.target.result;
        const expecteadBinaryData2 =reader.readAsDataURL(new Blob
          ([file.objectURL.changingThisBreaksApplicationSecurity]));

So I expect the result of expecteadBinaryData or expecteadBinaryData2 be a binary, but I get undefined. How should I get this?


text:
Q: Polymer app-route: multiple routes to same page? Is there a built-in method for routing multiple possible links to the same "page"?
For example, I have a '/' route that loads a landing page by binding the active attribute of that route to a property named landing-active, which is being observed. The most straightforwards way I can think of to allow converging routes is to create another app-route element for the new route, and bind its active attribute to the same landing-active property as the '/' route.
Is there a better/different way of handling this, or should I stick with my method?
Edit: I tried my method out, and it doesn't work. Here's my original route:
<app-route
  id='landing-route'
  route='{{route}}'
  pattern='/'
  active='{{landing-active}}'>
</app-route>

If I then add an alternate route by simply changing the pattern and id, then the '/' route no longer works. Changing the active binding on the new route fixes this issue, but also no longer allows it to rout as intended. So my conclusion is that I can't bind the same property to the active attribute of two separate app-route elements, so my routing method doesn't work.
What alternatives do I have?

A: *

*Option 1: Use two separate active variables for your two <app-route>s, and test for either variable (e.g., with a computed binding/property).

*Option 2: Use a different router component. <nebula-routing> might be the best option IMO, given that it has a similar API to <app-route> and supports regular expression in the route patterns.


text:
Q: Specify multiple attribute selectors in CSS What is the syntax for doing something like:
input[name="Sex" AND value="M"]

Basically, I want to select the input element that has the attribute name="Sex" as well as the attribute value="M":
<input type="radio" name="Sex" value="M" />

Elements such as the following should not be selected:
<input type="radio" name="Sex" value="F" />

A: Simple input[name=Sex][value=M] would do pretty nice. And it's actually well-described in the standard doc:

Multiple attribute selectors can be used to refer to several
  attributes of an element, or even several times to the same attribute.
Here, the selector matches all SPAN elements whose "hello" attribute
  has exactly the value "Cleveland" and whose "goodbye" attribute has
  exactly the value "Columbus":
span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }

As a side note, using quotation marks around an attribute value is required only if this value is not a valid identifier.
JSFiddle Demo

A: Just to add that there should be no space between the selector and the opening bracket.
The following will trigger every td with an attribute named attr
td[attr]

The following will trigger every elements inside a td with an attribute named attr (not the td itself)
td [attr]

A: Concatenate the attribute selectors:
input[name="Sex"][value="M"]

A: For concatenating it's:
input[name="Sex"][value="M"] {}

And for taking union it's:
input[name="Sex"], input[value="M"] {}


text:
Q: Feeding microcontroller and linear actuators (motors) with the same power supply I have already made a diagram using a motor controller.
The details of the actuators are:

*

*Input voltage: 12VDC

*Max Load: 750N(168.607lbs)

*Stroke Length: 16 inch

*Travel Speed: 12mm/s

*Duty Cyle: 25%.

Could you please check if it is ok?
Some of my concerns are:

*

*Be sure if the feed of 12 volts for the motors, and 5 volts for Arduino are correct  and can live together as shown.

*Be sure if the wiring for the Arduino, driver and motors is correct since it looks kind of simple.
Diagram1

I want to know if this is the natural approach by doing it with a voltage regulator to feed the Arduino and with 12V 10A power supply to feed the motors, or if there are other, better options to make the circuit feed only using one power supply (12V, 10A).
MDD10 Datasheet Link: https://www.robotshop.com/media/files/content/c/cyt/pdf/cytron-10a-7-30v-dual-channel-dc-motor-driver-shield-datasheet.pdf
UPDATE
I have increased power supply to 13A, also changed the linear voltage regulator (7805) to a switching voltage regulator (OKI-78SR-5), what do you think about this approach?
Diagram2

Or I should try with the 12V DC Vin of Arduino(I understand that it works with a linear voltage regulator)? Being this option, it could be maybe with a voltage pre-regulation stage(from 12V to 9V for example) or maybe connecting directly to the jack.
Diagram3

Thanks, Best Regards.
I'm adding a fourth diagram..
Diagram4

The orange color is used to represent a heavy wire which goes from the 12v power supply to the ground of the motor driver, from the ground of the motor driver goes a normal cable to the arduino ground, and from the arduino ground a normal cable to C2 then to the ground of the voltage regulator then to C1.
This is to avoid noise caused by the motor driver to the arduino and the voltage regulator.

A: I suggest you use a 9V linear regulator as a 'pre-regulator' to power the Arduino through the Vin pin or DC input jack. That way any noise on the 12V supply has to get through two stages of regulation before it can affect the Arduino.
The Arduino Uno's DC input jack has a diode in series for reverse voltage protection. This has the advantage that the power input can momentarily drop to zero without discharging the input capacitor. The same technique can be used on the pre-regulator. The circuit would look like this:-

simulate this circuit – Schematic created using CircuitLab
The voltage regulator ground should be connected directly to the Arduino ground, then to the motor driver ground, with another heavy wire going from the power supply to the motor driver ground. This prevents motor current from flowing through the ground wire between the regulator, Arduino and driver, which could cause glitches or worse.

A: Any time you are dealing with Point of load converters always start from the load you will be feeding. Once you understand your load and its requirements you may start working your way back. Load requirements may include Maximum Voltage Ripple, Maximum Tolerance Band, etc. There are more to be considered here but for hobby use this is enough to get you started with good POL design.
Lets look at our requirements

*

*Uno max current = 20mA @ Maximum Clock Frequency(Always
build in some Cushion if you can! ATMEGA_Datasheet

*Supply Voltage of 5V (Based on Datasheet)

*Low Pass Filtered VCC supply for AVCC (This implies a lower Ripple Voltage is asked for for the this)

Alright so now that we understand our requirements we can work backwards.
FIRST remember:
Liner Regulator (LDO)
Pros:
Simple, reliable, Low ripple
Cons:
Inefficient, Can get Hot  (Vin-Vout)*Load Current = Power (this number gets big quick
Switcher
Pros:
Efficient, Much Better Load Transient response
Cons:
Can get complicated, Higher Part Count
Alright now that that is understood lets look at your system.
The 12V -> Switcher(5V) ->Uno

*

*You want to smooth out the output of that converter, thus you will need to add some capacitance both on the input and the output. How much? Look Here I personally recommend Ceramics.
Do not get discouraged by the math! Just work your way through it. You can do it. The TI APP note does a great job walking you through everything.

*Now If you are feeding a Uno Dev Card I would recommend regulating down to 9V. This is echoing everyone else's point to use that which is already provided for you. No need to do more work than is necessary! IF you are feeding an ATMEGA chip straight the 5V should be fine. Just make sure to watch your Voltage Ripple.

*Regarding the Linear Regulator
This approach would indeed be "cleanest/easiest" BUT lets not forget how Linears operate!
(12V-5V)0.02A = 140mW.(Thanks Chris)*
Next lets get the temperature rise. 140mW * 65 C/W = 9.1 Degree Temperature Rise, in this case not horrible, but as you can see if your current goes up you can get really hot really fast. Note that 65C/W is the Junction to Ambient of that LDO
Lastly, Motors are EXTREMELY Noisy. I personally would be reluctant to connect the motors to the same ground as your Arduino. I would place a Ferite bead or at the very least a resistor between the Arduino Ground and the motor grounds. Especially if the Motor drive chip and the Uno share the same PCB. Bruce's Answer mentions this as well.


text:
Q: How to outline multiple states? I am creating an interactive geo heatmap dashboard. Take the figures below as an example. The 1st plot is the output. How can I outline multiple states like shown in the 2nd plot? I going to divide USA state into 10 divisions, and create a drop down menu to select and show specific division.
import plotly.graph_objects as go

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')

fig = go.Figure(data=go.Choropleth(
    locations=df['code'], # Spatial coordinates
    z = df['total exports'].astype(float), # Data to be color-coded
    locationmode = 'USA-states', # set of locations match entries in `locations`
    colorscale = 'Reds',
    colorbar_title = "Millions USD",
))

fig.update_layout(
    title_text = '2011 US Agriculture Exports by State',
    geo_scope='usa', # limite map scope to USA
)

fig.show()

A: It's possible to do something close to what you need using what you have here. I recognize that this solution is not exactly what you are looking for since the boundaries between states within the area in question are shown in my answer.  However, it is the closest to what you're looking for that I can think of how to do without calling other packages or tools. Hopefully it will help you figure out a more complete solution.
The basic idea behind this is that I'm adding a layer with the selected states, setting their alpha to 0, and then setting the state boarder to a given color.  My thought is that there may be a way to use the color mapping against the location data to overcome the issue of the lines appearing
import plotly.graph_objects as go

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')

fig = go.Figure(data=go.Choropleth(
    locations=df['code'], # Spatial coordinates
    #locations=['VA'],
    z = df['total exports'].astype(float), # Data to be color-coded
    locationmode = 'USA-states', # set of locations match entries in `locations`
    colorscale = 'Reds',
    colorbar_title = "Millions USD",
    marker_line_color='white',   # will still work if you put this back in black
))

fig.update_layout(
    title_text = '2011 US Agriculture Exports by State',
    geo_scope='usa', # limit map scope to USA
)

# to add these outlines"
# add layer of states to highlight
# turn their texture alpha to 0
# set their marker_line_color to a nice Blue
# and turn off the scale
chorpleth = go.Choropleth(
        locationmode='USA-states',
        z=[0,0,0,0,0,0,0,0,0,0,0,0],
        locations=['ND','SD','NE','KS','MO','IA','MN','WI','MI','IL','IN','OH'],
        colorscale = [[0,'rgba(0, 0, 0, 0)'],[1,'rgba(0, 0, 0, 0)']],
        marker_line_color='Blue',
        showscale = False,
    )

fig.add_trace(chorpleth)

fig.show()

Other solutions I can think of involve using cartopy, so I'll look into something along those lines since this is admittedly partial.


text:
Q: How to install the debian bash-completion using homebrew? I want bash to install bash command completion on my mac using brew.

A: install bash-completion
brew install bash-completion

Do not forget to add the following snippet to your .bash_profile:
if [ -f `brew --prefix`/etc/bash_completion ]; then
    . `brew --prefix`/etc/bash_completion
fi

This will include the completion commands into your interactive bash in Terminal.app.
To add a new completion script, just drop it into the bash_completion.d directory
cp my_completion_script `brew --prefix`/etc/bash_completion.d


text:
Q: Is there an adjective for 'speechless-making'? I wanted to write about intense fear, something like abject terror, but implying that it strikes you dumb with fear. Am I missing something obvious, or should I just settle for changing the wording to avoid the problem?

A: Are you looking for stupefying?

A: I can think of stunning, paralysing, shocking, staggering, traumatising, devastating, demolishing, overwhelming, shattering, ravaging terror.

A: There is exactly such a word:

dumbstruck
adjective
  so shocked or surprised as to be unable to speak: he was dumbstruck with terror.

[NOAD]

A: Another option I thought of today was aphonic, but I think that is a tad too esoteric, and more likely just to trip readers up.
In the end, I think the solution was staring me in the face:

abject, speechless terror

A: What about "I was rendered speechless"?  It might be so common that it's more of a cliche.

A: "nonplus" answers the broad question posed by your title.


text:
Q: Unwanted space in table cell when another cell has a tag within it I'm having trouble understanding why the two chunks of HTML below render differently. The yellow and pink table is missing a BR tag, and flows efficiently, the green and blue table has the
 tag in the middle of the text in the blue cell, and has unwanted space in the green cell. I've tried rendering as flex boxes and tables, and they render the same way. I've tried different browsers, and they render the same way.
What rule is being followed in the green and blue layout that causes the whitespace in the green cell?
How can I get rendering like the yellow-and-pink case and use
 tags? I'm actually after
 tags, but let's just talk about
 tags, which I figure are the most simple case.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
<xbr/>
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?

Screenshot:
If a height is assigned to a div, the whitespace is not removed (see the darker green below), and if a
 tag is allowed into a table which has a height on the cell, the whitespace is split between the top and bottom of the cell (see the lighter green below) - but the height attribute doesn't affect the rendering anyway:
This behaviour is exhibited in FireFox 80.0 and Chrome Version 85.0.4183.83

A: Here's what's going on:

*

*Inside of the div with display: flex; flex-flow: row you have two children, the green and the blue divs.

*The browser calculates their individual widths (it's the width because flex-flow: row) as follows:

*

*The calculation of the green div's width is straight forward. It's the width of the whole text on one line.
=> greenWidth

*The calculation of the blue div is a little bit more involved because of the
. This causes the text to be split in two. The browser then calculates the widths of these two bits of text that they would take on one line each. Then it takes the wider of these.
=> blueWidth

*Both, the green and the blue box have their default value for flex-basis which is auto. For the green box, the browser takes greenWidth and for the blue box it takes blueWidth as the result of auto.

I still haven't come up with an actual solution but maybe, based on the above, you might be able to figure something out.

A: In the flex-box the items are stretched to the height of the container (if height of items is not defined). However, You can change this behaviour by gibing the green div a height.
Suppose the height is 100px;

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
 incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque
 laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
 architecto beatae vitae dicta sunt explicabo.

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci
velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam
aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem
ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque
laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
architecto beatae vitae dicta sunt explicabo.
<xbr/>
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci
velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam
aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem
ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?

A: Christian pointed in the right direction. Understanding that the problem is down to sizing being affected by tags, I allowed the browser to size the un-tagged content, but hid its rendering.
The "solution" is to have two text bodies, one rendering with tags and the other without. The text without tags is color:transparent; and positioned with normal text flow. The text with tags is rendered on top of the document text flow in the location of the transparent text by using a z-index higher than the normal text. There is a chance that the text with tags will overflow the table, so layout your page with this possibility under consideration (or pad the text without tags a little):

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
<xbr/>
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?


text:
Q: htaccess mod_rewrite problems, what's wrong with my file? What's wrong with my .htaccess file?
RewriteEngine on
RewriteRule ^/([a-zA-Z]+)/([0-9]+)$ index.php?mode=$1&id=$2 [L]

Basically I want it to go from example.com/?mode=page&id=1 to example.com/page/1
From what I see,it's supposed to work but it doesn't...

A: *

*Remove leading / from your rule

*Add RewriteBase / after RewriteEngine line


text:
Q: Apply style, only if both classes are in use (media queries / bootstrap) Even if my browser is resized to use the sm style, this text-align applies to it - despite telling it to apply on md-3, not sm
In other words, I want to be able to apply a style only if media queries interprets my device as an sm screen. The style I have below, applies to all sizes - even md. How do I fix it?
My CSS:
div.col-md-3.subnav{
    text-align: center;
}

And the HTML:

Pricing

A: It's applied because there is class subnav on the div which defines text-align: center irrespective of current dimension.
You need to add media query rule for your specific alignment:
@media (min-width: 768px) {
    .subnav {
        text-align: center;
    }
}


text:
Q: Currency Mask JavaScript don't work I trying to use a currency mask in my laravel application, for example, I have a Input to get value from my orders, and I need to that be format in BRL (Brazilian Currency).
My Input

 R$
 <input type="number" class="form-control" aria-label="Amount (to the nearest dollar)" id="valor" name="valor" pattern="[0-9]*">

My Script

Input

Any suggestion? I read some examples in StackOverflow but I keep not understand.


text:
Q: Mongoose Promise with bluebird and typescript I am developing an application with nodejs/typescript and a mongodb database.
To query the database, I am using mongoose.
I've just read an article from the mongoose documentation on how to plug in an external promise library and it is very simple:
import mongoose = require("mongoose");
import Promise = require("bluebird");
mongoose.Promise = Promise;

Doing this is working fine. But I'd like to extend/override the type of the promise that is returned.
Here is an example of a function:
public getModel= () => {
    return MyModel.findOne().exec();
}

This function returns a _mongoose.Promise<MyModel> and I'd like to return a bluebird Promise<MyModel> because I know that is a bluebird promise.
Is there is anyway to change/extend/override the return type of mongoose query ?
Should I write a custom definition file for my app ? Any others suggestions would be appreciated.
Thanks !

A: Promise export as a variable in mongoose, so you can convert mongoose namespace as any first, and then set Promise to others.

*

*if you are using q lib.

*

*install npm install --save q @types/q first. tsc version >= 2.0.

*then add (<any>mongoose).Promise = Q.Promise;

*using bluebird lib, add code below.

*

*import Bluebird = require("bluebird");

*(<any>mongoose).Promise = Bluebird;

A:
Should I write a custom definition file for my app

Yes. It will mostly be a find and replace of Promise in the mongoose definition.

A: The mongoose team updated the definition file and you can now plug in and use your own promise library by assigning the MongoosePromise<T>.
Create a main .d.ts file for your application and add this:
declare module "mongoose" {
    import Bluebird = require("bluebird");
    type MongoosePromise<T> = Bluebird<T>;
}

Reference this file in your project and now Mongoose returns Bluebird Promise !
This also works for others promises library.
EDIT latest typings version
declare module "mongoose" {
    import Bluebird = require("bluebird");
    type Promise<T> = Bluebird<T>;
}

See documentation here

A: As of this writing, there is an open issue in the typings file that is installed if you use typings install mongoose to install the typings. Specificaly  typings file that is loaded imports mpromise, and that import statement results in inclusion of the full mpromise module definition file by typings and included in your typings\modules\mongoose\index.d.ts file.
Until this issue get's resolved, my workaround is to delete the module definition for ~mongoose~mpromise and replace the following line in the index.d.ts file:
import * as Promise from '~mongoose~mpromise';

with this one:
import Promise = require( "bluebird");

This is admittedly a temporary stop-gap as another call to typings install mongoose would revert this fix. For the curious, my current set up includes: typings ( version 2.0.0 ), npm ( 3.10.9 ), and node ( v6.9.2 )


text:
Q: how to support the screen readers to know the focused value in div and td element enter code herereplication procedure:enter code here
JQuery DatePicker sample link

*

*Open the attached link.

*Press Tab key outside the datePicker control

*Press Ctrl + ↓ then Ctrl + → or Ctrl + ← the focusing Date will change.

*I need to say currently the users focusing date is what?

Can you help me, how to give the support for users focused date into the screen readers. i have tried the aria-label and aria-selected attributes but not works correctly.
Like this I have colorPicker palate support sample in that sample I have the value for div element I have the same attribute (aria-label and aria-selected) in here also, but not works.
Can you please suggest me if there is an another way is present or my mistake in this.

table,td {
    border: 1px solid black;
}

Add a border to a table:

July

Su
Mo
Tu
We
Th
Fr
Sa

25
26
27
28
29
30
1

2
3
4
5
6
7
8

9
10
11
12
13
14
15

16
17
18
19
20
21
22

23
24
25
26
27
28
29

30
31
1
2
3
4
5

like this and i have attached my output on the image there while navigate the dates through the keyBoard using right/left/up/down arrow keys i have include the  "aria-label, data-value, id" attributes like aria-lable="focusing date is : 12/7/2017" data-value:"12/7/2017" id="cb854b9f-8f91-42d7-a55f-6ca1c5c39310_cell_selected"(same as tables aria-activedescendant attribute value)
but not work. the expecting result is when focus the date "13/7/2017" the screen reader should be says my aria-lable value with column no.


text:
Q: Add object with basic background-color then change it to other color with delay I have an ul. With javascript I add the li's to it. I need the added li with background-color #E4F3D6 then 10 seconds later change to #DDD as final color.
I know this is possible with animation and transition-delay but I don't figure out how.
I wrote this but doesn't work properly:
@-webkit-keyframes change-color {
    0% {
        background-color: #E4F3D6;
        /*-webkit-transition-delay: 5s;*/
    }
    100% { background-color: transparent; }
}
@-moz-keyframes change-color {
    0% {
        background-color: #E4F3D6;
        /*-moz-transition-delay: 5s;*/
    }
    100% { background-color: transparent; }
}
@keyframes change-color {
    0% {
        background-color: #E4F3D6;
        /*transition-delay: 5s;*/
    }
    100% { background-color: transparent; }
}

.test {
    height: 25px;
    background-color: #E4F3D6;
    -webkit-animation: change-color 2s ease;
    -moz-animation: change-color 2s ease;
    animation: change-color 2s ease;
}

Here a demo: https://jsfiddle.net/junihh/a657pd6q/4/
Anyone help me, please.

A: Set the transition-delay property in the CSS for the element itself:
.test {
  height: 25px;
  background-color: #E4F3D6;
  -webkit-animation: change-color 2s ease 5s forwards;
  -moz-animation: change-color 2s ease 5s forwards;
  animation: change-color 2s ease 5s forwards;
}

The above uses the shorthand alternative for the animation property:
animation: <animation-name> <animation-duration> <animation-type> <animation-duration> <animation-fill-mode>

The animation-delay property does precisely what its name suggests, it delays the start of the animation by the value specified (here 5s, five seconds); the animation-fill-mode property causes the final values of the animation to persist once the animation has completed:

document.getElementById('add').addEventListener('click', function() {
  var li = document.createElement('li');
  li.innerHTML = '

';
  document.getElementById('container').appendChild(li);
}, false);
* {
  margin: 0;
  padding: 0;
  border: 0;
  list-style: none;
}
#container {
  width: 200px;
  margin: 20px auto 0;
  padding: 15px;
  background-color: #FFF;
  border: solid 1px #DDD;
}
#container li {
  background-color: #DDD;
  margin-bottom: 4px;
}
#container li:last-child {
  margin-bottom: 0;
}
.button-box {
  margin: 20px auto 0;
  width: 100px;
}
#add {
  width: 100%;
  padding: 10px 0;
  background-color: #666;
  cursor: pointer;
  font-size: 14px;
  color: #FFF;
}
#add:active {
  background-color: #333;
}
@-webkit-keyframes change-color {
  0% {
    background-color: #E4F3D6;
  }
  100% {
    background-color: #F90;
  }
}
@-moz-keyframes change-color {
  0% {
    background-color: #E4F3D6;
  }
  100% {
    background-color: #F90;
  }
}
@keyframes change-color {
  0% {
    background-color: #E4F3D6;
  }
  100% {
    background-color: #F90;
  }
}
.test {
  height: 25px;
  background-color: #E4F3D6;
  -webkit-animation: change-color 2s ease 5s forwards;
  -moz-animation: change-color 2s ease 5s forwards;
  animation: change-color 2s ease 5s forwards;
}

  <button type="button" id="add">Add row</button>

JS Fiddle demo.
Note that, in the demo, I've used a final colour of #f90 instead of #ddd simply to make the animation more obvious (the difference between the start and end colours, otherwise, are easy to miss).


text:
Q: How to disable a TextField until the user has submitted the previous required field I am working on a project which includes adding customer information.
I have four TextFields that I wish to use to get the customer information from the user.
I want to disable each TextField until the user submits the previous required field. How do I do that?
I tried to do this for one of the text fields, but it did not work and is not complete:
TextField idTF = new TextField();
TextField nameTF = new TextField();
if (idTF.getText().isEmpty())
    nameTF.disableProperty();
TextField addressTF = new TextField();
TextField mobileTF = new TextField();

A: As mentioned by @MadProgrammer, you can add listener to the textProperty of the each TextField and turn off/on the disable property of the other textField, or alternatly you can create a BooleanBinding between the dependant fields.
The BooleanBinding can be created as below:
textField2.disableProperty().bind(
                    Bindings.createBooleanBinding(() -> textField1.isDisable() || textField1.getText() == null || textField1.getText().isEmpty(),
                            textField1.textProperty(), textField1.disableProperty()));

Below is the complete working example.

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TextFieldDemo extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane root = new StackPane();
        root.setPadding(new Insets(10));
        Scene scene = new Scene(root, 320, 300);
        primaryStage.setScene(scene);
        primaryStage.setTitle("TextField Demo");
        primaryStage.show();

        TextField tf1 = new TextField();
        TextField tf2 = new TextField();
        TextField tf3 = new TextField();
        TextField tf4 = new TextField();
        Button submitBtn = new Button("Submit");
        addBinding(submitBtn, tf1, tf2, tf3, tf4);
        VBox pane = new VBox(tf1, tf2, tf3, tf4, submitBtn);
        pane.setSpacing(10);
        root.getChildren().add(pane);
    }

    private void addBinding(Button submitBtn, TextField... textFields) {
        for (int i = 0; i < textFields.length; i++) {
            TextField tf = textFields[i];
            Node node = i == textFields.length - 1 ? submitBtn : textFields[i + 1];
            node.disableProperty().bind(
                    Bindings.createBooleanBinding(() -> tf.isDisable() || tf.getText() == null || tf.getText().isEmpty(),
                            tf.textProperty(), tf.disableProperty()));
        }
    }
}


text:
Q: Koszul complex for monomials Suppose I have a list of monomials $f_1, \dots, f_m \in R = K[x_1, \dots, x_n]$.
Is there a nice description of the cohomology of the Koszul complex
\begin{equation}
\cdots \rightarrow\bigwedge^{r+1}M^* \rightarrow \bigwedge^{r}M^* \rightarrow \cdots
\end{equation}
with $M = R^{\oplus m}$ and differential given by contracting with the vector
$(f_1,\dots,f_m)\in M$?
By nice, mean something that might glue together well in a global setting (over a toric variety).


text:
Q: Ghost field in Templavoilà I'm using this bit of Typoscript to generate some text.
field_test is created via TemplavoilàPlus.
# If field_test is filled in by the redactor,
# its content will be displayed in the frontend.

10 = TEXT
10.if.isTrue.field = field_test
10.value.field = field_test

I'm using several FCE from TV+ and I have many more fields handled via Typoscript. For some FCE, I didn't set field_test in TV+ and thus, it is not displayed in the frontend at all since the redactor can't fill it in in the backend. This is the normal behaviour.
However, for one the FCE, field_test is displayed anyway. This field is not set in TV+ and I can't find it in the XML. It is not displayed in the backend and then can't be filled in.
But it has existed at some point, and has been filled before it was removed from the TV+ FCE.
Now I have its ghost displayed in the frontend. How can I find it and delete it for good?

A: you need to identify those CEs which have set field_test and where this field should be empty.
You could edit every CE, change it's type to a type where the field id visible, check for empty and change type back to origin.
or you do some immediate SQL queries in a tool like phpmyadmin:
select * from tt_content where field_test!='' and (CType = ...)

A: I've found a workaround for my problem.
I simply recreated field_test in TV+, went to the backend to empty the content of that field (which was filled even though the field had been deleted).
Conclusion: When you delete a field in TV+, the content of that field still exist somewhere…


text:
Q: GlassFish v3.0.1 ignoring sun-web.xml I have a WAR (extendedname1.01.war) and I have set up a sun-web.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Sun ONE Application
Server 7.0 Servlet 2.3//EN" "http://www.sun.com/software/sunone/appserver/dtds/sun- web-app_2_3-0.dtd">
<sun-web-app>
   <context-root>/app</context-root>
 </sun-web-app>

When I deploy the war it ignores the context in my sun-web.xml and leaves the context root as /extendedname1.01.
The sun-web.xml is in the WEB-INF/ folder of my war.
Can anyone shed any light on this please?
Many Thanks

A: There is a problem with the admin GUI tool.
You should deploy your application through the command line asadmin tool:
for example:
./asadmin deploy extendedname1.01


text:
Q: remove 'load more' button when all data is loaded I'm trying to use a button to load more data from database with PHP.
Till now I can count the results and the results that are showing.
So when $count==$countAll, all the results are normally showing.
Can someone explain why this isn't working?
// Count all results
$allResults = $conn->prepare("SELECT*FROM tl_picture WHERE text LIKE '%$innerhtml%' ORDER BY id DESC");
$allResults->execute();
$countAll =$allResults->rowCount();
echo "Found results: ".$countAll."<br>";

//max 20 results showing
$statement = $conn->prepare("SELECT*FROM tl_picture WHERE text LIKE '%$innerhtml%' ORDER BY id DESC  limit 20");
$statement->execute();
$collection = $statement->fetchAll();
$count =$statement->rowCount();
echo "viewable results: ". $count;

<script>
<?php if($count==$countAll): ?>
        document.GetElementById('loadButton').style.display='none';
    } else {
        document.GetElementById('loadButton').style.display='block';
    }
    <?php endif; ?>
</script>

A: What you are trying to achieve is normally done with ajax calls. So the check for the visibility of the Load More button must be done with javascript after every asynchronous load. PHP runs on server side, once before sending the HTML document to your browser and doesn't help at all in this case.
Also you execute the sql query for all rows and then you do it again with limit this time. It is inefficient to run twice the same query just to get the number of all records.
The logic should be that you load 20 rows and each row should have an identifier. Using the identifier of the last loaded row, you ajax request the next 20 rows etc. If response data from ajax is empty, then you hide the Load More button (or disable it and set text to something like "No more records").

A: You might have an error in this script:
<script>
    <?php if($count==$countAll): ?>
        document.GetElementById('loadButton').style.display='none';
    } else {
        document.GetElementById('loadButton').style.display='block';
    }
    <?php endif; ?>
</script>

You might change it to something similar to:
<script>
    <?php if($count==$countAll): ?>
        document.GetElementById('loadButton').style.display='none';
    <?php } else { ?>
        document.GetElementById('loadButton').style.display='block';
    <?php endif; ?>
</script>

The problem might be that your } else { is in JavaScript, yet there might be no if for it?


text:
Q: Concatenate multiple columns into new column. csv file, python, pandas I have a large index of csv's with x number of columns and y number of rows. I want my code to run through each csv (while index loop) and combine columns with specific headers into a new column and then save the csv into a new path. This is my code so far but I'm getting error:
'utf-8' codec can't decode byte 0xa9 in position 33: invalid start byte

Any ideas?
import os
import pandas as pd

#code to add new row to all csvs with unique identifier stamp that combines
the following:
#wellkey+drillkey+lat+long+spuddate

files=['Apr 23 2018.csv','Apr 20 2018.csv']
index=0
os.chdir('file path')

#code to loop through all the files listed above
while index < len(files):
    os.chdir('file path')
    current_file=files[index]

    #unique identifier column
    df=pd.read_csv(current_file)
    df['Unique Identifier']=df['A'] + "-" + df['B'] + "-" + df['C'] + "-" +
    df['D'] + "-" + df['E']
    df.to_csv(current_file)

    #save new csv
    os.chdir('New file Path')
    index = index + 1

Thank you for your advice/comments/corrections.

A: When I run into this issue, the first thing I will try is adding encoding='ISO-8859-1 to my pd.read_csv() statement
So your statement will look like this:
df=pd.read_csv(current_file, encoding='ISO-8859-1')


text:
Q: Header View height in a ListView I'm working with a ListView that is part of an ListFragment. I want to add a header with a specific/custom height but it does not matter what I put in the height of the header view, always it has the same height. Is possible to modify the header view height of a ListView?
Below the code I use:
header.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp" />

ListFragment
 @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        TextView fakeHeader = (TextView)getActivity().getLayoutInflater().inflate(R.layout.header, null);
        getListView().addHeaderView(fakeHeader);
    }

A: When you pass in null as the second parameter to inflate(), you are saying there is no parent associated with the view. This has the unfortunate side effect where any layout_ attribute you use is ignored as layout_ parameters affect how the parent lays out the child view rather than directly affect the child (like other views): this pro-tip godes into more details on layout_ attributes.
You can use inflate(R.layout.header, getListView(), false) to pass in the ListView which will eventually the parent of your header view (note the false says to not add the view directly - ListView will do this automatically for you).


text:
Q: How to fix cell format as a date (with YYYYMMDD format) and texts are not allowed I want to fix the format of a range of cells as date with this formatting: "YYYYMMDD" and no texts are supposed to be allowed.
I also want this formatting to hold true if a user inserts a new row below "G12". Any help would be greatly appreciated.
The code is located in a command button in my sheet1. There was no error at all. But if my value in the cell are texts then it doesnt throw up an error like its supposed to.
This is the code I tried to run but its not working
  With Range("G12")
       if Len(.value) <> 8 Then
       MsgBox "Date format must be in YYYYMMDD"

       If not IsDate(.value) then
        Msgbox "Date of Birth is a Mandotory field"

       End If
       End If

  End With

Updated
If Not Intersect(Target, Range("F4:F13")) Is Nothing Then

   If Not IsNumeric(.Value) And Not cel.NumberFormat = "yyyymmdd" Then
            MsgBox "Date format must be in YYYYMMDD"
            cel.Value = ""
            Exit Sub
       Else: cel.NumberFormat = "yyyymmdd"
       End If
   End With

 End If

A: Use Data Validation to require that the column holds a date, and set the numberformat of the column to "YYYYMMDD". Any row inserted will inherit those rules in teh target column.

A: I think for this particular purpose you should make use of Worksheet_SelectionChange
Like put this code on in the Sheet where you are working
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

For Each cel In Target
If cel.Column = 7 Then

      With cel
           If Not IsNumeric(.Value) And Not cel.NumberFormat = "yyyymmdd" Then
                MsgBox "Date format must be in YYYYMMDD"
                cel.Value = ""
                Exit Sub
           Else: cel.NumberFormat = "yyyymmdd"
           End If
      End With

End If
Next
End Sub

This should make every cell in the G column with your required Format. You can include more checks if you want.


text:
Q: Запуск git от имени другого пользователя Использую vscode, через remote-ssh подключаюсь к хосту.
В файле /root/.bashrc добавил alias git='sudo -u user git'. Выполняя команду git из терминала vscode под рутом, ожидаемо гит выполняется от пользователя.
Однако  расширение vscode:git выполняя команду git rev-parse --show-toplevel отдает ошибку

fatal: detected dubious ownership in repository at '/...'

Можно ли как нибудь заставить расширение работать от другого пользователя?
P.S. Кроме git config --global --add safe.directory /...


text:
Q: Copying from one text box to another I have to copy the text from one text box to another using checkbox through jQuery I have applied jQuery event in my code, it works partially correct. Code is as follows:
<html>
<head>
    <script src="js/jquery.js" ></script>
</head>
<body>
    <form>
        <input type="text" name="startdate" id="startdate" value=""/>
        <input type="text" name="enddate" id="enddate" value=""/>
        <input type="checkbox" name="checker" id="checker" />
    </form>
    <script>
    $(document).ready(function(){
            $("#startdate").change(function(o){
        if($("#checker").is(":checked")){
            $("#enddate").val($("#startdate").val());
        }

});
});
    </script>
</body>
</html>

This code works as follows;
I always have checkbox checked by default hence whenever I insert the start date and then tab, the start date gets copied to enddate.

My Problem

but now if uncheck the checkbox and change the start date and then recheck the check box, the start date is not copied, Now what should be done in this situation? Please help me.

A: Something like this:
$(document).ready(function(){
    $("#startdate").change(function(o){
        if($("#checker").is(":checked")){
            $("#enddate").val($("#startdate").val());
        }
    });

    $("#checker").change(function() {
        if($(this).is(":checked")) {
            $("#enddate").val($("#startdate").val());
        }
    });
});

A: Add an event for the checkbox as well:
$('#checker').bind('click', function () {
    if ($(this).attr('checked')) {
       $("#enddate").val($("#startdate").val());
    };
});

Or maybe only if enddate does not have a value:
$('#checker').bind('change', function () {
    var endDate = $('#enddate');

    if ($(this).attr('checked') && jQuery.trim(endDate.val()) === "") {
       endDate.val($("#startdate").val());
    };
});

A: you can just .bind() a click event to your checkbox.
$('#checker').click(function(){
   if($(this).is(':checked')){
      $("#enddate").val($("#startdate").val());
   }
});


text:
Q: Scaling vector images in WPF Let's suppose, that we have the following vector image consisting of two paths:
<Path Data="M 0 0 L 4 0 L 4 8 L 0 8 Z" Fill="Black" />
<Path Data="M 4 0 L 8 0 L 8 8 L 4 8 Z" Fill="Black" />

The most important fact is, that this image is supposed to be 16x16 units (despite fact, that only 8x8 square area is covered by the actual image).
I want the image to scale to desired size - for example, I want to place it somewhere with size 32x32 (then, the drawn square should be of 16x16 size). How can I do it?
The even harder part is, that I want the image to reside in the resources. This can be solved in the following way:
<Canvas Width="16" Height="16" x:Key="MyImage">
    <Path Data="M 0 0 L 4 0 L 4 8 L 0 8 Z" Fill="Black" />
    <Path Data="M 4 0 L 8 0 L 8 8 L 4 8 Z" Fill="Black" />
</Canvas>

(...)

<ContentPresenter Content="{DynamicResource MyImage}" />

But that doesn't solve the problem with scaling. If it is possible, I would like a solution not involving usage of various Transforms.

A: If you want it to resize nicely to any size, place it in a Viewbox with Stretch="Fill".
<Viewbox Stretch="Fill" x:Key="MyImage">
    <Canvas Width="16" Height="16">
        <Path Data="M 0 0 L 4 0 L 4 8 L 0 8 Z" Fill="Black" />
        <Path Data="M 4 0 L 8 0 L 8 8 L 4 8 Z" Fill="Black" />
    </Canvas>
</Viewbox>

This will stretch the content to whatever the size of the Viewbox is.
If you want different stretching behaviour: System.Windows.Media.Stretch

A: I believe that you might have the wrong impression about vector graphics in WPF. While it is true that because WPF utilises vector graphics, it can smoothly scale these graphics, it should be noted that they do not scale themselves.
Therefore, you have a list of instructions that describe how to recreate an image using graphics primitives in your Path object, but it holds no resizing abilities. For resizing duties, you have two options: Use a ScaleTransform, or use a ViewBox (from the linked page on MSDN):
<Path Data="M10,100 C 60,0 100,200 150,100 z"
    Fill="{StaticResource linearGradientBackground}"
    Stroke="Black"
    StrokeThickness="2">
    <Path.RenderTransform>
        <ScaleTransform ScaleX="3.0" ScaleY="3.0" />
    </Path.RenderTransform>
</Path>

...

<ViewBox Stretch="Uniform">
    <Path Data="M10,100 C 60,0 100,200 150,100 z"
        Fill="{StaticResource linearGradientBackground}"
        Stroke="Black"
        StrokeThickness="2">
    </Path>
</ViewBox>


text:
Q: How to change load layout in Joomla view? By default  parent::display($tpl); loads components/com_my_component/views/my_component/tmpl/default.php, but in some cases i need to load other php file which is in the same folder near default.php (for example components/com_my_component/views/my_component/tmpl/lol.php). How to do this from view.html.php.
P.S.
Tried load loadTemplate and setLayout methods with no luck.

A: By default, joomla looks for the layout keyword in the URL to decide which layout to display. If this variable is empty or not present then the tmpl/default.php layout will be loaded.
By editting your view.html.php file you can set the default layout by using the JView API, e.g. $this->setLayout('lol') will make the URL example.com/yourview equivalent to example.com/yourview?layout=lol.
However, this change alone will result in Joomla overriding it's default behaviour so that the layout request will be ignored. This means that the request example.com/yourview?layout=lmao will also display example.com/yourview = example.com/yourview?layout=lol
You can solve this easily by adding a condition around the setLayout function so that only if the layout keyword is not present then you will set the default layout to lol, e.g.

    <?php
    # ...

      function display($tpl = null) {
        # ...

        # Edit : Set the default layout to 'lol'
        $layout = JRequest::getWord('layout', '');
        if (empty($layout)) $this->setLayout("lol");

        // Display the view
        parent::display($tpl);
      }

    # ...

A: I keep coming back to this and I've yet to find a satisfying solution.
What does work, from J1.5 right up to J3.4, for me has always been to set the $tpl variable in view.html.php
If $tpl is empty or "" then tmpl/default.php is displayed by default.
If you change $tpl to a string, e.g. $tpl="stacker" then it will look for and display tmpl/default_stacker.php
I've seen various differing theories on changing it earlier in the MVC so that it doesn't need the default_ pretext. e.g. tmpl/stacker.php
None have worked for me.

A: Solved the problem by myself. Need to use the method setLayout and pay attention to the input syntax
$this->setLayout('dafault:lol');
parent::display($tpl);


text:
Q: MariaDB 10.0 renames foreign keys on dump insert State:
Two exact database setups with MariaDb 10.0
One is full the other empty waiting for the dump to insert.
Foreign key constraint exist on a table:
ALTER TABLE `rel_account_account` ADD CONSTRAINT `FK_Account` FOREIGN KEY (`InAccountID`) REFERENCES `t_account` (`ID`) ON DELETE RESTRICT ON UPDATE CASCADE;

If I dump the database by
mysqldump -uroot -p --default-character-set=utf8 livedb -r live.sql

and restore it on the other system by
mysql -uroot -p --default-character-set=utf8 livedb
mysql> SOURCE live.sql

Afterwards the foreign keys are renamed to a specific schema:
<tablename>_ifbk<index>

that means the FK:
FK_Account

has been renamed automatically to:
rel_account_account_ifbk_1

I did not find anything about such a possibility in the docs, so i ask this here. Is this a configurable feature, because if its done automatically i would assume that it could be very critical?
Any ideas?
EDIT: Please see answer.

A: ok, seems i overwrote the dump before inserting it with another one created from NAVICAT MySql tool.
but this one, which should theoretically be the same, did not create the statements as shown by SHOW CREATE TABLE. (Thanks to @Michael Berkowski for the hint!)
I discovered that there is an option under advanced to use statements from SHOW CREATE TABLE, which does export the FK constraints with their names.
So the first dump did not set the FK names, therefor mariadb created it own key names for them, which is technically correct.
So it was a simple homemade problem, with a little technical salt.