Importing Ramda in Electron app builded by Rollup leads to error

Question: I'm trying to create a simple app using such stack (snippet from package.json with lib versions):
"electron": "^5.0.6"
"ramda": "^0.26.1"
"rollup": "^1.17.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.0.1",
"rollup-plugin-copy-glob": "^0.3.0",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-svelte": "^5.1.0",
"svelte": "^3.6.7"

and stumbled upon with an issue with importing ramda library: the problem is that if I import ramda in both renderer and main process of electron app, I get the following error:
Error: Cannot find module './chunk-ae261ffc.js'
Require stack:
- <path>/index.html
    at Module._resolveFilename (internal/modules/cjs/loader.js:659:15)
    at Function.Module._resolveFilename (<path>/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar/common/reset-search-paths.js:43:12)
    at Function.Module._load (internal/modules/cjs/loader.js:577:27)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at <path>/dist/renderer.js:3:18

My rollup config looks like:
export default [
    {
        input: ['src/entries/main.js', 'src/entries/renderer.js'],
        output: {
            dir: 'dist',
            format: 'cjs',
            sourcemap: true
        },
        plugins: [
            svelte({
                css: css => {
                    css.write('dist/svelte.css');
                }
            }),
            resolve(),
            commonjs()
        ],
        external: ['electron', 'child_process', 'fs', 'path', 'url', 'module', 'os']
    }
];

I use ramda in root component inside renderer process (App.svelte component):

{q()}

and within the entry file of the main process:
import * as R from 'ramda';

The strangest thing (as for me) is that if I comment any of ramda's import above then no error is thrown. Otherwise, I get the error I described in the beginning of this question
Upd
With @ScottSauyet's help, it makes clear that it could be working by replacing import with require. Yet I don't think it's an appropriate solution (rollup configuration should be changed instead, imho).
Comment: @user1820686 [try this](https://github.com/clitetailor/stackoverflow/tree/master/questions/57134084). It works find on my system.
Comment: Does this go away if you  do `import {always, ...} from 'ramda'`?  I know some similar bundling issues have for some people.
Comment: @ScottSauyet, unfortunately, it doesn't help. But...it seems to be working with `require`
Comment: I'm just surprised to see that the import statement in your html works at all (i.e. ``. Have a look at this [question](https://stackoverflow.com/q/37736836/1244884); I'd recommend using `require()` in your renderer scripts too.
Comment: @customcommander, thanks for you reply and link to question, but I guess it's not related to `import` or `require` usage inside html, because this code snippet is placed in .svelte component transpiled to JS. I'm going to update the question to remove this ambiguity
Comment: It seems like the share chunk `./chunk-ae261ffc.js` does not exists or can not be created. Have you check it in dist folder? imo, i think you should upgrade rollup to the newest version. There's no `experimentalCodeSplitting` and `experimentalDynamicImport` on the newest version. That might the reason why error occurs!
Comment: @CliteTailor, I've just tried to update rollup and remove incorrect properties in config, but unfortunately it didn't help
Comment: @customcommander: It's not a regular html file, it's a `.svelte` source file, so it will look different after compilation.
Comment: @CliteTailor, amazing, thanks for the sample. Your code is working on my system too...going to find what's the difference. Seems to be quite identical at first glance
Comment: @CliteTailor, if you would like, you could post your own answer with the fix I suggested as my answer. In that case, I will remove my answer and accept yours. Thanks for your help!
Comment: @user1820686 Not necessary, your answer is clear enough. You can mark it the right answer. If you like, you can give my github repo 1 star.
Answer: First of all, I greatly appreciate @CliteTailor's effort. This answer, by and large, based on his support.
The problem was in the snippet that I didn't copy to the original question.
I left my index.html file in root folder (it's being used in the renderer process) 'as-is' - didn't copy it in dist folder with other compiled code and used such link to this file:

According to @CliteTailor's code, I've just my some changes:
1) added copying of index.html to the dist folder in rollup.config.js:
export default [
    {
        input: ['src/entries/main.js', 'src/entries/renderer.js'],
        output: {
            dir: 'dist',
            format: 'cjs',
            sourcemap: true
        },
        plugins: [
            svelte({
                css: css => {
                    css.write('dist/svelte.css');
                }
            }),
            resolve(),
            commonjs(),
            copy({
                targets: [{ src: 'index.html', dest: 'dist' }]
            })
        ],
        external: ['electron', 'child_process', 'fs', 'path', 'url', 'module', 'os']
    }
];

2) replaced calling this index.html from the main file of the renderer process:
// old code
win.loadFile(path.resolve(__dirname, '../index.html'));
// fixed code
win.loadFile(path.resolve(__dirname, 'index.html'));

3) changed a link to compiled renderer file in index.html:

And now everything is working fine.


R Neural Net Issues

Question: Here is the updated code.   My issue is with the output of "results".  I'll post below as the format for readability.
library("neuralnet")
    library("ggplot2")
    setwd("C:/Users/Aaron/Documents/UMUC/R/Data For Assignments")
    trainset <- read.csv("SOTS.csv")
    head(trainset)
    ## val data classification
    str(trainset)
    ## building the neural network
    risknet <- neuralnet(Overall.Risk.Value ~ Finance + Personnel + Information.Dissemenation.C, trainset, hidden = 10, lifesign = "minimal", linear.output = FALSE, threshold = 0.1)
    ##plot nn
    plot(risknet, rep="best")

    ##import scoring set
    score_set <- read.csv("SOSS.csv")
    ##select subsets-training and scoring match
    score_test <- subset(score_set, select = c("Finance", "Personnel", "Information.Dissemenation.C"))
    ##display values of score_test

    head(score_test)
    ##neural network compute function score_test and the neural net "risknet"
    risknet.results <- compute(risknet, score_test)

    ##Actual value of Overall.Risk.Value variable wanting to predict. net.result = a matrix containing the overall result of the neural network
    results <- data.frame(Actual = score_set$Overall.Risk.Value, Prediction = risknet.results$net.result)
    results[1:14, ]

The output of results is not as expected.  For instance, the actual data is a number between 5 and 8, whereas "Prediction" displays outputs of .9995...for each result.
Thanks again for the help.
Comment: What's your so called "scoring" set? A validation set or a test set?
Comment: The scoring set is the exact same data as the training set (shown within the variable risknet).  The only difference is the value for Overall.Risk.Value
Answer: The default activation function in neuralnet is "logistic". When linear.output is set as FALSE, it ensures that the output is mapped by the activation function to the interval [0,1].(R_Journal (neuralnet)- Frauke Günther)
I just updated linear.output=TRUE in your code and final result looks much better.
Thanks for the help!
Comment: Was this a comment for my answer? If you find any answer that helps, add a coment and upvote/aceept the answer instead of posting a new one!
Answer: This is how you train and predict:

Use training data to learn model parameters (the variable risknet in your case)
Use parameters to predict scores on test data

Here is an example very much similar to yours that explains how this is done.

R Neural Net Issues


Notation for flute trills in music score

Question: I'm only playing simple pieces (Grade 1 in the UK) but even some of these have Tr notation next to a note, and a separate bit of score above the score.
What I notice is, the note in the main score is nothing like the notes shown in the trill pattern. e.g:

How should the trill "mini-score" be read? It's optional in my pieces but I'd at least like to know what it means.
By the way this is in the key of G-major, so F->F#.
Comment: You'll be okay to just post a bar or two. And it would really help us work out an answer for you. If you really don't want to copy the music, you could write a bit of it out by hand and post it.
Answer: That shows the note above the printed one to be played first (G), then the F, then G and F again, before the tune note of E, (printed), followed by the last E in the bar.The stave lines are not special, except that a note shown on a line belongs on a line. In this case, the two lines of stave shown happen to be the E and G lines.    Or the F might be F#...
Comment: Yeah, probably is F#, looks like a cadential figure in E Minor. Could be G# too, if it's E Major...!
Comment: @BobBroadley - it's grade 1, not too sure! Are your notes o.k?  Emin sound probable.
Comment: Ah yes, good point, probably no G#s at Grade 1! @MrBoy, might be good if you let other readers know what the key signature is.
Comment: Oh yes, the F is sharp in the key signature so it's in G/Em (I assume the former)
Answer: I'm guessing this is probably baroque music. In this period trills and other ornaments have specific ways they should be played; for a trill it is common to start a trill on the note above the one marked. In this case, the notes represented above the flute part are G F G F E. It's pretty unhelpful that they don't show all five stave lines, but I guess the editor is just trying to save space!
Answer: I'm also doing a little bit guessing:
Given that the small notes fill exactly the time of the trill with the slurred eighth note, I assume, it is a simplification: typically a trill would repeat its base note more than once, often much more than once, depending on the time avaliable, which is influenced by the tempo. So I guess, the statement of the editor is as follows: if you are a little bit timid concerning the trill, try at least these given notes as a sort of minimum embellishment. In a real score this would be signalled using "ossia" translating to "alternative".


$z^3 + z + 1 = 0,\quad z \in \mathbb C$ \ $\mathbb R, \quad$ prove $|z| \in (1, \sqrt2)$

