text:
Q: Convert Java Byte Array to a UTF-8 Python String I'm pulling JSON data through a REST API using Requests in Python.  Unfortunately, one of the fields contains all sorts of unescaped and control characters that breaks the JSON.
I don't control the data, but I can request it undecoded as a string that the application stores as a Java byte array.
For example: [B@1cf3bd82
The question is how do I decode the string back into the original UTF-8 text as I'm working through the JSON?  All of the examples I've found seem to work with a byte object, not a encoded string.
Thoughts?

A: You're currently printing out the result of calling toString() on the byte[]. That's never a good idea - arrays don't override toString().
You should use the new String(byte[], Charset) constructor:
String text = new String(bytes, StandardCharsets.UTF_8);

It's not entirely clear to me from the question where what is happening in terms of the data, but basically you need to modify the Java code - any Python code is probably irrelevant here.


text:
Q: Reversing list element in python How to reverse list element one by one in python?
I tried nested loop. But I couldn`t display second loop as "Result"
For example:
Input: 102 346 5897
Result: 201 643 7985

A: Assuming your input list consists of strings, you go like this:
> a = ['102','346','5897']
> for i in a:
>    print(i[::-1],end=' ')

returns 201 643 7985

A: Try the following solution. you can use [::-1] to reverse a string.
x = ["123", "456", "789"]

y = []
for i in range(0,len(x)):
    y.append(x[i][::-1])
print(y)
['321', '654', '987']

You can use following trick with number inputs assuming inputs are numbers.
x = [123, 456, 789]
y = []
for i in range(0,len(x)):
    y.append(int(str(x[i])[::-1]))
print(y)
[321, 654, 987]

A: You can use [::-1]
string='102 346 5897'
lst=string.split()[::-1]
print(' '.join(lst))

A: You can use the built in function 'reverse()' instead of for loop (more efficient code) :

code

def Reverse(lst):
   lst.reverse()
   return lst

lst = ["123", "456", "789"]
print(Reverse(lst))

output

['789', '456', '123']

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compile libxml2 get "error: storage size of 'hints' isn't known" I download libxml2 2.9.4 in here, when i ./configure; make, i get following error:
nanohttp.c: In function 'xmlNanoHTTPConnectHost':
nanohttp.c:1073:18: error: storage size of 'hints' isn't known
  struct addrinfo hints, *res, *result;
                  ^
nanohttp.c:1079:11: warning: implicit declaration of function 'getaddrinfo' [-Wimplicit-function-declaration]
  status = getaddrinfo (host, NULL, &hints, &result);
           ^
nanohttp.c:1079:2: warning: nested extern declaration of 'getaddrinfo' [-Wnested-externs]
  status = getaddrinfo (host, NULL, &hints, &result);
  ^
nanohttp.c:1085:35: error: dereferencing pointer to incomplete type 'struct addrinfo'
  for (res = result; res; res = res->ai_next) {
                                   ^
nanohttp.c:1089:7: warning: implicit declaration of function 'freeaddrinfo' [-Wimplicit-function-declaration]
       freeaddrinfo (result);
       ^
nanohttp.c:1089:7: warning: nested extern declaration of 'freeaddrinfo' [-Wnested-externs]
nanohttp.c:1073:18: warning: unused variable 'hints' [-Wunused-variable]
  struct addrinfo hints, *res, *result;
                  ^

the full output is here
here is my environment:
roroco@roroco ~/Downloads $ lsb_release  -a
No LSB modules are available.
Distributor ID: LinuxMint
Description:    Linux Mint 17.3 Rosa
Release:    17.3
Codename:   rosa
roroco@roroco ~/Downloads $ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.8/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.8.5-2ubuntu1~14.04.1' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libmudflap --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.8.5 (Ubuntu 4.8.5-2ubuntu1~14.04.1)

I try version 2.9.2 and 2.9.3, i get same error, how to compile libxml2 success?

A: I find the solution:
in nanohttp.c, the error line:
#if defined(HAVE_GETADDRINFO) && (defined(SUPPORT_IP6) || defined(_WIN32))
    {
    int status;
    struct addrinfo hints, *res, *result;

so i can disable ipv6 to don't compile this block code. I try following code will work:
./configure --enable-ipv6=no LIBS="-lpthread"; make

I find "--enable-ipv6" in "libxml2-src/configure"

A: For using "getaddrinfo" you must use POSIX.
For clean C, use gcc flag -std=gnu11 or -std=gnu99 instead с11/с99.
Checking for POSIX you can using this code:
#ifdef  __USE_POSIX
    #warning POSIX compatible
#else
    #warning no support POSIX
#endif


text:
Q: apply stats.percentileofscore function for multiple column I can't get result from column ['a percent'], only column ['b percent'] get filled.
can someone help ? or any reference link will be helpfull ? many thanks
test = pd.DataFrame({'a':[20,2,7,1,7,7,34],'b':[100,99,102,103,56,70,200]})
test['a percent'] = ''
test['b percent'] = ''

x = ['a','b']

for row in test.index:
    for x in x:
        test.loc[row,f'{x} percent'] = stats.percentileofscore(test[x],test.loc[row,x])/100

output:
    a   b   a percent   b percent
0   20  100 0.857143    0.571429
1   2   99              0.428571
2   7   102             0.714286
3   1   103             0.857143
4   7   56              0.142857
5   7   70              0.285714
6   34  200             1.0

A: You overwrite your x in for x in x, use a different name:
cols = ['a','b']

for row in test.index:
    for x in cols:
        test.loc[row,f'{x} percent'] = stats.percentileofscore(test[x],test.loc[row,x])/100

That said a better, vectorial method would be:
cols = ['a', 'b']
test.update(test[cols].apply(lambda c: stats.percentileofscore(c, c))
                      .div(100).add_suffix(' percent'))

Output:
    a    b a percent b percent
0  20  100  0.857143  0.571429
1   2   99  0.285714  0.428571
2   7  102  0.571429  0.714286
3   1  103  0.142857  0.857143
4   7   56  0.571429  0.142857
5   7   70  0.571429  0.285714
6  34  200       1.0       1.0


text:
Q: Angular-js2.0:->Module not found 'angular/core-js'?What this backtick means which covered template? module not found '@angular/core','@angular/platform-browser',same with 3rd one!!
   import {
  NgModule,
  Component
 } from '@angular/core';
 import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-   dynamic';

@Component({
     selector: 'hello-world',
     template:
    <div>
    Hello world
    </div>

   })
class HelloWorld {
     }
 @NgModule({
 declarations: [ HelloWorld ],
 imports: [ BrowserModule ],
 bootstrap: [ HelloWorld ],
 })

 class HelloWorldAppModule {}

 platformBrowserDynamic().bootstrapModule(HelloWorldAppModule);

A: Backticks define Template Strings \ Template literals in TypeScript and ES6.
These do allow strings to be multi-line (which is the main reason why Angular2 uses them, I suppose) and to use string interpolation features.
Sample for string interpolation:
var name = "World";
console.log(`Hello ${name}!`); // Outputs 'Hello World!'

A: In ES6, there is Template String feature, that says, we can form/concat string with backtick.
var name = 'Mustkeem';
var info = `My name is ${name}.`; // My name is Mustkeem.

Other important point to consider is, these backtick support for multi line templates.
However you should use Angular's interpolation syntax {{}} instead of ${}. Because angular's interpolation syntax have some merits like you can also use expressions ({{a + b / 2}}) and pipes ({{title | uppercase}}).


text:
Q: Angular 9: Custom directive to access value of child text input I am working on an Angular 8 custom directive that I will use to conditionally append/remove HTML elements, apply CSS, etc, to a label and input field, both wrapped by a div
One of the conditions that I will be checking for is whether or not the input field contains text upon initialization. However, I can't figure out how to access the child input field's value. Even when I try to console.log the value in ngAfterViewInit , it displays as empty, rather than the correct "The sample text".
How can I access the input's value from the directive applied to the parent node?
The directive will be applied to numerous inputs, but all with the same structure below, where a div wraps the label and an input bound via [(ngModel)].
I have a StackBlitz here: StackBlitz
HTML:

  Label
  <input type="text" [(ngModel)]='sampleText'>

TS:
import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  sampleText= 'Sample text'
}

Custom Directive
  import {
  Directive,
  ElementRef,
  OnInit,
  Renderer2,
  HostListener,
  AfterViewInit
} from "@angular/core";

@Directive({
  selector: "[appCollapsibleInput]"
})

export class CollapsibleInputDirective implements AfterViewInit {
  constructor(private elementRef: ElementRef, private renderer: Renderer2) {}

  rootEl;

  ngAfterViewInit() {
    //ref to the parent node
    this.rootEl = this.elementRef.nativeElement;

    //ref to the text input
    const inputField = this.elementRef.nativeElement.children[1];

    //Why is this logging empty??
    console.log("The input value: ", inputField.value);
  }
}


text:
Q: Inverse Laplace transform of the function: $F(s)=e^{-a\sqrt{s(s+r)}}$ I would like to find inverse Laplace transform of the function: $$F(s)=e^{-a\sqrt{s(s+b)}}$$
which $a$ and $b$ are positive real numbers and $s$ is a complex variable. It would be appreciated if someone can help me.

A: See my solution to this problem.  The analysis is identical, save for the denominator.
$$\oint_C ds \,e^{-a \sqrt{s (s+b)}}\, e^{s t}$$
where $C$ is the following contour pictured below:

This one's a bit odd because we are removing the branch point singularities by subtracting the inner contour $C_i$ from the outer contour $C_o$, i.e. $C=C_o+C_i$.
The integral about $C$ consists of the integral about vertical path (that ultimately becomes the ILT) and the integral about the outer arc.  We expect that this latter integral vanishes as the radius of the arc gets larger; this only happens when $a \lt t$ as shown below, by letting $s=R e^{i \phi}$; this integral over this arc is, for large $R$:
$$\left| \int_{\pi/2}^{3 \pi/2} d\phi \,e^{R (t-a) \cos{\phi}} \right|$$
Note that $\cos{\phi} \lt 0$ over the integration region, so that the integral only vanishes for $a \lt t$ when the contour opens to the left.
This leaves the integral over $C_i$ which consists of integrals above and below the real axis, between the branch points, and integrals about small circular arcs about the branch points.  These latter integrals vanish in the limit of the radii of the arcs going to zero. Thus, we are left with
$$\int_{c-i \infty}^{c+i \infty} ds e^{-a \sqrt{s (s+b)}}\, e^{s t} - \underbrace{ \int_0^{b} dx\, e^{i a \sqrt{x (b-x)}}\, e^{-x t}}_{s=e^{-i \pi} x} + \underbrace{ \int_0^{b} dx\, e^{-i a \sqrt{x (b-x)}}\, e^{-x t}}_{s=e^{i \pi} x} = 0$$
We set the sum of the integrals to zero because of Cauchy's theorem, i.e., there are no poles inside the contour $C$.  The second integral is the integral over the line below the real axis; the third is the integral over the line above the real axis.  Note that the phase transition was continuous from $-\pi$ to $\pi$ because we did not cross the branch cut; we did not see this explicitly because that information was included in the integrals about the branch points which vanished.
We do a little algebra and we have a real-valued integral for the ILT:
$$\frac{1}{i 2 \pi} \int_{c-i \infty}^{c+i \infty} ds \, e^{-a \sqrt{s (s+b)}} e^{s t} = \frac{1}{\pi} \int_0^b dx \, \sin{\left [ a \sqrt{x (b-x)}\right]} e^{-x t}$$
We make similar substitutions as with the other solution and we find the RHS is equal to
$$\begin{align}\frac{b}{2 \pi} e^{- b t/2} \int_0^{\pi} d\phi \, \sin{\phi} \, \sin{\left[\frac12 a b \sin{\phi}\right]} \, e^{b t/2 \cos{\phi}}\\ = -e^{-b t/2} \frac{1}{\pi} \frac{\partial}{\partial a} \int_0^{\pi} d\phi \,  \cos{\left[\frac12 a b \sin{\phi}\right]} \, e^{b t/2 \cos{\phi}}\\ = -e^{-b t/2} \frac{\partial}{\partial a} I_0\left( \frac{b}{2} \sqrt{t^2-a^2}\right)\end{align}$$
Note again that the contour is only closed to the left when $t>a$; when $t<a$ it is closed to the right.  Therefore the ILT of $e^{-a  \sqrt{s (s+b)}}$ is
$$\frac{a b}{2} e^{-b t/2} \left(t^2-a^2\right)^{-1/2} \, I_1\left(\frac{b}{2}\sqrt{t^2-a^2}\right) H(t-a)$$


text:
Q: Tell browser to always display MathJax as SVG? Lots of sites (or at least the ones I look at) have MathJax math support.  However, the default in just about every one seems to be to display as HTML/CSS, which simply does not work on any browser I've tried.  Doing a right-click on an equation and selecting 'display as SVG' gives me the equations, but it's a pain having to do it for every site.  Is there a way to tell the browser (via a user.css file or similar) to always display as SVG?
The MathJax site implies that it should be possible through web site config files, but all the documentation is addressed to people who are building web sites.  I'm just viewing other people's sites.


text:
Q: What were the names of the medals given out in Star Wars and what was written on them? At the end of the 1977 film "Star Wars: A New Hope" Luke, Han, and Chewie are presented with  medals in front of a large crowd by Princess Leia.
What were the names of the medals?  (Medal of Valor, etc.?)  Did they have anything written in them?

A:
As seen in this screenshot from the end of A New Hope (click to enlarge it), nothing is written on the medal.
Here is a close-up graphic of the medal:

According to Wookieepedia, this medal is called the "Medal of Bravery".
By the way, if you compare Han's medal to Peter Griffin's, you will find that Family Guy managed to make a fairly faithful version of it:


text:
Q: URL Amigable con Nginx - problema con archivos Intentaré ser lo mas explícito posible.
Amigos, estoy utilizando Nginx como servidor local y he estado modificando las url de manera amigable, pero tengo un problema, podrian ayudarme con esta solución? que estoy haciendo mal?
informo que todos mis proyectos estan en la carpeta www (localhost)
He logrado hacer que una url quede: http//localhost/miproyecto/producto/1000
Utilizando el siguiente código en nginx.conf:
location /miproyecto/producto/ {
    index index.php;
    try_files $uri $uri/ /miproyecto/producto/index.php?$args;
}

Tambien eliminé todas las extenciones de los archivos.
http//localhost/miproyecto/busqueda.php
A :
http//localhost/miproyecto/busqueda

Con el siguiente código:
location / {
    index  index.php index.html;
    try_files $uri $uri.html $uri/ @extensionless-php;
}

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

Aquí viene el mi problema y no se como solucionarlo (Aclaro con Apache me funciona de maravilla)
En vez de esta url:
http//localhost/miproyecto/negocio.php?empresa=nombreEmpresa
Quiero que quede así:
http//localhost/miproyecto/nombreEmpresa
Logré algo utilizando este código:
location /miproyecto/ {
    if (!-f $request_filename) {
        rewrite ^/miproyecto/(.*)+$ /miproyecto/negocio.php?$1;
    }
    index index.php
}

Pero mi problema aquí es que ahora si ingreso otra url por ejemplo:
http//localhost/miproyecto/registro
No abre el archivo correspondiente, es decirm no abre a registro.php
sino que piensa que le estoy mandando la palabra 'registro' como variable o nombre de empresa. Tampoco me toma el index.php es decir si coloco
http//localhost/miproyecto/
No me redirecciona al archivo index.php.
Y si modifico el código a esto:
location /miproyecto/negocio {
    index index.php;
    rewrite ^/miproyecto/(.*)+$ /miproyecto/negocio.php?$1;
}

Si me reconoce las urls que mencione anteriormente pero no me permite colocarla de la forma localhost/miproyecto/nombreEmpresa
No me permite hacer ambas cosas.

A: Si en vez de usar directorios para tus entradas location usaras expresiones regulares, efectivamente sería posible hacer lo que propones, dado que nginx intepreta las expresiones dándole prioridad a las más específicas por sobre las menos específicas, luego
location ~ ^/miproyecto/negocio {
  rewrite ^/miproyecto/(.*)+$ /miproyecto/negocio.php?$1;
}

tendría prioridad sobre
location ~ ^/miproyecto/ {
    if (!-f $request_filename) {
        rewrite ^/miproyecto/(.*)+$ /miproyecto/negocio.php?$1;
    }
}

Pero así como lo tienes, salvo jugar con el orden en que pones las reglas no creo que puedas hacer más.
Si no te animas a usar expresiones regulares para las entradas location lo único que se me ocurre es sugerirte que uses otro "namespace" para nombreEmpresa:
location /miproyecto/empresa {
    if (!-f $request_filename) {
        rewrite ^/miproyecto/(.*)+$ /miproyecto/negocio.php?$1;
    }
    index index.php
}


text:
Q: Parellel function call in python I am quite new to python.I have been thinking of making the below code to parellel calls where a  list of doj values are formatted with help of lambda,
m_df[['doj']] = m_df[['doj']].apply(lambda x: formatdoj(*x), axis=1)

def formatdoj(doj):
    doj = str(doj).split(" ")[0]
    doj = datetime.strptime(doj, '%Y' + "-" + '%m' + "-" + "%d")
    return doj

Since the list has million records, the time it takes to format all takes a lot of time.
How to make parellel function call in python similar to Parellel.Foreach in c#?

A: I think that in your case using parallel computation is a bit of an overkill. The slowness comes from the code, not from using a single processor. I'll show you in some steps how to make it faster, guessing a bit that you're working with a Pandas dataframe and what your dataframe contains (please stick to SO guidelines and include a complete working example!!)
For my test, I've used the following random dataframe with 100k rows (scale times up to get to your case):
N=int(1e5)
m_df = pd.DataFrame([['{}-{}-{}'.format(y,m,d)]
                        for y,m,d in zip(np.random.randint(2007,2019,N),
                        np.random.randint(1,13,N),
                        np.random.randint(1,28,N))],
                    columns=['doj'])

Now this is your code:
tstart = time()
m_df[['doj']] = m_df[['doj']].apply(lambda x: formatdoj(*x), axis=1)
print("Done in {:.3f}s".format(time()-tstart))

On my machine it runs in around 5.1s. It has several problems. The first one is you're using dataframes instead of series, although you work only on one column, and creating a useless lambda function. Simply doing:
m_df['doj'].apply(formatdoj)

Cuts down the time to 1.6s. Also joining strings with '+' is slow in python, you can change your formatdoj to:
def faster_formatdoj(doj):
    return datetime.strptime(doj.split()[0], '%Y-%m-%d')
m_df['doj'] = m_df['doj'].apply(faster_formatdoj)

This is not a great improvement but does cut down a bit to 1.5s. If you need to join the strings for real (because e.g. they are not fixed), rather use '-'.join('%Y','%m','%d'), that's faster.
But the true bottleneck comes from using datetime.strptime a lot of times. It is intrinsically a slow command - dates are a bulky thing. On the other hand, if you have millions of dates, and assuming they're not uniformly spread since the beginning of humankind, chances are they are massively duplicated. So the following is how you should truly do it:
tstart = time()
# Create a new column with only the first word
m_df['doj_split'] = m_df['doj'].apply(lambda x: x.split()[0])
converter = {
    x: faster_formatdoj(x) for x in m_df['doj_split'].unique()
}
m_df['doj'] = m_df['doj_split'].apply(lambda x: converter[x])
# Drop the column we added
m_df.drop(['doj_split'], axis=1, inplace=True)
print("Done in {:.3f}s".format(time()-tstart))

This works in around 0.2/0.3s, more than 10 times faster than your original implementation.
After all this, if you still are running to slow, you can consider working in parallel (rather parallelizing separately the first "split" instruction and, maybe, the apply-lambda part, otherwise you'd be creating many different "converter" dictionaries nullifying the gain). But I'd take that as a last step rather than the first solution...
[EDIT]: Originally in the first step of the last code box I used m_df['doj_split'] = m_df['doj'].str.split().apply(lambda x: x[0]) which is functionally equivalent but a bit slower than m_df['doj_split'] = m_df['doj'].apply(lambda x: x.split()[0]). I'm not entirely sure why, probably because it's essentially applying two functions instead of one.

A: Your best bet is to use dask. Dask has a data_frame type which you can use to create this a similar dataframe, but, while executing compute function, you can specify number of cores with num_worker argument. this will parallelize the task

A: Since I'm not sure about your example, I will give you another one using the multiprocessing library:
# -*- coding: utf-8 -*-
import multiprocessing as mp

input_list = ["str1", "str2", "str3", "str4"]

def format_str(str_input):
    str_output = str_input + "_test"
    return str_output

if __name__ == '__main__':
    with mp.Pool(processes = 2) as p:
        result = p.map(format_str, input_list)

    print (result)

Now, let's say you want to map a function with several arguments, you should then use starmap():
# -*- coding: utf-8 -*-
import multiprocessing as mp

input_list = ["str1", "str2", "str3", "str4"]

def format_str(str_input, i):
    str_output = str_input + "_test" + str(i)
    return str_output

if __name__ == '__main__':
    with mp.Pool(processes = 2) as p:
        result = p.starmap(format_str, [(input_list, i) for i in range(len(input_list))])

    print (result)

Do not forget to place the Pool inside the if __name__ == '__main__': and that multiprocessing will not work inside an IDE such as spyder (or others), thus you'll need to run the script in the cmd.
To keep the results, you can either save them to a file, or keep the cmd open at the end with os.system("pause") (Windows) or an input() on Linux.
It's a fairly simple way to use multiprocessing with python.


text:
Q: How to solve the differential equation $y''=\frac{y'}{y}$ I want to solve the initial value problem:
$$y''=\frac{y'}{y},\;\ y'(x=0)=1,\;\ y(x=0)=e$$
I have attempted to integrate on both sides but this results in a logarithm term on the r.h.s., which causes problems when I divide on both sides by it. I am not sure whether it is possible to isolate $y$.

A: Let us consider your initial value problem:
$$y''(x)=\frac{y'(x)}{y(x)},\;\ y'(0)=1,\;\ y(0)=e$$
Integrate on both sides with respect to $x$. Recognize that $y''(x)\ dx=dy'(x)$ and $y'(x)\ dx=dy(x)$:
$$\int y''(x)\ dx=\int \frac{y'(x)}{y(x)}dx\rightarrow\int dy'(x)=\int \frac{dy(x)}{y(x)}\rightarrow y'(x)=\ln(y(x))+\text{C}_1$$
Let $y'(0)=1$ and $y(0)=e$ and derive that $\text{C}_1=0$.
It follows that
$$y'(x)=\ln(y(x))\rightarrow \frac{y'(x)}{\ln(y(x))}=1$$
Integrate on both sides with respect to $x$. Recognize that  $y'(x)\ dx=dy(x)$:
$$\int \frac{y'(x)}{\ln(y(x))}dx=\int dx\rightarrow\int\frac{dy(x)}{\ln(y(x))}=\int dx\implies\text{li}(y(x))=x+\text{C}_2$$
Let $y(0)=e$ and derive that $\text{C}_2=\text{li}(e)$.
Therefore,
$$\text{li}(y(x))=x+\text{li}(e)$$
Here, $\text{li}(z)$ denotes the logarithmic integral.
This function does not have an inverse function, so we can't isolate $y(x)$.

A: Let $y'=f(y)=>y''=f'(y)y'=ff'=>ff'=f/y=>f\equiv0\ or f'=1/y=>$
$$
\\\int{df}=\int{dy/y}
\\f=\ln|y|+const
\\y'=ln|y|+const
\\x=\int{\frac{dy}{ln|y|+const}}
$$

A: $$y''=\frac{y'}{y}$$
$$\int y''dy=\int\frac{y'}{y}dy$$
$$y'=\ln|y|+C_1$$
$$y'=\ln|y|+\ln(C_2)$$
$$y'=\ln|C_2y|$$
$$\int\frac{dy}{\ln(y)}=\int dx$$
$$x=\int\frac{dy}{\ln(y)}+C_3$$
and this has no elementary antiderivative

A: Write your equation in the form
$$\frac{dy(x)}{dx}-\frac{d^2y(x)}{dx^2}y(x)=0$$ and Substitute $$v(y)=\frac{dy(x)}{dx}$$
Can you proceed?


text:
Q: VBA Userform After Update Text Box Order (Excel) I am having a hard time getting my text box sequence to work correctly in my userform.  I have 3 text boxes and 2 botton.  So the order is textbox 1, textbox 2, textbox3, button1, and button2.
Issue I am having is that when I enter data into textbox1, the focus keeps jumping to button2 which is as the end.  I need the textbox focus in order.
Private Sub USERFORM_INITIALIZE()
Me.loc.SetFocus
End Sub

Private Sub loc_AfterUpdate()
Me.sku.SetFocus
End Sub

Private Sub sku_afterupdate()
Me.qty.SetFocus
End Sub

Private Sub qty_afterupdate()
Me.submit.SetFocus
End Sub


text:
Q: Assigning a float to a string reference works—why? On a recent project, I ran into an error where I accidentally assigned a float to a string reference (instead of converting the float to a string, then assigning it).
The code looked something like this (tested under both Xcode/Apple LLVM 7.1 and GCC 4.9.2):
#include <iostream>
using namespace std;

static void get_text(string &s) {
    s = 1.0f;  // Legal (not even a warning!)
}

// This version gives a compiler error (as I'd expect)
// static void get_text(string &s) {
//     string out = 1.0f;
//     s = out;
// }

int main() {
    string s;
    get_text(s);
    cout << s << endl; // Prints garbage
    return 0;
}

Printing the string obviously results in garbage, but I'm not clear why this didn't give so much as a warning. (My best guess is that the compiler did some sort of implicit reinterpret cast to go from float, to int, to a memory address...?)
Is there a warning I could enable (in Xcode, ideally) that would prevent this sort of thing in the future?

A: This is because of the member function:
string& operator=( char ch );

There is implicit conversion from floating point to integer types in C++  (char is an integer type).
Normally you can use -Wfloat-conversion in g++ to get a warning about this conversion, but I tried it and it didn't warn. (Maybe compiler bug?)
A simple way to modify the code to get errors for unexpected floating/integer conversions is:
s = { 1.0f };

Another option is to make the function have string as return type (generally speaking this design is preferred to having an "out" reference parameter anyway):
static string get_text() { return 1.0f; }

Unfortunately this is one of many minor pitfalls surrounding the use of std::string, which was "designed" when C++ was still very young and it was not apparent what undesirable long term consequences would arise.


text:
Q: Problems with a 3 column layout with fixed left side I have a problem making a 3 column layout. I have tried all examples now online - used Google. None of this seems to solve my problem.
What I try to do is easy for people with knowledge.

*

*Make a 3 column fluid layout that cover the whole screen.

*Left column should be 230px width, fixed, height 100%.

*Center column and right column should be equal width.

*For both center - and right column they have to "float" into each other

Problem occur when you zoom out. Center column run away to left and make a huge white gap between center column and right column.
That is my problem.
center and right column need to be close to each other - no gap.
How can I solve this?
You can see my attempt here: Fiddle
Just zoom out, and you see the problem straight away. Need help to fix this. How?
Another problem occur if I use a div wrapper inside the center column with width set to 100%. Same problem as described above will happened. The text in both left and right column need to be float as well.
I can't use overflow:hidden because I need to - later - use a absolute div on right side of the center column to set a image arrow pointing to right column.

A: You mean something more like this: http://jsfiddle.net/gbRzM/?
(uses left, right and width properties to position everything)
.left {
    width: 230px;
position:fixed;
    background:GREEN;
}

.right {
    right:0;
    width:30%;
    position:fixed;
    background: RED;
}

.center {
    left:230px;
    right:30%;
    position:fixed;
    border:1px solid;
    background:YELLOW;
}

Or more accurately this: http://jsfiddle.net/HKJvP/?
(puts center and right in a new div, so that pixels and % can be mixed, allows equal width that you specified)
.left {
    width: 230px;
    position:fixed;
    background:GREEN;
}

.notleft{
    left:230px;
    height:100%;
    right:0;
    position:fixed;
}

.right {
    right:0;
    width:50%;
    position:absolute;
    background: RED;
}

.center {
    left:0;
    width:50%;
    position:absolute;
    border:1px solid;
    background:YELLOW;
}

A: give a fixed width to the parent element of three columns and add class clearfix
``
.clearfix:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

.clearfix {
    display: inline-block;
}

html[xmlns] .clearfix {
    display: block;
}

* html .clearfix {
    height: 1%;
}


text:
Q: Entity Framework setting datetime to null or min I'm using Entity Framework 5, Database First.
I am doing something I've done many times before, but for some reason it is not working.
My Table is defined as:

CREATE TABLE [dbo].[ActivationQueue](
[ID] [int] IDENTITY(1,1) NOT NULL,
[username] [nvarchar](255) NOT NULL,
[email] [nvarchar](255) NOT NULL,
[ActivationRequested] [datetime] NOT NULL,
[ActivationEmailSent] [datetime] NOT NULL,
[AccountActivated] [datetime] NOT NULL,
[ActivationAttempts] [int] NULL,
[ActivationKey] [uniqueidentifier] NULL,

CONSTRAINT [PK_Activations] PRIMARY KEY CLUSTERED
This is the code I use to retrieve a particular row:

ActivationQueue accountActivation = DbSet.FirstOrDefault(a => a.username.ToLower() == userName)

When I use DbSet.FirstOrDefault() to get the first row, the ActivationEmailSent column is always returning SQLDateTime.MinValue() even though it has a correct value. The ActivationRequested column is always returning the correct value.
I've used SQL profiler, and when I run the below SQL I get the correct DateTime value back.
exec sp_executesql N'SELECT TOP (1)
[Extent1].[ID] AS [ID],
[Extent1].[username] AS [username],
[Extent1].[email] AS [email],
[Extent1].[ActivationRequested] AS [ActivationRequested],
[Extent1].[ActivationEmailSent] AS [ActivationEmailSent],
[Extent1].[AccountActivated] AS [AccountActivated],
[Extent1].[ActivationAttempts] AS [ActivationAttempts],
[Extent1].[ActivationKey] AS [ActivationKey]
FROM [dbo].[ActivationQueue] AS [Extent1]
WHERE (LOWER([Extent1].[username])) = @p__linq__0',N'@p__linq__0         nvarchar(4000)',@p__linq__0=N'someusername'

The thing that gets me is that the mappings for the ActivationRequested and ActivationEmailSent are identical as are the definitions ( I just used updateModel in the edmx). But ActivationRequested returns the correct value, while ActivationEmailSent returns SQLDateTime.Min ( 1753-01-01 00:00:00.000 )
I don't know whether this helps, but when I set the column to be nullable, it just returned null.

A: Found the problem for anyone else that may come with this.
The model.store properties of the DateTime column had the precision attribute set to None whereas the Entity had the precision attribute set to 3.
Changing the precision attribute to none for both fixed the issue.
Though I am still baffled why it worked for one of the columns in the first place, and not the other even though they had identical mappings.


text:
Q: error Generic parameter 'ID' could not be inferred with DatePicker I have a couple of DatePickers in a view with the following code. Each DatePicker presents a digit, so "3" or "5". So for "3456" I have 4 DatePickers that can be changed individually.
struct DigitPicker: View {

    var digitName: String
    @Binding var digit: Int

    var body: some View {
        VStack {
            Picker(selection: $digit, label: Text(digitName)) {
                ForEach(0 ... 9) {
                    Text("\($0)").tag($0)
                }
            }.frame(width: 60, height: 110).clipped()
        }
    }
}

I get an error "Generic parameter 'ID' could not be inferred". So I guess the reason is that $digit must conform to Identifiable(). But how do I do that???

A: The compiler is resolving the ForEach using this extension:
extension ForEach where Content : View {

    /// Creates an instance that uniquely identifies views across updates based
    /// on the `id` key path to a property on an underlying data element.
    ///
    /// It's important that the ID of a data element does not change unless the
    /// data element is considered to have been replaced with a new data
    /// element with a new identity. If the ID of a data element changes, then
    /// the content view generated from that data element will lose any current
    /// state and animations.
    public init(_ data: Data, id: KeyPath<Data.Element, ID>, content: @escaping (Data.Element) -> Content)
}

And, as you can see, it can't infer the second argument of the init method.
You can make the second argument explicit to make the compiler happy.
ForEach(0 ... 9, id: \.self) { // identified by self
   Text("\($0)").tag($0)
}


text:
Q: What is an effective user id of a PHP process vs the real user id? I'm having a tough time finding the difference between the PHP functions posix_getuid and posix_geteuid. I know that posix_geteuid returns the effective user ID of the current process, but what does that mean? Also, whats the difference between setting the user id over setting the effective user id?

A: They're likely to always be the same for a PHP process. The only time they're generally different is when a process is running as setuid, which is incredibly unsafe to do for PHP scripts (because the interpreter can be easily subverted by environment variables).
Note also that you can only change the uid/euid of the current process when one of the two is currently set to 0 (root).


text:
Q: Why do some objects initilize themselves? FileSearchApp.java
package com.example.filesearch;

public class FileSearchApp {
    String path;
    String regex;

    public static void main(String[] args) {
        FileSearchApp app = new FileSearchApp(); // ?

        // some othe code
    }

}

Why there is this line FileSearchApp app = new FileSearchApp();? Why would an object need to recreate itself? And there is no issue calling a method like callMethod1();.

A: main is static, without creating a new instance, you can only call other static method of it.

A: There are two types of methods and four types of variables. As in this case the major two are,

*

*Instance

*Static

If you see the keyword static they are static if not instance.
They are in two different places. When starting the application you are inside the main method and it is static. To access instance variables or methods like path, regex and any other instance methods you need an object. That's where the statement new FileSearchApp() comes in.
The method local variable app holds your object so you can call all the instance things inside it using that object.
app.path;
app.regex;
app.instanceMethod();


text:
Q: How can i Add Customers name on Point of Sale Reciept How can i add customers name on Odoo 8 Pos Module to print on the receipt / Ticket
Here is the code i tried to modify in Odoo 8 POS (pos.xml file)
...static/src/xml

<t t-esc="new Date().toString(Date.CultureInfo.formatPatterns.shortDate + ' ' +
            Date.CultureInfo.formatPatterns.longTime)"/> <t t-esc="order.get('name')"/>

        <t t-esc="widget.pos.company.name"/>

        Phone: <t t-esc="widget.pos.company.phone || ''"/>

        User: <t t-esc="widget.pos.cashier ? widget.pos.cashier.name : widget.pos.user.name"/>

        Shop: <t t-esc="widget.pos.shop.name"/>

        customer : <t t-esc="order.changed.client.name"/>

        <t t-if="widget.pos.config.receipt_header">

                <t t-esc="widget.pos.config.receipt_header" />


text:
Q: Fatal error: Uncaught Error: [] operator not supported for strings - Codazon Themeframework -- Categoriestree.php After migrating a Magento 1.9.3.7 site between servers I am unable to access the settings page: Navigate to Admin> System> Configuration
The following error is displayed:

Fatal error: Uncaught Error: [] operator not supported for strings in /home/defaultwebsite/public/app/code/local/Codazon/Themeframework/Model/System/Config/Source/Categoriestree.php:28

Categoriestree.php:28 error here >>
$this->_categoriesTree[] = array('value' => $item['category_id'],'label' => str_repeat("–––", $level)." ".$item['name']);

A: May be this post helps , similar to your problem error
https://www.key2goal.com/article/wordpress-error-php-71-php-fatal-error-uncaught-error-operator-not-supported-strings
If you using php 7.1, then you need proper array define..
May be define like this
$this->_categoriesTree = array();


text:
Q: iOS: sin() Symbols not found for architecture i386 I'm trying to use sin(), cos(), tan() from math.h in an iPhone (simulator) app.
What do I need to change to get the standard C math library functions to link in?
I'm making calls from .cpp files.
e.g.
#include <math.h>
..
float f = tan( p1 );

Linker output:
  "tan(float)", referenced from:

      GetTan(float) in myfuncs.o

ld: symbol(s) not found for architecture i386

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Am I missing a needed framework?

A: In some environments you need to explicitly link libm in order to get transcendental math functions, so try adding -lm to your linker flags.


text:
Q: model return value in codeigniter I store the return value from my model in a $result:
$result = $this->absensi_m->absensi();

Based on what i return in the absensi() function, the value of $result will be one of these :

*

*FALSE

*'sudah absen' (a String)

*1 (indicating success)

Then i try to see the $result value using echo $result; and it returns 1
But, i get a strange error when i try to use $result for some validations :
        if($result == FALSE)
            $data['result'] = 'Anda Belum Terdaftar, Silahkan Daftar Dahulu :D';
        else if($result == 'sudah absen')
            $data['result'] = 'Anda Sudah Absen Hari Ini :D';
        else
            $data['result'] = 'Selamat Datang, '.$this->input->post('txtNama').'! ^^';

Although the value of  $result is 1, the second if ($result == 'sudah absen') always return TRUE.
Whats going on here?Thanks :D
This is the absensi() function in my model :
public function absensi() {
        $nama = $this->input->post('txtNama');
        $tanggal = date('Y-m-d', now());

        $this->db->select('umat_id');
        $terdaftar = $this->db->get_where('msumat', array('nama' => $nama));

        $row = $terdaftar->row_array();
        $sudah_absen = $this->db->get_where('msabsensi', array('umat_id' => $row['umat_id'], 'absensi_tanggal' => $tanggal));

        if($terdaftar->num_rows() != 0 && $sudah_absen->num_rows() == 0)
        {
            $data_umat = array(
            'umat_id' => $row['umat_id'],
            'status' => 'H',
            'absensi_tanggal' => date('Y-m-d')
            );

            return $this->db->insert('msabsensi', $data_umat);
        }
        else if($sudah_absen->num_rows() != 0)
            return 'sudah absen';
        else
            return FALSE;
    }

ANSWER :
I will answer here because you may be confused with a lot of comments/conversation.
I realized whats going on by using var_dump() and echo (Thanks to both answers below):
$result = $this->absensi_m->absensi();
var_dump($result);
echo $result;

The var_dump() returns bool(true) while the echo returns 1. This means that this problem is occured because i think the $result value is 1(integer), while the real value is TRUE(bool).
The conclusion is : echoing a variable with a TRUE(bool) value will result 1(integer), so use the var_dump() instead of echo.

A: first you can't return:
return $this->db->insert('msabsensi', $data_umat);

do this:
 $this->db->insert('msabsensi', $data_umat);
 return ...-> 1 or true or what you need

then you  should do:
if(!$result){
            $data['result'] = 'Anda Belum Terdaftar, Silahkan Daftar Dahulu :D';
        }
    if($result == 'sudah absen'){
            $data['result'] = 'Anda Sudah Absen Hari Ini :D';
         }
       if($result && $result !== 'sudah absen'){
            $data['result'] = 'Selamat Datang, '.$this->input->post('txtNama').'! ^^';
          }

then use var_dump(); to check what result is:
var_dump($result);

A: Are you sure this is happening? are you sure $result=1?
I find it hard to believe. Here's a fiddle output to your code
your function returns true not 1
you should add else if($result === 'sudah absen') to strictly check for the result.


text:
Q: Content to service via a CDN
*

*Which of these content is usually not very useful to service via a CDN

*

*Videos

*AJAX-requests

*Images

*HTML/CSS

*Videos

*Edge-Side includes

*JavaScript

Could someone please provide an answer with explanation. Thank You!

A: Static files, like javascript, html, images, video you can host on a cdn, your ajax requests needs to be processed so you could not host them on a cdn.
CDN, is basically a server where the user can only download your files, the most cdn hosters have multiple servers so its more common that a server is near your user, based on that download speed will be faster.
So if you have static content ( dosnt need to be processed like ajax / api calls ) you can host it on a CDN


text:
Q: Android Data Binding : can't find the setter for attribute Not sure how it works but according to this post it's possible to bind specific listener by using different namespaces.
I wanted to do the same thing with a searchview and bind a QueryTextListener to it but I get the following error :
Cannot find the setter for attribute 'bind:setOnQueryTextListener'
with parameter type android.widget.SearchView.OnQueryTextListener.

What I did in my ViewModel :
public class MembersFragmentViewModel extends BaseObservable {

    private Context context;
    private MembersAdapter adapter;
    private RecyclerView recyclerView;

    public MembersFragmentViewModel(Context context, MembersAdapter adapter, RecyclerView recyclerView) {
        this.context = context;
        this.adapter = adapter;
        this.recyclerView = recyclerView;
    }

    public SearchView.OnQueryTextListener getQueryTextListener(){
        return new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                List<Contact> filteredModelList = filter(adapter.getContacts(), query);
                adapter.animateTo(filteredModelList);
                if(recyclerView != null)
                    recyclerView.scrollToPosition(0);
                return true;
            }
        };
    }
    //Code ...

And the xml :
My namespace is declared in the layout tag like this :
xmlns:bind="http://schemas.android.com/apk/res-auto"

And my SearchView :
<android.support.v7.widget.SearchView android:id="@+id/searchview"
        android:layout_width="match_parent"
        android:layout_height="40dp"

        android:background="@drawable/rounded_search_view_background"
        bind:setOnQueryTextListener="@{viewModel.QueryTextListener}">

</android.support.v7.widget.SearchView>

This is my data tag :
<data>
   <variable
       name="viewModel"
       type="mypackagename.viewmodel.members.MembersFragmentViewModel"/>
</data>

Many thanks for any clue !

A: In my case the answer was just a wrong package name.
My SearchView was declared in xml with the following package name :
android.support.v7.widget.SearchView

And the package I used in the ViewModel was
android.widget.SearchView


text:
Q: Is it possible to create multiple jar files of same project I am working on a maven project which has 12 classes and all the classes have dependency on conf file which is included in the project. I want to create multiple jars of the same project. Let say I want to create separate jar for each classes so that my testing will be easier.Also, I have a main class which runs the entire project.
Could it be possible to do so??
Thanks in advance
I tried extracting the jar but I am able to do for the entire project and not for a particular class.
This my main class which runs the entire project
package dicom_ibe;

public class DicomManager
{
    public static void main(String[] args) throws Exception
    {
        DicomOrchestrator dcm = new DicomOrchestrator();
    }
}

A: create jars for different classes. Create new project with only main class. Add all created jar files as dependencies. This is will resolve you issue i guess.
What i did is..
1) Created test project which is having Main, HelloWorld, HelloIndia classes.
enter image description here
2) Then from eclipse -> right click on each class file and EXPORT -> jar, only for HELLOWORLD and HELLOINDIA class files, not for MAIN class
3) Created new project with MAIN class and added dependecies helloworld and helloindia jars to this new project and export this project as RUNNABLE JAR.
enter image description here
enter image description here
As per your question this process will create individual jars for all class files and final MAIN class jar will have all other jars as dependency. Hope this solution will help you.
Thanks..


text:
Q: wts: $e^{-nx}$ converges uniformly on $[r,\infty)$ $r>0$ wts: $e^{-nx}$ converges uniformly on $[r,\infty)$ when $r>0$
I feel that $x \in [r,\infty)$ $\Rightarrow$ $f_n(x) \rightarrow 0$.
I know that I am looking for some $N \in \mathbb{N}$ s.t. $|f_n(x)-0| < \epsilon$. That is, I want to find when $e^{-nx} < \epsilon$,  which is when $-nx < ln(\epsilon)$ or $n>-\frac{ln(\epsilon)}{x}$ for all x.
I know that I can't have my answer dependent upon x for uniform convergence, though. I thought it might work if I said $N=0$ (as it is always bigger than $-\frac{ln(\epsilon)}{x}$), but this yields $|f_n(x)-0|=e^{0} = 1$, which isn't strong enough. Similarly, letting N be any other integer doesn't work out very well either.
original booboo: here

A: We see that for $x\ge r>0$,$$ e^{nx} > nx \ge nr $$
So $$e^{-nx} < \frac{1}{nr}$$
Now you can see that neither $n$ nor $r$ are dependent on $x$ and you can easily prove the uniform convergence.  Note that if $r=0$ the above method will not work.


text:
Q: Count Areas in a Maze Maze
Write a function count_areas(diagonal_maze) that takes in a diagonal maze (as list of string) and returns the number of enclosed area in the diagonal maze. We assume that there are non-diagonal boundaries on the perimeter of the maze.
>`count_areas(["\//\\\\/", "\///\\\\", "//\\\\/\\", "\/\///"])
>12`

>'count_areas(["\/", "/\\"])
>4'

We make every \\ to represent only one \ because python syntax \ is special.
My idea is to look at the first row then compare the rest with the first....
However, it seems that there are too many conditions to consider.
Can someone clear up my logic?

A: This is easily solved using a disjoint set data structure:
Create a set for each vertical or horizontal boundary -- the ones between cells, and the ones around the edge of the maze.
For each / cell, join the sets for its top and left sides, and join the sets for its bottom and right sides.
For each \ cell, join the sets for its top and right sides, and join the sets for the bottom and left sides.
Finally, count the number of sets you're left with -- there will be one for each area of the maze.


text:
Q: How to set WIP limit in Azure DevOps Board - Sprint View In Azure DevOps Boards, we can set WIP limits for columns. Unfortunately it is only possible in the Boards view but not in the Sprint view, at least I found no possibility to do it. Did I miss something or is it really not possible. And if not, does someone why it is not possible?

A: Sprint view does not support WIP because WIP comes from Kanban. Sprint view is Agile/Scrum tool. Work in Progress limits:

An essential Kanban practice—Work in Progress limits, referred to as
"WIP limits"—constrains the amount of work your team undertakes at
each work stage.

A: The WIP limits are used to limit the number of work items in progress, and can help identify process bottlenecks and improve the Team's efficiency. These numbers are set per stage and act as the soft constraint that can be revisited later.
As a prerequisites, To use WIP Prerequisites, you must have a Kanban board you want to configure. When you add a team, you add a Kanban board for that team.
In other words, it's not available to  set WIP with Sprint View. Sorry for any inconvenience, this is by designed.


text:
Q: Is it normal for Hobbits to live without their parents? Based on my previous question, tried to understand why was Frodo living with Bilbo based on the assumption that it's not something normal. As Nathaniel pointed in a comment,

It could be perfectly normal for hobbits, as far as we know

So, this assumption was likely being drawn from my human experience. To clarify in case of any doubts, is that normal for hobbits or not?
By normal I mean that the majority would live that way. For instance, it could be considered normal in my hometown to have kids before marriage since 7 out of 10 newborns match that requirement (i know it's possible to judge "normality" based on other criterias (not necessarily through the majority) but that's not the intent here).

A: No, it is not normal.
Tolkien describes Hobbit society in the section 1 of the Prologue. He explicitly singles out Frodo and Bilbo as being unusual in this:

The houses and the holes of Shire-hobbits were often large, and inhabited by large families. (Bilbo and Frodo Baggins were as bachelors very exceptional, as they were also in many other ways, such as their friendship with the Elves.) Sometimes, as in the case of the Tooks of Great Smials, or the Brandybucks of Brandy Hall, many generations of relatives lived in (comparative) peace together in one ancestral and many-tunnelled mansion. All Hobbits were, in any case, clannish and reckoned up their relationships with great care.


text:
Q: How to determine interventional distributions from observational data? How do we compute/query interventional distributions from observational data (i.e. without knowledge of the causal graph such as a Structural Causal Model (SCM))?

A: In general, observational data is not sufficient to obtain the interventional distributions. You will "only" obtain the Markov equivalence class (e.g. with the pcalg R-package). E.g., think of two random variables $A$ and $B$, where your observation consists only of an $n\times 2$ table of $n$ observations of the pairs $(a_i, b_i)$. This table can only tell you (approximately) whether they are dependent or not. It doesn't contain any information about whether $A$ causes $B$, i.e. $A\to B$, or $B$ causes $A$, i.e. $A\leftarrow B$.
However, those equivalence classes are often not too large (see the linked paper above and this paper, section 3), so this can already contain lots of helpful information.
The standard methods of getting (some of) the interventional distributions via adjustment sets (e.g. the backdoor method) all presume some extra knowledge such as that the treatment does cause the outcome and the knowledge of all the confounders. But that information is often available, at least approximately.
Another approach is that of additive noise models: it often suffices to have only a little bit of qualitative information about the distributions to be able to identify the causal model and the interventional distributions.
Finally, also addressing the comments to the question, note that there is nothing that the method of potential outcomes can do that Pearl's causal graph approach cannot, and vice versa. It is just that some tasks are sometimes easier to tackle with one method than with the other; it is also often a question of subjective taste. For instance, the backdoor method is part of both approaches, and both deal with counterfactuals, too.


text:
Q: mmap load shared object and get function pointer I want to dynamically load a library without using functions from dlfcn.h i have a folder full of .so files compiled with:
gcc -Wall -shared -fPIC -o filename.so filename.c

And all of them have an entry function named:
void __start(int size, char** cmd);

(I know, probably not the best name)
then i try to call open over the so, then read the elf header as an Elf64_Ehdr load it into memory with mmap (i know i should use mprotect but i want to make it work first and then add the security) and finally adding the the elf header entry to the pointer returned by mmap (plus an offset of 0x100).
The test code is the following:
#include <elf.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>

typedef void (*ptr_t) (int, char**);

void* alloc_ex_memory(int fd) {
    struct stat s;
    fstat(fd, &s);
    void * ptr = mmap(0, s.st_size, PROT_READ | PROT_WRITE | PROT_EXEC,
    MAP_PRIVATE | MAP_ANONYMOUS, fd, 0);
    if (ptr == (void *)-1) {
        perror("mmap");
        return NULL;
    }
    return ptr;
}

void* load_ex_file(const char* elfFile) {
    Elf64_Ehdr header;
    void * ptr;
    FILE* file = fopen(elfFile, "rb");
    if(file) {
        fread(&header, 1, sizeof(header), file);

        if (memcmp(header.e_ident, ELFMAG, SELFMAG) == 0) {
            ptr = alloc_ex_memory(fileno(file));
            printf("PTR AT -> %p\n", ptr);
            printf("Entry at -> %lx\n", header.e_entry+256);
            ptr = (header.e_entry + 256);
        } else {
            ptr = NULL;
            }

        fclose(file);
            return ptr;
    }
    return NULL;
}

int main(int argc, char** argv) {
    ptr_t func = load_ex_file(argv[1]);
    printf("POINTER AT: %p\n", func);
    getchar();
    func(argc, argv);
    return 0;
}

Let me explain a bit further:
When i run objdump -d filename.so i get that the _start is at 0x6c0. The elf header entry point returns 0x5c0 (i compensate it adding 256 in dec).
Also pmap shows an executable area being created at lets say 0x7fdf94d0c000
 so the function pointer direction that i get and which i call is at 0x7fdf94d0c6c0  this should be the entry point and callable via function pointer. But what i get is, you guessed it: segfault.
Las thing that i would like to point out is that i have the same example running with (dlopen, dlsym, dlclose) but its required that i use the mmap trick. I have seen my professor implement it successfully but i cannot figure out how. (perhaps there is a simpler way that im missing).
I based the code on this jit example
Thank you in advance!
Edit: This is the code of the .c that i compile into .so:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void __start(int size, char** cmd) {
    if (size==2) {
        if (!strcmp(cmd[1], "-l")) {
            printf("******.********.*****@udc.es\n");
            return;
        } else if (!strcmp(cmd[1], "-n")) {
            printf("****** ******** *****\n");
            return;
        }
    } else if (size==1) {
            printf("****** ******** ***** (******.********.*****@udc.es)\n");
            return;
    }
    printf("Wrong command syntax: autores [-l | -n]\n");
}

A:
its required that i use the mmap trick. I have seen my professor implement it successfully but i cannot figure out how.

For this to work, your __start must be completely stand-alone, and not call any other library (you violated that requirement by calling strcmp and printf).
The moment you call an unresolved symbol, you ask the dynamic loader to resolve that symbol, and the loader needs all kinds of info for that. That info is normally set up during dlopen call. Since you bypassed dlopen, it is not at all surprising that your program crashes.
Your first step should be to change your code such that __start doesn't do anything at all (is empty), and verify that you can then call __start. That would confirm that you are computing its address correctly.
Second, add a crash to that code:
void __start(...)
{
  int *p = NULL;
  *p = 42;  // should crash here
}

and verify that you are observing the crash now. That will confirm that your code is getting called.
Third, remove the crashing code and use only direct system calls (e.g. write(1, "Hello\n", 6) (but don't call write -- you must implement it directly in your library)) to implement whatever you need.


text:
Q: How to get dropdown with list of colors?

<select name="color" class="form-control" id="color">
  <option value="">Choose</option>
  <option style="color:#0071c5;" value="#0071c5">◼ Dark blue</option>
  <option style="color:#40E0D0;" value="#40E0D0">◼ Turquoise</option>
  <option style="color:#008000;" value="#008000">◼ Green</option>
  <option style="color:#FFD700;" value="#FFD700">◼ Yellow</option>
  <option style="color:#FF8C00;" value="#FF8C00">◼ Orange</option>
  <option style="color:#FF0000;" value="#FF0000">◼ Red</option>
  <option style="color:#000;" value="#000">◼ Black</option>
</select>

Colors not showing do I need to install some plugins? I want to achieve this but I'm getting black box only

A: You need to apply the selected color to the selectbox. This can be easily achieved with JS via the change event.

const colorBox = document.getElementById('color');

colorBox.addEventListener('change', (event) => {
  const color = event.target.value;
  event.target.style.color = color;
}, false);
<select name="color" class="form-control" id="color">
<option value="">Choose</option>
<option style="color:#0071c5;" value="#0071c5">◼ Dark blue</option>
<option style="color:#40E0D0;" value="#40E0D0">◼ Turquoise</option>
<option style="color:#008000;" value="#008000">◼ Green</option>
<option style="color:#FFD700;" value="#FFD700">◼ Yellow</option>
<option style="color:#FF8C00;" value="#FF8C00">◼ Orange</option>
<option style="color:#FF0000;" value="#FF0000">◼ Red</option>
<option style="color:#000;" value="#000">◼ Black</option>
</select>


text:
Q: CSS attribute selector does not work a href I need to use attribute selector in css to change link on different color and image, but it does not work.
I have this html:
A PDF File

And this css:
a {
     display: block;
     height: 25px;
     padding-left: 25px;
     color:#333;
     font: bold 15px Tahoma;
     text-decoration: none;
 }
 a[href='.pdf'] { background: red; }

Why isn't the background red?

A: Use the $ after your href. This will make the attribute value to match the end of the string.
a[href$='.pdf'] { /*css*/ }

JSFiddle: http://jsfiddle.net/UG9ud/
E[foo]        an E element with a "foo" attribute (CSS 2)
E[foo="bar"]  an E element whose "foo" attribute value is exactly equal to "bar" (CSS 2)
E[foo~="bar"] an E element whose "foo" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar" (CSS 2)
E[foo^="bar"] an E element whose "foo" attribute value begins exactly with the string "bar" (CSS 3)
E[foo$="bar"] an E element whose "foo" attribute value ends exactly with the string "bar" (CSS 3)
E[foo*="bar"] an E element whose "foo" attribute value contains the substring "bar" (CSS 3)
E[foo|="en"]  an E element whose "foo" attribute has a hyphen-separated list of values beginning (from the left) with "en" (CSS 2)

source: http://www.w3.org/TR/selectors/

A: The accepted answer (using a[href$='.pdf']) assumes that that a link to a pdf will always end with .pdf. That is not necessarily the case, as the link could have a query string or a hash fragment, for example with a UTM tracking code or a page number, in which case those links would not be matched. In fact depending on your application this could be the case for most links.
A PDF File
A PDF File

If you want to ensure your rule is also applied in those cases you could match .pdf anywhere in the attribute using
a[href*='.pdf']

However this will then match some unlikely but unintended things, such as  a subdomain our.pdf.domain.com/a-page. But we can narrow it down further, as we know we would only use it match pdfs that have a query string or hash fragment. If we combine the 3 cases we should match all pdf links.
a[href$='.pdf'], a[href*='.pdf?'], a[href*='.pdf#'] {
    background: red;
}


text:
Q: Link list in Ada I am new to Ada, I am doing linked list program and facing some strange issue
When i am adding node in list i can traverse to last node and print node value,
but when i am traversing to actually print values program exits, below is my code,
with
Ada.Text_IO,
Ada.Integer_Text_IO;
use Ada;

procedure Ada_Link_List is

type Node;
type Node_Ptr is access Node;
type Node is
    record
        Id: Integer;
        Value: Integer;
        Next: Node_Ptr;
    end record;
        procedure Print_List(Firt_Node: in Node_Ptr) is
        Temp_Node : Node_Ptr;
        begin
            if Firt_Node = null then
                Ada.Text_IO.Put("List is Empty");
                Ada.Text_IO.New_Line;
            end if;
            Temp_Node := Firt_Node;
            Ada.Text_IO.Put("List -----");
            while Temp_Node.Next /= null loop
                Ada.Text_IO.Put("while -----");
                Integer_Text_IO.Put(Temp_Node.Id);
                Integer_Text_IO.Put(Temp_Node.Value);
                Temp_Node := Temp_Node.Next;
                Ada.Text_IO.Put("Printing node");
                Ada.Text_IO.New_Line;
            end loop;

        end Print_List;

        procedure Add_Node(Id: Integer; Value: Integer; New_Node: in out Node_Ptr) is
        Temp_Node : Node_Ptr;
        begin
            if New_Node = null then
                New_Node := new Node'(Id,Value,null);
                Ada.Text_IO.Put("Adding Head node");
                Integer_Text_IO.Put(New_Node.Id);
                Ada.Text_IO.New_Line;
            else
                Temp_Node := New_Node;
                while Temp_Node.Next /= null loop
                        Temp_Node := Temp_Node.Next;
                end loop;

                Ada.Text_IO.Put("Adding Next node");
                Ada.Text_IO.New_Line;
                Temp_Node := new Node'(Id,Value,null);
            end if;
        end Add_Node;

    Head_Node : Node_Ptr := null;

    begin
        Add_Node(1,1,Head_Node);
        Add_Node(2,2,Head_Node);
        Add_Node(3,3,Head_Node);
        Add_Node(4,4,Head_Node);
        Add_Node(5,5,Head_Node);
        Print_List(Head_Node);
        Add_Node(6,6,Head_Node);
        Ada.Text_IO.Put("*** Exit ***");

    end Ada_Link_List;

Help me with desired output that i want to print values.
Thanks

A: You are never really adding nodes.
All this does is creating a memory leak:
Temp_Node := new Node'(Id,Value,null);

I think you mean:
Temp_Node.Next := new Node'(Id,Value,null);

A: Easier and maybe more elegant using recursion
with
  Ada.Text_IO,
  Ada.Integer_Text_IO;
use Ada;

procedure Ada_Link_List is

    type Node;
    type Node_Ptr is access Node;
    type Node is record
      Id: Integer;
      Value: Integer;
      Next: Node_Ptr;
    end record;

    procedure Print_List(Node: in Node_Ptr) is
    begin
      if Node /= null then
        Integer_Text_IO.Put(Node.Id);
        Integer_Text_IO.Put(Node.Value);
        Ada.Text_IO.New_Line;
        Print_List(Node.Next);
      end if;
    end Print_List;

    procedure Append_Node(Id: Integer; Value: Integer; New_Node: in out Node_Ptr) is
    begin
      if New_Node = null then
        New_Node := new Node'(Id,Value,null);
        Ada.Text_IO.Put("Adding Head node");
        Ada.Text_IO.New_Line;
      else
        if New_Node.Next /= null then
          Append_Node(Id, Value, New_Node.Next);
        else
          Ada.Text_IO.Put("Adding Next node");
          Ada.Text_IO.New_Line;
          New_Node.Next := new Node'(Id, Value, null);
        end if;
      end if;
    end Append_Node;

    Head : Node_Ptr := null;

begin
    Append_Node(1, 1, Head);
    Append_Node(2, 2, Head);
    Append_Node(3, 3, Head);
    Append_Node(4, 4, Head);
    Append_Node(5, 5, Head);
    Print_List(Head);
    Append_Node(6, 6, Head);
    Print_List(Head);
end Ada_Link_List;


text:
Q: Sourcing BASH_ENV for non-interactive SSH commands I'm hoping to get the $BASH_ENV var to source for non-interactive ssh commands.
I do see my BASH_ENV:
ssh server.example.com env | grep BASH
BASH_ENV=/tmp/set_bash_env_profile

If I do simple ssh login, and env | wc -l I get 85, thanks to $BASH_ENV env var, but if:
ssh server.example.com env | wc -l
17

I get just 17...
I tried ForceCommand in the sshd_config as described here but in my case, the SSH_ORIGINAL_COMMAND is not being set.

A: Presumably you're setting BASH_ENV in your .bashrc. Bash loads .bashrc when it's interactive and not a login shell, or when it's a login shell that's invoked by rshd or (in many distributions, but it's a compile-time option) sshd. That's too late for this instance of bash. Put the commands directly in ~/.bashrc.
# .bashrc
if [[ $- = *i* ]]; then
  # Commands for interactive use: prompt, aliases, key bindings, etc.
  # Don't set environment variables here, that goes in .profile.
else
  # Commands executed only on remote logins.
  # You can set environment variables here. Do not output anything.
fi

If you only need to set environment variables, you can use ~/.pam_environment instead, which is used for any kind of login. See What's the best distro/shell-agnostic way to set environment variables?
For other ways to execute commands when logging in non-interactively over SSH, see sh startup files over ssh


text:
Q: TSQL - What Did I Update Here? update outbound.notification
set statuscode = 1
select * from outbound.Notification
where statuscode = 4 --not in (3,6)
and convert(varchar,createdtimestamp,102) > '2015.01.10'
and OutboundID <> 647

Executed the above query. Meant to have the select commented out, so that I could alternate between selecting queries in that status and updating them. What did I do to what rows?

A: You updated all rows of outbound.Notification. Your query is generally two separate queries.
First, this updates all rows of outbound.Notification:
update outbound.notification set statuscode = 1

Second, this is just a SELECT statement.
select * from outbound.Notification
where statuscode = 4 --not in (3,6)
and convert(varchar,createdtimestamp,102) > '2015.01.10'
and OutboundID <> 647


text:
Q: How to remove dash (-) and \n at the same time or some solution to this text cleaning I have been trying to remove dash(-) and \n for quite sometimes and it is not working.
I have tried using this code to remove -
gsub(" - ", " ", df1$text)

I have also tried using this code to remove \n
gsub("[\n]", " ", df1$text)

However, when I remove \n it becomes "abc-" when I remove dash(-), it becomes "abc\n". Is just a loop. All this result is in the console
When I try using \n to remove. In the console result
Df1

Id  text
1   I have learnt abc-d in school.
2   I want app-le.
3   Going to sc-hool is fun.

When I try using dash(-) to remove. In console result
Df1

Id  text
1   I have learnt abc\nd in school.
2   I want app\nle.
3   Going to sc\nhool is fun.

This is just loop and loop. I tried \n remove then dash(-) remove and all over again.
This is the data in dataframe. (It always stays the same)
Id  text
1   I have learnt abc- d in school.
2   I want app- le.
3   Going to sc- hool is fun

For the dataframe right after the dash(-) there is a space.
The data I am using is news article, I have copyed and pasted it in a excel file. But I try using r to clean it.
Could someone help me out with this. Thanks!
I don't mind sharing the data with you privately, but just do not disclose it. Because it is my school project.

A: gsub(" - ", " ", df2$text) is looking for a space, then a dash, then a space. The examples you give like app- le don't have a space before the dash, so they won't match. If you want to match a space next to a dash only if it's there, us ? to quantify the space:
df2 = read.table(text = 'Id|text
1|I have learnt abc- d in school.
2|I want app- le.
3|Going to sc- hool is fun', sep = "|", header = TRUE)

gsub(" ?- ?", " ", df2$text)
# [1] "I have learnt abc d in school." "I want app le."                 "Going to sc hool is fun"

## Maybe you want to replace it with nothing, not with a space?
gsub(" ?- ?", "", df2$text)
# [1] "I have learnt abcd in school." "I want apple."                 "Going to school is fun"

Since your example doesn't include any line breaks, I can't really tell what the issue is.


text:
Q: textIsSelectable property doesn't work with a Toolbar I have a normal TextView with the android:textIsSelectable property on true. This was working perfectly fine, even while I have the TextView inside of a ListView. But now I decided to use the new Toolbar as my ActionBar and it doesn't work anymore. I don't get a crash or anything, I only see the screen flickering on Lollipop devices when I longPress the TextView. On pre-Lollypop devices I see nothing happening.
Does anybody else have the same issue and is there a fix for it?

A: If you app theme extends one of .NoActionBar themes, you need to enable windowActionModeOverlay, to fix this issue.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="windowActionModeOverlay">true</item>
</style>

A: In your layout.xml file: Replace fill_parent with wrap_contentfor this element.

A: Try this, it worked for me :
In your toolbar layout, add the textview by yourself, an example :
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar
           xmlns:android="http://schemas.android.com/apk/res/android"
           android:id="@+id/toolbar"
           android:minHeight="?attr/actionBarSize"
           android:layout_height="?attr/actionBarSize"
           android:layout_width="match_parent">

           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:gravity="center"
               android:text = "Hi, there"
               android:textColor="#ff0000"
               android:textIsSelectable="true"/>

    </android.support.v7.widget.Toolbar>

I tested this on android v4.0.4 ICS, its working fine for me, I am able to select text on long press.
Hope this helps...


text:
Q: How to get element based on page url I have navigation in form of ul and li. If url is http://mydomain.com/somewiredpath/page21.htm?p=1 how can i get li element with this url? I don't care about rest of the url, need just li with "page21.htm".

            <imgsrc="...">

            <imgsrc="...">

<imgsrc="...">

<imgsrc="...">

PS: i'm going to add some styles to matched and parent elements, so if there is already some jquery function/plugin for that, it would be great to know.

A: function findLi(pagename) {
    return $('#navig a[href*="' + pagename + '"]').closest("li");
}


text:
Q: Why are Action and Predicate used or defined as delegates? Can somebody explain what is the exact reason behind using Action<T> and Predicate<T> as delegates in C#

A: What else would they be? Delegates are the most flexible and closest match to what Action<T>, Predicate<T> and Func<T> are modlling - an invocation list with specified parameter types (aka delegates).

A: The best way to explain why the idiom for performing action and predicate operations using the Action<T> and Predicate<T> delegates was chosen is to first consider the alternative. How could you accomplish the same thing without delegates? The next best thing would be to have interfaces IAction and IPredicate and force developers to declare a class and implement the appropriate interface for each different type of operation needed. But, the problem with that approach is that it requires more effort, more class proliferation, and less maintainable code. The delegate approach is a lot more convenient because you can write the logic inline with where it will be used using anonymous methods or lambda expressions.

A: Because they are delegates.

A: Are you asking why they exist, or why they're defined as delegates?
As to why they exist, perhaps the best reason is convenience.  If you want a delegate that returns no value and takes a single parameter of some type, they you could define it yourself:
public delegate void MyDelegate(int size);

And then later create one:
MyDelegate proc = new MyDelegate((s) => { // do stuff here });

And, of course, you'd have to do that for every different type you want to have such a method.
Or, you can just use Action<T>:
Action<int> proc = new Action<int>((s) => { /* do stuff here */ });

Of course, you can shorten that to:
Action<int> proc = (s) => { /* do stuff here */ });

As to "why are they delegates?"  Because that's how function references are manipulated in .NET:  we use delegates.  Note the similarities in the examples above.  That is, MyDelegate is conceptually the same thing as an Action<int>.  They're not exactly the same thing, since they have different types, but you could easily replace every instance of that MyDelegate in a program with Action<int>, and the program would work.

A: You are looking at the problem from the wrong point of view.
The question should not be "Why are Action<>, Func<> & Predicate<> delegates?"  (The answer to that is "because they need to be")
The real question is, "Why do we have specific named objects, to handle simple delegate tasks?  Why use Action<> in a place where a ordinary delegate would work?"
The answer is that those particular delegates are used a lot on the CLR itself, and since that they are used in CLR methods where the end developers will have to defined the method being called, the declaration for the delegate would have to be public.  So, Microsoft could have defined thousands of delegates, each used by just one CLR method, or define a simple way to specific what type of delegate is needed.


text:
Q: CameraX camera-core:1.0.0-beta01 crashed at Camera2Config.java defaultConfig() Recently, I tried CameraX camera-core:1.0.0-beta01.
Gradle:
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.example.dryeyescreener"
        minSdkVersion 27
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    def camerax_version = "1.0.0-beta01"
    implementation "androidx.camera:camera-core:1.0.0-beta01"
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    // If you want to use the CameraX View class
    implementation "androidx.camera:camera-view:1.0.0-alpha08"
    // If you want to use the CameraX Extensions library
    implementation "androidx.camera:camera-extensions:1.0.0-alpha08"
    // If you want to use the CameraX Lifecycle library
    implementation "androidx.camera:camera-lifecycle:${camerax_version}"

Started from this sentence:
   cameraProviderFuture = ProcessCameraProvider.getInstance(this);

Then, when I debugged to Camera2Config.java
    public CameraXConfig getCameraXConfig() {
        return defaultConfig();
    }

It crashed at:
    public static CameraXConfig defaultConfig() {
    // Create the camera factory for creating Camera2 camera objects
    CameraFactory.Provider cameraFactoryProvider = Camera2CameraFactory::new;

I searched there was an application example by using Kotlin and camera-core beta version without any issue. But the codes, I used the Java version, definitely crashed.
Has anyone implemented the CameraX Java version successfully? Or did I miss something?
Thanks,
Di
Please find the following from Logcat:
java.lang.BootstrapMethodError: Exception from call site #0 bootstrap method
        at androidx.camera.camera2.Camera2Config.defaultConfig(Camera2Config.java:52)
        at androidx.camera.camera2.Camera2Config$DefaultProvider.getCameraXConfig(Camera2Config.java:88)
        at androidx.camera.core.CameraX.getOrCreateInstance(CameraX.java:823)
        at androidx.camera.lifecycle.ProcessCameraProvider.getInstance(ProcessCameraProvider.java:103)
        at com.example.screener.MainActivity.onCreate(MainActivity.java:144)
        at android.app.Activity.performCreate(Activity.java:7326)
        at android.app.Activity.performCreate(Activity.java:7317)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3072)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3235)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6986)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
     Caused by: java.lang.ClassCastException: Bootstrap method returned null
        at androidx.camera.camera2.Camera2Config.defaultConfig(Camera2Config.java:52)
        at androidx.camera.camera2.Camera2Config$DefaultProvider.getCameraXConfig(Camera2Config.java:88)
        at androidx.camera.core.CameraX.getOrCreateInstance(CameraX.java:823)
        at androidx.camera.lifecycle.ProcessCameraProvider.getInstance(ProcessCameraProvider.java:103)
        at com.example.screener.MainActivity.onCreate(MainActivity.java:144)
        at android.app.Activity.performCreate(Activity.java:7326)
        at android.app.Activity.performCreate(Activity.java:7317)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3072)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3235)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6986)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

A: Seems the crashing issue from requesting Java 8.
Added the following in build.gradle, then the issue was solved.
android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}


text:
Q: Two different nodes giving same call to same MYSQL Database giving different responses I have my first NodeJS API running.  I have two API's now running (TEST and PROD).
These files are DIRECT copies of each other and running via App Manager in Cpanel.
Weirdly, one of the calls (Prod) is giving incorrect information on some of the calls... like it is giving 'old' data.
eg. a record was changed for an 'order' and a locationID was added to the database.
I have checked the database and it was added.
The test call:
https://www.myAPI.com.au/TEST/orders/myOrders/1709

Response:
{
    "Result": true,
    "order": {
        "orderID": 1709,
        "chemOrderID": 1243,
        "firstName": "test",
        "lastName": "test",
        "phone": "04123456",
        "email": null,
        "prefContact": 1,
        "itemName": "KN95 Box Of 30 ",
        "itemQuantity": 1,
        "plu": null,
        "modelNumber": null,
        "colour": null,
        "itemDetails": null,
        "supplier": "avacare",
        "itemSize": null,
        "amountPaid": 0,
        "receiptNumber": "00",
        "quotedPrice": 69.99,
        "orderComments": null,
        "reorder": 0,
        "isNDIS": 0,
        "isNDISPaid": 0,
        "onHold": 0,
        "requestedBy": 35,
        "orderedBy": 35,
        "receivedBy": 35,
        "finalisedBy": 0,
        "overdueBy": 0,
        "NDISBy": 0,
        "deletedBy": 0,
        "requestedByName": "Jac",
        "orderedByName": "Jac",
        "receivedByName": "Jac",
        "finalisedByName": null,
        "overdueByName": null,
        "deletedByName": null,
        "requestedDateShort": "18 Jan",
        "orderedDateShort": "18 Jan",
        "receivedDateShort": "18 Jan",
        "finalisedDateShort": null,
        "overdueDateShort": null,
        "deletedDateShort": null,
        "requestedDate": "2022-01-18T09:40:21",
        "orderedDate": "2022-01-18T09:50:33",
        "receivedDate": "2022-01-18T12:21:41",
        "finalisedDate": null,
        "overdueDate": null,
        "deletedDate": null,
        "etaMaxDateShort": "Thu, 20 Jan",
        "etaCode": 2,
        "locationID": 199,
        "supplierRef": null,
        "locationOther": null,
        "categoryID": 5,
        "categoryName": "GENERAL SHOP"
    }
}

Now this is correct.  The locationID is updated, the receivedDate, recivedByName and receivedBy are all correct and updated.
The same call on copied API: (same mysql user login. literally a duplicate of the api)
Call:
https://www.myAPI.com.au/prod/orders/myOrders/1709

Response:
{
    "Result": true,
    "order": {
        "orderID": 1709,
        "chemOrderID": 1243,
        "firstName": "test",
        "lastName": "test",
        "phone": "04123456",
        "email": null,
        "prefContact": 1,
        "itemName": "KN95 Box Of 30 ",
        "itemQuantity": 1,
        "plu": null,
        "modelNumber": null,
        "colour": null,
        "itemDetails": null,
        "supplier": "avacare",
        "itemSize": null,
        "amountPaid": 0,
        "receiptNumber": "00",
        "quotedPrice": 69.99,
        "orderComments": null,
        "reorder": 0,
        "isNDIS": 0,
        "isNDISPaid": 0,
        "onHold": 0,
        "requestedBy": 35,
        "orderedBy": 35,
        "receivedBy": 0,
        "finalisedBy": 0,
        "overdueBy": 0,
        "NDISBy": 0,
        "deletedBy": 0,
        "requestedByName": "Jac",
        "orderedByName": "Jac",
        "receivedByName": null,
        "finalisedByName": null,
        "overdueByName": null,
        "deletedByName": null,
        "requestedDateShort": "18 Jan",
        "orderedDateShort": "18 Jan",
        "receivedDateShort": null,
        "finalisedDateShort": null,
        "overdueDateShort": null,
        "deletedDateShort": null,
        "requestedDate": "2022-01-18T09:40:21",
        "orderedDate": "2022-01-18T09:50:33",
        "receivedDate": null,
        "finalisedDate": null,
        "overdueDate": null,
        "deletedDate": null,
        "etaMaxDateShort": "Thu, 20 Jan",
        "etaCode": 2,
        "locationID": null,
        "supplierRef": null,
        "locationOther": null,
        "categoryID": 5,
        "categoryName": "GENERAL SHOP"
    }
}

As can be seen, the aforementioned fields aren't filled!?
It's like the call is getting an old version of the database or something...
I can't understand this at all.
There is only one DB, i haven't created a test db, in reality this whole thing is testing (even the prod version), as I am learning and trying to understand how I will go about everything once it is actually live.


text:
Q: Call web server using django I would like to know how could I call a web server using django. Oaths server there is a application called appExaple:
the web server is: example.si.eus
And the application I want to use on the django framework is: appExample
I'm new at django, so please, be patient with me.

A: Django will handle incoming web requests - i.e. other people calling your server.
If you want to make calls to other server then the Python Requests framework is very good. It is completely independent from Django, but will work from within your Django code.
http://docs.python-requests.org/en/master/


text:
Q: Calculate row value referring previous rows in panda dataframe I'm trying to figure out a way to compare values from different rows in a dataframe to calculate a new column.
I've found these ways:

*

*Iterate over rows (I'm looking for a vectorized solution):

for index, row in df.iterrows():
   ....

*

*Merge the same dataframe multiple times using a shift over index, something like this:

d1 = data.shift()
data.merge(d1[["value col"]], how="inner", left_index=True, right_index=True)
Is there a way to access to the current dataframe from an apply method:
dataframe.apply(myfunction(row),axis=1)

def my_function(row, current_dataframe)
    index = row.name
    row_to_compare = current_dataframe.iloc[index-delta]
    row["new column"] = calc(row["value], row_to_compare["value"])
    return row

Passing it as argument doesn't seem to work:
data.apply(date_diff,axis=1,args=(data))
or
data.apply(lambda row,df: date_diff(row, df),axis=1,args=(data))

Keeps saying:
> ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Is there a way to make it work?
Thank you.

A: What do you want to calculate?
If it is simple enough you can vectorize completely. Note you can just add it as another column rather than having a separate merge step.
df["same"] = df[col] == df[col2].shift()

If it is a bit more complex then can you split it into multiple steps like the above? This will still be fast.
If you need multiple columns and rows then you you will have to use apply to process row by row or column by column but this is quite slow. Worst answer is to iterate! You should never need to do this.


text:
Q: UseCallback still triggering infinitely, What should I do? My code is:
const Chat = () => {
    const { type,title,roomId } = useParams();
    const [roomDetails, setRoomDetails] = useState(null);
    const [roomMessages, setRoomMessages] = useState([]);

    const getConversation = useCallback(() => {
        var parameters = {type:type,
                        title: title,
                        id : roomId
                    };
        const params = new URLSearchParams(parameters);
        console.log(title);
        axios.get(`/get/conversation?${params}`).then((res) =>{
            setRoomDetails(title)
            setRoomMessages(res.data)
        })
    });

    useEffect(() => {
        console.log("Hey")

        getConversation()

        //realtime processing
        const channel = pusher.subscribe('conversation');
        channel.bind('newMessage', function(data) {
            getConversation()
        });
    },[getConversation])

I don't know why but useEffect is triggering infinitely.
The logic in this is basically I have a URL: <Route path="/room/:type/:title/:roomId">
Which on rendering invokes the chat component option. Now of all these my params type and title will only change. But in some cases type will remain same, only title will change.
Even after adding them to callback function, I don't know why its rendering infinitely?
if it's easy to understand the relation between type and title is:
{
type :
  [{
    title:{},
    title{},
    title{}
  }]
}


text:
Q: Converting the Xml tags In my xml some of the xml element are empty for example:

So I want to modify the elements that are of the type shown above to convert to  type element so how can we do it in C# and update in the file.

A: Here's what I came up with:
private static void FormatEmptyNodes(XmlNode rootNode)
{
    foreach (XmlNode childNode in rootNode.ChildNodes)
    {
        FormatEmptyNodes(childNode);

        if(childNode is XmlElement)
        {
            XmlElement element = (XmlElement) childNode;
            if (string.IsNullOrEmpty(element.InnerText)) element.IsEmpty = true;
        }
    }
}

Then use it like this:
var doc = new XmlDocument();
doc.Load(inputFilePath);
FormatEmptyNodes(doc);
doc.Save(outputFilePath);

A: While you shouldn't use Regex to parse HTML (or XHTML, XML...), in your scenario you could use it to clean up your incoming strings using the pattern <([A-Za-z0-9_.]+)></\\1> and a replacement of <$1/>:
System.Text.RegularExpressions.Regex.Replace(
  "foo  bar not empty <tag></tag>",
  "<([A-Za-z0-9_.]+)></\\1>",
  "<$1/>")

This will return:
foo  bar not empty <tag/>

The regex can be understood as illustrated below (image generated by Regexper):