text:
Q: How to find the probability of winning this game? Here's a very simple "game":

*

*Standard 52 card deck, shuffled.

*You deal cards face up, one at a time, while counting up towards 13, starting back at 1 once you reach 13.

*If the number you count out is the number of the card, you lose, reshuffle, and start over.
If you get through the whole deck, counting to 13 four times without matching up your counted number with the flipped card number, you  win.

I programmed the game and ran it a few hundred million times.  It seems like the probability of winning is about 1.65% (unless my game logic is flawed!).
How would I manually calculate the probability of winning?

A: This is tricky to solve because the events "the number you count out at step $i$ is the number on the card" are not independent.
Wikipedia, in its article on derangements, cites an interesting formula for the solution.  It yields the answer

$$\frac{4610507544750288132457667562311567997623087869}{284025438982318025793544200005777916187500000000} \approx 0.016\,232\,727\,467\,194\,\ldots$$

A word is a sequence of letters from an alphabet. A derangement of a word is a permutation of its letters that differs from the original word in every place.  The question concerns a 52-character word constructed from an alphabet of 13 distinct "letters" (the cards).  The shuffled deck is the permutation and the game is won only when the permutation is a derangement.
The formula counts the number of derangements of a word having $r$ distinct letters whose counts are $n_1, n_2, \ldots, n_r.$  Let's call this $D(n_1,\ldots, n_r).$  The formula is

$$D(n_1,\ldots,n_r) = \pm \int_0^\infty \mathcal{L}_{n_1}(x)\mathcal{L}_{n_2}(x)\cdots\mathcal{L}_{n_r}(x)\,e^{-x}\mathrm{d}x$$

where the $\mathcal{L}_{n_i}$ are the Laguerre polynomials.  In the question $r=13$ and all the $n_i=4,$ where
$$\mathcal{L}_4(x) = (x^4 - 16x^3 + 72x^2 - 96 x + 24)/4!.$$
Thus, "all" we need to compute is
$$D(4,4,\ldots, 4) = \frac{\pm 1}{(4!)^{13}}\int_0^\infty (x^4 - 16x^3 + 72x^2 - 96 x + 24)^{13} e^{-x}\mathrm{d}x.$$
That's actually straightforward, because after expanding the power in the integrand a polynomial $$\eqalign{p(x) &= x^{52} + p_{51}x^{51} + \cdots + p_1 x + p_0\\&= x^{52} - 208 x^{51} + 20904 x^{50} - 1352416 x^{49} + \cdots + 876488338465357824}$$ appears and the integral becomes a linear combination of Gamma functions (factorials, essentially) with value
$$D(4,4,\ldots, 4) = \frac{\pm1}{(4!)^{13}}(52! + p_{51}51! + \cdots + p_1 1! + p_0 0!).$$
It's easiest to use a computer to find the coefficients $p_i.$  You need to perform the addition to high precision due to the cancellation of large values that occurs (notice the alternating signs of the coefficients).
To obtain a probability, invoke the implicit assumption that all permutations are equally likely (a fair shuffle).  The number of permutations of the word is

$$P(n_1,n_2,\ldots, n_r) = \binom{n_1+n_2+\cdots+n_r}{n_1,n_2,\ldots,n_r}=\frac{(n_1+n_2+\cdots+n_r)!}{n_1!\,n_2!\,\cdots\, n_r!}.$$

In the question this simplifies to
$$P(4,4,\ldots,4) = \frac{52!}{(4!)^{13}}.$$
The desired probability is obtained by dividing the number of derangements by the number of (equally likely) permutations,

$$\frac{D(4,4,\ldots,4)}{P(4,4,\ldots,4)} = \left|\frac{52! + p_{51}51! + \cdots + p_1 1! + p_0 0!}{52!}\right|.$$

I computed this with Wolfram Alpha.

A: You can do this with a binomial distribution. I used R.
Every time you turn over a card, you have a 1 in 13 chance of it matching the number you count out. You need to turn over 52 cards in a row, without a match. (You can think of it as four sets of 13, that doesn't change it).
In R (or whatever you use probably has a similar function).
> pbinom(q = 0, size = 52, prob = 1/13)
[1] 0.01557294

Equivalently, you need an event that has a 12/13 chance of happening (no match), but you need it to happen 52 times in a row.
> (12/13)^52
[1] 0.01557294

Very close, but not quite the same as you got in your simulation.
(Hmmm... my simulation gives a slightly higher number, not as high as yours. I'm not sure why.
> library(dplyr)
> CountOutCards <- function (x) {
+   sum(rep(1:13, 4) == sample(rep(1:13, 4), 52, FALSE))
+ }
>
> x <- (lapply(1:1e6, CountOutCards) ) %>% unlist
> mean(x == 0)
[1] 0.016093

)


text:
Q: Can't map between Jira project and FishEye i have installed Jira server. i have also installed FishEye
i have configured FishEye to see Jira installation and configured Jira to see FishEye.
from FishEye i can see all my Git repository. problem is, that i can't access code from Jira.
when looking at the FishEye configuration i see that the mapping section is empty... and i can't find a way to map it.
in the Associate Project with Repository Path i see that FishEye server is configured but i can't see any repository from the drop down list.
what did i do wrong? thanks!

A: Try to restart both Jira and Fisheye.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to reinstall On premises data gateway for Azure, since I am trying to resolve the No instance issue
It looks like you are trying to reinstall. Please uninstall the current version first.

No matter what I do:

*

*deleted the On-premises data gateway folder from C:/ProgramFiles/On Premise Data Gateway.

*Removed the registry entry to delete the service (though it still won't go even after restarting the system)

*Checked the logs at
C:\Users\PBIEgwService\AppData\Local\Microsoft\On-premises data gateway

I am unable to be successful with the reinstall. Can someone please help me with uninstalling the On premise gateway?

A: I don't have any experience with this program, but installed programs on Windows are also saved in the Package Cache (C:\ProgramData\Package Cache\{GUID}), and if there is a corresponding msi Windows thinks the program is installed.
Removing this folder (make sure you delete the correct one!) will enable windows to ask you if the entry should be removed from installed programs once you click uninstall again.
After this you should be able to install it again.


text:
Q: How to propagate a MouseEvent such as onEntered/onExited? According to the Qt documentation on MouseArea, only a 'composed' event such as clicked can be propagated to an item that is lower in z-order.
How can I replicate the same behaviour for a simple mouse event such as onEntered or onExited?
e.g. I have two rectangles, both with a MouseArea, where the upper rectangle covers the bottom right corner of the lower rectangle. If I click anywhere on either rectangle, including the overlapped region, both rectangles' MouseAreas will receive the onClicked signal because I've used propagateComposedEvents: true and set mouse.accepted = false in the handler of upperRect. However onEntered only works on the non overlapped portion of lowerRect.
Rectangle {
    id: lowerRect
    x: 0
    y: 0
    width: 100
    height: 100
    color: "blue"

    MouseArea {
        anchors.fill: parent
        onClicked: console.log("lowerRect was clicked")
        hoverEnabled: true
        onEntered: console.log("lowerRect was entered")
    }
}

Rectangle {
    id: upperRect
    x: 50
    y: 50
    width: 50
    height: 50
    color: "green"
    opacity: 0.8

    MouseArea {
        anchors.fill: parent
        propagateComposedEvents: true
        onClicked: {
            mouse.accepted = false
            console.log("upperRect was clicked")
        }
        hoverEnabled: true
        onEntered: console.log("upperRect was entered")
    }
}

A: You can manually call signals. Something like myMouseArea.entered() or myMouseArea.exited() (where myMouseArea is the id or reference to a MouseArea object) will work.


text:
Q: Why using std::sort() ) gives me garbage values? I was trying to solve a problem where I had to sort so I used the standard library std::sort function but I get a wrong output in the 2nd test case:
#include <bits/stdc++.h>

using namespace std;

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,i;
        cin>>n;
        int arr[n-1];

        for(i=1;i<=n-1;i++)
            cin>>arr[i];

        int size=sizeof(arr)/sizeof(arr[1]);
        sort(arr,arr+size);

        for(i=1;i<=n-1;i++)
            cout<<arr[i]<<" ";

        cout<<endl;
    }
    return 0;
}

I/P:
2
5
1 2 5 4
10
1 2 3 4 5 6 7 8 10

Expected O/P:
1 2 4 5
1 2 3 4 5 6 7 8 10

Actual O/P:
1 2 4 5
2 3 4 5 6 7 8 2013562 10

A: First of all, int arr[n-1]; is a variable length array. That's not actually part of C++, even though some compilers will tolerate it nevertheless. In most cases you can just use std::vector<int>(n-1); instead.
But look at this loop:
for(i=1;i<=n-1;i++)
    cin>>arr[i];

You're starting at 1 and got all the way up to n-1, however your array goes from arr[0] to arr[n-2]. So you got undefined behavior because you're writing one past the size of the array, and you also don't write to the first position (leading to more undefined behavior when you try to sort with this uninitialized value still present).
Instead, the loop should be for(i=0;i<n-1;i++) The same applies to where you're printing it. You can then sort the vector this way:
sort(arr.begin(), arr.end());

Also note that by doing n-1 you're always reading in and handling one less value that the user inputs, I'm not sure if that's your intention. If you want that, you could also just decrease n by one after reading it in instead of writing n-1 in multiple places.


text:
Q: Start Kivy app horizontally on android phone I'm new to Kivy and am trying to make a game that will load and play horizontally on an android phone no matter which direction the phone is oriented. Is there an easy way to do that? I looked through the Kivy documentation as well as some other sites & didn't find much. Thanks in advance!

A: You can set the landscape orientation in the buildozer.spec file.
# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all) orientation = landscape


text:
Q: How do you disconnect a Bluetooth device in a Windows driver so that Windows doesn't lose it's pairing? I'm currently working on a Windows driver for Nintendo Wii remotes and I want the PC to be able to disconnect the device without removing it's pairing. I know this behavior exists since my mouse is capable of doing it. What I want it to do is, when looking in Devices and Printers, the device should show as grayed out when off/out of range. Unfortunately I can't find any documentation on how to do this, either because I don't know what this exact behavior is called or because it's never clearly stated in the documentation. Does anyone have any idea how this is implemented?
EDIT: Realized this was probably not a Bluetooth specific feature since printers also make use of this and removed the Bluetooth tag.


text:
Q: Recommended way to interact with MySQL in Play framework (scala)? I'm a newbie, just started using Play framework (2.8.x). Is there any recommended way to interact with MySQL in Play framework using ORM framework (slick or something else ?? after I searched around)? As I usually interact with MySQL in Flask using SQLAlchemy under Python, I'd wish to do something likewise under scala.