Question: $z^3 + z + 1 = 0,\quad z \in \mathbb C$ \ $\mathbb R, \quad$ prove $|z| \in (1, \sqrt2)$
$z = a + ib$
(I have the solution for this problem, but I don't understand the following part of it):
Now, I got $$a^2+b^2 > 1$$
But I don't understand how this implies $$z < 1$$
and then how do we get $$|z|^3 = |z+1|$$
Can someone explain this to me? (I don't need you to solve the entire problem for me, as I understand the other parts of the solution. But if you are interested or have time you can do it)
Comment: $z<1$ does not make sense, since $z$ is a non-real number.
Answer: If you can show that a solution $z=a+bi$ to the equation $z^3+z+1=0$ must have the property that $a^2+b^2>1$ then you are implying that $|z|>1$ by definition of the absolute value of a complex number, not that $|z|<1$. But that's half of what we needed to show anyway, that $|z|\in(1,\sqrt{2})$.
To see that $|z^3|=|z+1|$ just rearrange your equation and take absolute values:
$$
z^3+z+1=0 \quad \Leftrightarrow \quad z^3=-z-1 \quad \Rightarrow \quad |z^3|=|-z-1|=|z+1|
$$
Comment: It said in the solution that $z<1$, which confused me but I'm new to complex numbers so I thought I was missing something. I guess that's just not correct. I understand the whole solution now thanks for answer.


Squid takes 2 minutes to cache a small pdf

Question: We are having a problem that certain pdf from a specific url take a long time to display. Squid seems to use a long time to cache it (over 2 minutes) for 110kb. If I browse this pdf without going through squid it works perfectly.
1359106030.833 120114 184.108.40.206 TCP_MISS/200 116194 GET http://www2.zhlex.zh.ch/appl/zhlex_r.nsf/0/9429732E0BEDB5EDC12574C60044A4CC/$file/xxx.pdf - DIRECT/188.8.131.52 application/pdf

You can also see the gap on tcpdump

It exists on our Squid 3.1 but also on Squid 3.2. It only occurs on pdfs from that url. Other pdf are working fine.
It can not be their server as it works smooth without going through the proxy
This is our sanitized config. It has been taken over from old squid versions and have not been ajusted since then.
acl manager proto cache_object
acl localhost src 127.0.0.1/32
acl bigip src xx.xx.xx.xx/32
acl to_localhost dst 127.0.0.0/8
acl monhost   src xx.xx.xx.xx/32
acl srv-ts-057   src xx.xx.xx.xx/32
acl srv-ts-058   src xx.xx.xx.xx/32
acl snmppublic snmp_community Fast3thernet
acl xxnet src xx.xx.xx.xx/16       # xx
acl xxnet src xx.xx.xx.xx/32   # HSWNAT
acl xxnet src xx.xx.xx.xx/16           # VoIP
acl xxnet src xx.xx.xx.xx/22       # HAP
acl xxnet src xx.xx.xx.xx/22      # HSSAZ
acl xxnet src xx.xx.xx.xx/24       # Management Netz 1
acl xxnet src xx.xx.xx.xx/24       # Management Netz 2
acl xxnet src xx.xx.xx.xx/24      # FET-DEV
acl xxnet src xx.xx.xx.xx/24      # FET-TEST
acl xxnet src xx.xx.xx.xx/24      # BET-DEV
acl xxnet src xx.xx.xx.xx/24      # BET-TEST
acl xxnet src xx.xx.xx.xx/24      # FET-VDP
acl xxnet src xx.xx.xx.xx/24      # FET-VDP
acl STAFFMGR src xx.xx.xx.xx/26
acl SSL_ports port 443 8443 28443 50001
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT
acl MONxxCH dstdomain mon.xx.ch
acl ZREG dstdomain zreg.xx.ch
acl PUT method PUT
http_access allow PUT xxnet
http_access deny PUT
acl PURGE method PURGE
http_access allow PURGE localhost
http_access deny PURGE
acl PROPFIND method PROPFIND
http_access allow PROPFIND srv-ts-057
http_access allow PROPFIND srv-ts-058
http_access deny PROPFIND
http_access allow manager localhost
http_access deny manager
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access deny to_localhost
http_access deny !STAFFMGR MONxxCH
http_access deny !STAFFMGR ZREG
http_access allow xxnet
http_access deny all
icp_access deny all
follow_x_forwarded_for allow localhost
follow_x_forwarded_for allow bigip
acl_uses_indirect_client on
delay_pool_uses_indirect_client on
log_uses_indirect_client on
http_port 22.214.171.124:8080
hierarchy_stoplist cgi-bin ?
cache_mem 768 MB
maximum_object_size_in_memory 32 KB
cache_dir ufs /var/cache/squid 25000 64 256
coredump_dir /var/cache/squid
#access_log /var/log/squid/access.log
#cache_log /var/log/squid/cache.log
cache_store_log none
#pid_filename /var/run/squid.pid
ftp_user firstname.lastname@example.com
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320
acl shoutcast rep_header X-HTTP09-First-Line ^ICY.[0-9]
acl apache rep_header Server ^Apache
request_timeout 30 seconds
cache_mgr firstname.lastname@example.com
#mail_from email@example.com
#mail_program /usr/local/bin/mutt
cache_effective_user squid
cache_effective_group squid
httpd_suppress_version_string on
visible_hostname srv-app-901.xx.ch
unique_hostname srv-app-901.xx.ch
snmp_port 3401
snmp_access allow snmppublic monhost
snmp_access deny all
snmp_incoming_address xx.xx.xx.xx
snmp_outgoing_address 255.255.255.255
icp_port 0
allow_underscore off
dns_retransmit_interval 3 seconds
dns_timeout 1 minute
dns_nameservers xx.xx.xx.xx
append_domain .xx.ch
max_filedescriptors 8192

Any idea what could cause this ?
Comment: The [squid blog](http://squidproxy.wordpress.com/2012/07/14/happy-eyeballs/) confirms incomplete implementation of "[Happy Eyeballs](http://tools.ietf.org/html/rfc6555)" in version 3.2
Answer: Problem solved!
I found out that the command "host www2.zhlex.zh.ch" will end in a timeout. Squid is first looking for an AAAA record (ipv6) but we are not using ipv6. This takes the 2 minutes before it timed out and looked for an A record.
I have disabled ipv6 on the system + I have added the following lines to squid.conf to force ipv4
acl to_ipv6 dst ipv6
tcp_outgoing_address <your_proxy_ipv4_address> !to_ipv6

Now everything works!


Forgetting old finger position

Question: I have played guitar for over 2 years and I know many riffs. One thing that came to my concern today is that when I started using this exercise with a metronome (below) I wasn't able to play the starting of the Cowboys from Hell solo (Bottom) at regular speed, like I was able to before. Any tips?
<code>----------------------5678
-----------------5678-----
------------5678----------
-------5678---------------
--5678--------------------
--

-----------------------------------------------------Etc.
------------------------------------------11 12 15
----------------------11 12 15 11 12 15
--11 12 15 11 12 15
</code>
Answer: This appears to be a case of learning something to muscle memory, then forgetting it. You have at least these options.

Slow it down. You aren't required to play something fast a tempo the first time in a while.
Develop overall better technique and finger dexterity, and don't forget about your picking hand, before attempting it again.
Get more variation in your exercises. Make up some of your own, for example something that seems totally random.

And since you are a relative beginner, i advise you to make sure that when you play it again you can:

Play it with low tension in both hands and arms. Pros play stuff like this with mental effort, not physical.
Play it with good posture. I won't detail further here, so use your favorite search engine to dig or ask your teacher.
Play it without looking at tab.
Make sure all notes are appropriately even, rhythmically and dynamically.
Answer: If you aren't yet used to playing with a metronome, the added information that you must respond to while playing can overload your brain, leading to mistakes.
 Often when players start to practice with a metronome they find that their time isn't as good as they thought it was. When playing a familiar piece you may find that many small adjustments are needed to keep in time; this new cognitive burden can distract the player.
One way to improve the situation is to practice tremolo picking with the metronome. Set the metronome to a comfortable tempo (e.g. 60 bpm). Fret any note, or play any open string; it does not matter what note you play. Match the tempo with quarter-notes, alternate picking on that one note. Work on this for a few minutes until it is smooth and in time, then work on playing eighth-notes in time until this is smooth. Then play eighth-note triplets, then sixteenth-notes, then sixteenth-note triplets. Next, increase the tempo (say, 70 bpm) and start over with quarter-notes, eighth-notes, eighth-note triplets, etc. Go through this exercise, increasing the tempo slightly each time you start over, until you can't keep up any more.
This exercise is useful because it allows you to focus on your picking and on your time, on interacting with a metronome and making corrections, without other distractions. It also helps you to identify the tempos at which you will meltdown. Keep notes on which tempos you use and how far you can go without losing control. You should notice an improvement in your ability to lock in with the metronome quickly, and playing familiar pieces with the metronome set at different tempos should then come easier.
This is a good warm-up exercise for when you begin a practice session. You can extend it by adding 32nd notes, 64th notes, 5-note groupings, by starting with sixteenth-note triplets and working back to quarter-notes, etc.

Forgetting old finger position


2D Boolean Array Vertical, Horizontal, and Diagonal Assignment

Question: Honestly I'm probably overthinking this, but if you have a boolean[8][8] array and a value of true within that, how would you make all horizontal, vertical, and diagonal values true as well?
For example, given the [X], how do I make all of the other values X as well:
0 0 X 0 0  X  0 0
0 0 0 X 0  X  0 X
0 0 0 0 X  X  X 0
X X X X X [X] X X
0 0 0 0 X  X  X 0
0 0 0 X 0  X  0 X
0 0 X 0 0  X  0 0
0 X 0 0 0  X  0 0

Right now I am able to do the vertical and horizontal:
for(int i = 0; i < 8; i++){
    for (int l = 0; l < 8; l++){
        if (boolean[i][l]){
            for (int k = 0; k < 8; k++){
                boolean[i][k] = true;
                boolean[k][l] = true;}
            }
        }
   }

Answer: First off, in your loop, you need a break away variable once you find the first true value. I'd suggest a boolean isFound as one of the conditions in your for loop. Aside from that, here is how I'd go about it (NOTE: This would be placed right below the vertical/horizontal in your loop):
//positive slope diagonal
if(((i - Math.min(i, l)) + k) < 8 && ((l - Math.min(i, l)) + k) < 8)
    testArray[(i - Math.min(i, l)) + k][(l - Math.min(i, l)) + k] = true;

//negative slope diagonal
if((k) < 8 && ((l + i) - k) >= 0 && ((l + i) - k) < 8)
    testArray[k][(l + i) - k] = true;

In this example, the two diagonals are split up. For the first diagonal, I check to make sure its position is within the bounds of the array (I'll explain how i determine the position in a bit.) Secondly, I determine the starting position's X and Y value of each diagonal, located in the parentheses. Lastly, I find the positions by moving K units in the X and Y direction (step by step) from the starting position to traverse the grid with the diagonal. The same is repeated for the diagnose pointing the other way, but the X value has K subtracted, not added, as as the diagonal points to the opposite direction. Exact logic for the starting position and movement can be best found by toying with the location or drawing my algorithm out.
Eg.
Placement (Note that I added in variable to make sure to stop after finding the one true value):
    boolean notFound = true;

    for(int i = 0; i < 8 && notFound; i++){
        for (int l = 0; l < 8 && notFound; l++){
            if (testArray[i][l]){
                for (int k = 0; k < 8; k++){
                    testArray[i][k] = true;
                    testArray[k][l] = true;

                    if(((i - Math.min(i, l)) + k) < 8 && ((l - Math.min(i, l)) + k) < 8)
                        testArray[(i - Math.min(i, l)) + k][(l - Math.min(i, l)) + k] = true;

                    if((k) < 8 && ((l + i) - k) >= 0 && ((l + i) - k) < 8)
                        testArray[k][(l + i) - k] = true;
                }
                notFound = false;
             }
         }
     }

Comment: Where exactly would the code get placed. Is it inside the 3rd loop or inside the if statement in the 2nd loop? Because this code does NOT work if it's inside the 3rd loop
Answer: Here's a full working example that solves this problem. See comments in the code for more details:
public class Boolean_Array
{
    private static final int SIZE = 8;

    public static void main(String[] args)
    {
        // create the boolean array
        boolean [][] boolArr = new boolean [SIZE][SIZE];

        // 1. Set the row, col of the true
        int row = 3;
        int col = 5;

        // 2. Make the vertical, horizontal and diagonals true
        for (int i = 0; i < SIZE; i++)
        {
            // Do the vertical and horizontal
            boolArr[row][i] = true;
            boolArr[i][col] = true;

            // Do the diagonals
            setDiagonol(boolArr, row - i, col - i, i); // up and to the left
            setDiagonol(boolArr, row - i, col + i, i); // up and to the right
            setDiagonol(boolArr, row + i, col - i, i); // down and to the left
            setDiagonol(boolArr, row + i, col + i, i); // down and to the right
        }

        print(boolArr);
    }

    private static void setDiagonol (boolean [][] boolArr, int row, int col, int i)
    {
        try
        {
            boolArr[row][col] = true;
        }
        catch (java.lang.ArrayIndexOutOfBoundsException aioobe)
        {
            // catching for convenience so we don't have to check the bounds
        }
    }

    private static void print (boolean [][] boolArr)
    {
        for (int i = 0; i < SIZE; i++)
        {
            for (int j = 0; j < SIZE; j++)
            {
                System.out.print(boolArr[i][j] == true ? "X " : "0 ");
            }
            System.out.println();
        }
    }
}

Output:
0 X 0 0 0 X 0 0
0 0 X 0 0 X 0 0
0 0 0 X 0 X 0 X
0 0 0 0 X X X 0
X X X X X X X X
0 0 0 0 X X X 0
0 0 0 X 0 X 0 X
0 0 X 0 0 X 0 0

Answer: Main class
public static void main(String[] args) {
    printGrid(3, 2);
    System.out.println();

    printGrid(5, 4);
    System.out.println();

    printGrid(7, 0);
    System.out.println();
}

public static void printGrid(int x, int y) {
    boolean[][] grid = new boolean[8][8];

    for (int i = 0; i < grid.length; i++) {
        for (int l = 0; l < grid[0].length; l++) {

            // horizontal and vertical
            if (x == i || y == l) {
                grid[i][l] = true;
            }

            // diagonals
            if (Math.abs(x - i) == Math.abs(y - l)) {
                grid[i][l] = true;
            }

            System.out.print(String.format("%-2s", grid[i][l] == true ? "X" : "O"));
        }

        System.out.println();
    }
}

Output
X O X O X O O O
O X X X O O O O
X X X X X X X X
O X X X O O O O
X O X O X O O O
O O X O O X O O
O O X O O O X O

O O O O X O O O
X O O O X O O O
O X O O X O O X
O O X O X O X O
O O O X X X O O
X X X X X X X X
O O O X X X O O
O O X O X O X O

X O O O O O O X
X O O O O O X O
X O O O O X O O
X O O O X O O O
X O O X O O O O
X O X O O O O O
X X O O O O O O
X X X X X X X X


Show that $R/I$ is a field, where $R$ is a PID , where $I$ is a nonzero prime ideal.

Question: Let $I \neq \{0\} $ be a proper ideal of a $PID$ $R$ such that the quotient ring $R/I$ has no zero divisors.
I have a problem in showing that $R/I$ is a field.
Help Needed!!
Comment: So what do you know about PID? $R/I$ being a integral domain means $I$ is a non zero prime ideal. Doe this help?
Answer: Are you familiar with prime and maximal ideals?  The assumption is that $I$ is prime.  $R/I$ is a field iff $I$ is maximal.  So you'd like to show that nonzero prime ideals in a PID are maximal.  Can you do that?
Comment: @Loper if $R$ is not commutative then the quotient need not be a field. A PID is generally defined to be commutative.
Comment: but here it is not given that R is commutative
Comment: Normally a PID is assumed commutative.
Answer: First prove that $I$ is prime:
let $ab\in I$ for $a,b\in R$ then. $ab+I=I\implies (a+I)(b+I)=I \implies a+I\in I\ or\ b+I\in I$
since $R/I$ has no zero divisors
Thus $I$ is prime and in a PID every non zero prime ideal is maximal
Answer: $I$ is generated by a single element $p$. The fact that $R/I$ has no zero divisors mean that if $ab\in R$ is divisible by $p$, then either $a$ is divisible by $p$ or $b$ is. Thus $p$ is prime. The maximal nonzero ideals in a PID are exactly the ideals generated by a single prime element. Thus $I$ is a maximal ideal, hence $R/I$ is a field.


What to do when cursor.movetofirst is false (SQLite)

Question: I'm working on a project using SQLite.
I did create my db a while ago and so on but yesterday i uninstall my app from the phone and tryed to run it again via eclipse and it seems that since that moment, it doesn't work anymore.
first the code :
my SQLHelper :
<code>    public class SQLHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "listopresto";

public static final String TABLE_CATEGORIES = "categories";
public static final String CATEGORY_NAME = "name";
public static final String CATEGORY_ID = "id";
public static final String CATEGORY_ID_PARENT = "parent_id";
public static final String CATEGORY_URL_IMAGE = "image_url";

public static final String TABLE_SHOPPING_LIST = "shopping_list";
public static final String SHOPPING_LIST_ID = "shopping_list_id";
public static final String SHOPPING_LIST_NAME = "shopping_list_name";
public static final String SHOPPING_LIST_DATE_CREATION = "shopping_list_date_creation";

public static final String TABLE_SHOPPING_LIST_ITEMS = "shopping_list_items";
public static final String SHOPPING_LIST_ITEMS_LIST_ID = "shopping_list_items_list_id";
public static final String SHOPPING_LIST_ITEMS_ID = "shopping_list_items_id";
public static final String SHOPPING_LIST_ITEMS_NB_ITEMS = "shopping_list_items_nb_items";
public static final String SHOPPING_LIST_ITEMS_CHECKED = "shopping_list_items_checked";

public static final String TABLE_INFOS = "infos";
public static final String INFOS_AGE = "age";
public static final String INFOS_MAIL = "mail";
public static final String INFOS_DISPLAY_PRICE = "display_price";
public static final String INFOS_TOKEN = "token";
public static final String INFOS_REFRESH_TOKEN = "refresh_token";
public static final String INFOS_TOKEN_EXPIRATION = "token_expiration";
public static final String INFOS_REFRESH_TOKEN_EXPIRATION = "refresh_token_expiration";
public static final String INFOS_APP_VERSION = "app_version";

public static final String TABLE_ITEMS = "items";
public static final String ITEM_ID = "id";
public static final String ITEM_NAME = "name";
public static final String ITEM_CATEGORY_ID = "item_category_id";
public static final String ITEM_PRICE = "item_price";

public SQLHelper(Context context){
    super(context, DATABASE_NAME, null, 25);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE_CATEGORIES = "CREATE TABLE " + TABLE_CATEGORIES + "(" + CATEGORY_NAME + " TEXT," + CATEGORY_ID + " INTEGER, " + CATEGORY_ID_PARENT + " INTEGER," + CATEGORY_URL_IMAGE + " TEXT" + ")" ;
    String CREATE_TABLE_INFOS = "CREATE TABLE " + TABLE_INFOS + "(" + INFOS_AGE + " INTEGER," + INFOS_MAIL + " TEXT," + INFOS_DISPLAY_PRICE + " TEXT," + INFOS_TOKEN + " TEXT," + INFOS_REFRESH_TOKEN + " TEXT," + INFOS_TOKEN_EXPIRATION + " TEXT, " + INFOS_REFRESH_TOKEN_EXPIRATION + " TEXT, " + INFOS_APP_VERSION + " TEXT" + ")";
    String CREATE_TABLE_ITEMS = "CREATE TABLE " + TABLE_ITEMS + "(" + ITEM_ID + " INTEGER," + ITEM_NAME + " TEXT," + ITEM_CATEGORY_ID + " INTEGER," + ITEM_PRICE + " REAL" + ")";
    String CREATE_TABLE_SHOPPING_LIST = "CREATE TABLE " + TABLE_SHOPPING_LIST + "(" + SHOPPING_LIST_ID + " INTEGER," + SHOPPING_LIST_NAME + " TEXT," + SHOPPING_LIST_DATE_CREATION + " TEXT" + ")";
    String CREATE_TABLE_SHOPPING_LIST_ITEMS = "CREATE TABLE " + TABLE_SHOPPING_LIST_ITEMS + "(" + SHOPPING_LIST_ITEMS_LIST_ID + " INTEGER," + SHOPPING_LIST_ITEMS_ID + " INTEGER," + SHOPPING_LIST_ITEMS_NB_ITEMS + " INTEGER," + SHOPPING_LIST_ITEMS_CHECKED + " INTEGER" + ")";
    db.execSQL(CREATE_TABLE_CATEGORIES);
    db.execSQL(CREATE_TABLE_INFOS);
    db.execSQL(CREATE_TABLE_ITEMS);
    db.execSQL(CREATE_TABLE_SHOPPING_LIST);
    db.execSQL(CREATE_TABLE_SHOPPING_LIST_ITEMS);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIES);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_INFOS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHOPPING_LIST);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHOPPING_LIST_ITEMS);
    onCreate(db);
}
/*
 *
 *  METHODES TABLE INFOS
 * z
 */

public void addInfos(InfosModel infos){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
     values.put(INFOS_AGE, infos.getAge());
     values.put(INFOS_MAIL, infos.getMail());
     values.put(INFOS_DISPLAY_PRICE, infos.getDisplayPrice());
     values.put(INFOS_TOKEN, infos.getToken());
     values.put(INFOS_REFRESH_TOKEN, infos.getRefreshToken());
     values.put(INFOS_TOKEN_EXPIRATION, infos.getTokenExpiration());
     values.put(INFOS_REFRESH_TOKEN_EXPIRATION, infos.getRefreshTokenExpiration());
     values.put(INFOS_APP_VERSION, infos.getAppVersion());
     db.insert(TABLE_INFOS, null, values);
     db.close();
}

public void updateInfos(InfosModel allInfos){
    String Query = "UPDATE " + TABLE_INFOS +
                         " SET " + INFOS_AGE + "=" + allInfos.getAge() +
                         ", " + INFOS_MAIL + "=\"" + allInfos.getMail() + "\""+
                         ", " + INFOS_DISPLAY_PRICE + "=\"" + allInfos.getDisplayPrice() + "\"" +
                         ", " + INFOS_TOKEN + "=\"" + allInfos.getToken() + "\"" +
                         ", " + INFOS_REFRESH_TOKEN + "=\"" + allInfos.getRefreshToken() + "\"" +
                         ", " + INFOS_TOKEN_EXPIRATION + "=\"" + allInfos.getTokenExpiration() + "\"" +
                         ", " + INFOS_REFRESH_TOKEN_EXPIRATION + "=\"" + allInfos.getRefreshTokenExpiration() + "\"" +
                         ", " + INFOS_APP_VERSION + "=\"" + allInfos.getAppVersion() + "\"";
    SQLiteDatabase db = this.getReadableDatabase();
    db.execSQL(Query);
}

public InfosModel getInfos(){
    String selectQuery = "SELECT * FROM " + TABLE_INFOS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor != null){

        if (cursor.moveToFirst()){
            InfosModel infos = new InfosModel();
            infos.setMail(cursor.getString(cursor.getColumnIndex(INFOS_MAIL)));
            infos.setAge(cursor.getInt(cursor.getColumnIndex(INFOS_AGE)));
            infos.setDisplayPrice(cursor.getString(cursor.getColumnIndex(INFOS_DISPLAY_PRICE)));
            infos.setToken(cursor.getString(cursor.getColumnIndex(INFOS_TOKEN)));
            infos.setRefreshToken(cursor.getString(cursor.getColumnIndex(INFOS_REFRESH_TOKEN)));
            infos.setTokenExpiration(cursor.getString(cursor.getColumnIndex(INFOS_TOKEN_EXPIRATION)));
            infos.setRefreshTokenExpiration(cursor.getString(cursor.getColumnIndex(INFOS_REFRESH_TOKEN_EXPIRATION)));
            infos.setAppVersion(cursor.getString(cursor.getColumnIndex(INFOS_APP_VERSION)));
            cursor.close();
            return (infos);
        }
    }
    return (null);
}

