NOT Differentiable in $z \Rightarrow$ NOT Holomorphic in $z$?

Question: I was studying complex analysis and suddently I got some kind of stupid question in my head, which is the following:
If I want to prove that a complex function isn't holomorphic at the origin (only an example), is it enough to prove that it's not differentiable there? i.e., is it enough to prove that
\begin{equation*}
f'(z) = \lim_{z\rightarrow0}\frac{f(z)-f(0)}{z-0} \hspace{.2cm} \text{does not exist}?
\end{equation*}
Or do I have to check if the CR-Equations aren't verified in any neighbourhood of the origin? (If they aren't verified, then the function isn't holomorphic).
Thanks for all the help in advance.
Comment: Complex differentiability $\iff$ holomorphicity $\iff$ analyticity $\iff$ Cauchy-Riemann equations hold (and several more iffs). Holomorphicity is a really strong condition.
Comment: @davidlowryduda Complex differentiability is a point-by-point condition. It is not equivalent to the following two. Complex differentiability in a neighborhood is what is equivalent to the rest.. Likewise, Cauchy-Riemann equations alone is also not equivalent. [Example for Cauchy-Riemann](https://math.stackexchange.com/q/1802036/917479). Example for differentiability $z\mapsto z|z|$ at $z=0$.
Comment: @plop You make an excellent point. Yes, it is necessary to be differentiable in a neighborhood.
Comment: Since "not Q implies not P" is equivalent to "P implies Q", the old title was really the opposite. But anyway, now it looks OK!
Comment: Thanks for the help!
Comment: The implication in the title is the opposite of the one you're actually asking about.
Comment: Hello @HansLundmark . Actually, what I am asking for is: NOT Differentiable in $z \Rightarrow$ NOT holormophic in $z$. And, from José Carlos Santos answer I believe that this is true. I will update the title anyway, thanks for noticing!
Answer: Under any definition of holomorphic function that I am aware of, all you have to check is that that limit doesn't exist. Note that it is perfectly possible that $(0,0)$ is a solution of the Cauchy-Riemann equations and, even so, $f$ is not differentiable at $0$ (take, say $f(z)=\sqrt{|\operatorname{Re}(z)\operatorname{Im}(z)|}$).
Comment: Thanks! Really helpfull :D
Answer: Yes, this suffices. Being holomorphic in a point means to be complex differentiable in that point (and, moreover, any point of a neighborhood). So being differentiable in one point is necessary for being holomorphic in that point.
Comment: Thanks! Clarified my doubt!


Compiling C code that uses both R and numpy on Linux

Question: I have some C code that uses both numpy and R. On Windows, it compiles with MSVC to a .dll which can be dynamically loaded from R and passes all the tests. However, I fail to make it work on Debian.
To investigate the problem I created the following minimal-ish example:

#include <Python.h>
#include <Rinternals.h>
#include <numpy/arrayobject.h>

SEXP main() {
   Py_Initialize();
   import_array();

   SEXP one = PROTECT(allocVector(INTSXP, 1));
   INTEGER(one)[0] = 1;
   npy_intp dims[1] = {1};
   int data[1] = {1};
   PyObject *another = PyArray_SimpleNewFromData(1, dims, NPY_INT, data);

   Rprintf("Hello, %d ", INTEGER(one)[0] + *(int*)PyArray_DATA(another));
   PyRun_SimpleString("print('worlds')");

   UNPROTECT(1);
   return one;
}

I can compile it with

cl /I "C:\Program Files\R\R-3.2.0\include" /I "C:\Python34\include" /I "C:\Python34\Lib\site-packages\numpy\core\include" /c hello.c
link /dll /export:main hello.obj Rdll.lib C:/Python34/libs/python34.lib

where Rdll.lib was created from %R_HOME%\bin\x64\R.dll with

pexports R.dll > R.exp
link /lib /def:R.exp /machine:x64 /out:Rdll.lib

Then it can be used from R:

> dyn.load(paste0("hello", .Platform$dynlib.ext))
> .Call("main")
Hello, 2 worlds
[1] 1

When, however, I compile it on Debian with

gcc -shared -fPIC -I/usr/share/R/include -I/usr/include/python2.6 -lpython2.6 -L/usr/lib64/R/lib -lR hello.c -o hello.so

and import it from R the following happens:

> dyn.load("hello.so")
> .Call("main")
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.6/numpy/__init__.py", line 132, in <module>
    import add_newdocs
  File "/usr/lib/pymodules/python2.6/numpy/add_newdocs.py", line 9, in <module>
    from lib import add_newdoc
  File "/usr/lib/pymodules/python2.6/numpy/lib/__init__.py", line 4, in <module>
    from type_check import *
  File "/usr/lib/pymodules/python2.6/numpy/lib/type_check.py", line 8, in <module>
    import numpy.core.numeric as _nx
  File "/usr/lib/pymodules/python2.6/numpy/core/__init__.py", line 5, in <module>
    import multiarray
ImportError: /usr/lib/pymodules/python2.6/numpy/core/multiarray.so: undefined symbol: _Py_ZeroStruct

 *** caught segfault ***
address 0x4, cause 'memory not mapped'

It does produce segmentation faults unless everything related to numpy is commented out. Interacting with pure Python from R seems to be OK. But as soon as import_array() is called there is a segfault. I added -I/usr/share/pyshared/numpy/core/include/ out of desperation and it didn't change anything.
Finally, if I compile the following (similar to the previous, but slightly changed) code

#include <Python.h>
#include <Rinternals.h>
#include <numpy/arrayobject.h>

int main() {
   char *localArgs[] = {"R", "--silent"};
   Rf_initEmbeddedR(2, localArgs);
   Py_Initialize();
   import_array();

   SEXP one = PROTECT(allocVector(INTSXP, 1));
   INTEGER(one)[0] = 1;
   npy_intp dims[1] = {1};
   int data[1] = {1};
   PyObject *another = PyArray_SimpleNewFromData(1, dims, NPY_INT, data);

   Rprintf("Hello, %d ", INTEGER(one)[0] + *(int*)PyArray_DATA(another));
   PyRun_SimpleString("print('worlds')");

   UNPROTECT(1);
}

on the same Debian machine with

 gcc -I/usr/share/R/include -I/usr/include/python2.6 -lpython2.6 -L/usr/lib64/R/lib -lR hello.c -o hello

and call it with

LD_LIBRARY_PATH=/usr/lib64/R/lib R_HOME=/usr/lib64/R ./hello

it suddenly doesn't crash, works well and produces "Hello, 2 worlds", as expected.
The versions are:
Windows: Compiler Version 19.00.23506 for x64, Python 3.4.4, numpy 1.9.3, R 3.2.0
Debian: gcc version 4.4.5 (target: x68_64-linux-gnu), Python 2.6.6, numpy 1.4.1, R 3.2.1
What am I doing wrong?
Update: Tested on Ubuntu with both Python 3.2 and Python 2.7 with both gcc and clang. The problem persists.
Answer: A solution that works (with this example as well as with the real code) is to load libpythonX.Y.so with dlopen:
 #include <Python.h>
 #include <Rinternals.h>
 #include <numpy/arrayobject.h>

 #ifndef _WIN32
 #include <dlfcn.h>
 #endif

 SEXP main() {
 #ifndef _WIN32
    dlopen("libpython2.6.so", RTLD_NOW | RTLD_GLOBAL);
 #endif
    Py_Initialize();
    import_array();

    SEXP one = PROTECT(allocVector(INTSXP, 1));
    INTEGER(one)[0] = 1;
    npy_intp dims[1] = {1};
    int data[1] = {1};
    PyObject *another = PyArray_SimpleNewFromData(1, dims, NPY_INT, data);

    Rprintf("Hello, %d ", INTEGER(one)[0] + *(int*)PyArray_DATA(another));
    PyRun_SimpleString("print('worlds')");

    UNPROTECT(1);
    return one;
}

I do not, however, fully understand why it is needed.


handling 'this' in an addEventListener

Question: I want to call handleRangeUpdate in such a way that it would be dependent on the event which it is called so that it can decide to execute console.log(this.value)
However upon passing e into handleRangeUpdate through the addEventListener, the value of this then changes from input to window, or to handleRangeUpdate not being called at all, depending if I used arrow functions or tried to bind/call this to the listener.
My issue and question is this (no pun intended), how do I pass the proper this to the listener in addEventListener?
const sliders = player.querySelectorAll('.player__slider');
sliders.forEach(slider => slider.addEventListener('change', handleRangeUpdate));
sliders.forEach(slider => slider.addEventListener('mousemove', handleRangeUpdate));

and the html for the sliders:
<input type="range" name="volume" class="player__slider" min="0" max="1" step="0.05" value="1">
<input type="range" name="playbackRate" class="player__slider" min="0.5" max="2" step="0.1" value="1">

Comment: simple ... don't use arrow function notation - i.e. use the right tool for the job, a chisel isn't good at hammering nails
Comment: You have to define `handleRangeUpdate` using `function`, otherwise it is not possible to pass a dynamic `this` to it. If you insist on using arrow functions or bound functions for some reason, you can only use `e.currentTarget` and not `this`.
Comment: You need to add an [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example so we can help you.
Comment: Arrow functions are NOT just syntactic sugar.
Answer: I believe this will work but having a code sample from codepen on your end would be more helpful. You need to bind the handlers. addEventListener will always execute the handler function in the this context of the element or object that triggered the event.
const sliders = player.querySelectorAll('.player__slider');
sliders.forEach(slider => slider.addEventListener('change', () => handleRangeUpdate.bind(this)));
sliders.forEach(slider => slider.addEventListener('mousemove', ()=> handleRangeUpdate.bind(this)));

Comment: There's nothing wrong in the code that the OP has posted up to now. Your snippet however will definitely not work.

handling 'this' in an addEventListener


Create new field type for custom content

Question: I want to create a new content type called "Message". It will have a couple of fields, "message-body" which will be plain text and "addressees". The addressees field should reflect a list of the registered users of the site.
The idea is to create a field type that will be a checklist where all users of the site can be selected, and those that are will receive the message in "message-body" via drupal_set_message($msg).
I am not suceeding so far in creating a custom field type. The Field API documentation is not very clear.
Thanks.
Answer: You maybe already found the solutions for you problem.
I think in your case you can use Entity Reference. In your custom content type you can create a new field with the Entity Reference type. Then on the configuration page you can choose which entity to reference, like node, taxonomy or users, with different types of widget.
Here's a link of the Entity Reference module.
Answer: Why not make a content type via the menu interface www.yoursite.com/admin/structure/types/add.
Or you need it as a module that you can re-distribute?
An easier way then is to make use of features. It allows you to 'export' a built content type into a module. Enabling the module (on another site), then creates all the fields that where in the export.
Comment: Thanks for your answer. I am not sure that you understand what I require. It is not creating a new content type that is the problem, but creating a custom field for that content type. I am more or less being able to manage, following this nice tutorial: http://evolvingweb.ca/story/poutine-maker-introduction-field-api-drupal-7-part-1
Comment: Then I misunderstood you indeed.


Como ler um charde um arquivo e converter para inteiro

Question: O trecho de código a seguir deveria mostrar o valor inteiro do único caractere armazenado no arquivo. quando eu coloco uma letra como 'a' por exemplo funciona. mas quando eu coloco esse simbolo: þ. e vários outros ele mostra -2 na tela. sendo que esse simbolo de acordo com a tabela ASCII tem valor 231. o codigo é este:
#include <stdio.h>

int main() {
    FILE *ptr;
    char c;
    ptr = fopen("teste.txt", "r");
    fscanf(ptr, "%c", &c);
    printf("%d", c);
    return 0;
}

a unica coisa armazenada em teste.txt é o simbolo þ.
Comment: O simbolo  **þ** parece não ter na tabela ASCII, fiz a leitura aqui com seu código e o valor que retornou foi -61. Qual SO vc esta usando?
Comment: Não, a tabela ASCII só vai até o código 127. Você está pegando uma extensão dela. Aí pode variar o que retorna. O caractere que você está usando provavelmente é considerado um caractere *multibyte*, por isso está gerando esta confusão. Se você abrir o arquivo em algum software que permita ler o arquivo byte a byte, provavelmente vai achar 2 ou mais. Aí o arquivo está lendo só o primeiro.
Comment: Entendi, vou ver isso. Meu SO é o Windows 7 profissional
Comment: Aconselho a leitura de [O Mínimo Absoluto Que Todo Desenvolvedor De Software Absolutamente, Positivamente Precisa Saber Sobre Unicode E Conjuntos de Caracteres (Sem Desculpas!)](http://local.joelonsoftware.com/wiki/O_M%C3%ADnimo_Absoluto_Que_Todo_Desenvolvedor_De_Software_Absolutamente,_Positivamente_Precisa_Saber_Sobre_Unicode_E_Conjuntos_de_Caracteres_(Sem_Desculpas!))
Comment: De uma olhada nesta tabela http://ic.unicamp.br/~everton/aulas/hardware/tabelaASCII.pdf aqui vc pode ver o caracter que vc quer, porem ele e um pouco diferente.
Answer: Na instrução
printf("%d", c);

o char é automaticamente convertido para int sem ser preciso fazer nada.
É parte da regra "integer promotions" (ver 126.96.36.199p6 no Standard C11 (inglês))
Comment: Por default os compiladores usam o C89. Eu próprio nunca usei o C11 mas do que parece as críticas são horríveis.
Comment: A regra é a mesma para C89 e [C99](http://port70.net/~nsz/c/c99/n1256.html#126.96.36.199p6), mas eu não tenho um link para o primeiro. Quanto às críticas ... a remoção de `gets()` foi positivo! Tirando isso (eu já não usava o `gets()` anteriormente) também não uso as novidades do C11 e uso poucas do C99.
Comment: A unica razão que utilizo o C99 é para declarar variaveis em laços loop de resto não faço a mínima o que mudou.


Help needed accessing the %UserProfile%\AppData\Roaming\Microsoft\Crypto folder

Question: Z:\Users\markk\AppData\Roaming\Microsoft>whoami
shunranet\markk

Z:\Users\markk\AppData\Roaming\Microsoft>cacls Crypto
Z:\Users\markk\AppData\Roaming\Microsoft\Crypto NT AUTHORITY\SYSTEM:(OI)(CI)F
                                                BUILTIN\Administrators:(OI)(CI)F
                                                SHUNRANET\markk:(OI)(CI)F

Z:\Users\markk\AppData\Roaming\Microsoft>attrib Crypto
   S    I    Z:\Users\markk\AppData\Roaming\Microsoft\Crypto

Z:\Users\markk\AppData\Roaming\Microsoft>dir Crypto
 Le volume dans le lecteur Z s'appelle System
 Le numéro de série du volume est CE62-FA00

 Répertoire de Z:\Users\markk\AppData\Roaming\Microsoft\Crypto

Fichier introuvable

Z:\Users\markk\AppData\Roaming\Microsoft>

How is it possible that I have full control of this folder, but still cannot browse its contents?
P.S.
I need to fix it, because this is why I suspect the following command fails:
Z:\>MakeCert.exe -r -ss my -n "CN=DO_NOT_TRUST_FiddlerRoot, O=DO_NOT_TRUST, OU=Created by http://www.fiddler2.com" -sky signature -eku 220.127.116.11.22.214.171.124.1 -h 1 -cy authority -a sha1 -m 120
Error: Can't create the key of the subject ('JoeSoft')
Failed

Z:\>

And I need this command to succeed in order to debug HTTPS traffic with Fiddler.
Comment: I guess sysadmins do not visit this site...
Answer: You seem to be confused, the files you are looking for probably exist.
The Crypto folder, as you may have noticed in your attrib command, is a system folder, this means it is not shown when using the dir command by itself.
C:\Users\myuser\AppData\Roaming\Microsoft>dir
 Volume in drive C has no label.
 Volume Serial Number is E042-CE10

 Directory of C:\Users\myuser\AppData\Roaming\Microsoft

01/17/2012  10:26 AM    <DIR>          Access
04/29/2010  01:49 PM    <DIR>          ActiveSync
01/12/2010  11:39 AM    <DIR>          AddIns
04/01/2010  09:44 AM    <DIR>          CLR Security Config
06/28/2010  11:10 AM    <DIR>          CLView
09/06/2011  12:24 PM    <DIR>          Communicator
01/12/2010  11:41 AM    <DIR>          Document Building Blocks
......

Notice that the Crypto folder is not shown, but if we do a 'dir /a' we see it.
C:\Users\myuser\AppData\Roaming\Microsoft>dir /a
 Volume in drive C has no label.
 Volume Serial Number is E042-CE10

 Directory of C:\Users\myuser\AppData\Roaming\Microsoft

01/04/2012  12:58 PM    <DIR>          .
01/04/2012  12:58 PM    <DIR>          ..
01/17/2012  10:26 AM    <DIR>          Access
04/29/2010  01:49 PM    <DIR>          ActiveSync
01/12/2010  11:39 AM    <DIR>          AddIns
04/01/2010  09:44 AM    <DIR>          CLR Security Config
06/28/2010  11:10 AM    <DIR>          CLView
09/06/2011  12:24 PM    <DIR>          Communicator
09/07/2011  11:34 AM    <DIR>          Credentials
02/05/2010  08:30 AM    <DIR>          Crypto
01/12/2010  11:41 AM    <DIR>          Document Building Blocks
......

The same is true with the Keys and RSA folders within the Crypto folder, they are marked as System. In fact everything withing the RSA folder is marked as System.
C:\Users\myuser\AppData\Roaming\Microsoft>attrib Crypto
   S    I    C:\Users\myuser\AppData\Roaming\Microsoft\Crypto

C:\Users\myuser\AppData\Roaming\Microsoft>attrib Crypto\RSA
   S    I    C:\Users\myuser\AppData\Roaming\Microsoft\Crypto\RSA

C:\Users\myuser\AppData\Roaming\Microsoft>attrib Crypto\Keys
   S    I    C:\Users\myuser\AppData\Roaming\Microsoft\Crypto\Keys

Thus if you were to run dir within the Crypto folder it would show you that no files or folders exist (that are not System files) but a dir /a would show them.
C:\Users\myuser\AppData\Roaming\Microsoft\Crypto>dir
 Volume in drive C has no label.
 Volume Serial Number is E042-CE10

 Directory of C:\Users\myuser\AppData\Roaming\Microsoft\Crypto

File Not Found

C:\Users\myuser\AppData\Roaming\Microsoft\Crypto>dir /a
 Volume in drive C has no label.
 Volume Serial Number is E042-CE10

 Directory of C:\Users\myuser\AppData\Roaming\Microsoft\Crypto

02/05/2010  08:30 AM    <DIR>          .
02/05/2010  08:30 AM    <DIR>          ..
02/05/2010  08:30 AM    <DIR>          Keys
01/12/2010  11:18 AM    <DIR>          RSA
               0 File(s)              0 bytes
               4 Dir(s)  70,075,576,320 bytes free

C:\Users\myuser\AppData\Roaming\Microsoft\Crypto>

I don't know what the issue is actually creating your keys, but I don't think it is a permissions issue or any other unexplained oddity. I know this is late getting to you, but it does explain what you are\were seeing.


Automated website folder backup system needed? Any recommendations?

Question: Hi guys is there any backup software that can take periodic backups of online website folders and store them offline on a local system. Need something robust and would be nice if theres something free that can do the job :)
Something that I could just install and let it run on a periodic basis. My local system is running on Windows XP
Answer: Wget, Unison, Rsync or you could even try something with version control software.
I use them all, depending on context.
Wget is nice to mirror a web site via ftp, Unison is nice to spread modifications on the same data in different places (and let you refine the hierarchy between them), Rsync synchronises well between two places, and subversion is nice to have a total backup solution that let you go back to the beginning and trace every modification of every file per line (not recommended for non-text files, although some won't do much difference - I use it on a complete chaotic company intranet).
No "easy" way though, at least if you want something thrust-worthy and efficient.
Comment: I think the Unison link is http://en.wikipedia.org/wiki/Unison_(file_synchronizer)
Comment: I don't think it's possible to link to that particular page as the link is truncated slightly - sort it out serverfault! http://en.wikipedia.org/wiki/Unison_(file_synchronizer)
Answer: You can try The Windows Version of Bacula
Answer: Similar to unison but superior imho, how about using dropbox (Linux, Windows and Mac clients available) and symlinking your web directory (exclusive of logs) to your dropbox folder?
Alternatively, instead of running a "hot copy" backup, you could periodically compress all the relevant web folders into an archive located in the dropbox directory, which would then automatically back that up for you online (as well as downloading to any other machines you have "dropbox"-ed). Then put a batch file in your XP startup folder that copies or moves all backup archives into another directory on your machine (n.b. if you move the file out of the dropbox folder on one machine, it is then removed from the online "folder", and finally the other clients synchronise with the online "folder" and remove the file too - there is still undelete functionality online if required).
If you're not familiar with dropbox here are a few of it's features (or here's a screencast):

"Live" sync of data to online storage
folder
When client installed on 2+
machines the dropbox folder
synchronises with the online version
Version control and undelete function
2GB free storage with upgrade to
100GB @ $199/pa
Answer: I would recommend using wget.exe to download the complete website to a local folder running as a scheduled task.
Comment: Wget won't backup. It only downloads visible content.
Answer: For example: You can output your databases backups to a dedicated folder, and then write a simple script to FTP the content to your local server and then move the files transfered to an archive folder on the remote server.
Answer: if you also need "invisible" content to backup, then you could use rsync to synchronize your local backup with the online content
Answer: I think you're approaching it from the wrong side.  I can see needing to bring down a copy of a database, but why the files?  You should already have a copy of your published content locally in your development environment, preferably in a source control system.
If your application creates new files, or you just have to work on the live version, then there are a number of FTP programs that will do scheduled runs using a script.  FTP Voyager, for example, will allow you to create a script to download your root FTP folder to a local folder, then schedule it daily.  Granted, it's not free, but it is inexpensive and will get the job done.


Weird linq-to-sql error

Question: the error happens in this line:
<code>OldPerson.PersonSerial = context.DB.Persons.Max(Function(p) p.PersonSerial) + 1
</code>

Could not find key member 'ID' of key
  'ID' on type 'Nationality'. The key
  may be wrong or the field or property
  on 'Nationality' has changed names.

there's a person table containing a foreign key to the nationality table.
i checked up that the column names match
what might be the cause of this error?
Comment: Is there a base-class in the mix here? http://connect.microsoft.com/VisualStudio/feedback/details/480761/linq-to-sql-xml-mapping-association-key-to-different-member-name-than-column-name-throws-invalidoperationexception
Comment: yes both person and nationality inherit a base class
Comment: @Marc Gravell:man how did you figure it out on the fly!
Answer: looks like sharing a base class for partial linq generated classes is causing this issue.
i removed the inheritance from the base class and it worked. No idea why though!
Comment: The scenario is not supported.

Weird linq-to-sql error


Existence of Minimum Value

Question: Assume $x\ge0$, show that the function $f(x,y)=(2xy+y^2)e^{-x}$ has a minimum value. Note that actual minimum value is $-4e^{-2}$.
Answer: Note that
$$f(x,y)=(x+y)^2 e^{-x}-x^2e^{-x}.$$
The first term is $\ge 0$. The second term is a function of $1$ variable, which is easy to analyze. For example, we can express it as $\dfrac{x^2}{e^x}$, and use the fact that $e^x\gt \dfrac{x^2}{2!}$.
Comment: Thank you! I am grateful for your incredibly speedy response.
Comment: You are welcome. It was quick because the "completing the square" strategy was so clearly useful.

Existence of Minimum Value


Printing empty brackets?

Question: I have a simple program that should take two arrays, convert them into lists, and take out the values that are the same. For some reason though I am getting a value of:
<code>[]
[]
[]
[]
</code>
Although the result should be "eggs", "lasers", "hats", "pie" - "lasers", "hats" which should get me a result of "eggs" "pie".
Here is my code:
<code>public class Arraystring {

    public static void main(String[] args) {
        String[] things = { "eggs", "lasers", "hats", "pie" };
        List<String> list1 = new ArrayList<String>();
        for (String x : things) {
            list1.add(x);
        }
        String[] thingstwo = { "lasers", "hats" };
        List<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list2.size(); i++) {
            list2.add(thingstwo[i]);
        }
        editlist(list1, list2);
    }

    public static void editlist(Collection<String> l1, Collection<String> l2) {

        Iterator<String> it = l1.iterator();
        while (it.hasNext()) {
            if (l2.contains(it.next())) {
                System.out.println("hui");
                it.remove();
            }
            System.out.println(l2);
        }
    }
}
</code>
Comment: What is the value of `list2.size()` in that second `for` loop?
Comment: @Rich In editlist(), instead of iterating over l1 and checking whether l2 contains current element or not, you could have simply use the method removeAll. `l1.removeAll(l2);`
Comment: Take a look at `toString` method. It is used by `System.out.println` and in case of collections it generates String with its elements in a form `[element0, ..., elementN]`. But because of `i < list2.size();` condition you didn't place anything in `l2` so as result you printed `[]`.
Comment: `for (int i = 0; i < list2.size(); i++) {  list2.add(thingstwo[i]); }` try to describe what happens in this code.
Comment: @Sotiros Delimanolis You are right, I meant to have this:
Comment: @Pshemo for(String i : thingstwo)

 {
  list2.add(i);

 }
Comment: And there you have solution to your problem :)
Comment: @Pshemo But now with this, a new issue comes up. My output is [lasers, hats]. I have two questions, why is the [] there in lasers, hats? Also, Shouldn't the output be everything **except** [lasers, hats], shouldn't it be "eggs" "pie"? Thank you so much for all the help you provided, I appreciate it greatly! :)
Comment: In `editlist` method: from which collection you are removing items and which collection you are printing? Also are you sure that you want to print it inside your loop?
Comment: @Pshemo The code works when doing System.out.println(l1); , but I really want to learn **how it works**;  what is going on  in the code at  the .remove(). Is it removing a value from the iterator itself...? I fail to see where I am removing the items from l2, although that is what the code reflects. Please explain. BTW: Thanks, you are helping a fellow programmer out a lot!
Comment: @Pshemo Also, I did move the printing outside the loop.
Comment: "*I fail to see where I am removing the items from `l2`*" well, that is probably because you are not removing items from `l2`, you are removing them only from `l1` via `it.remove();`. Your loop uses iterator `it` to iterate over all elements in `l1` (since this iterator was created by `l1`). Now `if (l2.contains(it.next()))` tests if `l2` contains element returned by iterator, and if it does (when `contains` returns `true`) you are executing `it.remove();` which via `it` removes from `l1` item which iterator returned with `next()`.
Comment: @Pshemo I guess the part that I was confused on was the fact that since the iterator was created by l1, by removing the iterator (which i'm assuming is an instance of l1) you are removing parts of l1, right? If so, then this makes a lot of sense now! Thank you so much for that great explanation :) What I still don't understand is why the output is inside of square brackets ([ ])...? Thanks1
Comment: Oh wow! I didn't know that, thanks Sandeep! I have liked your comment. What I still don't understand is why the output is inside of square brackets ([ ]), instead of just plain text in the console though. Again, thanks for the help1
Comment: @Pshemo Wow, that makes a lot more sense now. Thanks! I have liked your comment also.
Answer: First your line in Arraystring {..}
<code>    for (int i = 0; i < list2.size(); i++) {
</code>
should be
<code>    for (int i = 0; i < thingstwo.length; i++) {
</code>
And then you are printing the wrong list in editlist(..):
<code>        System.out.println(l2);
</code>
should be
<code>        System.out.println(l1);
</code>

Printing empty brackets?


Estimating importance of variables in a multilayer perceptron

Question: From online search so far, I have only found Garson Algorithm as a method for deducing the importance of variables in a Multilayer Perceptron. However the current Garson algorithm included in the 'NeuralNetTools' package for R calculates the importance for a MLP with single hidden layer only and doesn't work for 2 hidden layers.
Is there any other package that runs Garson algorithm on MLP with 2 hidden layers?
Also, is there any other approach to calculate the importance of variables in a MLP apart from Garson algorithm?
Comment: There are two parts.  The first is the (revolutionary) diagrammatic Jacobian.  Before Wan the gradients were each analytically derived, and a single learning approach could be a thesis.  He gave a general solution for the field.  (http://digitalcommons.ohsu.edu/cgi/viewcontent.cgi?article=1032&context=csetech)  The second part is the delta method.  It relates to Jacobian to the variance.  (http://www.math.montana.edu/~parker/PattersonStats/Delta.pdf). Here is a ref that suggests "Garson" is pretty bad. (http://www.massey.ac.nz/~mkjoy/pdf/Olden,Joy&DeathEM.pdf)
Comment: Have you considered the Eric-Wan diagrammatic jacobian with the Delta rule?
Comment: No I haven't... but I can't find much info on it on the web?
Comment: Thanks for the reference. You can put this answer rather than comment.
Answer: Why not trying the same approach as the one used for random forests ? Given a train/test set split of the data, you train your model then test it and observe the error.
Now, for each column of the test set, generate a random permutation of the elements and observe the new error. If the change observed is not important, then the predictor had little impact on the forecast.
For a more accurate estimation of the importance, you can perform a K-fold CV instead of just splitting the data.
I never saw anyone using it with neural networks. However, it applies successfully to SVMs.
The good thing with this approach is that it is completely independent of the learning method you are using - you can implement it once and for all.
Comment: Training and testing with different combinations of variables is my last option since I have some 200 variables in my neural net. This is a rather tedious option to try so many combinations of variables. Any idea on how K-fold CV works with NN?
Answer: Have you considered the Eric-Wan diagrammatic jacobian with the Delta rule?
There are two parts to this.

The first is the (revolutionary) diagrammatic Jacobian. Before Wan
the gradients were each analytically derived, and a single learning
approach could be a thesis. He gave a general solution for the field.
(here is the link)
The second part is the delta method. It relates to Jacobian to the
variance. (math.montana.edu/~parker/PattersonStats/Delta.pdf).

BTW:
Here is a ref that suggests "Garson" is pretty bad. (http://www.massey.ac.nz/~mkjoy/pdf/Olden,Joy&DeathEM.pdf)
Given that "sensitivity analysis" performs fairly well, you might like this link:
https://beckmw.wordpress.com/2013/10/07/sensitivity-analysis-for-neural-networks/


No mysqld or mysql.server after mariadb-server install

Question: So... likely I'm an idiot, but I'm stuck. I just set up a CentOS 7 on Digial Ocean and I can't seem to get the MariaDB/MySQL server running.
Some output
[root@hostname ~]# yum list installed |grep maria
mariadb.x86_64                        1:5.5.37-1.el7_0                @updates
mariadb-libs.x86_64                   1:5.5.37-1.el7_0                @updates
mariadb-server.x86_64                 1:5.5.37-1.el7_0                @updates

So it's installed, can we at least see the client?
[root@hostname ~]# which mysql
/bin/mysql

Let's try and start the server, just for fun
[root@hostname ~]# service mysqld start
Redirecting to /bin/systemctl start  mysqld.service
Failed to issue method call: Unit mysqld.service failed to load: No such file or directory.
[root@hostname ~]# mysqld
-bash: mysqld: command not found
[root@hostname ~]# mysql.server start
-bash: mysql.server: command not found
[root@hostname ~]#

And this is where I get lost. Looking at what is actually installed, there is no server/daemon
[root@hostname ~]# ls -la /bin/my*
-rwxr-xr-x 1 root root 3419136 Jun 24 10:27 /bin/myisamchk
-rwxr-xr-x 1 root root 3290760 Jun 24 10:27 /bin/myisam_ftdump
-rwxr-xr-x 1 root root 3277032 Jun 24 10:27 /bin/myisamlog
-rwxr-xr-x 1 root root 3320200 Jun 24 10:27 /bin/myisampack
-rwxr-xr-x 1 root root 2914904 Jun 24 10:27 /bin/my_print_defaults
-rwxr-xr-x 1 root root 3533016 Jun 24 10:27 /bin/mysql
-rwxr-xr-x 1 root root  111587 Jun 24 10:24 /bin/mysqlaccess
-rwxr-xr-x 1 root root 3089712 Jun 24 10:27 /bin/mysqladmin
-rwxr-xr-x 1 root root 3253112 Jun 24 10:27 /bin/mysqlbinlog
lrwxrwxrwx 1 root root      26 Sep  8 03:06 /bin/mysqlbug -> /etc/alternatives/mysqlbug
-rwxr-xr-x 1 root root 3090832 Jun 24 10:27 /bin/mysqlcheck
-rwxr-xr-x 1 root root    4247 Jun 24 10:24 /bin/mysql_convert_table_format
-rwxr-xr-x 1 root root   24558 Jun 24 10:24 /bin/mysqld_multi
-rwxr-xr-x 1 root root   27313 Jun 24 10:24 /bin/mysqld_safe
-rwxr-xr-x 1 root root 3173968 Jun 24 10:27 /bin/mysqldump
-rwxr-xr-x 1 root root    7913 Jun 24 10:24 /bin/mysqldumpslow
-rwxr-xr-x 1 root root    3315 Jun 24 10:24 /bin/mysql_find_rows
-rwxr-xr-x 1 root root    1261 Jun 24 10:24 /bin/mysql_fix_extensions
-rwxr-xr-x 1 root root   34826 Jun 24 10:24 /bin/mysqlhotcopy
-rwxr-xr-x 1 root root 3082072 Jun 24 10:27 /bin/mysqlimport
-rwxr-xr-x 1 root root   16204 Jun 24 10:24 /bin/mysql_install_db
-rwxr-xr-x 1 root root 2923136 Jun 24 10:27 /bin/mysql_plugin
-rwxr-xr-x 1 root root   11578 Jun 24 10:24 /bin/mysql_secure_installation
-rwxr-xr-x 1 root root   17473 Jun 24 10:24 /bin/mysql_setpermission
-rwxr-xr-x 1 root root 3084760 Jun 24 10:27 /bin/mysqlshow
-rwxr-xr-x 1 root root 3104240 Jun 24 10:27 /bin/mysqlslap
-rwxr-xr-x 1 root root 3442464 Jun 24 10:27 /bin/mysqltest
-rwxr-xr-x 1 root root 2918416 Jun 24 10:27 /bin/mysql_tzinfo_to_sql
-rwxr-xr-x 1 root root 2995400 Jun 24 10:27 /bin/mysql_upgrade
-rwxr-xr-x 1 root root 2913960 Jun 24 10:27 /bin/mysql_waitpid
-rwxr-xr-x 1 root root    3888 Jun 24 10:24 /bin/mysql_zap

Anyone care to point out what I'm doing wrong here?
Answer: Should anyone stumble across this, i found the solution here: https://ask.fedoraproject.org/en/question/43459/how-to-start-mysql-mysql-isnt-starting/
Repost below

To start MariaDB on Fedora 20, execute the following command:
systemctl start mariadb.service

To autostart MariaDB on Fedora 20, execute the following command:
systemctl enable mariadb.service

After you started MariaDB (do this only once), execute the following command:
/usr/bin/mysql_secure_installation

Comment: Trying `sudo systemctl start mariadb`, I get `Failed to start mariadb.service: Unit mariadb.service failed to load: No such file or directory.`
Comment: `sudo systemctl enable mysqld` before `sudo systemctl start mysqld` did the trick, it seems.
Comment: thanks @donquixote I've never encountered that behaviour before (needing to enable before starting) with systemd. it looks like mysqld.service can be successfully disabled after starting and not stop the service. I want to explicitly start and stop the mysql service and not have it run automatically on boot.
Answer: When you run:
yum install mysql

command by default it installs MariaDB not MySQL.
So try the following command:
yum list installed | grep mariadb

if mariadb-server is missing try this following command:
yum install mariadb-server

it installs the server package then start the service:
systemctl start mariadb

or:
service mariadb start

My issue was solved in this way.
Comment: This seems to be the correct answer as of late 2016.  When installing mysql on CentOS it will install maria db, but it may not install the server (which is weird)  This did the trick.
Comment: Thorough and simple explanation, and it even worked! I am on the new Amazon Linux. Thanks!
Comment: @CraigJacobs I also had to install the server separately on Amazon Linux.
Answer: The service name is mariadb so you can start it using:
service mariadb start

Stop it using:
service mariadb stop

And restart it using:
service mariadb restart

Comment: CentOS 7 is using `systemd`, so you should use the appropriate `systemctl` commands instead of the old `service` commands.
Answer: See if mysqld is under /usr/libexec/ directory. At least with CentOS 6.5 the usual MySQL installs the server itself there.
Also see the output from systemctl list-units to see the name for you MariaDB server.
Comment: mysqld is indeed present in the `/usr/libexec/` directory. However I don't see anything about MariaDB (or MySQL) in the output of the `systemctl list-units` command
Answer: I had a similar problem trying to start the mariadb service

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'

I figured the issue was in non-matching yum packages - some were installed from the special mariadb repo and others from the centos official repo. Thus I had to drop the custom yum repo entry, delete MariaDB packages and install mariadb-server anew, then the service would start without problem.
Comment: The output states `@updates` as the repo, so that doesn't seem to be the case here. This may still be useful to someone else, so thank you for sharing :-)
Answer: @OP Please pick a best answer;
@Moderator please lock question;
Ran into this same issue, tried the other steps mentioned to no avail; what my problem was being logged in as root/sudo su, after exiting su and running $ systemctl status mariadb I recieved
mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
   Active: inactive (dead)

I then ran $ sudo systemctl enable mariadb recieving
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.

Then starting mariadb with $ sudo systemctl start mariadb - No error/message so it should be good, but no harm in checking $ systemctl status mariadb
mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2018-10-17 10:07:00 CDT; 5min ago
  Process: 18093 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
  Process: 18000 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 18092 (mysqld_safe)
    Tasks: 20
   CGroup: /system.slice/mariadb.service
           ├─18092 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
           └─18261 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket=/var/lib/mysql/mysql.sock

Oct 17 10:06:58 centos-7.shared mariadb-prepare-db-dir[18000]: MySQL manual for more instructions.
Oct 17 10:06:58 centos-7.shared mariadb-prepare-db-dir[18000]: Please report any problems at http://mariadb.org/jira
Oct 17 10:06:58 centos-7.shared mariadb-prepare-db-dir[18000]: The latest information about MariaDB is available at http://mariadb.org/.
Oct 17 10:06:58 centos-7.shared mariadb-prepare-db-dir[18000]: You can find additional information about the MySQL part at:
Oct 17 10:06:58 centos-7.shared mariadb-prepare-db-dir[18000]: http://dev.mysql.com
Oct 17 10:06:58 centos-7.shared mariadb-prepare-db-dir[18000]: Consider joining MariaDB's strong and vibrant community:
Oct 17 10:06:58 centos-7.shared mariadb-prepare-db-dir[18000]: https://mariadb.org/get-involved/
Oct 17 10:06:58 centos-7.shared mysqld_safe[18092]: 181017 10:06:58 mysqld_safe Logging to '/var/log/mariadb/mariadb.log'.
Oct 17 10:06:58 centos-7.shared mysqld_safe[18092]: 181017 10:06:58 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
Oct 17 10:07:00 centos-7.shared systemd[1]: Started MariaDB database server.


swift Value of type 'SKNode' has no member 'rotate'

Question: I created a class named Robber that extends SKNode and I added instance of that class to the game.
but when I want to call custom function on instance it says "Value of type 'SKNode' has no member 'rotate' "
why that doesn't works?

my GameScene class:

enter code here

func addRobber(){
    lastRobber = false
    robber = Robber(x: Int(frame.width),y: Int(frame.height),h:Int(frame.height),so:sOp)
    self.addChild(robber as Robber)
}
override func didMove(to view: SKView) {
    addRobber()
}
[...]
override func update(_ currentTime: TimeInterval) {
      [...]
      for sprite in self.children{
            if( sprite is  Dots_Destroy.Robber)  {
                sprite.rotate()     //Value of type 'SKNode' has no member 'rotate'
            }
      }
}

my Robber class

import SpriteKit
import GameplayKit
import Foundation
class Robber:SKNode{
    let sprite = SKSpriteNode(imageNamed: "wrog.png")
    let sprite2 = SKSpriteNode(imageNamed: "dzialowrog.png")
    let spriteNode = SKNode()
    let g = true
    var life = 2
    init(x:Int,y:Int,h:Int,so:SimpleOpponent){
        super.init()
        [...]
        self.physicsBody?.affectedByGravity = false
        self.name = "rob"
        self.addChild(sprite)
        self.addChild(sprite2)
        self.position = so.sprite.position
        self.physicsBody?.categoryBitMask = 0x1 << 103
        self.physicsBody?.collisionBitMask = 0x1 << 104
        self.physicsBody?.contactTestBitMask = 0x1 << 1

    }
    func rotate(){
        self.run(SKAction.rotate(byAngle: 3.15, duration: 0.3))

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

Answer: is there a suggestion to fix the problem by Xcode? try it and see. Xcode is actually very helpful and solving issue by itself.
Click the red alert "i" icon that is showing on the line of the error, try any suggestions by Xcode or just click fix if possible.
Comment: I cat't do this here


Simplifying a Boolean algebra equation

Question: I have a boolean algebra equation that i'm not able to simplify fully.
\begin{align}
&(c+ab)(d+b(a+c))\\
&(c+ab)(d+ba+bc)\\
&cd+ abc + bc^2+abd+a^2 b^2 + ab^2 c\\
&\text{using boolean laws $x^2=x$ and $x+x=x$}\\
&cd + bc + abd + ab + (abc +  abc)\\
&cd + bc + abd + ab + abc
\end{align}
And now I get stuck. Mathematica simplifies this to $ac+bc+bd$, but I just don't see how.
Comment: This is a Boolean ring, not algebra.
Answer: You might have typed this into Mathematica incorrectly. Here's the solution:
\begin{align*}
(c+ab)(d+b(a+c)) & =(c+ab)(d+ab+bc))\\
 & =cd+abc+bc+abd+ab+abc\\
 & =cd+abc+bc+abd+ab\\
 & =cd+bc+ab(c+d+1)\\
 & =cd+bc+ab
\end{align*}
Here's Wolfram Alpha computing the same thing (DNF).
Comment: Weird that it's different answer than what my Mathematica computes. `BooleanMinimize[(C && (A ||
       B)) || (D && (B || (A && C)))] // TraditionalForm` yields $(A \wedge C) \vee (B\wedge C)\vee(B\wedge D)$.
Answer: You have backwards the AND's and the OR's entered in Mathematica, you should use:
BooleanMinimize[(C || (A && B)) && (D || (B && (A || C)))
|| = AND (*)
&& = OR (+)

Simplifying a Boolean algebra equation


android app tab layout

Question: I have recently started making android apps.
I want to make a app with a few tabs and each tabs has a different title and when u go on it the tab has information and pictures that you can scroll through.
How do i do this ive gone the the main xml in my res/layouts/main.xml and had a look round and found a tab thing but when i drag it on and run a emulator it just come up with the welcome thing i typed as a little hello world kinda thing what do i do please help
Answer: You could use the tutorial on Android.com
http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
Comment: yer ive also looked at this thing called droiddraw
Comment: ive looked at that but it dosent really tell you how to put things on the tabs like pictures text and the abillity to scroll down
Comment: one more thing i cant seem to find my project folders in my workspace theres nothing there where are they

android app tab layout


Calculating the distribution, expected value and variance

Question: I have no idea how to solve the following problem.
Could someone give me some pointers on how the solve the following problem?

Choose a random country. Taken $n$ persons from this country.
Define random variable $X$ as the number of persons $(\leq n)$ that claim to have a specific disease.
  Define $q$ as the percentage of people in the country with this specific disease, then r.v. $Q$ varies from country to country. Assume $Q \stackrel{d}{=} U[0,1]$.
a) How is $X|Q=q$ distributed?
b) calculate $E[X]$ and Var$[X]$.
Answer: Hint:
a) $(X|Q=q)$ is the sum of $n$ variables taking value $1$ with probability $q$ and $0$ otherwise.
b) Start with the computation on the variance conditionally to the value of $Q$.


How to add sub title name in the header using pixture reloaded sub theme of drupal 7.x?

Question: I need to add sub title name(with different font) next line of the "site name" in the header.
Am using  pixture-reloaded sub theme. could anybody, please help me out, where should i change and what piece of code i should add to diplay it out.
for example:
site name: Drupal Answers
next line of the site name, i need one more line to display :  Welcome to out job portal.
How can i alter my coding. Please help me out.thanks
Answer: The "sub title name" you are referring to is called the "Site Slogan" in Drupal.  In Drupal 7, you can add or edit your site slogan on the Site Information page (/admin/config/system/site-information).
Then, on the Pixture Reloaded settings page, just make sure that the "Site Slogan" checkbox under "Toggle Display" is checked.  You don't need any custom code.


How to detect robocopy's failure to delete from source?

Question: On my SQL Server instance I use SQL Agent to run a daily backup job in two steps.
One of the steps uses Robocopy to move local backup files to network storage.
The command to move the files looks like this:
robocopy M:\backups \\NAS\backups$\Database /MOV /MIR /XJ /NP /COPY:DT

The output of the command in the job step history looks like this:
-------------------------------------------------------------------------------
ROBOCOPY     ::     Robust File Copy for Windows
-------------------------------------------------------------------------------
Started : Fri Jul 20 00:55:42 2012
Source : M:\backups\
Dest : \\NAS\backups$\Database
Files : *.*
Options : *.* /S /E /COPY:DT /MOV /PURGE /MIR /NP /XJ /R:1000000 /W:30
------------------------------------------------------------------------------
3  M:\backups\
      *EXTRA File       15.5 m  GeoDisplay_Full_2012-07-19-000004.bak
      *EXTRA File       41.3 m  GeoDisplay2_Full_2012-07-19-000004.bak
      *EXTRA File      264.1 g  Webstore_Full_2012-07-19-000004.bak
      New File          15.5 m  GeoDisplay_Full_2012-07-20-000002.bak
      New File          41.4 m  GeoStore_Full_2012-07-20-000002.bak
      New File         302.1 g  Webstore_Full_2012-07-20-000002.bak

      2012/07/20 04:34:50 ERROR 32 (0x00000020) Deleting Source File M:\backups\Webstore_Full_2012-07-20-000002.bak  The process cannot access the file because it is being used by another process.
------------------------------------------------------------------------------
      Total    Copied   Skipped  Mismatch    FAILED    Extras
Dirs :         1         0         1         0         0         0
Files :         3         3         0         0         0         3
Bytes : 302.187 g 302.187 g         0         0         0 264.181 g
Times :   3:38:57   3:38:45                       0:00:00   0:00:11
Speed :            24720063 Bytes/sec.
Speed :            1414.493 MegaBytes/min.
Ended : Fri Jul 20 04:34:50 2012.
Process exit code 3.

The text output clearly shows ERROR 32. Robocopy failed to honor the /MOV switch (delete from source after copy) because another process had a handle on one file when robocopy tried to delete it.
Robocopy returned exit code 3 (new files copied to destination and extra files deleted from destination). This is correct but incomplete because there is no way to tell from the error code that any operation failed.
SQL Agent considers only the return code, not the command output, when determining the success of a command shell operation. I could modify the Robocopy command to save the output to disk, and parse the output in an extra job step, but this requires extra programming and would add another dependency to the backup job.
Is there any way to detect this kind of failure without searching Robocopy's text output for the string ERROR 32?
Comment: I would think twice using something like Robocopy alone to rely on for backups shipping.
Comment: @GregAskew It's version XP027.
Comment: This evil kind of error output makes robocopy's claim to robustness a little shaky. Are there any more-robust options available, preferably a utility that ships with Windows?
Comment: What method other than searching the text output (log) are you looking for to detect an error?  My brain keeps going back to how else you'd detect an error if you didn't check the log somehow... but I've been off my game this week, so that could be it too.
Comment: @Sergei What tool would you use instead? Would you use Robocopy and something else?
Comment: @HopelessN00b SQL Agent looks at the exit code to work out whether the command was successful. Robocopy is capable of setting a failure bit on the failure of some operations, but doesn't set a failure bit when it fails to delete from the source.
Comment: @isme Gotcha, I understand now.  Might be a good idea to point that out in the question too, but I'm not sure if it'll do any good... if Robocopy fails to delivery proper/expected output, the only solutions I can think of are not using it (like Sergei suggested, probably not a good idea to rely on it for backups anyway), or writing a script that goes in after Robocpy to make sure it did things right.  (Either checking against the file system or parsing the log for `ERROR 32`.)  Doesn't seem too appealing to me, so I'd be tempted to tell the bossman he needs to buy backup software for backups.
Comment: What is the version of robocopy.exe?
Answer: Whether it's RoboCopy or some other method, I prefer to log all output and then post-process the log. I personally prefer Perl for that task but use whatever you're comfortable with. I aslo like to have the test checking script email me the results, showing just whether it succeeded or in the case of a failure the relevant lines from the log.
In my opinion, any backup operation that does not include reporting the results is a disaster waiting to happen, simply because you cannot possibly have confidence in an operation that is not checked. Humans do an appallingly poor job of checking logs, so make the extra effort to write the script. Without it you can just about be guaranteed that some critical operation will fail one day and you'll be none the wiser for it, possibly risking far more than just the data.
Comment: Thanks, John. If we were to continue using Robocopy, we would process the logs. We thought about the effort involved in implementing a log-processing solution versus simplifying our system architecture. In the end we mapped the network storage as a local drive so that we use only SQL Server's built-in functionality. We already have log-processing solutions for SQL Server, so we have reduced the risk of missing something.
Comment: I consider this a bug in Robocopy and have reported it here: https://github.com/MicrosoftDocs/windowsserverdocs.de-de/issues/49
Answer: The exit code description "new files copied to destination and extra files deleted from destination" is not technically accurate.  You should not rely only on the description.
The exit code 0x3 is a bit flag.  The friendly message should be interpreted as follows:
"One of more files were copied successfully"
PLUS
"Extra files or directories were detected.  Examine the log file for more information."
Code    Meaning
0   No errors occurred and no files were copied.
1   One of more files were copied successfully.
2   Extra files or directories were detected.  Examine the log file for more information.
4   Mismatched files or directories were detected.  Examine the log file for more information.
8   Some files or directories could not be copied and the retry limit was exceeded.
16  Robocopy did not copy any files.  Check the command line parameters and verify that Robocopy has enough rights to write to the destination folder.

Robocopy exit codes
https://blogs.technet.com/b/deploymentguys/archive/2008/06/16/robocopy-exit-codes.aspx
The upshot is John is correct.  There's no way around examining the logs if you want to have a robust backup operation.  Additionally, you may want to have a script that runs after the Robocopy operation that removes the handle to the dangling files, then removes the files.


Linear equivalence implies algebraic equivalence for divisors

Question: From here: can someone provide a proof of the true implication (linear implies algebraic)? I am taking definitions from Griffiths-Harris, 461.
I'm afraid I really fail to see how the existence of a (meromorphic) section whose principal divisor is $D$ implies the "deformation" property at the base of the definition of algebraic equivalence.
Thank you in advance.
Answer: Write out the definitions. Suppose $C,D$ are divisors on $X$. They're linearly equivalent if there is a meromorphic function $f$ so that $C=D+(f)$, or in other words, the map $\mathcal{O}(C)\to \mathcal{O}(D)$ given by $1\mapsto f$ is an isomorphism. They are algebraically equivalent if there exists a connected scheme $T$ with points $t_1,t_2\in T$ and a line bundle $L$ on $X\times T$ so that $L|_{X\times t_1}\cong \mathcal{O}(C)$ and $L|_{X\times t_2}\cong\mathcal{O}(D)$.
Do you see a natural choice of $T$ for the case of two linearly equivalent divisors?
Comment: Of course! I did not take the "isomorphism" into account. So with one point one just chooses $L=\mathcal O(D_1)$ and it works. Thanks! Just a thing about algebraic equivalence: how does one prove that the definition with bundles implies the one with divisors? (Cfr. https://ocw.mit.edu/courses/mathematics/18-727-topics-in-algebraic-geometry-algebraic-surfaces-spring-2008/lecture-notes/lect2.pdf for this latter.)
Comment: Perhaps $\mathbb A^1$  with as $L$ something related to the zero locus of some kind of combination of $f$ and $t$ (the variable associated to $\mathbb A^1$)?
Comment: Think harder. Does the one point space work?
Comment: Guess. Take $L_1=\mathcal O(D_1),L_2=\mathcal O(D_2)$ as in the definition in the linked paper. Take $T=\mathbb P^1$, $t_1=0,t_2=\infty$. Then the divisor on $X\times T$ given by $f(x)=t$ satisfies $f(x)=0$ iff $x\in D_1$, $f(x)=\infty$ iff $x\in D_2$, for a suitable choice of representatives $D_1,D_2$.


How to sort the content types/bundles on /node/create page

Question: I want to reorder the list of available content types on the create content page.
I have node-add-list.html.twig and entity-add-list.html.twig inside my custom theme template folder.
Twig then outputs the array of all types or bundles/content types in alphabetical order. How can I sort this a different way? And can I hard code the links I want in this file or can I output each content type individually?
Answer: You can do this in preprocess by overriding this code from node.module:
function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = array();
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = array(
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

Or you can replace the foreach loop in the twig template
node-add-list.html.twig

    {% for type in types %}

{{ type.add_link }}

{{ type.description }}

    {% endfor %}

with a hard-coded list:

{{ types.article.add_link }}

{{ types.article.description }}

{{ types.page.add_link }}

{{ types.page.description }}

Comment: I see how you can edit the page, but how would you specifically sort the content types with these methods?
Comment: you would have to reorder the array `types` in preprocess, for example reverse the order `$variables['types'] =  array_reverse($variables['types']);
`
Comment: THanks 4k4. {{ types.article.add_link }} This works on a plain Drupal site. Now I am trying it on another site that has the Group module and workbench. I think when using the group module it uses the template entity-add-list.html.twig for site authors instead of  node-add-list.html.twig. And the output is {{ bundle.add_link }}{{ bundle.description }} instead of {{ type.add_link }}{{ type.description }}. So I tried {{ bundle.article.add_link }}{{ bundle.article.description }} but it did not work. I dont think the output for bundle is coming from the node.module #501 because that uses type
Comment: This is the generic entity add list. Try plural of bundle: `{{ bundles.article.add_link }}`. You should also be able to manipulate the `bundles` array in preprocess: `mytheme_preprocess_entity_add_list()`
Comment: Thanks I did try the plural but it didn't work. I will try mytheme_preprocess_entity_add_list()
Comment: Just thinking that this was easy in Drupal 7.I went to the
Navigation menu and changed the order, then went to /node/add/ page and the new order is displayed. In D8 I went to Administration menu and changed the order and saved it. The order is saved but If I look at the /node/add/ page it still has the old order? This is just something I wanted to test. I am not using types, I am using bundles instead. and instead of the  /node/add page I have /group/7/node/create/
Comment: Yes, try the preprocess and check the content of variables. Should be not problem to find this out. I don't use the group module, so I can't help.
Answer: Unfortunately not so easy.
Please take a look,
I've already answered that in a previous question.
How to modify the page at admin/structure/types?


Easy way to add Functional or Kernel tests to a View?

Question: I have an administrative View that has a couple access checks based on current user. I would like to add an automated test to the view.
Since I only need to check the result count (no specific field) based on whats set in a users profile, how can I test this view?
Fields I will normally scaffold in setUp() using FieldConfig class, is there a similar one for Views?
These run in CI (I don't know how DTT works in this regard) and the View is apt to change, copying a YAML file into a module can often be forgot (and carry many dependencies with it).
Answer: I wound up using Drupal Test Traits.
The only thing left for me to do is obtain a copy of the database to run the tests in CI, which I can use Drush to grab.


Robots.txt and language exclusion

Question: I want to add a language on my drupal 6 site but I want that Google doesn't index every page in this language (fr).
Can I use robots.txt and and add something like this?
Disallow: /fr/*

Answer: Drupal by default comes with robots.txt file. You can find the file in Drupal Root.
Yes, you can go ahead and change. Below code also should work.
Disallow: /fr/

But, if you use
Disallow: /fr/*

As per wikipedia

Universal * match The Robot Exclusion Standard does not mention
  anything about the * character in the Disallow: statement. Some
  crawlers like Googlebot and Slurp recognize strings containing *,
  while MSNbot and Teoma interpret it in different ways.
Comment: [Robots.txt](http://drupal.org/project/robotstxt) module might come in handy.
Comment: Robots.txt module can be used only if "Use this module when you are running multiple Drupal sites from a single code base (multisite) and you need a different robots.txt file for each one." Otherwise it's easy to edit robots.txt
Comment: I would prefer always editing through admin dashboard. its much easier. provided you play around with robots.txt often

Robots.txt and language exclusion


Martingale convergence $\Rightarrow$ non uniformly integrable?

Question: $\sup_{n} E[|X_{n}|\mathbb{1}_{[X_{n}|>c}]\rightarrow0$ as $c \rightarrow \infty$, being the definition of uniform integrability, should not occur if the martingale converges? Why is that?
Further, one apparently can argue that $E[X_{n}]=c \not=0 \Rightarrow$ non-uniformly integrable, though I do not see also how this should work (the indicator function within the expectation I thought would have allowed $E[X_{n}]=c$ to not negate u.i.)
Comment: Which notion of martingale convergence are you referring to? Almost surely or $L^1$? Either way, it is certainly possible that the martingale converge and be uniformly integrable : in fact  if  the convergence is in $L^1$ then uniform integrability can be shown easily.
Comment: a.s. -- perhaps though, the argument I am trying to decipher works because it is also true that $E[X_{n}] =$const
Comment: that is, there is martingale convergence and the expectation at each n is a constant.
Comment: If $X_n$ is a martingale, then from the tower property it is clear that $E[X_n]  = E[X_0]$ is a constant. I don't see what you are trying to prove. Are you trying to prove that if a martingale  converges a.s. then it is not uniformly integrable?
Comment: either that 1. Martingale converges then not u.i., 2. constant expectation implies not u.i., or 3. martingale converges AND expectation constant implies not u.i.  -- Unfortunately the proof I am reading was not really clear about the predicate used but stated that the expectation was constant for all $n$ and that the martingale converges, therefore "clearly" it is not u.i.
Comment: I guess the problem for me is that I am not seeing how that all connects with the definition of u.i. (shouldnt $\sup_{n} E[|X_{n}|\mathbb{1}_{[X_{n}|>c}]\rightarrow0$ still be the case?)
Comment: Oh ok, I think that equivalence was not immediately apparent to me. Thanks!
Comment: Definitely the one where you explain the equivalence and the comment you made prior to that
Comment: I am done, thanks for the conversation(+1).
Answer: COMMENT 1 : See, a uniformly integrable martingale which converges almost surely, converges in $L^1$ as well. As a consequence, whatever random variable $X_n$ converges a.s. to, must have the same expectation as $X_0$. Now, if it is clear from the construction of the $X_n$ that you are looking at, that the limit does not have the same expectation as $X_0$ (or any of the $X_i$) then "clearly" the martingale is not UI, where "clearly" is to the author(and to you now)!
COMMENT 2 : The definition of UI is not used in the "clearly" part, it seems. Instead the following fact is used : given a sequence of (integrable) random variables $X_n$ and a random variable $Y$, the fact that $X_n  \to Y$ in probability and $X_n$ is UI, is equivalent to $X_n \to Y$ in $L^1$. In your context, I want you to find the $Y$ which the $X_n$ goes to a.s. and hence in probability. Maybe by looking at the expectations you can see that $X_n \to Y$ in $L^1$ is not possible, and therefore $X_n$ cannot be UI.
Comment: Also, for reference, your answer pointed me to the generalization of my problem: https://en.wikipedia.org/wiki/Vitali_convergence_theorem
Comment: Very interesting. Thank you for the reference!


Is it possible for R/exams to export exercises to Blackboard using $$ for Latex equations?

Question: I want to use R/exams to produce Blackboard quizzes for a physics course. However, there is a problem with the display of equations within Blackboard. MathML output does not reproduce clearly on different browsers (e.g., square root signs are fine on Firefox but mangled on Safari and absent on Chrome) and my institution prefers I not use MathJax.
Blackboard is able to correctly display LaTeX equations written within the text using the $$ delimiter e.g., $$a_n =\sqrt{2}$$. So my question is whether exams2blackboard can output for Blackboard in a way that preserves the LaTeX for equations within the text but adds the $$? Or whether there's another way of achieving this using R/exams?
Answer: Preserving LaTeX: When you have $$...$$ markup in your code, then plain pandoc will preserve this in the conversion to HTML provided that there are math elements that it cannot emulate in plain HTML. This would be the case for \sqrt{...} for example while x^2 would simply be emulated. So you can experiment with this using exams2blackboard(..., converter = "pandoc-quiet"). I'm not sure that it works though - haven't got access to Blackboard for testing.
Adding $$: To the best of my knowledge this is not provided by pandoc and I wouldn't know how to work around this in R/exams.
Rendering MathML: This is generally not available on Chrome, so it isn't surprising that Chrome doesn't handle square roots etc. In Safari MathML should usually work ok, I wouldn't be aware that it generally has problems with square roots - but we definitely saw occasional problems on Safari. Firefox is the only mainstream browser with really excellent MathML support.
In summary: If the first option above does not work well enough for your, then I would recommend to either require students to use Firefox - or to include MathJax in the exercises. If your institution does not want you to include MathJax, maybe there is a way to generally provide MathJax inside Blackboard for them?
Comment: Thanks. I'll experiment with that and report back.


How to group a list of numbers into certain categories

Question: I am trying to figure out how to take in a list of numbers and sort them into certain categories such as 0-10, 10-20, 20-30 and up to 90-100 but I have the code started, but the code isn't reading in all the inputs, but only the last one and repeating it. I am stumped, anyone help please?
def eScores(Scores):

    count0 = 0
    count10 = 0
    count20 = 0
    count30 = 0
    count40 = 0
    count50 = 0
    count60 = 0
    count70 = 0
    count80 = 0
    count90 = 0

    if Scores > 90:
        count90 = count90 + 1
    if Scores > 80:
        count80 = count80 + 1
    if Scores > 70:
        count70 = count70 + 1
    if Scores > 60:
        count60 = count60 + 1
    if Scores > 50:
        count50 = count50 + 1
    if Scores > 40:
        count40 = count40 + 1
    if Scores > 30:
        count30 = count30 + 1
    if Scores > 20:
        count20 = count20 + 1
    if Scores > 10:
        count10 = count10 + 1
    if Scores <= 10:
        count0 = count0 + 1

    print count90,'had a score of (90 - 100]'
    print count80,'had a score of (80 - 90]'
    print count70,'had a score of (70 - 80]'
    print count60,'had a score of (60 - 70]'
    print count50,'had a score of (50 - 60]'
    print count40,'had a score of (40 - 50]'
    print count30,'had a score of (30 - 40]'
    print count20,'had a score of (20 - 30]'
    print count10,'had a score of (10 - 20]'
    print count0,'had a score of (0 - 10]'

    return eScores(Scores)

Comment: @user1249113: the `TypeError` you're talking about is not a result of the code you're showing.  How are you calling the function?
Comment: a better approach would be to use an array to store the counts, and then just divide the number by 10 to see which bucket it falls in to...
Comment: My code will return this "TypeError: eScores() takes exactly 1 argument (3 given)". Yes I am new to python, anyone direct me in the right direction as to why this is happening and possibly showing where in the code its forcing this, thanks.
Comment: I am calling the function within the python shell itself, by doing eScore(5,15,25,35,etc.) testing it out.
Comment: @user1249113 eScore() only accepts one input, `Scores`. But you are trying to pass it several, `eScore(5,15,25,35,etc.)` If you want to allow multiple inputs treat `Scores` as a [array](http://docs.python.org/tutorial/datastructures.html) and pass in a list like: `eScore([5,15,25,35,etc.])` (note the brackets)
Comment: Show the part where you "read" the input (i.e. create the list of scores and then pass it to the function). I see no list of data here.
Answer: Each time eScores is called is sets all the counters (count10, count20) back to zero. So only the final call has any effect.
You should either declare the counters as global variables, or put the function into a class and make the counters member variables of the class.
Another problem is that the function calls itself in the return statement:
return eScores(Scores)

Since this function is (as I understand it) supposed to update the counter variables only, it does not need to return anything, let alone call itself recursively. You'd better remove the return statement.
Answer: One thing you're making a mistake on is that you're not breaking out of the whole set of if's when you go through.  For example, if you're number is 93 it is going to set count90 to 1, then go on to count80 and set that to one as well, and so on until it gets to count10.
Comment: I see that now. How can I break out of that and not allow that to happen? Just wondering.
Comment: What would be the easiest way, I mean.
Comment: Don't just keep using 'if', rather use 'elif'
Answer: Your code is repeating because the function is infintely recursive (it has no stop condition).  Here are the relevant bits:
def eScores(Scores):
    # ...
    return eScores(Scores)

I think what you'd want is more like:
def eScores(Scores):
    # same as before, but change the last line:
    return

Since you're printing the results, I assume you don't want to return the values of score10, score20, etc.
Also, the function won't accumulate results since you're creating new local counts each time the function is called.
Answer: Why don't you just use each number as a key (after processing) and return a dictionary of values?
def eScores(Scores):
    return_dict = {}
    for score in Scores:
        keyval = int(score/10)*10 # py3k automatically does float division
        if keyval not in return_dict:
            return_dict[keyval] = 1
        else:
            return_dict[keyval] += 1
    return return_dict


Typescript "exports not defined" error when not exporting

Question: I am building an electron app using typescript. I have set up my tsconfig as follows:
{
    "compilerOptions": {
        /* Basic Options */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "commonjs",                  /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */

        "outDir": "./build",                      /* Redirect output structure to the directory. */

        "strict": true,                           /* Enable all strict type-checking options. */

         "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */

        "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    },
    "include": [
        "./src"
    ]
}

I have to mention that I am not using webpack or browsify.
So, I have to typescript files at the moment, one responsible for creating the main window and one responsible of handling events (basically one for the main thread and one for the renderer). I am using only imports in both of them, no exports. The problem is that in the renderer script (in it's javascript form) I get this line after running tsc : Object.defineProperty(exports, "__esModule", { value: true });, which causes the 'exports not defined' error when running the app.
I've tried removing the module property from tsconfig as suggested in other posts, but it didn't help. If I remove that line of code in the javascript file, everything works. But I don't know what I should do to stop tsc from adding that line of code, since in the other javascript file it doesn't appear. Thanks in advance for helping!
Here are my typescript files with their compiled javascript equivalents
app.ts
import {app,BrowserWindow,desktopCapturer, DesktopCapturerSource} from 'electron';
import * as path from 'path';

function createWindow(){
const mainWindow:BrowserWindow = new BrowserWindow({
    width:800,
    height:600
});

mainWindow.loadFile(path.join(__dirname,"../src/assets/index.html"));
mainWindow.webContents.openDevTools()

}
app.on('ready',createWindow);

app.js
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var electron_1 = require("electron");
var path = __importStar(require("path"));
function createWindow() {
    var mainWindow = new electron_1.BrowserWindow({
        width: 800,
        height: 600
    });
    mainWindow.loadFile(path.join(__dirname, "../src/assets/index.html"));
    mainWindow.webContents.openDevTools();
}
electron_1.app.on('ready', createWindow);

renderer.ts
import { desktopCapturer, DesktopCapturerSource } from "electron";

function onLoad(){
    desktopCapturer.getSources({
        thumbnailSize: {
            width: 256,
            height: 256,
        },
        types: ["screen", "window"]
    }, (error: Error, srcs: DesktopCapturerSource[]) => {
        if (error)
            throw error;
        let p: HTMLElement | null = document.querySelector("#tag");
        for (let src of srcs)
            if (p){
                let temp = src.name + ' ';
                p.textContent += src.name;
            }
    })
}

document.addEventListener("DOMContentLoaded", onLoad);

renderer.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var electron_1 = require("electron");
function onLoad() {
    electron_1.desktopCapturer.getSources({
        thumbnailSize: {
            width: 256,
            height: 256,
        },
        types: ["screen", "window"]
    }, function (error, srcs) {
        if (error)
            throw error;
        var p = document.querySelector("#tag");
        for (var _i = 0, srcs_1 = srcs; _i < srcs_1.length; _i++) {
            var src = srcs_1[_i];
            if (p) {
                var temp = src.name + ' ';
                p.textContent += src.name;
            }
        }
    });
}
document.addEventListener("DOMContentLoaded", onLoad);

Answer: I'm not positive but I think this should help:
// TypeScript considers non-module files to be files without `export`s.
// https://stackoverflow.com/a/41975448/5051090
export {};

https://stackoverflow.com/a/41975448/5051090
Try tacking it on to the bottom of your modules.
Answer: I figured it out! The problem was the compile target. Switcging from es5 to es6 fixed the issue


How can I cancel an NSOperation in the same thread that the operation?

Question: When I cancel an NSOperation (when user presses a button) cancel method is called from the main thread, but evidently the operation is running in another thread.
So, to avoid race conditions when I change _isExecuting and _isFinished, I think cancel (or at least its logic) should be called from the same thread that the NSOperation. Apart from that, when user cancels it, several files are deleted and it takes time. Because cancel is called from main thread, all the app becomes unresponsive for a while, which is ugly.
How can I execute cancel code in the same thread that the current NSOperation?
I tried this in cancel (similar to what I saw in ASIHTTPRequest):
<code>if (_operationThread) {
    [self performSelector:@selector(cancelOnRequestThread) onThread:_operationThread withObject:nil waitUntilDone:NO];
} else {
    [self cancelOnRequestThread];
}
</code>
And _operationThread is setted in start method using:
_operationThread=[NSThread currentThread];
But it doesn't work.
Any idea or suggestion?
Note: I use concurrent operations, so I use start instead of main.
Thanks a lot for help.
Ricardo.
Answer: It's fine to call cancel on an NSOperation from the main thread. The cancel method is thread-safe.
That shouldn't cause any blocking on your main thread because the cancel method itself shouldn't be doing any work. If you have overridden the cancel method of your operation to delete files, etc then that is the wrong approach. You shouldn't override the cancel method, instead just check the isCancelled method at regular points within the operation's main method (e.g. inside any tight loops) and then return from main early if isCancelled returns YES, which will then cancel the operation on the same thread as the rest of the execution.
If that's how you've implemented it already and you're still having performance issues, is it possible that your operation is not really running on a background thread at all? For example if you've added it to the queue returned by [NSOperationQueue mainQueue] then that's actually running on the main application thread.


What is the right way to get number of items from a field?

Question: In code review I saw a developer using count($paragraph->field_events) to get the number of referenced entities.
I thought, surely that can't work, that can't be right.  So the question is, what is the correct way to get the number of items from a field on an entity?
Answer: Using count() on a field is acceptable because there is an implementation of Countable::count in the ListInterface implemented by ItemList class where it overloads the count method to count the items, from which FieldItemList and EntityReferenceFieldItemList inherit.
So you can use:
$paragraph->field_events->count()

or
count($paragraph->field_events)

synonymously.  They do the same thing.
From ItemList.php:
public function count() {
  return count($this->list);
}

If you'd like test this, you can play with this simple class.  If you remove the "Implements Countable" calling count(a) on object a doesn't return the count() method, but if you add it back, it does.  So on a low level, Drupal is using this so you can call count() on fields.


postgresql query c++ callback

Question: Is it possible with any existing c++ library to implement a callback that returns when a query is completed?
I've found this, but I'm not sure if that's what I want.
I'd like to wait the boost::thread writing to the database until the write is completed.
If this is possible, please link the library and an example.
Comment: Just `join` the thread don't work for you?
Comment: @MatheusOl thank you for looking!  i don't want to block.  i simply want the thread that's performing the database query to `wait`/`sleep` until the query is finished.  i don't want that thread to block cores from being used by other threads while waiting for the query's response.
Comment: how are you sending the query to the database? Generally you should sent it synchronously, so you don't need to worry about that, after sending the query (e.g. `PQexec`) the thread will already "`wait`" until the query is finished.
Comment: Ok. I'll send an answer to clarify that.
Answer: I was looking for something like this too, ended up doing an async libpq wrapper: http://github.com/metherealone/postgrespp - It uses Boost.ASIO though, not threads. I hope this helps.
Answer: From the libpq docs about PQexec function:

Submits a command to the server and waits for the result.

Similar to that, the PQexecParams and PQexecPrepared also wait for the query to be executed. So, using those functions you don't need to worry about waiting, the API will do that for you.
If you need to asynchronously send query to the database, you can use the asynchronous functions.
Comment: Just to clarify, it is not the `boost` that "chooses" what thread will run on each CPU core, it is a job done by the OS and `boost` has no control over it. So, you can run 100 threads on a 4 core machine, that the OS's scheduler will take care of controlling them.
Comment: will the boost thread continue to use the core while it waits, or will that core be freed so that other threads can use it?
Comment: @Gracchus: I don't know exactly what you meant by "core". But the thread will (kind of) sleep until the query returns, but, of course, it does not use CPU time while it is sleeping.
Comment: so while the thread that's trying to write to the database is waiting for the query result, other boost threads will automatically take its place and use the CPU?
Comment: Yes. There is actually some work on that thread, but if the query is too slow there will be almost no work on the client side. Notice that if your PG server will consume CPU to process this query, so if it is local, there will be concurrency to resources with your boost threads.

postgresql query c++ callback


How to set IP proxy from a given proxy pool?

Question: I have been given a proxy pool link http://10.10.5.17:5009/proxy_pool that outputs the following:
<code>{
    "msg": "success",
    "list": [
        "18.104.22.168:34621",
        "126.96.36.199:25995",
        "18.104.22.168:35513",
        "126.96.36.199:49366",
        "18.104.22.168:45037"
    ],
    "data": "18.104.22.168:25995"
}
</code>
These IPs change every few minutes. I'd like to know how to set this up in Scrapy.
I have seen tutorials showing how to add every single IP in settings.py and then call it in middlewares.py, but I cannot do it this way since I need to read IPs from the link (And they change rapidly).
Comment: Can you please edit your question and show your efforts so far?
Comment: I wish I could, but the way that I used to use is to directly copy IPs from the link I provided and call them in middlewares.py, however, this way won't work anymore since IPs varied all the time, I don't know where to start right now.
Comment: It's completely unclear as to what you are requesting and without an example, it's impossible to help you. https://stackoverflow.com/help/how-to-ask
Answer: <code>import json
import random

def start_requests(self):
    proxy_request = scrapy.Request(url='http://10.10.5.17:5009/proxy_pool', callback=self.prepare_request)
    yield proxy_request

def prepare_request(self, response):
    target_url = 'XXX'
    proxy_response = json.loads(response.body_as_unicode())
    proxy_list = [proxy for proxy in proxy_response['list']]
    request = scrapy.Request(url=target_url, meta={'proxy': random.choice(proxy_list)}, callback=self.scrape)

def scrape(self, response):
...
</code>
Answer: You'll have to write your own downloader middleware that handles downloading the proxy list initialy, getting a new list every now and then, and assigning a random proxy from the current list to each request.
You should start by reading the documentation about downloader middlewares. Then, I recommend you find existing middlewares that deal with proxies (e.g. scrapy-rotating-proxies) and learn from them.


Python imported class and list in a list

Question: I've defined class (say for different car types) in file student.py:
class car:

    def __init__(self, name, engine, no_of_seats, power_source):
        self.name = name
        self.engine = engine
        self.no_of_seats = no_of_seats
        self.power_source = power_source

Then I've imported it to main_project.py
from student import car

I've created, say 3 different car types with data related to the class. Now I would like to print e.g. only power_source for all 3 car types with at once. My idea was to make list in a list but I doesn't work. Here is piece of my code:
list = [car("Audi", 2.0, 4, "gasoline")], [car("Porsche", 3.0, 7, "gasoline")], [car("Lexus", 2.4, 5, "hybrid")]

Now, I cannot access specific item in a list. I can access whole list but it prints following message:

I get this by using:
print(list[0])

My questions are:
- is the way I'm trying to achieve it proper?
- is it possible to include in the variable "list" other variables for different car types?
Thank you
Comment: ... Your `list` hides the built in - and is in fact a `tuple` of 1 element lists ...
Comment: Testing your code, I get `[<__main__.car instance at 0x7fd92dd41a50>]`. Please post a proper [mcve].
Answer: There are a few mistakes in your syntax that will cause problems. First, lit's considered bad practice to use "list" as a name for a list, as it overrides the builtin name list. Add an underscore at the end to be pythonic:
list_ = []

Next up, you use square brackets to close off every element of the list, when you should keep every element in the one pair of square brackets.
# Don't do this
list_ = [elem_1], [elem_2], [elem_3],...

# Do this
list_ = [elem_1, elem_2, elem_3]

And then finally, to answer your question, you are filling your list up with car objects. But you want to fill it up with the power_source attributes of the cars objects. So use dot syntax to call the attribute from the car object
list_ = [car("Audi", 2.0, 4, "gasoline").power_source, car("Porsche", 3.0, 7, "gasoline").power_source, car("Lexus", 2.4, 5, "hybrid").power_source]

Comment: you destroy the cars by only storign the power_source. Better do `cars = [car("Audi", 2.0, 4, "gasoline"), car("Porsche", 3.0, 7, "gasoline"), car("Lexus", 2.4, 5, "hybrid")]` and then `powersources = [a.power_source for a in car]`
Comment: "list is a protected name in python, so you are forbidden to use "list" as a name for a list" => plain wrong (if that was the case the code wouldn't compile). It's just a builtin name, you are free to override it, but this is indeed bad practice since it tends to confuse the reader and can create issues elsewhere.


Concurrency-Three parabolas sharing common directrix.

Question: I have found this result by exploring for new problems.
If three parabolas share a common directrix and each pair intersect each other in two points, then, the lines joining the two intersection points of each pair of parabolas are concurrent.
The proof is quite simple, so my question is :
Has anyone seen this before? Any reference?
Comment: Why don't you see about publishing your result in a journal like Forum Geometricorum? The editor will certainly know if the result is new. Link: http://forumgeom.fau.edu/index.html
Comment: Publishing in that journal is not that easy. I think the editor of FG don't know the result. He just make a comment about the foci and the point of concurrence. I am asking the editor of Jounal of Classical Geometry for references. Thanks.
Answer:
I found a useful reference and an interesting theorem called the Three Conics Theorem  which is similar to yours, but not the same. Here is a link: http://mathworld.wolfram.com/ThreeConicsTheorem.html , and another reference: "The Seven Circles Theorem and other new theorems" by C.J.A. Evelyn, G.B. Money-Coutts, and J.A. Tyrrell (1974).
As you can see , the three conics intersect at I and J and intersect in pairs at (Q1,P1) , (Q2,P2) , (Q3,P3) . The three segments, Q1P1, Q2P2 , Q3P3 are concurrent at X. This picture is taken from the book mentioned above, (there is a similar diagram at mathworld).
Answer: This is a particular case of Neville:
The common chords of three focus-sharing conics meet in the vertices of
a quadrangle. In the case of three ellipses, only one of the four vertices
is real. In the case of three parabolas, it degenerates further.
www.aip.de/People/deliebscher/Publikationen/DreiEllipsen.ps


SAS - proc tabulate - background

Question: when I run the following code in SAS
DATA TEST2;
input A1 B1 C1;
cards;
1 6 0
1 6 1
2 7 0
2 6 1
2 6 0
1 7 0
1 7 1
run;

proc format ;
 value couleur
   low - 50 = "red"
   50- 100 = "green"
   . = "white"
 ;
run ;

proc tabulate data=test2;
CLASS A1 B1 C1 /missing;
TABLE A1,
      B1*C1*(N PCTN<C1>* [style=[background=couleur.]])*(F=4.) ALL*F=7. /RTS=8
     ;
run;

it gives me
proc tabulate
What should I do when I want the color coding to be applied only to percentages (columns), where C1=1? Thanks in advance for answers.
Answer: PROC TABULATE DATA=TEST;
    CLASS A1 B1 C1 /MISSING;
    TABLE A1,
        B1*C1*(N (PCTN<C1> * [STYLE=[BACKGROUND=couleur.]]))* (F=4.) ALL*F=7. /RTS=8;
RUN;

Is this what you mean?
Comment: Thank you for yor answer but your proc tabulate seems to give exactly the same result as the proc tabulate I posted in december.

SAS - proc tabulate - background


Android: Unable to Decrypt Value

Question: Successfully get Right encrypted value but facing problem to decrypt that value(already encrypted).
Value:   123456
Encrpted:   ncSzDj4j8l44iM5qgaqHgA==
Why i got java.lang.Exception: [decrypt] Invalid int: "Bo" ?
Is there any solution / Suggestion it would be appreciated. Thanks
MainActivity.java
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;

    import java.net.URLDecoder;

    public class MainActivity extends AppCompatActivity {
        ApiCrypter3 apiCrypter;

    //123456
    //ncSzDj4j8l44iM5qgaqHgA==

      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            apiCrypter = new ApiCrypter3();
            try {
                byte[] encryptedRequest = this.apiCrypter.encrypt(value);
                String EncryptStr = new String(encryptedRequest, "UTF-8");
                Log.e("ENCRYPTION: ", EncryptStr.toString());

                String res = new String(this.apiCrypter.decrypt(EncryptStr), "UTF-8");
                res = URLDecoder.decode(res, "UTF-8");
                Log.e("DECRYPTION: ", res.toString());

               } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

ApiCrypter3.java
  package <your package name>;

    import android.util.Base64;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;

    public class ApiCrypter3 {

    private byte[] sessionKey = {your 16 character key}; //Where you get this from is beyond the scope of this post
    private byte[] iv = {your 16 character value}; //Ditto
    private IvParameterSpec ivspec;
    private SecretKeySpec keyspec;
    private Cipher cipher;

    public ApiCrypter3()
    {
        ivspec = new IvParameterSpec(iv);
        keyspec = new SecretKeySpec(sessionKey, "AES");

        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    public byte[] encrypt(String text) throws Exception
    {
        if(text == null || text.length() == 0) {
            throw new Exception("Empty string");
        }
        byte[] encrypted = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            encrypted =  Base64.encode(cipher.doFinal(text.getBytes("UTF-8")), Base64.DEFAULT);
        }
        catch (Exception e) {
            throw new Exception("[encrypt] " + e.getMessage());
        }
        return encrypted;
    }

    public byte[] decrypt(String code) throws Exception
    {
        if(code == null || code.length() == 0) {
            throw new Exception("Empty string");
        }
        byte[] decrypted = null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            //decrypted = Base64.decode(cipher.doFinal(code.getBytes()),Base64.DEFAULT);
            decrypted = Base64.decode(cipher.doFinal(hexToBytes(code)),Base64.DEFAULT);
        }
        catch (Exception e) {
            throw new Exception("[decrypt] " + e.getMessage());
        }
        return decrypted;
    }

    public static String bytesToHex(byte[] data) {
        if (data==null) {
            return null;
        }
        int len = data.length;
        String str = "";
        for (int i=0; i<len; i++) {
            if ((data[i]&0xFF)<16) {
                str = str + "0" + Integer.toHexString(data[i]&0xFF);
            }
            else {
                str = str + Integer.toHexString(data[i]&0xFF);
            }
        }
        return str;
    }

    public static byte[] hexToBytes(String str) {
        if (str==null) {
            return null;
        }
        else if (str.length() < 2) {
            return null;
        }
        else {
            int len = str.length() / 2;
            byte[] buffer = new byte[len];
            for (int i=0; i<len; i++) {
                //No effect
                //buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                buffer[i]=Integer.valueOf(str.substring(i*2,i*2+2),16).byteValue();
                }
            return buffer;
        }
    }
}

Logs:
04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption E/ENCRYPTION:: ncSzDj4j8l44iM5qgaqHgA==
04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption W/System.err: java.lang.Exception: [decrypt] Invalid int: "nc"
04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption W/System.err:     at com.test.com.encrytiondecryption.ApiCrypter3.decrypt(ApiCrypter3.java:64)
04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption W/System.err:     at com.test.com.encrytiondecryption.MainActivity.onCreate(MainActivity.java:41)

Comment: Check my anwer, i posted
Answer: It looks like the exception is being thrown by this line in your hexToBytes function, and then caught and rethrown in decrypt:
buffer[i]=Integer.valueOf(str.substring(i*2,i*2+2),16).byteValue();

The problem is that the string you are passing in to the hexToBytes function is Base64 encoded, it's not a hex string, so reading the first two characters as an integer causes an exception.
Change the line in decrypt to this:
decrypted = cipher.doFinal(Base64.decode(code,Base64.DEFAULT));

When you encrypt you are encrypting and then Base64 encoding, so when you decrypt you should do it in the reverse order: Base64 decode then decrypt.
Comment: It Works. Thank you.
Comment: I have not tried that yet, but it's totally correct, I am saying it blindly, but I am sure it's correct, thanks :)
Answer: Do This simple way::
package com.encrytiondecryption;

import android.util.Base64;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class ApiCrypter5 {
    byte[] sessionKey = {your 16 character key}; //Where you get this from is beyond the scope of this post
    private byte[] iv = {your 16 character value }; //Ditto
    private IvParameterSpec ivspec;
    private SecretKeySpec keyspec;
    private Cipher cipher;

    public ApiCrypter5() {
        ivspec = new IvParameterSpec(iv);
        keyspec = new SecretKeySpec(sessionKey, "AES");

        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    public String encrytData(String text) throws Exception {

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

        byte[] results = cipher.doFinal(text.getBytes());

        return Base64.encodeToString(results, Base64.NO_WRAP | Base64.DEFAULT);

    }

    public String decryptData(String text) throws Exception {
        byte[] encryted_bytes = Base64.decode(text, Base64.DEFAULT);

        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

        byte[] decrypted = cipher.doFinal(encryted_bytes);

        return new String(decrypted);

    }

}

Android: Unable to Decrypt Value


The three defining properties of an equivalence relation can be formulated in algebraic terms

Question: I am studying Naive Set Theory and stuck to understand algebraic part of equivalence relation. Can you please explain what these inclusions mean?

The algebra of relations provides some amusing formulas. Suppose that,
temporarily, we consider relations in one set $X$ only, and, in
particular, let $I$ be the relation of equality in $X$ (which is the same
as the identity mapping on X). The relation I acts as a multiplicative
unit; this means that $IR = RI = R$ for every relation $R$ in $X$. Query: is
there a connection among $I$, $RR^{–1}$, and $R^{–1}R$? The three defining
properties of an equivalence relation can be formulated in algebraic
terms as follows: reflexivity means $I ⊂ R$, symmetry means $R ⊂ R^{–1}$, and
transitivity means $RR ⊂ R$.
Halmos, Paul R.. Naive Set Theory (Dover Books on Mathematics) (p.
41). Dover Publications. Kindle Edition.
Comment: In set theory, relations between elements of a set are encoded as sets of pairs, therefore the inclusions mean inclusions as sets.
Comment: Example: reflexivity. You have to check that if $I = \{ (a,a) \mid a \in X \} \subseteq R$ then relation $R$ is reflexive. And similarly for the other two properties of an [Equivalence relation](https://en.wikipedia.org/wiki/Equivalence_relation#Definition).
Comment: A *relation* $R$ on a set $X$ is a set of *pairs*: $R \subseteq X \times X$.
Comment: You can find several related posts here. For example: [If $R$ is a transitive relation, then $R\circ R\subseteq R$](https://math.stackexchange.com/q/876621) and [the questions linked there](https://math.stackexchange.com/questions/linked/876621).
Answer: In set theory a binary relation on a set $X$ is some (any) subset of $X\times X.$ We can write $I_X=\{(x,x):x\in X\}$, which is a subset of $X\times X.$ For subsets $R, S$ of $X\times X$ we can write $$R^{-1}=\{(y,x): (x,y)\in R\}$$ and $$RS=\{(x,z):\exists y\,(\,(x,y)\in R\land (y,z)\in S\,)\}.$$ In particular $RR=\{(x,z):\exists y\,(\,(x,y)\in R\land (y,z)\in R\}$.
We can also show that a binary relation $R$ on $X$ is an equivalence relation  iff $I_X\subseteq R=R^{-1}=RR.$
BTW. In topology $I_X$ is called the diagonal of $X\times X.$
Comment: If you're interested in paring down the def'n, observe that if $\emptyset\ne R=R^{-1}=RR $ then $I_X\subset R.$