A: There is no one recommended way of doing database calls on Scala.
When it comes to Play Framework, then quite often it was used together with Slick because of who developed them. But Slick is Functional-Relational-Mapping, not Object-Relational-Mapping.
If you want to use ORM, you would have to use Hibernate as many people came to conclusion that ORMs do more harm than good in a long run, so nobody develops any ORM solution. (Not intending to argue about it here, just explaining why you won't find native ORM Scala solution that is maintained today).
When it comes to where community leans, you should consider some "safe SQL builder" like Doobie, Quill or jOOQ.
But as I said, nobody will ever tell you that there is some one solution that everybody would pick no matter what.


text:
Q: Leap year checker failing unknown test cases I'm using Sololearn to learn Python and I got stuck with that exercise.

Task conditions: You need to make a program to take a year as input and output "Leap year" if it's a leap year, and "Not a leap year", if it's not.

To check whether a year is a leap year or not, you need to check the following:

*

*If the year is evenly divisible by 4, go to step 2. Otherwise, the year is NOT a leap year.

*If the year is evenly divisible by 100, go to step 3. Otherwise, the year is a leap year.

*If the year is evenly divisible by 400, the year is a leap year. Otherwise, it is not a leap year.

My code:

Sololearn is hiding some test cases to avoid cheating. There are 7 test cases and 2 of them is failed.
What am I missing?

A: Well you should rethink your code: if we input the year 4 (which is a leap year) what will the output of your code be?
Here is the rule to know if a year is a leap year:
To be a leap year, the year number must be divisible by four – except for end-of-century years, which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not. 2020, 2024 and 2028 are all leap years.

A: Look at your step 2 in your rules and how you have implemented that in your code.
According to your rules 2024 is a leap year - but your code says it isn't.
I wont give you the corrected code, because this is almost certainly homework, but you haven't implemented step 2 correctly.


text:
Q: nginx - bind() to 0.0.0.0:80 failed (98: Address already in use) I've got a reverse proxy with 5 server configs set up, however since the start it's always been complaining about not being able to listen on the ports I specified so the server has been unable to start.
I've tried a few things:

*

*Split config into multiple files inside sites-available and creating symlinks to sites-enabled

*Delete the listen property and allowing it to fall back to defaults

*Changing the ports to ipv6only=on - this caused an error

*Changing the ports to [::]:80

*Changing the ports so that there are no conflicts, ie, 80, 81, 82, etc.

Using netstat I can see that nothing is running on the ports I need, and when I run nginx -t I get a successful output saying syntax is ok and nginx.conf test is successful.
This is my nginx output:
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:81 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:82 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:83 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:84 failed (98: Address already in use)

Does anybody know why this is caused? Thanks in advance
Edit: lsof -Pni | grep LISTEN output:
sshd      1288     root    3u  IPv4  15712      0t0  TCP *:22 (LISTEN)
sshd      1288     root    4u  IPv6  15714      0t0  TCP *:22 (LISTEN)
nginx    14025     root    6u  IPv6 852470      0t0  TCP *:80 (LISTEN)
nginx    14025     root    7u  IPv6 852471      0t0  TCP *:443 (LISTEN)
nginx    14026 www-data    6u  IPv6 852470      0t0  TCP *:80 (LISTEN)
nginx    14026 www-data    7u  IPv6 852471      0t0  TCP *:443 (LISTEN)
dnsmasq  23894  dnsmasq    5u  IPv4 650875      0t0  TCP *:53 (LISTEN)
dnsmasq  23894  dnsmasq    7u  IPv6 650877      0t0  TCP *:53 (LISTEN)

Here's my server configs:
server {
        listen 80;
        server_name hac-staging-proxy.redant.cloud;

        location / {
                proxy_pass http://195.219.8.212/;
                proxy_set_header Host www.uat2prd.halfordsautocentres.com;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_buffering off;
        }
}

server {
        listen 81;
        server_name halfords-c1-staging-proxy.redant.cloud;

        location / {
                proxy_pass http://195.219.8.206/;
                proxy_set_header Host www.c1.uat2prd.halfordsautocentres.com;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_buffering off;
        }

}

server {
        listen 82;
        server_name halfords-c2-staging-proxy.redant.cloud;

        location / {
                proxy_pass http://195.219.8.206/;
                proxy_set_header Host www.c2.uat2prd.halfordsautocentres.com;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_buffering off;
        }

}

server {
        listen 83;
        server_name halfords-staging-proxy.redant.cloud;

        proxy_redirect http://www.uat2prd.halfords.com http://halfords-staging-proxy.redant.cloud;
        proxy_redirect https://www.uat2prd.halfords.com https://halfords-staging-proxy.redant.cloud;

        location / {
                add_header Set-Cookie Experiment=FH;
                resolver 127.0.0.1;
                proxy_pass http://www.uat2prd.halfords.com;
                # sub_filter_types *;
                sub_filter 'www.uat2prd.halfords.com' 'halfords-staging-proxy.redant.cloud';
                sub_filter 'www.c1.uat2prd.halfords.com' 'halfords-c1-staging-proxy.redant.cloud';
                sub_filter 'www.c2.uat2prd.halfords.com' 'halfords-c2-staging-proxy.redant.cloud';
                sub_filter_once off;
                proxy_set_header Set-Cookie Experiment=FH;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_buffering off;
        }
}

server {
        listen 84;
        server_name halfords-staging-proxy.redant.cloud2;

        proxy_redirect https://www.uat2prd.halfords.com https://halfords-staging-proxy.redant.cloud;
        proxy_redirect http://www.uat2prd.halfords.com http://halfords-staging-proxy.redant.cloud;

        ssl_certificate           /etc/nginx/domain.cert;
        ssl_certificate_key       /etc/nginx/domain.key;
        ssl_dhparam               /etc/ssl/certs/dhparam.pem;

        ssl on;
        ssl_session_cache  builtin:1000  shared:SSL:10m;
        ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers "INTENTIONALLY REMOVED"
        ssl_prefer_server_ciphers on;

        location / {
                add_header Set-Cookie Experiment=FH;
                resolver 127.0.0.1;
                proxy_pass https://www.uat2prd.halfords.com;
                # proxy_ssl_session_reuse off;
                # sub_filter_types *;
                sub_filter 'www.uat2prd.halfords.com' 'halfords-staging-proxy.redant.cloud';
                sub_filter 'www.c1.uat2prd.halfords.com' 'halfords-c1-staging-proxy.redant.cloud';
                sub_filter 'www.c2.uat2prd.halfords.com' 'halfords-c2-staging-proxy.redant.cloud';
                sub_filter_once off;
                proxy_set_header Set-Cookie Experiment=FH;
                proxy_set_header Host www.uat2prd.halfords.com;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_buffering off;
        }
}

A: Don't have 'listen *:80' at the same time as 'listen [::]:80' (and similarly for port 443).
The reason being on a dual-stack IPv4/IPv6 host, if you listen on an IPv6 TCP port X, and there is nothing listening on IPv4 TCP port X, you will get both. If you see a connection come in as ::ffff:1.2.3.4 (where 1.2.3.4 is an IPv4 address), then this is what is happening. This is called an IPv4-mapped IPv6 addresses.
This, when nginx then goes to listen on the IPv4 port 80 (0.0.0.0:80), it will run into the fact that it also has effectively done so (via [::]:80).
There are plenty of implementation-specifics around this behaviour, but unless you are versed in network programming, I won't mention them here.
Hope that helps,
Cameron


text:
Q: Compile boost with std=c++11 or other standards such ash c++14 I am using a Visual Studio GDB project and I have a problem including the the boost linux libraries in the linker inputs.
This are the error received:

undefined reference to `std::__cxx11::basic_string, std::allocator >::_M_create(unsigned
  long&, unsigned long)'

It seems that the library is not recognized as being compiled with -std=c++11
The commands used to compile the library are:
sudo ./boostrap.sh
sudo ./b2 toolset=gcc cxxflags="-std=c++11"
make
sudo make install

The compilation worked well.
I am using the boost 1.62.0 version and the gcc-5.4.0 version to compile the library. The library included in visual studio project as linker input is libboost_system.a
I think the error from visual studio is related to c++11 compilation.
Could you please tell me if the compilation procedure is ok?
If not, please tell which is the right procedure to compile the library for c++11?
Does the error mean something else?

A: Your steps to compile Boost with c++11 enabled are correct (although you don't need all the sudo). The problem then must be how you compile your own program: it should use exactly matching flags. Check that your program isn't e.g. using the compiler default, which could well be c++14 or c++03.


text:
Q: How to permanently switch of KDE Power Management warning about battery recall I have Kubuntu 12.04 installed. Each time I boot I receive a notification that the battery I am using has been recalled. This is not actually the case, as the recall doesn't apply to T61 model of Thinkpad. The message looks like this:

I would like to permanently dismiss this notification.
I have tried:

*

*copying /lib/udev/rules.d/95-upower-battery-recall-lenovo.rules to /lib/udev/rules.d/96-upower-battery-recall-lenovo.rules and modifying some of the logic in there. Note the higher number, intended to take priority over rule in /lib/udev, but it doesn't appear to.

*modified "/apps/gnome-power-manager/notify/perhaps_recall" property to be unchecked using gconf-editor
How do I get rid of this annoying warning?

A: 2 days ago i installed KDE Plasma Desktop on top of Ubuntu 12.04 and i get similar warnings(for Toshiba notebook). I could not find any solution except this:
Go Settings > System Settings > Power Management
Under "Power Management", click Advanced Settings > Configure Notifications
Then uncheck "Play a sound" and "Show a message in a popup" options for "Broken Battery(or something similar to this; i translated from Turkish, it might be different.)" notification.
I just found this solution and tested twice(once by logging off and once by restarting); notification was gone.
And please consider: This probably is not a right way to get rid of this wrong and annoying notification.
Hope this helps.


text:
Q: scipy.optimize.minimize with general array indexing I want to solve an optimization problem with the method 'COBYLA' in scipy.optimize.minimize as follows:
test = spopt.minimize(testobj, x_init, method='COBYLA', constraints=cons1)
y = test.x
print 'solution x =', y

However, since the program is quite large, a scalable way to write the objective function (and the constraints) is to use a general index for the arguments. For example, if I could use x['parameter1'] or x.param1 instead of x[0], then the program would be easier to read and debug. I tried both writing x as an object or a pandas Series with general indexing like x['parameter1'], as follows:
def testobj(x):
    return x['a']**2 + x['b'] + 1

def testcon1(x):
    return x['a']

def testcon2(x):
    return x['b']

def testcon3(x):
    return 1 - x['a'] - x['b']

x_init = pd.Series([0.1, 0.1])
x_init.index = ['a','b']

cons1 = ({'type': 'ineq', 'fun': testcon1}, \
    {'type': 'ineq', 'fun': testcon2}, \
    {'type': 'ineq', 'fun': testcon3})

but whenever I pass that into the minimize routine, it throws an error:
return x['a']**2 + x['b'] + 1
ValueError: field named a not found

It works perfectly if I use the normal numpy array. Perhaps I'm not doing it right, but is that a limitation of the minimize function that I have to use numpy array and not any other data structure? The scipy documentation on this topic mentions that the initial guess has to be ndarray, but I'm curious how is the routine calling the arguments, because for pandas Series calling the variable with x[0] or x['a'] are equivalent.

A: As you note, scipy optimize uses numpy arrays as input, not pandas Series. When you initialize with a pandas series, it effectively converts it to an array and so you cannot access the fields by name anymore.
Probably the easiest way to go is to just create a function which re-wraps the parameters each time you call them; for example:
def make_series(params):
    return pd.Series(params, index=['a', 'b'])

def testobj(x):
    x = make_series(x)
    return x['a']**2 + x['b'] + 1

def testcon1(x):
    x = make_series(x)
    return x['a']

def testcon2(x):
    x = make_series(x)
    return x['b']

def testcon3(x):
    x = make_series(x)
    return 1 - x['a'] - x['b']

x_init = make_series([1, 1])
test = spopt.minimize(testobj, x_init, method='COBYLA', constraints=cons1)
print('solution x =', test.x)
# solution x = [  1.38777878e-17   0.00000000e+00]


text:
Q: ARM UEFI C StdLib BDS As I understand, If I build an UEFI application with the StdLib Pkg, it has a dependency to the ShellPKg and the application must be started through the new Shell (UEFI Interactive Shell v2.1 EDK II UEFI v2.60). So starting the application manually through the 2.1 Shell built with ShellPkg works, but not with the EBL shell, or through the gBS->StartImage.
To my question: is it possible to start an UEFI application that is using a Library built with StdLib through the BDS (boot device selection), without starting an Shell first and use startup.nsh to startup the UEFI application that you want?
For example trying to bootup the UEFI application with StdLib, with the following command in BDS won't work as its not started through Shell:
    Status = gBS->StartImage(ImageHandle, NULL, NULL);
So what I would like to achieve is a function call to execute a UEFI application with StdLib package during the boot in BDS. Most preferable not through startup scripts.
BR
Gigu

A: Yes, you can execute UEFI application through BDS.
To launch/execute UEFI application through BDS we need to use BOOT#### NV variable to launch/execute UEFI application.
To load UEFI driver through BDS we can use DRIVER#### NV variable to load DXE, UEFI drivers.
Using this way we don't need to use Starup.nsh way or Shell environment to launch/execute UEFI application.


text:
Q: How to serialize a custom formatted time to/from xml in Go? When serializing a datetime to/from xml how do I make it use a custom time format?

A: Just as you'd implement json.Marshaler and json.Unmarshaler for doing this with JSON (there are many posts about that on StackOverflow and the internet);
one way is to implement a custom time type that implements encoding.TextMarshaler and encoding.TextUnmarshaler.
Those interfaces are used by encoding/xml when encoding items (after first checking for the more specific xml.Marshaler or xml.Unmarshaler interfaces, however those later ones have to do full XML encoding themselves).
E.g. something like (full example on the Go Playground):
const fixedFormat = "Mon Jan 02 2006"

type myTime1 struct {
    time.Time
}

func (m myTime1) MarshalText() ([]byte, error) {
    text := m.Time.Format(fixedFormat)
    return []byte(text), nil
}
func (m *myTime1) UnmarshalText(text []byte) error {
    t, err := time.Parse(fixedFormat, string(text))
    if err == nil {
        m.Time = t
    }
    return err
}

or
type myTime2 time.Time

func (m myTime2) MarshalText() ([]byte, error) {
    text := time.Time(m2).Format(fixedFormat)
    return []byte(text), nil
}
func (m *myTime2) UnmarshalText(text []byte) error {
    t, err := time.Parse(fixedFormat, string(text))
    if err == nil {
        *m = myTime2(t)
    }
    return err
}

Either of those can be used in place of time.Time as part of a larger data structure used with xml (un)marshalling. E.g.:
type Foo struct {
    Date1 myTime1 `xml:"date1"`
    Date2 myTime2 `xml:"date2"`
}

The difference in how these custom time types are defined changes how you use them with regular time.Time values.
E.g.
m1 := myTime1{time.Now()}
fmt.Println(m1)
if m1.Before(time.Now()) {}
t1 := m1.Time
// compared to:
m2 := myTime2(time.Now())
fmt.Println(time.Time(m2))
if time.Time(m2).Before(time.Now()) {}
t2 := time.Time(m2)

A: It depends how your format looks like, but a good starting point should be the time library. http://golang.org/pkg/time/
layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)


text:
Q: How to host a wordpress blog from a domain pointed to an app hosted with google app engine? I have a Python web app hosted with Google App Engine with a .com pointed towards the App Engine app. I would like to start a Wordpress blog at mydomain.com/blog.
Since Wordpress runs on PHP, I reckon it would be easier to host the Wordpress blog on my other web host account with cpanel and change some domain pointer. What is the best way to achieve this?
I suppose setting a DNS A Name record for 'blog' to point to my other web host account will create blog.mydomain.com and solve this. But is there a way to have mydomain.com/blog pointed to the other web hosting account with the Wordpress blog? Thank you.

A: Another approach similar to renab's: on your Wordpress box you can configure the Apache (or any other sensible http server) to work as a proxy in front of your App Engine application for every URL but the /blog one (which would be served directly).
You could also enable some level of caching on the Apache server and save a little on processing costs.

A: A simple solution may be to create the A record you mentioned in your question then put an index.html in the blog/ directory on app engine that contains
window.location = "http://blog.mydomain.com"
as the onload function of the body tag.
Another solution is adding a .htaccess file which redirects http://www.mydomain.com/blog to http://blog.mydomain.com.
Edit: As mentioned in the comment below, appengine does not support this method. I am leaving it in for the off chance that it will help someone who has a similar question not related to app engine.
A similar redirect would be needed for the domain without www in front of it.
Edit for better htaccess example:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com$
RewriteRule ^blog/(.*) http://blog.mydomain.com/$1 [R=301,L]

You will have to check my htaccess syntax, its been a while since I had to write rewrite rules, and I don't have a webserver handy to test it


text:
Q: How to access next and previous keys in an OrderedDict in Python 3.5 I have an OrderedDict structure that is ordered through key sorting, in the following fashion:
from collections import OrderedDict

my_regular_dict = {
    '1': 'first value',
    '2': 'second value',
    '3': 'third value'
}

my_ordered_dict = OrderedDict(sorted(my_regular_dict.items(), key=lambda t: t[0]))

In my_ordered_dict I would like to be able to call a method that given a key, returns the next one, but in Python 3.5, something like this:
>>> my_ordered_dict.get_next_key('1')
'2'

I know that previously in python 3.4 and others you could access the map and just grab the key with no problem, but that changed with the new C based implementation in python 3.5, leaving no possibility to access private methods.
I've been dragging my head with this for a few hours now and I can't get around it, is there any way at all to do this, or am I doing this just wrong?

A: probably not very efficient because of the index method (could be improved with bisect since the keys are sorted in your case), and also because of the creation of a list at each call (which could be avoided by iterating on the keys with a loop using a memory effect to compare to the previous element & return the current one) but here's my proposal:
from collections import OrderedDict

def gnk(self, k):
    l = list(self.keys())
    i = l.index(k)
    if i<len(l)-1:
        return l[i+1]
    else:
        raise Exception("last key")

OrderedDict.get_next_key = gnk

my_regular_dict = {
    '1': 'first value',
    '2': 'second value',
    '3': 'third value'
}

my_ordered_dict = OrderedDict(sorted(my_regular_dict.items()))  # no need for custom key, keys cannot be equal

print(my_ordered_dict.get_next_key('1'))

It adds a method to OrderedDict class, which creates the keys as list (not very efficient, I admit) then looks for the index of the key and takes the next index.
Maybe not what you're looking for, since it's O(n) without bisect, that you can use only if the keys are sorted using lexicographical order.
EDIT: method using bisect, O(log(n)) complexity (but the keys 2 list is still O(n):
import bisect

def gnk(self, k):
    l = list(self.keys())
    i = bisect.bisect_left(l,k)
    if i<len(l)-1:
        if l[i]!=k:
            raise KeyError(k)
        return l[i+1]
    else:
        raise Exception("last key")

As some comments hint at, the solution may not work in Python 3.6+, so a better way to do this would be to implement a custom dictionary class using bisect for lookup, and a real list for the keys. Writing such a class is doable (but will take time to finetune if you really want to emulate a dictionary closely) but beyond a concise answer.


text:
Q: what means this javascript code function (function () {
    // do somethig
})();

What means this function in parentheses? ()();
Some developers creates functions like this in js files directly.

A:
What means this function in parentheses? ()();

That means a self-invoking function in JavaScript.
Notice to the: (); - That is a calling.
Your function, which is anonymous BTW, will be invoked automatically without any caller intervention, but by itself, once it's declared.
In addition, as @Thilo suggested, it is also to get an isolated scope for local variables.

A: this is the self invoking anonymous function. This means the function within the first () parenthesis is the function which has no name and by next (); parenthesis you can understand that it is called at the time it is defined. And you can pass any argument in this second () parenthesis which will be grabbed in function which is in the first parenthesis. see this example:
(function(obj){
    //do something with this obj
})(object);

here the 'object' you are passing will be accessible within the function by 'obj', as you are grabbing it in the function signature.


text:
Q: Elastic Search query_shard_exception failed to execute query on datetime field recently I use Kibana for get data from ElasticSearch.
There are that node:
  { "_index" : "impasti",
    "_type" : "impasti",
    "_id" : "2019-01-02T15:25:20",
    "_score" : 1.9806902,
    "_source" : {
      "sensor" : "Temperature",
      "mac_address" : "",
      "time" : "2019-01-02T14:25:19.728709Z",
      "unit" : "'C",
      "value" : 20.937
    }},

I try get the data by the time field, into datetime range or exactly datetime.
But when I run this query
POST /impasti/impasti/_search
{'query':{
    "query_string": {
      "default_field": "time",
      "query": "2019-01-02T14:25:19.728709Z"
    }
  }
}
the response is an error like this:
"type": "query_shard_exception" "reason": "Failed to parse query [2019-01-02T14:25:19.728709Z]",

Where is the mistake?
Thanks guys

A: Error states that you would need to do something more in order for the ES query parser to understand that the value is a date and not a string/text/keyword type:
Moreover date fields are usually used for a particular range. Below is how it can be done via adding Range feature
Using query_string:
POST your_index_name/_search
{
  "query": {
    "query_string": {
      "default_field": "time",
      "query": "time:[2019-01-02T14:25:19.728709Z TO 2019-01-02T14:25:19.728709Z]"
    }
  }
}

Generally it is [min To max] for finding docs in specified time range, but in case if you want to find documents for that date, mention same date for both min and max.
Using Range Bool Query:
POST you_index_name/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "mydate": {
              "gte": "2019-01-02T14:25:19.728709Z",
              "lte": "2019-01-02T14:25:19.728709Z"
            }
          }
        }
      ]
    }
  }
}

The above is an example of Range Query using query DSL
Alternatively you can also make use of a simple match query to get what you want whilst using query DSL via Term Query, that is because internally it is stored as long value.
POST your_index_name/_search
{
  "query": {
    "term": {
      "mydate": "2019-01-02T14:25:19.728709Z"
    }
  }
}

Note: Elasticsearch internally stores the date values in the form of long datatype in its inverted index as mentioned in this link

A:
Could you update that query which gives you this error in the question. I can quickly check and let you know.

Sure!
This is the query
`POST /impasti/impasti/_search{
      "query":{
           "filtered": {
               "query": {
                   "query_string": {
                       "default_field": "time",
                       "query": "time:[2019-01-02T14:20:19.728709Z TO 2019-02-02T14:25:19.728709Z]"
                    }
               },

               "filter": {
                   "term":{ "sensor": "temperature" }
                }
         }
     }
}`

It get this error:
no [query] registered for [filtered]


text:
Q: Remove/Hide/Delete an array of features from Azure Map This is a follow on questions from Azure Maps (with Turf.js) - can't get the 'points' from the SymbolLayer
I now have a function that loads the data "onclick" from a JSON location.
What I am trying to do is now Remove the data. A toggle-on / toggle-off function.
Full code is: https://espiritos.projectwebdev.co.uk/index-v1.0.8a.html
But the key function I am concerned with is:
$(document).on("click", ".toggleCounty.on", function(event) {
  if ($(this).hasClass("on")) {
    var elementsToRemove = "";
    $(this).toggleClass("off");
    $(this).toggleClass("on");
    var countyID = $(this).attr("data-countyID");

    var url = geoJsonData[countyID].url;
    $.getJSON(url, function(data) {
      var noOfFeatures = Object.keys(data.features).length;
      console.log(noOfFeatures);
      for (var i = 0; i < noOfFeatures; i++) {
        console.log("[" + i + "]");
        console.log(data.features[i]);
        datasource.remove(data.features[i]);
        // map.data.remove(data.features[i]);
        debugger;
      }
    });
  }
});

I do an API lookup from a variable "geoJsonData":
var geoJsonData = [
  {
    name: "Hertfordshire",
    shown: "off",
    url:
      "https://www.naptan.projectwebdev.co.uk/api/v1/get/stoppoints?fields=all&format=geojson&filter=NptgLocalityRef|E0000708",
    geomType: "points"
  },
  {
    name: "Hampshire",
    shown: "off",
    url:
      "https://www.naptan.projectwebdev.co.uk/api/v1/get/stoppoints?fields=all&format=geojson&filter=NptgLocalityRef|E0044074",
    geomType: "points"
  },
  {
    name: "Oxfordshire",
    shown: "off",
    url:
      "https://www.naptan.projectwebdev.co.uk/api/v1/get/stoppoints?fields=all&format=geojson&filter=NptgLocalityRef|E0000708",
    geomType: "points"
  }
];

I load in the "features" from the JSON...
And then I just can't work out how to remove those features from the map.
I have popped a "debugger;" where the issue is.
I am extremely grateful for any guidance. Thank you.

A: It looks like in the first code block you are loading GeoJSON data from the web and then trying to remove it from a data source, but you never add it to the data source. That won't work. If you previously loaded the same data into the data source, I don't think that would work either since these are fundamentally different JSON object instances. The one way you can get this to work is to add unique ID's to each feature in your GeoJSON files. Then the data source can do a match on that. For example:
{
  "type": "Feature",
  "id": 1,
  "geometry": {
    "type": "Point",
    "coordinates": [-0.61827807482, 51.537852954]
  },
  "properties": {
    "AtcoCode": "040000000127",
    "NaptanCode": "bucgjtjt",
    "CommonName": "Farnham House",
    "Street": "Farnham Lane",
    "Indicator": "adj",
    "NptgLocalityRef": "E0044074",
    "GridType": "UKOS",
    "Easting": "495927",
    "Northing": "183010",
    "StopType": "BCT",
    "BusStopType": "MKD",
    "TimingStatus": "OTH",
    "CompassPoint": "SE",
    "Degrees": "135",
    "StopAreaRef": "",
    "AdministrativeAreaRef": "70"
    }
},

Note you will need to make sure all id's across all your files are unique.
Some other approaches you can consider;

*

*If there is a property in each feature that can relate a feature back to its original file (i.e. "source": "Hertfordshire"), then you could us a filter in the layers to control what is rendered based on this property.

*If you only ever load the data for one file at a time and remove all other data, then consider using the datasource.setShapes function. This will overwrite all data in the data source.

Update
I have put together a more in depth sample that shows toggling between different data sets. It looks like these data sets are small, so I load them the first time they are needed into the data source and leave them in there. Then to toggle I simply use a filter at the layer level. This makes it much faster to reload a data set a second time. This will work fine for data sets that are tens of thousands in size. If you are working with larger data sets, then removing the data might be something to consider. I also noticed when putting this sample together, the URL for the first and last data set you provided are the same (assuming this is an error).
<!DOCTYPE html>

    <title></title>

    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />


text:
Q: Strategy for minimizing bank conflicts for 64-bit thread-separate shared memory Suppose I have a full warp of threads in a CUDA block, and each of these threads is intended to work with N elements of type T, residing in shared memory (so we have warp_size * N = 32 N elements total). The different threads never access each other's data. (Well, they do, but at a later stage which we don't care about here). This access is to happen in a loop such as the following:
for(int i = 0; i < big_number; i++) {
    auto thread_idx = determine_thread_index_into_its_own_array();
    T value = calculate_value();
    write_to_own_shmem(thread_idx, value);
}

Now, the different threads may have different indices each, or identical - I'm not making any assumptions this way or that. But I do want to minimize shared memory bank conflicts.
If sizeof(T) == 4, then this is is easy-peasy: Just place all of thread i's data in shared memory addresses i, 32+i, 64+i, 96+i etc. This puts all of i's data in the same bank, that's also distinct from the other lane's banks. Great.
But now - what if sizeof(T) == 8? How should I place my data and access it so as to minimize bank conflicts (without any knowledge about the indices)?
Note: Assume T is plain-old-data. You may even assume it's a number if that makes your answer simpler.

A: tl;dr: Use the same kind of interleaving as for 32-bit values.
On later-than-Kepler micro-architectures (up to Volta), the best we could theoretically get is 2 shared memory transactions for a full warp reading a single 64-bit value (as a single transaction provides 32 bits to each lane at most).
This is is achievable in practice by the analogous placement pattern OP described for 32-bit data. That is, for T* arr, have lane i read the idx'th element as T[idx + i * 32]. This will compile so that two transactions occur:

*

*The lower 16 lanes obtain their data from the first 32*4 bytes in T (utilizing all banks)

*The higher 16  obtain their data from the successive 32*4 bytes in T (utilizing all banks)

So the GPU is smarter/more flexible than trying to fetch 4 bytes for each lane separately. That means it can do better than the simplistic "break up T into halves" idea the earlier answer proposed.
(This answer is based on @RobertCrovella's comments.)

A: On Kepler GPUs, this had a simple solution: Just change the bank size! Kepler supported setting the shared memory bank size to 8 instead of 4, dynamically. But alas, that feature is not available in later microarchitectures (e.g. Maxwell, Pascal).
Now, here's an ugly and sub-optimal answer for more recent CUDA microarchitectures: Reduce the 64-bit case to the 32-bit case.

*

*Instead of each thread storing N values of type T, it stores 2N values, each consecutive pair being the low and the high 32-bits of a T.

*To access a 64-bit values, 2 half-T accesses are made, and the T is composed with something like `
uint64_t joined =
    reinterpret_cast<uint32_t&>(&upper_half) << 32  +
    reinterpret_cast<uint32_t&>(&lower_half);
auto& my_t_value = reinterpret_cast<T&>(&joined);

and the same in reverse when writing.
As comments suggest, it is better to make 64-bit access, as described in this answer.


text:
Q: State of child when parent calls useState update function Suppose I have the following code snippet (Please consider it as a pseudo code)
Parent.js
const [state,action]=useState(0);
return <View><Child1/><Button onPress={()=>action(1)}/></View>

Child1.js
const [state]=useState(Math.random());
return <Text>{state}</Text>

So my question is when I click the button in the parent will the Chil1 state change or not.
On my local machine it seems it changes.

A: The benefit of useState is that once a component is mounted, the state value does not change across re-renders until the update state function is called, passing a new state value.
Therefore, even though your parent component Button press state change triggers a rerender of the child, since the child component is only being rerendered and not unmounted/remounted, the initial state of Math.random() would remain the same.
See useState in React: A complete guide

A: I don't know what exact scenario is, but if you just set default state, the state will be memorized like Scenario 1
Scenario 1
In this way, the state of Child will not be changed even if Parent re-render
const Child = () => {
  const [state] = useState(Math.random());
  return
{state}

}

const Parent = () => {
  const [, action] = useState(true);
  return (
    <>
      <button onClick={() => action(false)}>Not Change</button>
      <Child />
    </>
  );
}

Scenario 2
Unless you remove it and then re-render Parent even if memorize all Child, that is
const Child = () => {
  const [state] = useState(Math.random());
  return
{state}

}

const Parent = () => {
  const [state, action] = useState(true);

  useEffect(() => {
    if (!state) action(true)
  }, [state])

  return (
    <>
      <button onClick={() => action(false)}>Change</button>
      {state && <Child />}
    </>
  );
}

Scenario 3
By the may, if you don't use default state, in this way, it will be changed every rendering like that
const Child = () => {
  return
{Math.random()}

}

const Parent = () => {
  const [, action] = useState(true);

  return (
    <>
      <button onClick={() => action(prev => !prev)}>Change</button>
      <Child />
    </>
  );
}

Scenario 4
If we don't want Child to re-render, we can try memo to memorize it
const Child = memo(() => {
  return
{Math.random()}

})

Scenario 5
However, when Child has props, perhaps we should invole useCallback or useMemo to make sure the values or memory addresses of props are "fixed" like constant, so that Child won't re-render
(We don't have to use useCallback or useMemo all the time, it doesn't much matter when there is no performance problem)
const Child = memo((props) => {
  return
{Math.random()}

})

const Parent = () => {
  const [, action] = useState(true);
  const style = useMemo(() => ({}), [])
  const onOK = useCallback(() => alert(1), [])
  return (
    <>
      <button onClick={() => action(prev => !prev)}>Change</button>
      <Child className="test" style={style} onClick={onOK} />
    </>
  );
}


text:
Q: Jquery Multiple submit buttons I have two buttons within my form. Each of them should submit the form to a different PHP file (one normal submit and one ajax call). At least that's the idea. When I click the buttons nothing happens. I've looked at other questions here on stackoverflow, but I can't figure out what I'm doing wrong.
HTML:
<form id="sform" name="sform" method="post" action="answer.php" class="sform" enctype="multipart/form-data">
Option 1
<select id="option1" name="option1">
<option selected>None</option>
<option>Yellow</option>
<option>Green</option>
<option>Red</option>
</select>

Option 2
<select id="option2" name="option2">
<option selected>None</option>
<option value="F">Purple</option>
<option value="M">Brown</option>
<option value="T">Blue</option>
</select>

<textarea class="input-block-level" id="summernote" name="summernote" rows="18"></textarea>

<input type='button' value='Submit form' id="view" name="view"/>
<input type='button' value='Submit form' id="send" name="send"/>
</form>

jQuery:
jQuery(document).ready(function($){

$( "#send" ).click(function() {
    alert("hi");
   $("#sform").submit();
}

$( "#view" ).click(function() {

    /* stop form from submitting normally */
    event.preventDefault();

    /* get some values from elements on the page: */
    var $form = $( this ),
        /*url = $form.attr( 'action' ),*/
        postData = {
            option1: $form.find( '#option1' ).val(),
            option2: $form.find('#option2').val(),
            message: $form.find('#summernote').val(),
            js: 'true'
        };

    /* Send the data using post and put the results in a div */
    jQuery.ajax({
        type: "POST",
        url: "reply.php",
        data: postData,
        success: function(response){
            jQuery('#result').empty().append(response);
        }
    });

});
});

A: The call to .click() is not closed:
$( "#send" ).click(function() {
    alert("hi");
    $("#sform").submit();
}
//^ need closing parenthesis

So to make it complete by adding the closing parenthesis after the function brackets (i.e. );):
$( "#send" ).click(function() {
    alert("hi");
    $("#sform").submit();
});

As Taplar mentioned in a comment on your question, the event reference should be passed to the callback :
$("#view").click(function(event) {

 /* stop form from submitting normally */
 event.preventDefault();

Per the comment by epascarello, you can make the button that submits the form a regular submit button:
<input type='submit' value='Submit form' id="send" name="send" />

In doing that, the click handler on that input becomes superfluous.
And we can make the send button a button element instead of an input with type="button"
<button id="view" name="view">View</button>

Also note that calling .find() on $(this) bound to the click handler associated with the element with id attribute view will find no elements under that button. In order to get the values of the elements under the form as it is structured, you should set $form to the parent element of the button (i.e. $(this)) - e.g.:
var $form = $(this).parent()

See the example below (Note: the form will not get submitted per the StackOverflow sandbox environment - to see the form submission in action, see this plunker).

 jQuery(document).ready(function($) {
 //when we change the input type to 'submit' for this button then this becomes un-needed
   /*$("#send").click(function() {
     alert("hi");
     $("#sform").submit();
   });*/
   $("#view").click(function(event) {

     /* stop form from submitting normally */
     event.preventDefault();

     /* get some values from elements on the page: */
     var $form = $(this).parent(),
         /*url = $form.attr( 'action' ),*/
         postData = {
           option1: $form.find( '#option1' ).val(),
           option2: $form.find('#option2').val(),
           message: $form.find('#summernote').val(),
           js: 'true'
         };
     /* Send the data using post and put the results in a div */
     jQuery('#result').append('would trigger AJAX call');
console.log('form data to submit',postData);
     //disabling this since we have no reply.php available
     /*jQuery.ajax({
       type: "POST",
       url: "reply.php",
       data: postData,
       success: function(response) {
         jQuery('#result').empty().append(response);
       }
     });*/
   });
 });

<form id="sform" name="sform" method="post" action="answer.php" class="sform" enctype="multipart/form-data">
  Option 1
  <select id="option1" name="option1">
    <option selected>None</option>
    <option>Yellow</option>
    <option>Green</option>
    <option>Red</option>
  </select>

 Option 2
  <select id="option2" name="option2">
    <option selected>None</option>
    <option value="F">Purple</option>
    <option value="M">Brown</option>
    <option value="T">Blue</option>
  </select>

  <textarea class="input-block-level" id="summernote" name="summernote" rows="18"></textarea>

<button id="view" name="view">View</button>
  <input type='submit' value='Submit form' id="send" name="send" />
</form>

A: jQuery(document).ready(function(jQuery) {

    jQuery( "#send" ).click(function(event) {
        event.preventDefault();
        jQuery( "#view" ).trigger( "click" );
    }

    jQuery( "#view" ).click(function(event) {
        event.preventDefault();
        submitForm('#sform');
    });

    function submitForm(id) {

        var formId = id;
        var $form = $(formId),
            /*url = $form.attr( 'action' ),*/
            postData = {
                option1: $form.find( '#option1' ).val(),
                option2: $form.find('#option2').val(),
                message: $form.find('#summernote').val(),
                js: 'true'
            };

        /* Send the data using post and put the results in a div */
        jQuery.ajax({
            type: "POST",
            url: "reply.php",
            data: postData,
            success: function(response){
                jQuery('#result').empty().append(response);
            }
        });

    }

});

A: You have a missing closing bracket for the #send function.
Also, pass in the event to the functions, and "this" refers to the button, not the form, so use "closest" to find the form.
jQuery(document).ready(function($) {
    $("#send").click(function(e) {
        alert("hi");
        e.preventDefault();
        $("#sform").submit();
    });

    $("#view").click(function(e) {

        /* stop form from submitting normally */
        e.preventDefault();

        /* get some values from elements on the page: */
        var $form = $(this).closest("form");
        var postData = {
                option1: $form.find('#option1').val(),
                option2: $form.find('#option2').val(),
                message: $form.find('#summernote').val(),
                js: 'true'
            };

        /* Send the data using post and put the results in a div */
        jQuery.ajax({
            type: "POST",
            url: "reply.php",
            data: postData,
            success: function(response) {
                jQuery('#result').empty().append(response);
            }
        });

    });
});


text:
Q: Sum of gravitational force $W$ and contact force $N$ on a book at rest on table is not 0 There is a book on the table fixed rigidly to the earth. The book is at rest with respect to the earth. The acceleration of this book with respect to the earth is 0. The forces on this book are
a) Gravitational force W exerted by earth.
b) Contact force N exerted by the table.
Is the vector sum of both the forces 0?
A renowned physics book - Concepts of physics by H.C Verma states that "on a very accurate measurement, the above answer is no. The sum of the forces is not 0 although the book is at rest. The earth is not strictly an inertial frame. However, the sum is not too different from 0 and we can say that earth is an inertial frame of reference to a good approximation."
Can someone please elaborate on this? Why the sum is strictly not 0?

A: Because, as they said, Earth is not an inertial frame, there are also some pseudo-forces acting on the book, like the centrifugal force related to the rotation of Earth. The book is at rest in this non-inertial frame, which means that the sum of all forces and pseudoforces in this frame is equal to zero. The sum of all real forces is only almost zero.

A: The brief answer is, the earth is spinning, and your book is rotating together with the earth. There need to be some force to maintain the rotation of the book, the centripetal force. Without that force on it, the book cannot just rotate by itself. That's where the net force comes from.
You can actually calculate the net force for the book's rotation with earth. Let's take approx. $v \sim 460m/s$ as the speed of the spinning earth on the equator, where you will need max centripetal force, and radius of earth $R \sim 6400km$. Use $F = mv^2/R$, we will get the centripetal acceleration $0.03 m/s^2$, only 0.3% of the gravitational acceleration, $10 m/s^2$.
That is, you will have maximumly about 0.3% of W left, after summing W and N.
I hope the calculation is correct.

A:
If there exists a book on a table the book is exerted a force on the table through weight due to gravity

The force that the book exerts on the table is not a gravitational force, it's a normal force.
The table react with an equal and opposite force which is also a normal force. So the book exerts a normal force on the table, and the table exerts a normal force on the book.

But is the force acting on the table due to gravity?

No, it's not, and in fact this force (the normal force) is only indirectly due to gravity.
The only relevant gravitational force is the force exerted by the Earth on the book. The book also exerts a gravitational force back on the Earth, but because the Earth is so heavy, that force has no noticeable effect. (The Earth also exerts a gravitational force on the table, and the table on the Earth, but those don't matter so much in this particular scenario.)

A: There are two forces acting on a mass $m$ at the Equator.
The force due to the gravitational attraction of the Earth $F_{\rm G}=\dfrac{GM_{\rm E}m}{R^2_{\rm E}}$ and the force due to the mass being in contact with the Earth, $Z'$.

If the mass was not accelerating then its equation of motion would be $F_{\rm G} - Z' = m\,0$ and so those two forces would be equal in magnitude but opposite in direction.
However the Earth is spinning about its axis and so is the mass with an angular speed $\omega$ so the equation of motion of the mass is $F_{\rm G} - Z' = m\,R_{\rm E} \,\omega^2$.
This shows that $F_{\rm G} \ne Z'$.
You can think of the gravitational force having two components $X'$ and $Y'$.
The $X'$ component takes care of the centripetal acceleration $X' = m\,R_{\rm E}\, \omega^2$ and the $Y'$ component take care of the contact force due to the Earth.
The effect is a bit more complex at other positions on the Earth but non existent at the Poles where the mass would undergo no centripetal acceleration.

A: A brief statement would be:-The earth is only an approximate inertial reference frame as it rotates about its axis with a very small angular velocity which makes it a non inertial reference frame but it would be a good approximation to treat it as an inertial frame.


text:
Q: asp.net gridview formatting I have a gridview which has three columns date, pnl, cumpnl
I am able to add some formatting when applied to all cells using code such as
Protected Sub OnRowCreated(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        For Each cell As TableCell In e.Row.Cells
            cell.Font.Size = 10
            cell.HorizontalAlign = HorizontalAlign.Center
        Next
    End If

End Sub

Within that For...Next loop how can I reference only the cells in the pnl and cumpnl columns? I don't see anyway to reference cells by the columnheader name or index.
Update:
by Using a RowDataBound event I can now reset the format of the values in the columns but the setting of the forecolor based on the cells value keeps erring ("Input string not in correct format"). Also, I am hardcoding the the column indexes. I need a way to dynamically get the column index based on the column header name
Protected Sub gvDataRetrieval_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvDataRetrieval.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        For i As Integer = 1 To 2
            e.Row.Cells(i).Text = FormatCurrency(e.Row.Cells(i).Text, 2).ToString()
            If Double.Parse(e.Row.Cells(i).Text) < 0 Then e.Row.Cells(i).ForeColor = Drawing.Color.Red
        Next
 End If
End Sub

A: Outside for each loop:
e.Row.Cells(index)

Eg.
For adding header tooltip:
    Protected Sub Grid1_RowCreated(ByVal sender As Object, ByVal e As GridRowEventArgs)
       //setting row cells
    If e.Row.RowType = DataControlRowType.DataRow Then
      For i As Integer = 1 To e.Row.Cells.Count
        If i = 1 Then
           e.Row.Cells(i).Font.Size= 8
        ELSE
           e.Row.Cells(i).Font.Size= 12
        END IF
      NEXT
    End If
    End Sub

A: Kapil's code in C#
        private void DataGrid1_RowCreated(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 1; i < e.Row.Cells.Count; i++)
            {
                if (i == 1) { e.Row.Cells[i-1].Font.Bold = true; } else { e.Row.Cells[i-1].Font.Bold = false; }
            }
        }
    }


text:
Q: Graph Theory: Bipartite test To determine if following graphs are bipartite:
a) the graph on 7 vertices one for each day of week, where two days are adjacent exactly if they share a letter in their name (but the letter must not be "d","a" or "y")
b) the graph on 7 vertices one for each day of week, where two days are adjacent exactly if they do not share a letter in their name (but the letter must not be "d","a" or "y")
c) edge graph of a cube
d) edge graph of tetrahedron
My try:
I think I got c and d. c would be bipartite and d is not.
Need help in a and b (not able to figure out)