public int getInfosCount() {
    String countQuery = "SELECT  * FROM " + TABLE_INFOS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
 }
}
</code>
the java activity where i'm using the function getInfo:
<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_screen);
    SQLHelper sqlHelper = new SQLHelper(this);
    InfosModel infos = sqlHelper.getInfos();
    Log.i("infos", infos.getMail());
 }
</code>
The problem comes from the getInfos() function i believe.
My cursor isn't null but the function moveToFirst() fails but i don't know why and i don't know what to do to fix this since i've never had that problem before and my database was working well ..
thank you for the help :)
bottus.
edit : i tryed to see how many row i'm having in the infos table, there is zero row and that's why movetofirst() fail i believe but the behavior is exactly the same if i had a row in the table ..
Comment: WHat's the error you get?
Answer: Per the Android documents:

This method will return false if the cursor is empty.

So you must not have any data there, and you should manage appropriately. Check for typos, etc.
Comment: see : edit : i tryed to see how many row i'm having in the infos table, there is zero row and that's why movetofirst() fail i believe but the behavior is exactly the same if i had a row in the table ..
Comment: The behavior is not the same if there is any number of rows, I use this all the time. If you want to see how many rows there are, see Cursor.getCount(), that should let you verify the number of rows.
Comment: that is what i do with my function getInfosCount and the number returned is 0
Comment: Exactly. You don't have any rows, that is why your function returns false.


Solution of: Let $k,n \in \mathbb{N}$ and $\frac{n(n-1)}{4} = \frac{k(k-1)}{2} $