A: After you remove the letters d, a, and y and all repeated letters from the names of the weekdays, you have
$$\begin{array}{ll}
1&\text{Monday}&\text{mno}\\
2&\text{Tuesday}&\text{estu}\\
3&\text{Wednesday}&\text{ensw}\\
4&\text{Thursday}&\text{hrstu}\\
5&\text{Friday}&\text{fir}\\
6&\text{Saturday}&\text{rstu}\\
7&\text{Sunday}&\text{nsu}
\end{array}$$
I'll use the numbers in the first column as names of the $7$ vertices of the graphs (a) and (b). In graph (a) we have the following edges, with a shared letter in parentheses:
$$\begin{align*}
&13(n),17(n),\\
&23(e),24(s),26(s),27(s),\\
&34(s),36(s),37(n),\\
&45(r),46(r),47(s)\\
&56(r),\\
&67(s)
\end{align*}\tag{1}$$
Suppose that the graph is bipartite, with parts $V$ and $W$, and without loss of generality suppose that $1\in V$. The first line of $(1)$ shows that $3$ and $7$ must be in $W$, since there are edges between them and $1$. Since $7\in W$, and $7$ is joined by edges to $2,3,4$, and $6$, these four vertices must join $1$ in $V$. And we have an edge $56$, so with $6\in V$ we must have $5\in W$. That is, we must have
$$V=\{1,2,3,4,6\}\quad\text{and}\quad W=\{5,7\}\;.$$
Unfortunately, this doesn't work, because we have an edge $23$ between two vertices in $V$. Thus, graph (a) is not bipartite.
Note that we didn't actually need all of the information. It's enough to see that we have edges $23,27$, and $37$, forming a triangle: a bipartite graph cannot contain a triangle.
Now that you've seen this, see if you can deal with graph (b) on your own.


text:
Q: Wrong data types when reading data with spark if I try to specify the schema when reading a file using pyspark, the read method doesn't fail when the schema is incorrect. For example:
schema = '''
{
"fields":
[
{"metadata":{},"name":"id0","nullable":true,"type":"integer"},
{"metadata":{},"name":"id1","nullable":true,"type":"integer"},
{"metadata":{},"name":"name","nullable":true,"type":"integer"},
{"metadata":{},"name":"timestamp","nullable":true,"type":"string"}
],"type":"struct"}
'''
schemaFromJson = StructType.fromJson(json.loads(schema))

df2 = spark.read.format("csv") \
      .option("header", True) \
      .schema(schemaFromJson) \
      .load(s3InputPath)

yields
+----+----+----+---------+
| id0| id1|name|timestamp|
+----+----+----+---------+
|null|null|null|     null|
|null|null|null|     null|
|null|null|null|     null|
|null|null|null|     null|
+----+----+----+---------+

because the "name" field is a string and I told it to read as integer.
Is there any way of making the read method fail in such cases?
Data sample:
id0,id1,name,timestamp
10,1,Name1,01/03/2021 13:00
10,2,Name2,01/03/2021 13:00
10,3,Name3,01/03/2021 13:00
10,4,Name4,01/03/2021 13:00