Question: Let $k,n \in \mathbb{N}$, $k,n < 101 $ and $\frac{n(n-1)}{4} = \frac{k(k-1)}{2} $.
How can I solve this and find $n$ and $k$ in an analytic way without trying some solutions?
Answer: solving the given equation $$n^2-n=2k^2-2k$$ for $n$ we get
$$n=\frac{1}{2}+\sqrt{\frac{1}{4}+2k^2-2k}$$
or
$$n=\frac{1}{2}-\sqrt{\frac{1}{4}+2k^2-2k}$$
now you Can solve the inequality
$$n=\frac{1}{2}+\sqrt{\frac{1}{4}+2k^2-2k}<101$$
writing the inequality in the form
$$\sqrt{\frac{1}{4}+2k^2-2k}<101-\frac{1}{2}$$
squaring this we get
$$2k^2-2k<101^2-101$$ and from here we get the interval
$$\frac{1}{2}\left(1-\sqrt{20201}\right)<k<\frac{1}{2}\left(1+\sqrt{20201}\right)$$
Comment: Thank you, but i must still try for which $k$ is $n \in \mathbb{N}$
Comment: should i post also this for you?
Comment: No, i know how to solve this, when i try different values of k. My question is, is  there an  purely analytic way ?
Comment: i hope this will Help you!!


Prove $H_{2^m} \leq 1 + m$, where $H_n = \sum\limits_{k=1}^n \frac{1}{k}$

Question: I really I am not seeing how to continue my approach, which is this.

Base case:

$m = 1$, so we have $H_2 \leq 2$, where $H_2 = \sum\limits_{k=1}^2 \frac{1}{k} = \frac{1}{1} + \frac{1}{2} = \frac{3}{2}$
So our base case is proved, since $\frac{3}{2}$ is less than $2$.

Induction hypothesis:

Let $m$ be arbitrary. Let's assume $H_{2^m} \leq 1 + m$ is true.

Induction step:

Let's prove that $H_{2^{m+1}} \leq 1 + (m + 1)$ is also true.
$H_{2^{m+1}}$ means that instead of going until ${\frac{1}{2^m}}$, we continue until $\frac{1}{2^{m+1}}$.
We know how to sum until ${\frac{1}{2^m}}$, so $H_{2^{m+1}}$ = $H_{2^m}$ + TOTAL - $H_{2^m}$
Now, unfortunately, I am not seeing how can I go ahead proving using this approach...
Answer: Note that
$$H_{2^{m+1}}-H_{2^m}=\sum_{n=2^{m}+1}^{2^{m+1}}\frac{1}{n}$$
In this sum each term is less than $\frac{1}{2^{m}}$ and you have $2^{m}$ terms, so:
$$\sum_{n=2^{m}+1}^{2^{m+1}}\frac{1}{n} \leq 2^{m} \cdot \frac{1}{2^m}\leq 1$$
Answer: Hint:
$$H_{2^{m+1}}=H_{2^m}+\dfrac{1}{2^m + 1}+\dfrac{1}{2^m + 2}+ \ldots +\dfrac{1}{2^{m + 1}-1}+\dfrac{1}{2^{m + 1}}$$
Answer: Hint
$\frac{1}{2^m+1}+\frac{1}{2^m+2}+\ldots +\frac{1}{2^{m+1}}<\frac{1}{2^{m}}+\frac{1}{2^{m}}+\ldots +\frac{1}{2^{m}}=2^m\cdot \frac{1}{2^m}=1$
This is the induction step that is missing
Answer: Hint: $$H_{2^{m+1}} = H_{2^{m}}+\sum_{i = 2^m+1}^{2^{m+1}}\frac{1}{i}$$ Now you have an equality involving $H_{2^{m+1}}$ and $H_{2^{m}}$, so you can apply the induction hypothesis and tangle with the quantity $$\sum_{i = 2^m+1}^{2^{m+1}}\frac{1}{i}$$ to get your result.


Does this type of chord progression have a name?

Question: I listen to a lot of pop punk/emo type music. I've noticed theres a specific change in chords that I hear a lot and really like, but I don't know much about music theory.
Here are some examples:
g em c cm
b f# g#m e
g d c cm
d g em7 a7
I know they aren't in the same key, but they all seem to have a similar feel (to me at least). Does this kind of chord change have a name? I've been wondering why they sound so similar.
Comment: It's four different chord progressions so there isn't a single name for all four. Chord progressions don't have names but they do have Roman numerals used to specify the same profession no matter which key they are in. These four have four different sets of Roman numerals because they are different.
Comment: @ToddWilcox not all chord progressions have names, but there are several that do,
Comment: You should use capital letters, lower case implies minor quality. So, `G Em C Cm` would read G major E minor C major C minor. If that's what you mean, fix the case in your post.
Answer: The four listed progressions are all distinct from one another, but they all fit into the broad category of cadential progressions. A "cadence" is a harmonic progression (i.e., chord progression) that leads from a feeling of tension to a feeling of resolution, from dissonance to consonance, from instability to stability: a feeling of having "arrived" at a point of musical rest. To the degree that a person doesn't hear — or isn't trained to hear — the specific differences, cadences will tend to share a similar "sound" — a sense of tension and relaxation.
In the kind of music being referenced, there is typically a certain chord that "feels like home". Taking that to be the first chord in each of the given progressions, it's also the case that the final chord in each progression, while different from each other, are chords commonly used to "lead back" to the "home chord".
The table below shows the four chord progressions

As given;
Rewritten to share the same home chord (i.e., "transposed");
Given in standard music theory analysis notation (i.e., Roman numeral analysis);
Named according to the particular cadence type involved.

Original progression
Transposed progression
Analytical notation
Cadence type

G Em C Cm
C Am F Fm
I vi IV iv
Plagal cadence (IV or iv -> I)

b f# g#m e
C G Am F
I V vi IV
Plagal cadence

g d c cm
C G F Fm
I V IV iv
Plagal cadence

d g em7 a7
C F Dm7 G7
I IV ii7 V7
Authentic cadence

Observations:

Most of these are "plagal" cadences; however, unless trained to hear the difference between different cadence types, they can all sound "the same": i.e., they all sound like the music coming to rest.
All involve the "same" chords in the sense that ii, iv, IV, and vi can all be used interchangeably to a large extent.

The "interchangeability" of certain chords can be shown by reducing them to their "musical role". "Tonic function" chords (T) are the ones most at rest; "Dominant function" chords (D) are the most "tense" and tend to move ("resolve") to a T chord; and "Pre-dominant function" chords tend to lead to D chords. ("Tend", but not a hard and fast rule.)
In those terms, the given chord progressions can be reduced to their functional equivalents in this way:

T P P P
T D P P
T D P P
T P P D
Comment: Doesn't essentially every four or three chord pop or rock progression have a cadential nature in the sense that you describe here? Is there anything these four in particular share that we wouldn't hear in any other pop or rock chord progression?
Comment: @ToddWilcox In fairness, probably not. When a pop/rock musician strays from the basic three-or-four-chord formulae, the rest of the band tells them to stop playing jazz. (Unless it's a prog rock band, of course.) But at the level the OP seems to be asking, my feeling is that a broad answer like this fits the bill, even though it could just as well apply to chord progressions not addressed in the question.
Answer: There aren't many chord progressions that have names most musicians would recognize. So unfortunately, I don't think there is a name I can give you for these progressions. That said, there is something that stands out to me about them, something that is stylistically important and that will help you find music with similar harmonies: All four progressions are very simple!
As Aaron pointed out in their answer, the first three chord progressions are all different ways of ordering the I, IV, and V chords. These are the most common chords in most western music. The fourth chord progression has a ii V I chord movement, which is also incredibly common. The chord progressions you've listed keep it simple, don't push boundaries, and have a very clear and understandable sense of direction.
To be clear, this is not a bad thing at all!
Punk and emo music are both genres about embracing angst and giving the middle finger to a stupid world. The ethos of punk is to stick it to the man, and emo music unapologetically lets loose about how much life can suck. These are both very in-your-face genres that embrace exaggerated energy and eschew subtlety.
For these genres, very straightforward chord progressions are a strength. Loud chords with clear direction have a way of hitting like a brick wall in a way that more pretentious music theory just can't match. And keeping the chords simple means that the listener's attention is kept on the lyrics and the music's driving energy. The simple chord progressions don't come from a lack of creativity or artistic merit in the slightest. On the contrary, they are a very smart choice for aggressive music that focuses on the lyrics.
Answer: Your progressions re-written with capitol letters and Roman numeral analysis after...

G Em C Cm  --- G:I vi IV iv

B F# G♯m E --- B:I V vi IV

G D C Cm   --- G:I V IV iv

D G Em7 A7 --- D:I IV ii7 V7

I assume all of these get repeated.
There are some similarities between them.
The only one that jumps out as having a sort of name is B F♯ G♯m E, that's the I V vi IV "Axis of Awesome" used in a thousand pop hit songs.
When if comes to finding similarities in chord progressions, it's worth pointing out that most chord progressions share similarities, because music works with common patterns. Chord progressions (harmony) is not reinvented with each new song. Similarities should not comes as a surprise.

when the progressions repeat you have IV iv | I in two of them. It doesn't have a name, but it's a popular thing to do, and it's chromatic, so it stands out. You can call the second chord, the iv, a "borrowed" chord, it's a subdominant, normally a major chord in a major key, but in this case "borrowed" from the parallel minor key G minor, but you can also think of it as just descending chromatic steps with the E natural to E flat to D.
several of the two chord progressions involve major/minor relative pairs, either the lower or upper relative: G Em, Em C, G♯m E, G Em7. There is nothing unusual about those progressions, but pop music sort of emphasizes them more than classical style. Pop might vamp back and forth between I and vi or I and iii, but classical style wouldn't do that. This may be too common to think of as a unique feature shared by these progressions. It's more like any pop progression might do this.
the last one - D G Em7 A7 --- D:I IV ii7 V7 - has something going on when in a particular voicing, like this on guitar D xx0232 G 320033 Em7 022030 A7 x02020. On the B string you have the half step movement from fret 3 to 2, that's a D down to C♯. That D gets emphasis as either the chord seventh, or possibly viewed as a suspension. It's not exactly analogous to the half steps in IV iv I, but there is a similarity in that, in each progression, one of the half steps is "special." In one case it's a chromatic half step, in the other it is a dissonant half step. Maybe you hear some similarity between those?

Other than the minor iv shared by two, I personally wouldn't lump these all together as sounding alike and somehow unique from other pop progressions. They sound similar is the very broad sense that they are all common pop progressions. I just laid out what you might be hearing as similarities.
Just a side note, you see the minor iv getting clever names like the "Beatle chord" or something else. It was used long before The Beatles or any other cute name. It can be involved in something called the "backdoor" progression, but that particular progression also is defined by the ♭VII chord. Unless you're really playing a backdoor progression, don't call it that.
You might like this: https://www.angelfire.com/fl4/moneychords/lesson.html


no such element: Unable to locate element: when I use elementToBeClickable method

Question: I have to wait for an element to appear and then click on it. Here is the code I tried and getting the NoSuchElementException.
I have 300 seconds to wait for the element, but it is trying to find the element:
tpo.fwOptimizationTestResults() without waiting for 300 seconds
WebElement fwResults = (new WebDriverWait(driver, 300))
        .until(ExpectedConditions.elementToBeClickable(tpo.fwOptimizationTestResults()));

public WebElement fwOptimizationTestResults() {
    //return driver.findElement(By.xpath("//*[@class='table table-condensed table-bordered']"));
    return driver.findElement(By.xpath("//table[contains(@class, 'table-condensed')]"));
}

Error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//table[contains(@class, 'table-condensed')]"}
  (Session info: chrome=75.0.3770.80)

Answer: The exception is not from elementToBeClickable, it's from fwOptimizationTestResults. You are using driver.findElement() which throws the exception and evaluates before the expected condition.
There are two overloads, elementToBeClickable(WebElement) and elementToBeClickable(By), you should use the second one
WebElement fwResults = (new WebDriverWait(driver, 300)).until(ExpectedConditions.elementToBeClickable(By.xpath("//table[contains(@class, 'table-condensed')]")));

Comment: Perfect, can you explain these two overloads, ElementToBeClickable(IWebElement) andElementToBeClickable(By). In the Page object model, I'm using the same xpath as mentioned by you. What makes the difference.
Comment: @VamshiM There are two `elementToBeClickable()` methods, one receive  `WebElement`, which you used, as a parameter and the second one receive `by` as a parameter and locate the element internally, so the time span is used. You tried to locate the element with `driver.findElement()`, which throws an exception immediately.
Comment: please help me out with changes to be made for the fwOptimizationTestResults to avoid this exception. Thanks a lot for your help
Comment: @VamshiM You can return `By` instead of `WebElement`, `public By fwOptimizationTestResults() {
    return By.xpath("//table[contains(@class, 'table-condensed')]");
}`
Answer: You might want to amend your code to add ignoring stanza to the WebDriverWait
 so it won't fail on NPEs:
WebElement fwResults = (new WebDriverWait(driver, 5))
        .ignoring(NullPointerException.class)
        .until(ExpectedConditions.elementToBeClickable(tpo.fwOptimizationTestResults()));

and in its turn put your WebElement function inside the try block and instead of throwing an exception - return null in case if element is not found:
public WebElement fwOptimizationTestResults() {
    try {
        return driver.findElement(By.xpath("//table[contains(@class, 'table-condensed')]"));
    } catch (NoSuchElementException ex) {
        return null;
    }
}

More information:

FluentWait
How to use Selenium to test web applications using AJAX technology


Intersection Safe Families

Question: I'm looking at a past homework solution and there is a part of it I don't understand. Specifically I'm talking about number 2 in this problem set:

Let $m=\lfloor(8/7)^{n/3}\rfloor$. Show that there exist distinct sets $A_1,A_2,\dots,A_m\subseteq[n]$ such that for all distinct $i,j,k\in[m]$ we have $A_i\cap A_j\nsubseteq A_k$.

Given $A_1, A_2, A_3,..., A_m$ which are subsets of $ [n]  $. Can someone explain in detail why the probability of $A_i \cap A_j \subseteq A_k$ is equal to  $(\frac7 8)^{n}$.
Comment: For each $x \in [n]$, the three membership values can assume any of the eight (equally likely) possibilities except for one: $x \in A_i \wedge x \in A_j \wedge x \not\in A_k$.  So each $x \in [n]$ is okay with independent probability $7/8$; hence all $n$ are okay with probability $(7/8)^{n}$.
Answer: Suppose that $A_i\cap A_j\subseteq A_k$. Then for each $r\in[n]$ one of the following must be true:

$r\in A_i$ and $r\in A_j$ and $r\in A_k$.
$r\in A_i$ and $r\notin A_j$, in which case it doesn't matter whether $r\in A_k$.
$r\notin A_i$ and $r\in A_j$, in which case it doesn't matter whether $r\in A_k$.
$r\notin A_i$ and $\notin A_j$, in which case it doesn't matter whether $r\in A_k$.

Since each $r\in[m]$ is in any given $A_s$ with probability $\frac12$, the probability of (1) is $\frac12\cdot\frac12\cdot\frac12=\frac18$. The probability of (2) is $\frac12\cdot\frac12\cdot1=\frac14$, and exactly the same calculation gives the probability of (3) and the probability of (4). These four possibilities are mutually exclusive, so the probability that one of them is true is $\frac18+\frac14+\frac14+\frac14=\frac78$.
In other words, for each $r\in[n]$ the probability that $r$ behaves in one of the ways consistent with $A_i\cap A_j\subseteq A_k$ is $\frac78$. This is the case independently for each $r\in[n]$, so the probability that all of them behave properly is $\left(\frac78\right)^n$.
Answer: The sets $A_i$ were constructed by taking each element of $[n]$ with probability $\frac 12$.  An element $p$ can render $A_i \cap A_j \subseteq A_k$ false if it is in $A_i$ and $A_j$ but not in $A_k$.  This requires three choices to be right, so happens in $\frac 18$ of the cases.  To have $A_i \cap A_j \subseteq A_k$ true, none of the elements can render it false, so the chance is $(\frac 78)^n$

Intersection Safe Families


Interval song for a Perfect 4th where the note ascended to is not the tonic?

Question: I've been trying to develop my relative pitch, and I've seen the suggestion of using "interval songs". This makes sense to me, but I've noticed something about every song I've seen suggested for the interval of a Perfect 4th: it's always the dominant to the tonic. This makes the tool more difficult to use in my head.
Can anyone recommend any pieces (the more well-known the better) that begin with the tonic to the subdominant?
Comment: Community Wiki for interval reference songs: [Wiki: List of reference songs for interval training (esp. A5/d5; M6; m6)](https://music.stackexchange.com/questions/7805/wiki-list-of-reference-songs-for-interval-training-esp-a5-d5-m6-m6).
Answer: The guitar riff of "Bad to the Bone" by George Thorogood uses a perfect fourth from the root up (and so do many other blues riffs).
Comment: @Tim: What I meant was that going from the tonic to the fourth is a very common thing to do in the blues/rock idiom. Think of Deep Purple's Black Night riff (actually stolen from Ricky Nelson's version of Summertime), or Led Zeppelin's Black Dog, where in both cases the 1-4 happens somewhere in the middle of the riff.
Comment: Not to mention in folk music.  The interval from the pickup to the first downbeat in "This Land is Your Land" is from one to four also.
Answer: The opening riff to "Blister in the Sun" outlines a fourth between tonic and the fourth.  (It's not just 1-4, it's more like 1-3-1-4-3; but it might be useful since it's just such a simple earworm....)


Commerce Paypal- How can I change the "Order No. at Site Name" string?

Question: I'm using the Commerce PayPal module to redirect users to PayPal to pay for their orders.
However, when I do this, the transaction that Commerce provides to PayPal is called

Order # at [Site name]

However, on my site, the store is just one part of it, and the store has a different name than the rest of the site, so I would like to override this string and replace [Site name] with the explicit name of my store.
However, I haven't been able to track down where I can edit this.  I tried searching for a number of variations on the Translate interface page and I also tried using grep on my modules directory but I haven't been able to locate it.
Answer: All of my payment gateway modules, and my recommended best practice for others', is to include a final opportunity before the payment API request is dispatched for developers to alter the request parameters if desired. How you do that in the PayPal modules depends on which payment method you're using. I'm going to assume this is a PayPal Payments Standard (WPS) initiated payment, so the hook you want is:
hook_commerce_paypal_wps_order_form_data_alter()
If it's one of the others, refer to their *.api.php files to find the appropriate hook, but note that some API requests are run through a helper function in the root commerce_paypal.module.


maven multi threaded build leading to OverConstrainedVersionException

Question: I am using maven-3.2.3 ,maven-depedency-plugin-3.0.2 and maven-assembly-plugin-3.0.0 all of which are thread safe, but when running maven build with 4 threads
(mvn clean install -T 4),
I'am intermittently hitting
org.apache.maven.artifact.versioning.OverConstrainedVersionException
This never occurs if I try to build it with single thread, (mvn clean install )
Here is the stack-trace of the error
23:31:55 org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-assembly-plugin:3.0.0:single (my-service-dependency-assembly) on project my-service: Failed to create assembly: Unable to resolve dependencies for assembly 'service-third-party-dependencies'
23:31:55    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
23:31:55    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
23:31:55    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
23:31:55    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
23:31:55    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call(MultiThreadedBuilder.java:188)
23:31:55    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call(MultiThreadedBuilder.java:184)
23:31:55    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
23:31:55    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
23:31:55    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
23:31:55    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
23:31:55    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
23:31:55    at java.lang.Thread.run(Thread.java:745)
23:31:55 Caused by: org.apache.maven.plugin.MojoExecutionException: Failed to create assembly: Unable to resolve dependencies for assembly 'service-third-party-dependencies'
23:31:55    at org.apache.maven.plugins.assembly.mojos.AbstractAssemblyMojo.execute(AbstractAssemblyMojo.java:530)
23:31:55    at org.apache.maven.plugins.assembly.mojos.SingleAssemblyMojo.execute(SingleAssemblyMojo.java:58)
23:31:55    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:132)
23:31:55    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
23:31:55    ... 11 more
23:31:55 Caused by: org.apache.maven.plugins.assembly.archive.ArchiveCreationException: Unable to resolve dependencies for assembly 'service-third-party-dependencies'
23:31:55    at org.apache.maven.plugins.assembly.archive.DefaultAssemblyArchiver.createArchive(DefaultAssemblyArchiver.java:204)
23:31:55    at org.apache.maven.plugins.assembly.mojos.AbstractAssemblyMojo.execute(AbstractAssemblyMojo.java:476)
23:31:55    ... 14 more
23:31:55 Caused by: org.apache.maven.plugins.assembly.artifact.DependencyResolutionException: Failed to resolve dependencies for assembly:
23:31:55    at org.apache.maven.plugins.assembly.artifact.DefaultDependencyResolver.resolveTransitively(DefaultDependencyResolver.java:235)
23:31:55    at org.apache.maven.plugins.assembly.artifact.DefaultDependencyResolver.resolve(DefaultDependencyResolver.java:118)
23:31:55    at org.apache.maven.plugins.assembly.artifact.DefaultDependencyResolver.resolveDependencySets(DefaultDependencyResolver.java:154)
23:31:55    at org.apache.maven.plugins.assembly.archive.phase.DependencySetAssemblyPhase.execute(DependencySetAssemblyPhase.java:95)
23:31:55    at org.apache.maven.plugins.assembly.archive.DefaultAssemblyArchiver.createArchive(DefaultAssemblyArchiver.java:181)
23:31:55    ... 15 more
23:31:55 Caused by: org.apache.maven.artifact.versioning.OverConstrainedVersionException: No versions are present in the repository for the artifact with a range [13.0.0,14.0.999)
com.mygroup.group:my-artifact:jar:null

Comment: Based on the message `Unable to resolve dependencies for assembly 'service-third-party-dependencies'
23:31:55    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)`  I would recommend to clean your local cache ($HOME/.m2/repository) and try to build your project via `mvn clean package` nothing more...this should work without any issue...
Comment: @khmarbaise with `mvn clean package` it works fine, but the issue is only when I use parallel build feature that maven provides.
Comment: Have you checked that the given version range `with a range [13.0.0,14.0.999)
com.mygroup.group:my-artifact:jar:null` of your artifacts exists in your repository?
Comment: @khmarbaise yea the version exists
Comment: So now we reached the point that we can't continue without full pom files and assembly descriptor etc.
Answer: After running multiple the build multiple times figured out that there is an issue with maven-assembly-plugin's dependency resolution. The assembly plugin does not honour the exclusions  defined in the pom.xml when creating an assembly.
To Fix this issue I moved the dependency gathering part to maven-dependency-plugin and used assembly plugin only to create the tar bundle of all the artifacts.
That solved the issue.


Specifying which properties to use in a custom drop-down Ember component

Question: I've created a reusable drop-down component in Ember:
/app/components/dropdown/component.js
import Ember from 'ember';

export default Ember.Component.extend({
  tagName: 'select',
  classNames: ['form-control'],
  placeholder: null,
  items: null,
  selected: null,
  change: function(event) {
    var items = this.get('items');
    var index = event.target.selectedIndex;
    var selected = items ? items[index - 1] : null;
    this.sendAction('selectedChanged', selected);
  }
});

/app/components/dropdown/template.js
{{#if placeholder}}
<option value="">{{placeholder}}</option>
{{/if}}
{{#each items as | item |}}
<option value="{{item.id}}" selected={{is-equal item selected}}>{{item.name}}</option>
{{/each}}

The component currently uses the 'name' property as the label for the option. However, I want the ability to specify what property to use, in order to make the component more flexible (so that I can sometimes use, for example, 'displayName').
With the old Ember Select component, you could do the following:
{{view "select"
  content=programmers
  optionValuePath="content.id"
  optionLabelPath="content.firstName"
  value=currentProgrammer.id
}}

...and tell it which properties to use for both the value and label. I'd like to do something similar, but I'm not sure how. (I tried reading through the source but it was a bit beyond me). Thanks in advance.
Answer: <option value="{{ember-get item optionValuePath}}" selected={{is-equal item selected}}>{{ember-get item optionLabelPath}}</option>

You will need to implement the ember-get helper, in Ember 2.0 there is a default heper called get which will make the following redundant.
import Ember from 'ember';

export function emberGet(params/*, hash*/) {
    return Ember.get(params[0], params[1]);
}

export default Ember.HTMLBars.makeBoundHelper(emberGet);

Also take a look at this jsbin which has an example of what you are trying to achieve.


Multiple popover for one button

Question: I'm using Twitter Bootstrap to create some popover.
Is it possible to match e.g. two popovers to one single button and to call both at the same time by clicking on the button?
Answer:
two popovers to one single button

seems difficult.but,

call both at the same time by clicking on the button

will be ok.
try

surround the button by a element or put a "blank" element next to the button.
then call the element popover on the same button.

Code like
<button type="button" class="btn" id="myButton">Double</button>

Multiple popover for one button


How to integrate Azure Edge Module to a Spring boot application

Question: I have a spring boot application that extracts data from a device with the specified intervals using spring scheduling.
Now I wanted to integrate the same spring boot application to push data using Gateway module.I am not able to find any integration point
Comment: Which container did you want to run the application in , windows container or linux container? Have you followed the sample and is it helpful for you?
Answer: You can refer to this repo on GitHub. It contains samples on Java. The tutorial Azure IoT Edge BLE Data Converter Module with Java showcases how one might build a module for Azure IoT Edge in Java.


Button remains focused after clicking

Question: I'm getting some trouble with a toolbar I made. In this I have 4 JButtons and below a JTable, which is set on focus when my windows shows in order to see the JButtons unfilled.
This is how I set each JButton:
    btn = new JButton("New");
    btn.setFocusPainted(false);
    btn.setBackground(SystemColor.window);
    btn.setVerticalTextPosition(SwingConstants.BOTTOM);
    btn.setHorizontalTextPosition(SwingConstants.CENTER);
    btn.addActionListener(new ActionListener() {
        ...
    });
    btn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    toolBar_General.add(btn);
    btn.setIcon(new ImageIcon(MainWindow.class.getResource("/icons/file11.png")));

Example of my toolbar at start: http://www.tiikoni.com/tis/view/?id=0ef950b
But after clicking on a JButton, it remains filled after itsactionListener does his work.
Example of my toolbar after clicking a JButton: http://www.tiikoni.com/tis/view/?id=9e88ea4
My question is: how can I mantain my buttons contentAreaFilled property true (so the user can tab between components in my window and see which control he has selected) and unfocus my button after the user click?
The result I would like to have is that of the first photo.
Comment: I need 4 more reputation for posting images... I think they will be useful.
Comment: Are you creating new instances of each JButton or are you reusing the same field? from your code snippet it looks like you're doing the latter
Comment: I create new istances for each `JButton`. I wanted to show how I set each of my `JButtons`
Comment: Do you have any need for added the additional calls to setFocusPainted and setCursor. Alot of Swing behavior comes prerolled in the components themselves
Comment: Unfortunately I didn't see the hand cursor so I had to call `setCursor`. I wanted also to disable the dotted border so I called `setFocusPainted`.
Comment: Add a link to the picture and someone with enough rep will edit it in for you
Comment: Maybe you are talking about a `JToggleButton`?
Comment: I upload some images so maybe the question is clearer.
Answer: I think the call you are looking for is:
btn.setRequestFocusEnabled(false);

this will stop your buttons from taking over the focus when the mouse clicks them, achieving the goal of not having the keyboard focus painted for mouse users. However it still lets keyboard-centric users "tab over" to them.
If one of your buttons gets the initial focus, however, then the keyboard focus will still render there. In that case, you probably want to select some other sensible component to place the initial keyboard focus onto by calling:
otherComponent.requestFocusInWindow();

Answer: Are you talking about the input Focus? (the dotted rectangle a component shows when it has the focus)
You can explicitly disable a component getting the focus by calling setFocusable(false) on the component (e.g. every button). It does not prevent you from clicking on the buttons, but it does prevent you from cycling the focus with the tab-key to it.
Comment: No, I'm not. I posted some images so maybe the question is clearer.

Button remains focused after clicking


Python: Replace First Word That Shows Up with Another Word

Question: I have seven fruits that you are allowed to use in a sentence and you are allowed to write with more then one and as many times as you want. They are Watermelon, Pear, Peach, Orange, Apple, Banana and Grapes. I want to report the sentence back and also replace the first fruit that comes out no matter if the word is shown multiple times and there is multiple fruits that are given in allowed list with Brussel Sprouts as seen below.

In: Apple apple apple what is a watermelon have to do to get an apple?
Out: Brussel sprouts apple apple what is a watermelon have to do to get an
  apple?
In: The apple likes orange
Out: The brussel sprouts likes orange

Right now I'm messing with this code below, but this only works for one fruit, and I need to check all seven at the same time to see which one is first and to have it replaced.
print sentence.replace("apple", "brussel sprouts", 1)

How do I do this?
Comment: What's your expected output?
Comment: It's showing now what I should expect.
Answer: Through re.sub . (.*?) at the first helps to capture all the characters just before to the first fruit. And the pattern (?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes) matches the first fruit name. So by replacing the matched characters by the characters inside group index 1 will give you the desired output.
>>> import re
>>> s = "Apple apple apple what is a watermelon have to do to get an apple?"
>>> re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', s)
'brussel sprouts apple apple what is a watermelon have to do to get an apple?'
>>> re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', 'The apple likes orange')
'The brussel sprouts likes orange'

(?i) called case-insensitive modifier which forces the regex engine to do a case-insensitive match.
Answer: There are two separate problems here; The first is find'ing the position of a fruit if it exists in the string. The second is replace'ing the one who was found first. Since I don't want to solve your homework problem for you, I'll simply show you a small example that should get you started in the right direction.
sentence = "Apple apple apple what is a watermelon have to do to get an apple?".lower() # We lowercase it so that "Apple" == "apple", etc.
index = sentence.find("apple")
print(index)
>>> 0
index = sentence.find("banana") # This is what happens when searching for fruit not in sentence
print(index)
>>> -1

Now that you know about find, you should be easily able to figure out how to combine a series of find and replace operations to get your desired output.


The inverse Laplace transform of $e^{-z}\textrm{Ei}(z)z^{-1}\log(z).$

Question: For a work I need to evaluate the following integral: $$\frac{1}{2\pi i}\int_{c-i\infty}^{c+i\infty}e^{uz}e^{-z}\textrm{Ei}\left(z\right)z^{-1}\log\left(z\right)dz,\ c>0,\,u>2$$ where $\mathrm{Ei}\left(z\right)$ is the exponential integral function. I know that $$\mathfrak{L}^{-1}\left(z^{-1}\log\left(z\right)\right)\left(u\right)=(-\log\left(u\right)-\gamma)1_{u>0}$$ where $\gamma$ is the Euler-Mascheroni constant, so my idea was to find the inverse Laplace transform of $e^{-z}\textrm{Ei}\left(z\right)$ and then to use the convolution theorem. I found that $$e^{-z}\textrm{Ei}\left(z\right)=PV\int_{0}^{\infty}\frac{e^{-uz}}{1-u}du\tag{1}$$ so my question is:

Can I use the convolution theorem even if the integral in $(1)$ exists only in the sense of the Cauchy Principal Value? In other words, can I write $$\frac{1}{2\pi i}\int_{c-i\infty}^{c+i\infty}e^{uz}e^{-z}\textrm{Ei}\left(z\right)z^{-1}\log\left(z\right)dz=PV\int_{0}^{u}\frac{\log\left(t\right)+\gamma}{u-t-1}dt?$$

I don't know if it is a standard property or is a idiocy. I searched in my textbooks but I didn't find anything like that. Thank you for your time.
Comment: Can you explain $\mathfrak{L}^{-1}\left(z^{-1}\log\left(z\right)\right)\left(u\right)=-\log\left(u\right)-\gamma$ ? (you forgot something like a $1_{u > 0}$)
Comment: @reuns Sorry, there was a typo! About the ILT, I found it at page 980 of the following book https://www.crcpress.com/Handbook-of-Integral-Equations-Second-Edition/Polyanin-Manzhirov/p/book/9781584885078
Comment: But for $\Re(z) > 0$ : $\displaystyle e^{-z} \text{Ei}(-z) =-\int_1^\infty \frac{e^{-(u+1)z}}{u}du=-\int_2^\infty \frac{e^{-uz}}{u-1}du$ and $\displaystyle \mathcal{L}^{-1}[e^{-z} \text{Ei}(-z)](u) = -\frac{1_{u > 2}}{u-1}$. The principal value comes when you look at $\Re(z) < 0$.
Comment: @reuns Sorry, I don't get it. I have to invert $e^{-z}\textrm{Ei}(z)$, not $e^{-z}\textrm{Ei}(-z)$ and I'm not sure I can use the convolution since the integral exists in terms of PV.
Comment: Ah ok for $\text{Ei}(z)$ you are right. In that case, why not look at $\Re(z) < 0$ ($c < 0$) to make everything convergent ?
Comment: @reuns Unfortunately I have to take $\mathrm{Re}(z)>0.$
Comment: Yes but you can do the switch of the domain of convergence at the end, after the convolution. That's why we need some details about $\mathfrak{L}^{-1}\left(z^{-1}\log\left(z\right)\right)\left(u\right)=-\log\left(u\right)-\gamma$
Comment: @reuns I see what do you mean, it is a good idea, thank you. However, do you know if the convolution holds even if we consider the PV?
Comment: Yes it should, assuming you meant $(\log (u) + \gamma) 1_{u <0}$ ! That's why I need to see the steps
Comment: @reuns Ok I see. I found this formula in a book but I think you are right, it should be $(\log(u)+\gamma)1_{u>0}$. In my problem I have to consider $u>2$ but you are right.
Answer: $\because\mathcal{L}_{z\to t}^{-1}\left\{\dfrac{\textrm{Ei}(z)\ln z}{z}\right\}$
$=\mathcal{L}_{z\to t}^{-1}\left\{\dfrac{\gamma\ln z}{z}+\dfrac{\ln^2z}{z}+\sum\limits_{n=1}^\infty\dfrac{z^{n-1}\ln z}{n!n}\right\}$ (according to https://en.wikipedia.org/wiki/Exponential_integral#Convergent_series)
$=\mathcal{L}_{z\to t}^{-1}\left\{\dfrac{\gamma\ln z}{z}+\dfrac{\ln^2z}{z}+\sum\limits_{n=0}^\infty\dfrac{z^n\ln z}{(n+1)!(n+1)}\right\}$
Contains the term $\ln z$
Answer: Your derivation is correct and can be made rigorous through the use of distributions. If
$$(f, \phi) = \int_0^\infty (-\ln u - \gamma) \phi(u) du, \\
(g, \phi) = \operatorname{v.\!p.} \int_0^\infty \frac {\phi(u)} {1 - u} du$$
($f$ is just a regular distribution), then
$$\mathcal L[f] = \frac {\ln z} z, \\
\mathcal L[g] = e^{-z} \operatorname{Ei}(z), \\
\mathcal L[f * g] = \frac {\ln z} z e^{-z} \operatorname{Ei}(z).$$
The convolution is defined as
$$(f * g, \phi) = (f \otimes g, (x,y) \mapsto \phi(x + y)) = \\
(f, x \mapsto (g, y \mapsto \phi(x + y))).$$
$f*g$ is a functional that can be identified with the ordinary function $h(u)$ defined by your formula on any interval not containing $u = 1$.
Further, the inverse transform exists in the sense of ordinary functions, which means that $f*g$ doesn't have a singular component, and this also holds:
$$\mathcal L[h] = \frac {\ln z} z e^{-z} \operatorname{Ei}(z).$$
$h(u)$ has a singularity of the order $\ln^2$ at $u = 1$.


Mediation model with linear regression

Question: In my master thesis I have drawn a few hypotheses. I have answered them all with linear regression. In these linear regressions, I took control variables into account.
My question is: do I have to run a mediation analysis? Or is it also possible to report the regressions of all relations separately (for example: X -> Y, X -> M, M -> Y and A -> Y)?
Here is how my model look like:

My main hypothesis is about the relation between X and Y.
I hope my question is clear.
Thank you in advance!
Answer: You can run regression models separately, if you follow the Baron-Kenny approach. As far as I know, there are two general approaches to test for mediation: (1) path models (and, SEM, of course) and (2) the Baron-and-Kenny approach (see item (a)). I use Mplus to run my mediation models which is very handy (+ bootstrapped standard errors).
Unfortunately, you did not tell us what software package you are using to do your analysis. You have a couple of options:
(a) You might be interested in D Kenny's website on mediation . He gives a very clear description how to proceed in order to test for a mediation effect (see "Baron and Kenny Steps").
(b) If you happen to use Stata or R for your analysis, you could check out the ATA website on Stata Frequently Asked Questions (search for 'mediation') or the R package mediation. If you use SPSS, you will like this website. Kenny's website also offers a couple of tips for different software packages, e.g. how to get bootstrapped standard errors in SPSS or SAS.
Comment: @Bernd (+1) Very good response. I pointed to similar material in an [earlier response](http://stats.stackexchange.com/questions/9605/calculating-the-mackinnon-empirical-distribution-test-to-test-mediation) of mine :-)
Comment: @Ann I found some resources for mediation analysis with SPSS (including Sobel's test and bootstraped estimates of path coefficients) on [Andrew F. Hayes](http://www.afhayes.com/spss-sas-and-mplus-macros-and-code.html)'s website.
Comment: @Ann I do not know your data (or your theoretical model). So, it is hard to comment on this behaviour (which is not uncommon though). Regarding "running the whole model", see chapter "Covariates" on Kenny's website.
Comment: Thank you for your answer!
My software package is SPSS (19).
If I run my model in linear regression with all my independent variables at once: only one predictor is significant.
When I run them separately with the dependent variable, all the predictors are significant.
Can I choose for this method (running the regressions separately instead of running the whole model at once)?
Thank you!
Comment: Thank you both! :-) (I can not vote up because I need 15 reputation)
Well, the only problem left is the following:
When you have a dependent variable with two or more independent variables, you conduct a multiple regression analysis.
In my case, I have three independent variables (X, M and A).
Where do I leave variable A in my mediation analysis?
I conducted the mediation with variables X, M and Y. But variable A is left out. Is that a problem?
Thank you!
Comment: @chl Thanks! I really should have searched for older answers before I post my answer.
Comment: @Bernd Thank you! I will run the model with A as a covariate.
Answer: Whether you control for A depends on what you are trying to accomplish. Including A in the model will increase your R-squared.
But if A is uncorrelated with X or M (as your diagram indicates) then inclusion/non-Inclusion of A will not affect coefficients or p-values for X or M.

Mediation model with linear regression


Django path error while trying install skin for Admin

Question: I'm trying to install the following skin for my Django admin. I followed all the instructions till the part where I have to update my urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf.urls import handler404, handler500
from django.conf import settings
from django.conf.urls.static import static

url(r'^admin/', include('djadmin.urls')),
I've changed the code and tried entering
path('admin/', djadmin.urls),
also tried
path('admin/', include(djadmin.urls)),
But its still giving me an error in this line of code. I've added djadmin to my installed files and also updated the middleware.
Could anyone help me out?
Comment: can add the error traceback?
Comment: @Kaushal Sharma I added one answer. Please do try it
Comment: File "D:\Pycharm work\Buggie\Buggie\urls.py", line 24, in
    path('admin/', include(djadmin.urls)),
NameError: name 'djadmin' is not defined
Comment: Add it to the question.
Answer: Add quote symbols (" and ") to the djadmin.urls as
path('admin/', include("djadmin.urls")),


missing 1 required positional argument: 'self' while using classmethod in staticmethod

Question: I write class Person in Python 3.8. When I use calc_all() method to calculate income for every instance in instances, I get an error.
Code:
import math
class Person:
    instances = []
    @classmethod
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.level = 1
        self.job = ""
        self.work_place = None
        Person.instances.append(self)
    def do_level(self,income):
        return income*math.sqrt(self.level*self.work_place.level)
    def calc_income(self):
        pass
    def calc_life_cost(self):
        pass
    def calc(self):
        income = self.calc_income()
        cost = self.calc_life_cost()
        return self.do_level(income) - cost
    @staticmethod
    def calc_all():
        zigma = 0
        for instance in Person.instances:
            zigma = zigma + instance.calc()
        return zigma

p = Person('X',12)
p2 = Person('Y',15)
print(Person.calc_all())

Error:

zigma = zigma + instance.calc()
TypeError: calc() missing 1 required positional argument: 'self'

Comment: What does the line `Person.instances.append(self)` make sense. Is it appending correctly???
Comment: Do u want to append name,age,etc to to the instances list????
Comment: @Arpit I'm not sure about my code, But when i print it : ```[<__main__.Person object at 0x000001F4C094E488>, <__main__.Person object at 0x000001F4C094E4C8>]``` I want a list of all person objects
Comment: What u basically want in in your instances list???
Comment: @Arpit every person object I create
Comment: You can't append object name. Object name is used to call the class functions outside the class. You can append the values u provided as argument to the class
Answer: What are you trying to accomplish by making __init__ a classmethod? You could freely remove it. After this you will still have an error, since self.work_place does not have attribute level.
Comment: I reproduced your code and get an implementation error, you should add implementations for `calc_income` and `calc_life_cost`, cheers. And remove `@classmethod` from `__init__` you do not need it.
Comment: The problem was @classmethod, Thanks


Query parameter only returning one result

Question: I can't seem to understand why is the following returning only the first result? when there are multiple students with that same name and I'm clearly looping through the dictionary. Any thoughts?
<code>    students = {
    1: {
        "name": "John",
        "age": 18,
        "hobbies": ["Programming", "Swimming", "working out"]
    },
    2: {
        "name": "John",
        "lol": "random",
        "age": 18,
        "hobbies": ["Programming, swimming, working out"]
    },
     3: {
        "name": "Bob",
        "age": 18,
        "hobbies": ["Programming", "Swimming", "working out"]
    },
}
@app.get("/get-student")
async def get_student_by_name(name : str):
    for id in students:
        if students[id]["name"] == name:
            return students[id]
    return {"Data": "Student not found"}
</code>
The returned result is always the first one in the dictionary.
Comment: `return` works only once.
Comment: What do you expect to get?
Comment: @crazyzubr if I pass John as a parameter, shouldn't the expected result be both John's?
Answer: This won't work since you're using 'return' statement inside the loop, if for example you are looking for 'john' the first time this parameter is found return is executed and function ends.
You could for example save those values and return them all, let me show you:

Instead of return, declare a list ids = []at the beginning of the function and every time john is found you add the id to the results list, ids.append(students[id]). Finally after the loop just return ids list, or if len(ids) is 0 just return None for error management.

Code example:
<code>    @app.get("/get-student")
    async def get_student_by_name(name : str):
        ids = []
        for id in students:
            if students[id]["name"] == name:
                ids.append(students[id])
        if len(ids) is 0:
            return {"Data": "Student not found"}
        else:
            return ids
</code>


cakephp authenticate basic only valid users

Question: I am using the Auth with authenticate Basic.
Is there a way to check if the user is active = 1?
I would like to check that for the Form and the Basic method.
The Basic method is used, when a user log in from an iphone app sending username and password via http header.
public $components = array('Session', 'RequestHandler', 'Auth' => array(
        'loginAction' => array(
            'controller' => 'api',
            'action' => 'login'
        ),
        'authenticate' => array(
            'Basic' => array(
                'userModel' => 'Appuser',
                'fields' => array(
                    'username' => 'name'
                )
            ),
            'Form' => array(
                'userModel' => 'Appuser',
                'fields' => array(
                    'username' => 'name'
                )
            )
        )
    ));

Answer: Use the scope setting of the AuthComponent and set it using the ALL constant:
public $components = array(
    'Auth' => array(
        'loginAction' => array(
            'controller' => 'api',
            'action' => 'login'
        ),
        'authenticate' => array(
            AuthComponent::ALL => array(      // Use this to apply common settings
                'userModel' => 'Appuser',
                'fields' => array(
                    'username' => 'name'
                ),
                'scope' => array(
                    'Appuser.active' => 1       // This is the check you need
                )
            ),
            'Basic',
            'Form'
        )
    )
);

For more info, refer to this section in the book.


On hook_entity_presave how do I know if it is a new node?

Question: I'm using the hook
function nvgh_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
}

but I only need to do something when the node is new (not when it is edited). How to do this? I'm inspecting the entity with kint but cannot find a good indicator for this... also kint is disappearing as the node view is redirected into view modes.
How to do this?
Answer: Use the Entity::isNew() method:
if ($entity->isNew()) {
  // ...
}


If $A$ is a $2\times 2$ matrix with a repeated eigenvalue $r$, then $\mathrm{e}^{At}=\mathrm{e}^{rt}\left[I+(A-rI)t\right]$

Question:
If $A$ is a $2\times 2$ matrix with a repeated eigenvalue $r$, show that  $\mathrm{e}^{At}=\mathrm{e}^{rt}\left[I+(A-rI)t\right]$.

I have already been able to show that if $A$ is an arbitrary $2\times 2$ matrix
$$
\left(
\begin{array}\\
a & b \\
c & d
\end{array}
\right),
$$
the repeated eigenvalue $r$ must be equal to
$\,r=\dfrac{a+d}{2}$.
From here, my first thought was to take the determinant of the matrix
$$\mathrm{e}^{rt}\left[I+(A-rI)t\right],$$
and show that it is equal to $$\det(\mathrm{e}^{At}),$$ but then I started thinking this would be useless since two unequal matrices can have the same determinant.
I've tried directly substituting $r$ into the right-hand side of the equation as well, but with no luck.

Does anyone have any suggestions on how to proceed from here?
Answer: As $r$ is an eigenvalue of multiplicity 2 of the $2\times 2$ matrix $A$,
then $A$ does not have any other eigenvalues, and its characteristic polynomial should be
$$
p(x)=(x-r)^2,
$$
and by Cayley-Hamilton Theorem we have that
$(A-rI)^2=0$.
Next observe that
$$
\mathrm{e}^{tA}=\mathrm{e}^{rt}\mathrm{e}^{t{(A-rI)}}=\mathrm{e}^{rt}\sum_{n=0}^\infty
\frac{(A-rI)^n}{n!}=\mathrm{e}^{rt}\sum_{n=0}^1
\frac{(A-rI)^n}{n!}=\mathrm{e}^{rt}\big(I+
(A-rI)\big)
$$
Answer: This is much simpler if you observe that what you're trying to prove is invariant under conjugation/similarity.  That is, it suffices to show this for some matrix similar to $A$, not necessarily $A$ itself.
Note that if $A$ has a repeated eigenvalue of $r$, then it must be similar either to $\begin{pmatrix}r & 0 \\ 0 & r\end{pmatrix}$ or to $\begin{pmatrix}r & 1 \\ 0 & r\end{pmatrix}$.
Comment: @TheMobiusLoops Well, $A$ is always similar to $A$, so there's that.  But as I said, we know that $A$ is similar to one of the two matrices above.  It's a good exercise to show this directly for $2\times 2$ matrices, but it follows from the Jordan normal form.
Comment: But can we always guarantee that there will be a similar matrix to $A$?
Comment: @TheMobiusLoops Similarity is just a convenience anyway; the real point here is that the condition of the problem implies that $(A-rI)^2 = 0$.  This should be an enormous help in actually computing the power series $e^{At}$.
Comment: I tried using $A=PBP^{-1}$ where $B$ is the diagonal matrix with entries $r$, but I'm still not getting the condition to be satisfied.
Comment: @TheMobiusLoops The $P$ and $P^{-1}$ pull entirely out of both sides of the equation.  You only need to verify it when $A$ equals one of the two matrices I mentioned.  If the similarity argument doesn't make sense to you, try my other suggestion: write $A=rI + N$, verify that $N^2=0$, and use this (and power series!) to show that $e^{At} = e^{rt} (I + Nt)$.
Comment: I got it! Thanks for the help. I ended up using the similarity argument.
Answer: They key observation is to write the relation as
$$e^{(A-rI)t}=I+(A-rI)t.
$$
This is clearly true once you notice that $(A-rI)^2=0$. You can prove this using the Jordan form as Slade mentioned: a $2\times2$ matrix with both eigenvalues equal to zero has its square equal to zero.


Read file splitted by "|" and containing "#" character

Question: I 'm download a zip file containing a text file with this structure:
ANO|MES|NUMERO_ORDEM|CODIGO_ORGAO|MATRICULA|NOME|CPF|VINCULO|CARGO|FUNCAO|REMUNERACAO_BASE|BENEFICIOS|EVENTUAIS|HORAS_EXTRAS|JUDICIAIS|COMISSAO|TETO_REDUTOR|IRRF|CONTRIBUICAO_PREVIDENCIARIA|FONTE|TOTAL|ANO_MES
2019|2|108010|12200218000179|17794|AILSON DE MELO SOUZA|###.539.0##-##|Estatutário|AGENTE ADMINISTRATIVO||2131.45|0.0|0.0|0.0|0.0|0.0|0.0|0.0|223.46|SEPLAG|1907.99|2019/02
2019|2|108011|12200218000179|17801|ANDREA ALVES COUTO VANDERLEI|###.837.7##-##|Estatutário|PROFESSOR||3661.66|0.0|0.0|0.0|0.0|0.0|0.0|105.59|402.78|SEPLAG|3153.29|2019/02
2019|2|108012|12200218000179|17805|RENATO VASCO DE ALMEIDA NETTO|###.244.8##-##|Estatutário|PROFESSOR||1830.83|0.0|0.0|0.0|0.0|0.0|0.0|0.0|201.39|SEPLAG|1629.44|2019/02

I`m using R:
temp = tempfile()
download.file("http://transparencia.al.gov.br/media/arquivo/folha_ativo-2019.zip",temp)
arquivo = read.table(unz(temp, "folha_ativo-2019.txt"), sep = "|")
arquivo
unlink(temp)

But I have some problems with the read.table function, I think it's because of the characters "|" and "#". So how do I read files with these types of characters in R?
Comment: You can also try with different functions for reading in data. E.g., `data.table::fread()`, `vroom::vroom()`, or `readr::read_delim()` with `delim = "|"`. All these work with the sample you pasted above.
Answer: A few points:

Remove the # comment character specification by adding comment.char="" to the read.table statement.
the file has a header (use header = TRUE)
the last line of the file also has a header so read in the lines and remove it
use as.is=TRUE if you want character rather than factor columns
| should not be a problem

No packages are used.
L <- readLines(unz(temp, "folha_ativo-2019.txt"))
L <- head(L, -1) # remove header on the last line
arquivo <- read.table(textConnection(L), sep = "|",
  header = TRUE, comment.char = "", as.is = TRUE)

giving:
> str(arquivo)
'data.frame':   509407 obs. of  22 variables:
 $ ANO                        : int  2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 ...
 $ MES                        : int  2 2 2 2 2 2 2 2 2 2 ...
 $ NUMERO_ORDEM               : int  108010 108011 108012 108014 108016 108018 108019 108021 108022 108023 ...
 $ CODIGO_ORGAO               : num  1.22e+13 1.22e+13 1.22e+13 1.22e+13 1.22e+13 ...
 $ MATRICULA                  : int  17794 17801 17805 17811 17816 17875 17878 17888 63964 17896 ...
 $ NOME                       : chr  "AILSON DE MELO SOUZA" "ANDREA ALVES COUTO VANDERLEI" "RENATO VASCO DE ALMEIDA NETTO" "ROGERIO RODRIGUES DOS SANTOS" ...
 $ CPF                        : chr  "###.539.0##-##" "###.837.7##-##" "###.244.8##-##" "###.002.5##-##" ...
 $ VINCULO                    : chr  "Estatut<e1>rio" "Estatut<e1>rio" "Estatut<e1>rio" "Estatut<e1>rio" ...
 $ CARGO                      : chr  "AGENTE ADMINISTRATIVO" "PROFESSOR" "PROFESSOR" "PROFESSOR" ...
 $ FUNCAO                     : chr  "" "" "" "" ...
 $ REMUNERACAO_BASE           : num  2131 3662 1831 1831 1831 ...
 $ BENEFICIOS                 : num  0 0 0 0 0 0 0 0 0 0 ...
 $ EVENTUAIS                  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ HORAS_EXTRAS               : num  0 0 0 0 0 0 0 0 0 0 ...
 $ JUDICIAIS                  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ COMISSAO                   : num  0 0 0 0 0 0 0 0 0 0 ...
 $ TETO_REDUTOR               : num  0 0 0 0 0 0 0 0 0 0 ...
 $ IRRF                       : num  0 106 0 0 0 ...
 $ CONTRIBUICAO_PREVIDENCIARIA: num  223 403 201 201 201 ...
 $ FONTE                      : chr  "SEPLAG" "SEPLAG" "SEPLAG" "SEPLAG" ...
 $ TOTAL                      : num  1908 3153 1629 1629 1629 ...
 $ ANO_MES                    : chr  "2019/02" "2019/02" "2019/02" "2019/02" ...


Understand the output layer of transformer

Question: I'm trying to understand transformer from the paper, attention is all you need. I'm puzzled by the last piece on the linear -> softmax block on the decoder output, and wasn't able to find more information about it.
From the original paper, in section 3.4 Embeddings and Softmax, the authors state that:

Similarly to other sequence transduction models, we use learned
  embeddings to convert the input tokens and output tokens to vectors of
  dimension dmodel. We also use the usual learned linear transformation
  and softmax function to convert the decoder output to predicted
  next-token probabilities. In our model, we share the same weight
  matrix between the two embedding layers and the pre-softmax linear
  transformation, similar to [30]

So this seems that the output of the decoder is a word vector, for example $(d_{model}, 1)$. Here, I think $d_{model}$ is the number of dimensions for the dense projected vector, I might be wrong. Then multiplied by this matrix of $(N_w, d_{model})$ to become a big $(N_w, 1)$ vector, and then send to softmax. Here $N_w$ is the number of vocabulary.
So how did they derive this vector from the decoder? My understanding, probably wrong, is that each multi-head attention layer generates $(maxlen, d_{model})$ matrix. $maxlen$ is the maximum length of all input sentences, padded by 0. So the output of the decoder would be matrix of size $(maxlen_{source} + maxlen_{target}, d_{model})$, instead of a one word-vector.
Thank you!
Answer: The decoder has different behaviours in training and inference stage. In the training stage, all the inputs for the decoder are known, so the decoder can generate all the outputs at one feed forward operation. The shape of the decoder's output should be ($maxlen_{target}, d_{model}$). Then multiplied with the pre-softmax linear layer, whose shape is $(N_{w}, d_{model})$, you will get the predicted distribution on the output vocabulary. The equation is shown as follows:
$$P_{(N_{w},maxlen_{target})}=W_{(N_{w}, d_{model})}X_{(maxlen_{target}, d_{model})}^{T}$$
As described in [1], the pre-softmax linear layer can also be treated as word embedding, whose parameters can be shared with the input embedding layer.

Press, Ofir, and Lior Wolf. "Using the Output Embedding to Improve Language Models." Proceedings of the 15th Conference of the European Chapter of the Association for Computational Linguistics: Volume 2, Short Papers. Vol. 2. 2017.


$a_n=2^n+3^n+6^n-1$. Find all positive integers that are primes to all terms of the sequence.

Question: Let the sequence $a_n=2^n+3^n+6^n-1, n\in\mathbb N_{> 0}$. Find all positive integers that are prime to all terms of this sequence. I have no idea how to approach this, but I know that I CAN'T use Euler's theorem or any generalization/extension of fermat's little theorem as it's on a later chapter in the textbook.
If possible, fully explain all steps.
Comment: This was a 2005 IMO problem.
Comment: The key insight is that $\frac12 + \frac13 + \frac16 - 1 = 0$; but this should be understood as an equality in the field $\mathbb Z/p\mathbb Z$.
Comment: let $n$ be a $p-2$, where $p$ is a prime greater than 3 and use fermat's little theorem
Comment: The Aos related forum thread: https://artofproblemsolving.com/community/c6h44573p282138.
Answer: If $n=2$, $a_n=48$.
Now let $p$ be a prime greater than $3$, and $n=p-2$. Using Fermat's little theorem,
$$
2^{p-2}+3^{p-2}+6^{p-2}-1\equiv 1/2+1/3+1/6-1=0 \;(mod\; p)
$$
So in the sequence we have all the primes, meaning the only positive integer prime to all $a_n$ is $1$
Answer: Thought it could be useful to cite the solution from The IMO Compendium A Collection of Problems Suggested for The International Mathematical Olympiads: 1959-2009:

We will show that $1$ is the only such number. It is sufficient to prove that for every prime number $p$ there exists some $a_m$ such that $p \mid a_m$. For $p=2,3$ we have $p\mid a_2=48$. Assume now that $p>3$. Applying Fermat's theorem, we have
  $$
6a_{p-2}=3\cdot 2^{p-1}+2\cdot 3^{p-1}+6^{p-1}-6\equiv 3+2+1-6=0 \pmod{p}.
$$
  Hence $p \mid a_{p-2}$, i.e. $\gcd(p,a_{p-2})=p>1$. This completes the proof.

Notice this is very similar to @Exodd's answer, although it avoids fractions.


Windows XP Pro Update KB2707511 installing over and over

Question: I am having a very peculiar issue installing Windows Updates on Windows XP Pro SP3. This is installed on a Virtual Machine (Oracle VirtualBox) with VM guest tools installed. I'm trying to get it up to date, but the update KB2707511 keeps repeatedly installing. It installs in a matter of about 5 seconds, then completes successfully. 20 seconds later, there's another update ready for the exact same one. I've tried restarting the machine and running both auto updates and updates from within the browser. The same one just keeps appearing.
What is this issue coming from? How do I get around it?
Answer: Depends on what have you've actually tried, honestly.  (Assuming you've tried more than just trying to install it over and over, at least.)
Check the event logs for any errors or warnings related to the install, try uninstalling it completely and letting in install again, and if that doesn't work, there's an MS KB article on this issue (which has different resolutions for the different causes of this behavior).