Thanks

A: You can provide mode=PERMISSIVE|FAILFAST|DROPMALFORMED:
Scenario 1: Store unprocessed data into another column:
schema = '''
{
"fields":
[
{"metadata":{},"name":"id0","nullable":true,"type":"integer"},
{"metadata":{},"name":"id1","nullable":true,"type":"integer"},
{"metadata":{},"name":"name","nullable":true,"type":"integer"},
{"metadata":{},"name":"timestamp","nullable":true,"type":"string"},
{"metadata":{},"name":"_corrupt_record","nullable":true,"type":"string"}
],"type":"struct"}
'''
schemaFromJson = StructType.fromJson(json.loads(schema))

df2 = spark.read.format("csv") \
    .option("header", True) \
    .option("columnNameOfCorruptRecord", "_corrupt_record") \
    .schema(schemaFromJson) \
    .load(s3InputPath, mode='PERMISSIVE')
df2.show()

Output:
+---+---+--------+----------------+--------------------+
|id0|id1|    name|       timestamp|     _corrupt_record|
+---+---+--------+----------------+--------------------+
| 10|  1|    null|01/03/2021 13:00|10,1,Name1,01/03/...|
| 10|  2|    null|01/03/2021 13:00|10,2,Name2,01/03/...|
| 10|  3|    null|01/03/2021 13:00|10,3,Name3,01/03/...|
| 10|  4|    null|01/03/2021 13:00|10,4,Name4,01/03/...|
| 10|  5|40028922|01/03/2021 13:00|                null|
+---+---+--------+----------------+--------------------+

Scenario 2: Raise an exception
df2 = spark.read.format("csv") \
    .option("header", True) \
    .schema(schemaFromJson) \
    .load(s3InputPath, mode='FAILFAST')

Output:
[...]
Caused by: org.apache.spark.sql.catalyst.util.BadRecordException: java.lang.NumberFormatException: For input string: "Name1"
[...]

Scenario 3: Handle only valid data
df2 = spark.read.format("csv") \
    .option("header", True) \
    .schema(schemaFromJson) \
    .load(s3InputPath, mode='DROPMALFORMED')
df2.show()

Output:
+---+---+--------+----------------+
|id0|id1|    name|       timestamp|
+---+---+--------+----------------+
| 10|  5|40028922|01/03/2021 13:00|
+---+---+--------+----------------+


text:
Q: Proving continuity of a map from $D^2$ onto $S^2.$ I am following the lecture note in topology given by our instructor. There I found a proof of the fact that $D^2/S^1$ is homeomorphic to $S^2.$ The proof of this result goes along the following lines $:$

Let us denote the inverse of the stereographic projection from $S^2 - N$ onto $\Bbb R^2$ by $\mathscr I.$ Then define a function $f : D^2 \longrightarrow S^2$ as follows $:$
$$
f : x \longmapsto
  \begin{cases}
      \mathscr {I} \left (\frac {x} {1 - |x|} \right ) & x \in D^2 \setminus S^1 \\
      N & x \in S^1
      \end{cases}
$$
This map is continuous and surjective and hence by universal property of quotient topology we have a bijective continuous map $\overline {f} : D^2/S^1 \longrightarrow S^2.$ Now since $D^2/S^1$ is compact (being the image of the compact space $D^2$ under the quotient map) and $S^2$ is Hausdorff it follows that $\overline {f}$ is a homeomorphism and this proves the result.

Here I don't understand why $f$ is continuous. It is clear that $f$ is a continuous bijection from $D^2 \setminus S^1$ onto $S^2 - N.$ But how do I show that $f$ is continuous  $S^1\ $? Any help or suggestion will be appreciated.
Thanks in advance.

A: On $S^1$, $f$ is constant.  We must show that if $x_n\to x\in S^1$, where $x_n\in D^2$,  then $f(x_n)\to N$.  That seems clear.  As $|x|\to1$, $\left\lvert\frac x{1-|x|}\right\rvert\to\infty$ and $$\mathscr I\left(\frac x{1-|x|}\right)\to N$$

A: Another proof (less explicit but topologically correct): $D^2\setminus S^1$ is just the open unit disk which is homeomorphic to $\Bbb R^2$. So when we form $D^2{/}S^1$ we're left with in essence $\Bbb R^2$ unioned with the identified boundary, which is just a point in the quotient space, and together the form a compact Hausdorff space. So $D^2{/}S^1$ is just a one-point compactification of $\Bbb R^2$ and by unicity of that space it's homeomorphic to $S^2$, another one-point compactification of $\Bbb R^2$.


text:
Q: java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7 I'm not able to run a simple spark job in Scala IDE (Maven spark project) installed on Windows 7
Spark core dependency has been added.
val conf = new SparkConf().setAppName("DemoDF").setMaster("local")
val sc = new SparkContext(conf)
val logData = sc.textFile("File.txt")
logData.count()

Error:
16/02/26 18:29:33 INFO SparkContext: Created broadcast 0 from textFile at FrameDemo.scala:13
16/02/26 18:29:34 ERROR Shell: Failed to locate the winutils binary in the hadoop binary path
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.
    at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:278)
    at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:300)
    at org.apache.hadoop.util.Shell.<clinit>(Shell.java:293)
    at org.apache.hadoop.util.StringUtils.<clinit>(StringUtils.java:76)
    at org.apache.hadoop.mapred.FileInputFormat.setInputPaths(FileInputFormat.java:362)
    at
org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015)
    at org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015)
    at
org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176)
    at
org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176)

    at scala.Option.map(Option.scala:145)

    at org.apache.spark.rdd.HadoopRDD.getJobConf(HadoopRDD.scala:176)

    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:195)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)

    at scala.Option.getOrElse(Option.scala:120)

    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)

    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)

    at scala.Option.getOrElse(Option.scala:120)

    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)

    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1929)

    at org.apache.spark.rdd.RDD.count(RDD.scala:1143)

    at com.org.SparkDF.FrameDemo$.main(FrameDemo.scala:14)

    at com.org.SparkDF.FrameDemo.main(FrameDemo.scala)

A: *

*Download winutils.exe

*Create folder, say C:\winutils\bin

*Copy winutils.exe inside C:\winutils\bin

*Set environment variable HADOOP_HOME to C:\winutils

A: 1) Download winutils.exe from https://github.com/steveloughran/winutils
2) Create a directory In windows "C:\winutils\bin
3) Copy the winutils.exe inside the above bib folder .
4) Set the environmental property in the code
  System.setProperty("hadoop.home.dir", "file:///C:/winutils/");
5) Create a folder "file:///C:/temp" and give 777 permissions.
6) Add config property in spark Session ".config("spark.sql.warehouse.dir", "file:///C:/temp")"

A: You can alternatively download winutils.exe from GITHub:
https://github.com/steveloughran/winutils/tree/master/hadoop-2.7.1/bin
replace hadoop-2.7.1 with the version you want and place the file in D:\hadoop\bin

If you do not have access rights to the environment variable settings
  on your machine, simply add the below line to your code:

System.setProperty("hadoop.home.dir", "D:\\hadoop");

A: On Windows 10 - you should add two different arguments.
(1) Add the new variable and value as - HADOOP_HOME and path (i.e. c:\Hadoop) under System Variables.
(2) Add/append new entry to the "Path" variable as "C:\Hadoop\bin".
The above worked for me.

A: if we see below issue

ERROR Shell: Failed to locate the winutils binary in the hadoop binary path
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.

then do following steps

*

*download winutils.exe from  http://public-repo-1.hortonworks.com/hdp-
win-alpha/winutils.exe.

*and keep this under bin folder of any folder you created for.e.g. C:\Hadoop\bin

*and in program add following line before creating SparkContext or SparkConf
System.setProperty("hadoop.home.dir", "C:\Hadoop");

A: Follow this:

*

*Create a bin folder in any directory(to be used in step 3).

*Download winutils.exe and place it in the bin directory.

*Now add System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR"); in your code.

A: I got the same problem while running unit tests. I found this workaround solution:
The following workaround allows to get rid of this message:
    File workaround = new File(".");
    System.getProperties().put("hadoop.home.dir", workaround.getAbsolutePath());
    new File("./bin").mkdirs();
    new File("./bin/winutils.exe").createNewFile();

from: https://issues.cloudera.org/browse/DISTRO-544

A: Here is a good explanation of your problem with the solution.

*

*Download the version of winutils.exe from https://github.com/steveloughran/winutils.

*Set up your HADOOP_HOME environment variable on the OS level or programmatically:
System.setProperty("hadoop.home.dir", "full path to the folder with winutils");

*Enjoy

A: Setting the Hadoop_Home environment variable in system properties didn't work for me. But this did:

*

*Set the Hadoop_Home in the Eclipse Run Configurations environment tab.

*Follow the 'Windows Environment Setup' from here

A: *

*Download winutils.exe and hadoop.dll in your windows machine.

*create folder C:\hadoop\bin

*Copy winutils.exe and hadoop.dll in newly created hadoop folder

*Setup environment variable
HADOOP_HOME=C:\hadoop

A: On top of mentioning your environment variable for HADOOP_HOME in windows as C:\winutils, you also need to make sure you are the administrator of the machine. If not and adding environment variables prompts you for admin credentials (even under USER variables) then these variables will be applicable once you start your command prompt as administrator.

A: I have also faced the similar problem with the following details Java 1.8.0_121,
Spark spark-1.6.1-bin-hadoop2.6, Windows 10 and Eclipse Oxygen.When I ran my WordCount.java in Eclipse using HADOOP_HOME as a system variable as mentioned in the previous post, it did not work, what worked for me is -
System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR");
PATH/TO/THE/DIR/bin=winutils.exe whether you run within Eclipse as a Java application  or by spark-submit from cmd using
spark-submit --class groupid.artifactid.classname --master local[2] /path to the jar file created using maven /path
to a demo test file /path to output directory command
Example: Go to the bin location of Spark/home/location/bin and execute the spark-submit as mentioned,
D:\BigData\spark-2.3.0-bin-hadoop2.7\bin>spark-submit --class com.bigdata.abdus.sparkdemo.WordCount --master local[1] D:\BigData\spark-quickstart\target\spark-quickstart-0.0.1-SNAPSHOT.jar D:\BigData\spark-quickstart\wordcount.txt

A: That's a tricky one... Your storage letter must be capical. For example "C:\..."


text:
Q: How to stop FontAwesome adding style tag when using data-fa-transform attribute I am currently implementing Content Security Policy in my application.
My application uses FontAwesome library for icons and I use data-fa-transform attribute to operate some transformations to the icons like explained in the Power Transforms page of the docs.
When executing the page, FontAwesome adds a style="transform-origin: XXem XXem;" tag to the svg tag.
Is there any way to prevent this behavior ? This causes problem with the Content Security Policy not allowing inline style tags (and no, I do not want to use unsafe-inline which defeats the purpose of CSP alltogether).
Not using data-fa-transform ultimately solves the problem but this is a usefull feature and if I could keep using it without this inconvenience, it would be very helpful.
When searching for info, I found out that adding this style tag is apparently "on purpose" in the code.
I do not understand why through neither how to prevent this.


text:
Q: Adding re-usable content in page from same site I am facing issue with adding Re-usable content in SharePoint 2016. I have a site collection and a sub-site under sitecollection. I have added some content in re-usable content list at sub-site level. When I try to add Re-usable content in page in sub-site, it shows me entries from re-usable content list at site collection level, instead of re-usable content list in same site.
I tried to check Reusable content list ID in web properties of both root web and sub-site. Both webs have correct re-usable content list ID.
Please help me to display content from re-usable content list at sub-site level.
Thanks in advance.


text:
Q: How can I extend a class in Node JS by my custom constructor? I have the following in a Node Js model. This file exists in another project that cannot be changed but is locally available to the other projects.
module.exports = {
    base: require('*/cartridge/models/product/decorators/base'),
    availability: require('*/cartridge/models/product/decorators/availability')
};

All the methods here act like constructors of the class Product. Now I want to add another attribute that should be available when I try to access Product.badge. For this, I have tried to extend the above model in the following way:
var indexBase = require('*/cartridge/models/product/decorators/index');

indexBase.badge = require('*/cartridge/models/product/decorators/badge');

module.exports = indexBase;

But it seems throw an error, I have tried to log the Badge Type, but I still cannot access the badge type here.
I am calling the above object as the following:
var decorators = require('*/cartridge/models/product/decorators/index');
decorators.badge(product, variantProduct);

I want to know how can I extend an existing class as I want to add a custom constructor?
Here only the syntax is based on Node Js but this code is written for SFRA in Salesforce B2C Commerce.

A: All you need to do is in the index.js file:
var indexBase = module.superModule;

instead of:
var indexBase = require('*/cartridge/models/product/decorators/index');

and it will work perfectly fine.


text:
Q: A question about the residue calculus Suppose I have a convergent definite integral of the form $$\int_{-\infty}^\infty \frac{f(x)}{x^2(e^x-1)}\text{d}x,$$
where $f(x)$ has no poles, and I want to try to evaluate it using the residue calculus. I can choose the semi-circular contour $\Gamma$ with positive orientation consisting of paths $\gamma_1 = z$, for $-R\leq z\leq R$, and $\gamma_2=Re^{i\theta}$, for $0\leq\theta\leq\pi$.
Assuming the integral over $\gamma_2$ is zero, then am I right in thinking that the integral is equal to $2\pi i$ times the sum of the residues of the integrand, and that the poles occur at $x=2\pi i k$, where $k\geq 0$ is an integer?
It is this last part I am unsure of. Is this the correct way to consider the poles and calculate the residues?

A: Your contour causes problems: the integrand is not holomorphic on the real axis.
The poles are given by $z^2(\operatorname{e}^z-1) = 0$.
There is a double pole at $z=0$ and a simple pole when $\operatorname{e}^z-1=0$.
The solutions to $\operatorname{e}^z-1=0$ are $z \in \{2\pi i k : k \in \mathbb{Z}\}$. Notice that $k$ need not be positive. Any integer value of $k$ will be sufficient. For example, $\operatorname{e}^{-2\pi i} = \operatorname{e}^{2\pi i} = 1.$
In reality, you will need a so-called beehive contour where you go along the real axis from $-R$ to $-\varepsilon$, then around $\varepsilon \operatorname{e}^{-it}$ with $\pi \le t \le 2\pi$, then along the real axis from $\varepsilon$ to $R$, and then back around along $R\operatorname{e}^{i\theta}$ with $0 \le \theta \le \pi$. Then you look at the limit as $R \to \infty$ and $\varepsilon \to 0$.


text:
Q: AngularJS: How to set ng-model or change scope value from directive I have created a directive for input, select, and radio directives.
<input ng-model="data-ng-model="answers.{{name}}" is not working
Here is my HTML:

        <text-control-dir data-que-obj="que.QuestionData" data-selected-ans="answers[que.QuestionData._attributeName]"></text-control-dir>

        <select-control-dir data="que.QuestionData"></select-control-dir>

         <radio-control-dir data="que.QuestionData"></radio-control-dir>

         <hidden-control-dir data="que.QuestionData"></hidden-control-dir>

Here is my directive:
   function textControlDir()
    {
        return {
            transclude: true,
            restrict: 'E',
            /*scope: {
                queObj: '=',
                selectedAns: '='
                },*/
            template: '
\n\
                       {{queObj._text}}\n\

<input data-ng-model="answers.{{name}}" type="text" name="{{name}}" class="form-control" id="{{id}}" value="{{selectedAns}}">
\n\

',
            link: function (scope, element, attrs)
            {
                var queObj = scope.que.QuestionData;
                scope.queObj = scope.que.QuestionData;
                scope.name = queObj._attributeName;
                scope.id = queObj._attributeName;
                var selectedAns = '';
                if(scope.answers)
                {
                   selectedAns = scope.answers[scope.name];
                }
                if(selectedAns && selectedAns != '')
                {
                    scope.selectedAns = selectedAns;
                }
                else
                {
                    scope.selectedAns = scope.queObj._pageAttributes.defaultValue;
                }
            }
        };
    }

How do I dynamically manage the ng-model? I want to map $scope.answers.{{name}} when user changes anything in input box.

A: You can require ngModel.
return {
    require: 'ngModel',
}

Then you can update the ng-model accordingly using       ngModel.$setViewValue(newValue);
Below is a simple example on how can achieve the same:
http://jsfiddle.net/t2GAS/2/

A: You can do this:
 data-ng-model="name"

Now in the controller you can do this:
$scope.answers.name = name; // <--- the ng-model assigned to answer.name in $scope


text:
Q: Unable to delete a file with nodejs in protractor I'm trying to delete the file with nodejs fs and I notice that file has been generated then trying to delete (failed to delete the file) while the file is not even uploaded on browser with protractor. Generate and delete file functions are created using nodejs fs.
So how can I put them in a way then wait until file is uploaded then delete the file?
helper.generateFile(filePath);
helper.uploadFile(UploadButtonElement, filePath);
uploadButtonElm.click();
helper.deleteFile(filePath);

Is there a way to execute deleteFile only when below two actions are completed.
helper.uploadFile(UploadButtonElement, filePath);
uploadButtonElm.click();

Thanks.

A: Protractor operations schedule promises to do things.  They do not actually do them.  Thus, your helper functions will end up running well before any of the protractor code actually accomplishes what you asked.  Use then to chain your dependencies explicitly.  Like so:
helper.generateFile(filePath);
helper.uploadFile(UploadButtonElement, filePath);
uploadButtonElm.click().then(function() {
   helper.deleteFile(filePath);
});

Please read https://github.com/angular/protractor/blob/master/docs/control-flow.md and https://code.google.com/p/selenium/wiki/WebDriverJs#Understanding_the_API

A: function deleteAlreadyDownloadedFiles(extension,username) {
        let os = require('os');
        console.log('USERNAME HERE IS'+require("os").userInfo().username);
        var downloadDirectory = '/Users/'+require("os").userInfo().username+'/Downloads/';

        const fs = require('fs');
        const path = require('path');
        const directory = '/Users/'+require("os").userInfo().username+'/Downloads/';
        fs.readdir(directory, (err, files) => {
            if (err) throw err;
             for (const file of files) {
                fs.unlink(path.join(directory, file), err => {
                    if (err
                        && (err.code === "EACCES" || err.code === "EPERM")) {
                        console.log("Retrying rename file: ")
                        return;
                    }
                });
            }
        });
    }


text:
Q: Java : Reload webapp in the servlet and then redirect request I have a configuration page in my app. When user changes configuration and submits it, I would like to reload my application with new configuration properties and then redirect to some page. I was able to reload my application using some suggestions I found here
Start / stop a web application from itself?
but I am not able to redirect to new page after the application has reloaded.
More details.
public class ConfigurationServlet extends HttpServlet implements ContainerServlet{

    private static final long serialVersionUID = 1L;
    private SalsaEnvironment salsaEnv;
    protected Host host = null;
    protected Wrapper wrapper = null;
    protected Context context = null;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // update configuration properties
        .
        .
        .

        // reload app once configuration is changed
        restartWebApp(resp.getWriter(), "/salsadb");

        // simple redirect/forward - does not work - gives following exception
        // java.lang.NullPointerException org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
        //resp.sendRedirect("/salsadb/account");
        //req.getRequestDispatcher("/account");

        // invalid old session, create a new one and try to redirect - does not work
        req.getSession(false).invalidate();
        req.getSession(true);
        req.getRequestDispatcher("/account");
    }

    @Override
    public Wrapper getWrapper() {
        // TODO Auto-generated method stub
        return this.wrapper;
    }

    @Override
    public void setWrapper(Wrapper wrapper) {
        this.wrapper = wrapper;
        if (wrapper == null) {
            context = null;
            host = null;
        } else {
            context = (Context) wrapper.getParent();
            host = (Host) context.getParent();
            Engine engine = (Engine) host.getParent();
            try {
            } catch (Exception e) {
                // ?
            }
        }
    }

    private void restartWebApp(PrintWriter writer, String path){
        if ((path == null) || (!path.startsWith("/") && path.equals(""))) {
            System.out.println("invalid path");
            return;
        }
        String displayPath = path;
        if( path.equals("/") )
            path = "";

        try {
            Context context = (Context) host.findChild(path);
            if (context == null) {
                /*writer.println(sm.getString
                               ("managerServlet.noContext",
                                   RequestUtil.filter(displayPath)));*/
                System.out.println("no context");
                return;
            }

            context.reload();
            //writer.println(sm.getString("managerServlet.reloaded", displayPath));
            System.out.println("reloaded webapp");
        } catch (Throwable t) {
            log("ManagerServlet.reload[" + displayPath + "]", t);
            /*writer.println(sm.getString("managerServlet.exception",
                                        t.toString()));*/
            System.out.println("excpetion during reloading the webapp");
        }
    }

A: You'll probably not be able to do that as your server-side code has just been restarted.
I'd recommend an AJAX based client-side approach, where you constantly ping some servlet of yours until app is "back up" and then move to the new page via JavaScript.
For this to work, you'd first send the redirect to the reload-checking page and then (say after 1s to allow the browser fetch the redirected page) initiate the restart:
    req.getSession(false).invalidate();
    req.getSession(true);
    resp.sendRedirect("check_restart_status.jsp");
    //Use a timer or whatever
    new Thread(() -> {
        try{
          Thread.sleep(5000);
        } catch(InterruptedException ie) {
          return;
        }
        restartWebApp("/salsadb");
    }).start();


text:
Q: Tiled .tmx Image rendering with SpriteKit and Swift I have created a tiled .tmx file to create an orthogonal maze type game (my first attempt at writing a game). Is there a customary way to render images in iOS using SpriteKit?
There doesn't seem to be much written about this with regards to Swift. Some pointers in the right direction is all I need.


text:
Q: How to connect & deactivate Azure Active Directory through PowerShell While trying to connect to Azure AD with cmdlets Connect-MsolService it prompts for credentials but I am a bit confuse which credentials I have to provide than through cmdlets Get-Credentials I have got the credentials but that also didn't work.
However my aim is to connect to Azure AD through powershell & also activate/deactivate or start/stop Azure AD through powershell...Please put some light on this or provide some help...

A: When you use the PowerShell and Connect-MsolService you have to provide the target directory admin account - an account with full administrative permissions on the Directory tenant. And currently you cannot just provide credentials, you have to use that window that prompts for credentials.
However I don't really understand what you mean by start/stop Azure AD. Azure AD is a cloud service that runs constantly. You cannot start or stop it. You have it. You may disable user accounts in it, but you certainly cannot stop the service. If you better describe your question it will be easier to help you!


text:
Q: Is there a way to create arrow subSymbol on top of geometry generated symbol using PyQGIS? Currently, I am trying to figure out how to set a subsymbol for a PyQGIS generated geometrygeneratorsymbol layer. As can be found in the code I tried multiple things resulting in crashing the kernel or nothing at all. The images represent the manual workflow which works fine. I am interested in transferring this 'Simple line' option to 'Arrow' in an automated way.
from qgis.core import (
    QgsVectorLayer,
    QgsSingleSymbolRenderer,
    QgsLineSymbol,
    QgsFillSymbol,
    QgsProject,
    QgsRectangle,
    QgsArrowSymbolLayer,
    QgsMultiRenderChecker,
    QgsProperty,
    QgsSymbolLayer,
    QgsMapSettings,
    QgsSymbol
)

from qgis.core import QgsVectorLayer,  QgsProject
layer = QgsVectorLayer( "?query=SELECT from_country, ubc_processing_plant, delivered_tonnes_2019, make_line(Centroids_countries.geometry, UBC_processing_2030.geometry) FROM ubc_flows JOIN Centroids_countries ON ubc_flows.from_country = Centroids_countries.NUTS_NAME JOIN UBC_processing_2030 ON ubc_flows.ubc_processing_plant = UBC_processing_2030.name", "vlayer", "virtual" )
QgsProject.instance().addMapLayer(layer)

def test_3(self):
        sym = self.renderer().symbol()

        shape_sym = QgsGeometryGeneratorSymbolLayer.create({'geometryModifier': 'difference(difference(make_line(start_point($geometry), centroid(offset_curve($geometry, length($geometry)/-10.0)), end_point($geometry)), buffer(start_point($geometry), 10000)), buffer(end_point( $geometry), 10000))', 'outline_color': 'black', 'symbolType': '1'})
        shape_sym.setSymbolType(QgsSymbol.Line)

        arrow = QgsArrowSymbolLayer.create(
            {
                "arrow_width": "3",
                "head_length": "3",
                "head_thickness": "3",
                "head_type": "0",
                "arrow_type": "0",
                "is_curved": "1",
                "arrow_start_width": "3"
            }
        )
        fill_sym = QgsFillSymbol.createSimple(
            {"color": "#8bcfff", "outline_color": "#000000", "outline_style": "solid", "outline_width": "0.1"}
        )

        #shape_sym.setSubSymbol(arrow)
        #shape_sym.setSubSymbol(sym_layer)
        sym.changeSymbolLayer(0, shape_sym)

test_3(layer)

A: The answer to set a subsymbol in PYQGIS qgis 3.x
Replace the sub symbol with the new marker symbol:
shape_sym.subSymbol().changeSymbolLayer(0, arrow)


text:
Q: Please How to Parse a Web Site with PHP I do a simple project in my department. I want to call the movie at the movie site, but I don't know how to write a regular expression. I've tried everything in a variety of ways, but I can't. I don't know how to fill out the code. Let me know. I am not using jquery, but I am only using simple html dom, snooping.

A: If what you want is to have a list of all times, put them in a n array with something like this(you do not need regex for this if you are usin php dom parser):
$timesArray = [];
foreach($html->find('div[class=info-timetable] li a em') as $times) {
        $timesArray[] = $times->plaintext;
};

PS: Never post images with your code, instead paste the code in your question mate!


text:
Q: NSLayoutManager glyph generation and caret position I have a text editor app, which uses Markdown-style formatting. Formatting characters are hidden when caret/selection is not on the corresponding line.
I'm successfully using shouldGenerateGlyphs: method in NSLayoutManagerDelegate to manipulate what is drawn on NSTextView. I'm using pure delegation and haven't subclassed the layout manager itself.
However, I can't understand how I can position the caret correctly after glyph regeneration. After selection has changed, I'm calling a method (here called hideAndShowMarkup) which regenerates glyphs for both the line currently edited and the one that was selected earlier. Because some glyphs are added on screen, caret gets rendered wrong.
-(void)hideAndShowMarkup {
    [self.layoutManager invalidateGlyphsForCharacterRange:currentLine.range changeInLength:0 actualCharacterRange:nil];
    [self.layoutManager invalidateGlyphsForCharacterRange:prevLine.range changeInLength:0 actualCharacterRange:nil];

    [self.layoutManager ensureGlyphsForCharacterRange:currentLine.range];
    [self.layoutManager ensureGlyphsForCharacterRange:prevLine.range];

    [self updateInsertionPointStateAndRestartTimer:YES];
}

updateInsertionPoint... doesn't work here, as ensuring glyphs seems to run asynchronously.  I've tried calling it in didCompleteLayoutForTextContainer: delegate method too, but to no effect.
Is there a way to detect when the glyphs have actually been drawn, and to ensure insertion point position after that?

A: NSLayoutManager is surprisingly poorly documented, and understanding its inner workings required looking through implementations in random public repositories.
To change glyphs in a range and have the caret position correctly, you first need to invalidate glyphs for both of the changed ranges, and then invalidate the layout for the range the caret is about to be positioned in.
Then, after making sure that there is a current graphic context, glyphs can be redrawn synchronously. After this, updating insertion point works normally.
In the example below, I have two objects, line and prevLine which contain ranges for both the line on which caret is positioned now, and the one caret moved away from.
-(void)hideAndShowMarkup {
    [self.layoutManager invalidateGlyphsForCharacterRange:line.range changeInLength:0 actualCharacterRange:nil];
    [self.layoutManager invalidateGlyphsForCharacterRange:prevLine.range changeInLength:0 actualCharacterRange:nil];
    [self.layoutManager invalidateLayoutForCharacterRange:line.range actualCharacterRange:nil];

    if (NSGraphicsContext.currentContext) {
        [self.layoutManager drawGlyphsForGlyphRange:line.range atPoint:self.frame.origin];
        [self.layoutManager drawGlyphsForGlyphRange:prevLine.range atPoint:self.frame.origin];
    }

    [self updateInsertionPointStateAndRestartTimer:NO];
}


text:
Q: Extracting Numeric Data from a Field Using SQL I have a column in an Access table with data that is a string of HTML text, and within the text are numeric data points that I want to separate out, like "Number of Customers", "Sales", and "Profit".
For example, one item in the field sales_description could be "The Number of Customers on 11/27/2020 was 99 with Sales: 967 and Profit: 190"
So far, I've been using the REPLACE function in SQL to remove common characters that I don't want. Now, I want to see if I can use TRIM and SPLIT to get three columns for # Customers, Sales, and Profit.
For this example, the query to pull everything from the table and remove some HTML text is:
SELECT order_id, order_date, REPLACE(REPLACE(sales_description, '', ''), '', '')
FROM sales_data;
I want to write a query where the results to have the following fields and value types:

order_id (ex: 0143823)
order_date (ex: 11/27/2020)
num_customers (ex: 35)
sales (ex: 280)
profit (ex: 56)

Thank you for any help you can lend, and let me know if I should provide more details.

A: There is no ID to extract, but the Number, Sales, and Profit are pretty easy to pull using VBA:
? Val(Split(s, "Sales: ")(1))
 967
? Val(Split(s, "Profit: ")(1))
 190
? Val(Split(s, " was ")(1))
 99

The date takes a little more:
? CDate(Split(Split(s, "Number of Customers on")(1), " ")(1))
2020-11-27

You can write a wrapper function to call these from SQL to extract the values.