PDU wiring - is this normal (or even safe)?

Question: I removed the side panel of our server rack so I can clean up some of the wiring.  Inside I found the PDU was wired like in the picture.  Instead of an incoming power cable, there's just 3 uninsulated spade connectors.
Is there any reason for wiring it like this instead of using a C19 to appropriate connector for your country cable?
Or did whoever do this just not have the right cable handy, and figure this is good enough?

Edit:
When I say uninsulated, the metal parts of the spade connectors do look completely bare.  I haven't looked too closely to see if there's clear insulation or something, but it doesn't look like it, and it's live.
Edit 2
Proper cables are being dropshipped and will be installed as soon as they arrive.  In the mean time nobody is going to go anywhere near it.  I can easily cut power to the PDU so replacement wont be a problem.
Edit 3
The cable to the PDU has been replaced with a proper one.  No electrician needed.  No fires, no injuries.  Yay!  The faulty cable has been destroyed so nobody ever gets tempted to do something like that again.  For extra damage, the cord they attached those spades to was only an 18 gauge cable, not the 14 gauge ones usually used for servers.
Comment: Also: Danger, Will Robinson!
Comment: I did the only honest thing.. Posted this to Hacker News.
Comment: Oh. Oh wow. Do you happen to work in the produce industry?
Comment: @mfinni still alive :)  Proper cables are on their way and I'll be doing some emergency maintenance as soon as they get here.  In the mean time, nobody is going anywhere near that rack.
Comment: Holy Flurking Schnit, Batman.
Comment: If the cabinet was wired by a vendor you may need to involve them in the repair. Get an electrician to document the issues.  If the cabinet was wired by an employee, fix the problem and have a chat with the employee.
Comment: Let me just repeat what seems to be the sentiment here... WHAAA?!?!?!?
Comment: != Normal + != Safe = DANGER!
Comment: I hope Grant lets us know if he's still alive.
Comment: I'm a little worried that someone would receive an item in this state and think "yes, that's just what we need" and connecting it right up, instead of "OMFG **WHAT***" and burning it it with fire before disposing of the ashes carefully.
Comment: Apparently they received the (used) PDU wired up this way from whoever sold it to us.  It was years ago, and I don't know who did it, but I would sure love have some word with them.
Comment: I've done worse in my shop at home to plug in my 240v grinder... Romex enxtension cord + stripped wires jammed into an outlet!! with no ground!
I'm lucky to be alive.
Comment: If by words, you mean a good percussive attitude adjustment with the goal of recalibrating one's safety standards.
Comment: @Grant In addition to the obvious horror, it appears you don't have the rack connected to the ground lug (bottom-right of the PDU) -- [If it's not already grounded you should really ground your rack while you're fixing the other stuff](http://serverfault.com/a/132068/32986), and honestly having an electrician check the rest of the setup if it's more than just one rack probably wouldn't be a bad idea :-)
Comment: @voretaq7 I am aware of the missing ground and intend fix that as well.  I just have a single rack, easy enough to check everything myself.
Answer: That's shockingly bad (sorry!). If that cable gets yanked out by someone, at the very best it will short out and hopefully trip the circuit breaker, possibly taking out power in other racks or even other parts of the building. Worst case, somebody could be killed.
Personally I'd do the following:

Carefully secure the rack. Lock it up, post a notice to admins to not touch it under any circumstances. Make sure people are aware there is a dangerous electrical fault within the rack. If you have a server failure, so be it, that is too dangerous for anyone but a trained electrician to go near it. The stakes are too high.
Call a professional registered electrician to fix that.
Plan for downtime whilst the electrician does what's needed.
Find out who was responsible for that, and if they are still employed, report them to management, as they should be severely disciplined for putting other people at risk.
Comment: OP says proper cables are en route. I think your plan, while safe, is overkill. You describe the risks and points 1 and 4 are valid. Calling an electrician to replace a dodgy cable is a waste of his time and your money. Get the spares, plan downtime, pop the breaker and replace the cable.
Comment: **Calling an electrician to replace a dodgy cable is a waste of his time and your money.** Maybe - but my sympathies lean towards Bryan's point of view, @Freiheit because when you find something like this you don't know what else could be wrong. I think having things checked over and tested by an electrician isn't an unreasonable step to take after finding something like this. I've been electrocuted 3 times by faulty equipment, just minor shocks but still very painful and distressing. Being careful about this kind of thing stops being overkill when it starts being you that gets the shock.
Comment: @Bryan and RobM - I see your point of view. I had not considered that one gremlin often breeds other gremlins and that a trained electrician would be more likely to spot those. I also had not considered that as an IT person the job risks are different than what an electrician would be trained for or work with. Thank you for clarifying!
Comment: Shower of sparks waiting to happen.
Comment: @Freiheit, Getting an electrician in to replace a cable isn't overkill. Try telling that to your sys admin's family if he got fried. Getting a professional in to replace that cable safely isn't going to cost very much. Consider the fact that risk = severity * probability. The risk is too high. Just like we wouldn't recommend a electrician should install a mail server (which carries little danger), a system admin shouldn't mess with electrical systems that they don't fully understand.
Comment: I've done enough electrical work that I have no issue doing it myself.  Power can be cut, the other end of the cable pulled, and checked with my non contact voltage detector before I do anything.  But if I hadn't done electrical work before I would certainly call an electrician.
Answer: I'd worry about that.  When you say uninsulated, do you really mean those are live and unprotected?  If so, that's not safe.  Find an electrician to help, and stay out of there while you do it!
Answer: That is a fire (or electrical accident) waiting to happen.  Nothing good can come of that.  It is negligent and noncompliant and most definitely not normal.  I'd imagine it wouldn't be a fun thing to try and explain to an insurance company either, in the event.  I can imagine a dozen different scenarios in which that connection becomes a disaster either to uptime, property, or safety.
You need to disconnect the power above that connection immediately (eg. the other end of the cord).  I personally wouldn't bother with an electrician just to unplug the other side of that, assuming the other side isn't just as much of an atrocity and also assuming that there isn't some other circumstance making that dangerous.  If you want to be extra cautious (it never hurts), wear some electrically insulating gloves and get a voltage tester (designed to test for mains current) to ensure that the leads on the jerry-rigged side of that cable aren't live.
Once there isn't any current in that system, if you feel safe doing so, carefully remove those blade connectors (if they will slide off), or better still, remove the PDU from that environment and seperate the cable from the rest of the assembly elsewhere.  Destroy the plug on the other side of that cable and throw it away.  It's a great pity you can't track down whoever is responsible for it; they need a stern lecture from a fireman.
Absolutely do not leave this with current running through it!  Can you imagine what might happen if a metal object were to fall in there, connecting that mounting rail to mains current, or something?  Even if you cordon that thing off it's not safe.
Even supposing there was a thin coating of some insulating substance in there, that wouldn't be nearly enough to protect it from all the things that might occur.
It would be better for you to run without the redundant power source than for you to allow that to continue to exist in your environment.  I would even sooner move the equipment to another rack (if that isn't a redundant PDU) than leave that in place.
Answer: This has to be rectified very soon! Those spade connectors are not designed for the amperage that could potently be drawn should all of the connected devices require full load. Also the earth will not be sufficient should there be an issue.
Please please please plan urgent downtime NOW! Isolate the power to the PDU and replace with the correct cable.  This is a huge safety issue and needs sorting, sod downtime. The cost of a law suit will be more.
Comment: Those look like 14-16A connectors and that looks like a 16A PDU. I'd be more concerned with the electrocution hazard then I would of the connectors "failing" or of the equipment being damaged. Of course, equipment damage isn't to be taken lightly but I'd be more concerned with the risk to human life and health.
Comment: It is indeed a 16amp PDU.  The connectors actually work fine...until someone drops their screwdriver.
Answer: Are you sure, these are really powered lines and not just the grounding, going to the earth-leakage-switch ?
(okay, that should be isolated, too, just for safety, but it shouldn't carry any power for more than a few ms - then the ELS will cut off).
Comment: Absolutely certain.  That's the PDU's C19/C20 connector, and the other end of that cable is a standard wall outlet plug (NEMA 5-15).  And if anyone did grounding with a green, a black and a white wire, they'd have some explaining to do anyways.
Comment: I've never seen an earth leakage switch wired up with spade connectors (that's not to say it's never been done, but at least inmy experience it's usually screwed down securely where you can't accidentally pull/knock it loose).
Comment: I have this kind of Dell PDU or one as near as makes no odds. That's the power.
Comment: In many places, earth leakage switches or GFIs aren't required by code in this application and often aren't in use.  In any event you should never, ever, ever rely on a GFI alone for safety.
Comment: He does say that's where the incoming power cable should be.


ng-bootstrap click handler not working in dropdown

Question: I have a a button dropdown menu which I have directly copied from this ng-bootstrap example.
The dropdown works but if add a click handler to the dropdown buttons as follows, it doesn't fire when the button is clicked:

      <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</button>

        <button ngbDropdownItem click="clicked()">Not Me</button>
        <button ngbDropdownItem click="clicked()">Me neither</button>
        <button ngbDropdownItem click="clicked()">Nor me</button>

Here is a Stackblitz example forked from the original example.
Am I doing something really stupid? Thanks in advance.
Answer: click should be surrounded by brackets:

  <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</button>

    <button ngbDropdownItem (click)="clicked()">Not Me</button>
    <button ngbDropdownItem (click)="clicked()">Me neither</button>
    <button ngbDropdownItem (click)="clicked()">Nor me</button>

Also make sure you have implemented method clicked() in your component
Comment: Thanks, damn I *did* do something stupid - thanks for answering. In my original code I didn't miss the brackets though and it's still not firing.


How to anchor buttons at the bottom of the layout?

Question: I'd like the OK / Cancel buttons to be anchored at the bottom (even when there's more items on the list that can be shown on the screen). Here's what it currently looks like:

The buttons are on the top, not on the bottom.
The layout that contains the buttons:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:orientation="horizontal"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:stretchColumns="true"
             android:id="@+id/buttons_layout">
    <TableRow>
        <Button
            android:id="@+id/btnOK"
            android:background="@color/pomegranate"
            android:text="OK"
            android:layout_gravity="fill_horizontal"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnCancel"
            android:background="@color/wet_asphalt"
            android:text="Cancel"
            android:layout_weight="1"
            android:layout_gravity="fill_horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </TableRow>
</TableLayout>

The composite layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <ListView android:id="@+id/options_list"
              android:layout_width="fill_parent"
              android:layout_height="match_parent">
    </ListView>
    <include layout="@id/buttons_layout"
             android:layout_alignParentBottom="true"
             android:layout_height="match_parent"
             android:layout_below="@id/options_list"/>
</RelativeLayout>

I followed the guidelines I read on http://developer.android.com/guide/topics/ui/layout/relative.html
I tried this answer - https://stackoverflow.com/a/6285438/168719 - it hasn't helped me.
I suspected that it might not work because the list view doesn't "know" how tall it is, so the button layout doesn't know where to place itself, either. But I ruled it out by setting the ListView height to an arbitrary value like 100dp. The buttons are still superimposed over it.
I fiddled with all the layout attributes, but I can't get it to work.
Apart from the solution, I would also like to know why mine doesn't work...
Comment: why dont you just change RelativeLayout to a LinearLayout with an orientation of vertical? Or just put the button in the layout with the  listview and put them at the bottom?
Comment: 1. I did that, but now the list view pushes the buttons out of the view (unless you set the ListView height to a fixed value). I'd also like to know what was incorrect about my use of `RelativeLayout`.
2. I want to reuse the button layout.
Answer: the layout should be something like this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <ListView android:id="@+id/options_list"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_above="@+id/layout_buttons" >
    </ListView>
    <include android:id="@+id/layout_buttons"
             layout="@id/buttons_layout"
             android:layout_alignParentBottom="true"
             android:layout_height="wrap_parent"
             android:layout_width="wrap_content"/>
</RelativeLayout>

Answer: you can use tab to do it
you can see this tutorial
Android Tab Layout Tutorial
Answer: you could try using it this way
<relativelayout1>

<relativelayout2 specify layout below listview with id="list">
    <button1>
    <button2>
</relativelayout2>

<listview id="list">
</listview>

</relativelayout1>

so this will ensure no matter how long your list is you always get the buttons below your list. so you can have a scrolling list and a static buttons below the list
Answer: try this. Put the include tag inside another RelativeLayout, then be sure ListView is above the new RelativeLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parentLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/buttonsContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" >

        <include
            android:id="@+id/buttons"
            android:layout_width="wrap_content"
            layout="@layout/buttons_layout" />
    </RelativeLayout>

    <ListView
        android:id="@+id/options_list"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/buttonsContent" >
    </ListView>

</RelativeLayout>

Answer: Try like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/layout_buttons"
            android:orientation="vertical" >
        <ListView android:id="@+id/options_list"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
        </ListView>
       </LinearLayout>
        <include android:id="@+id/layout_buttons"
                 layout="@id/buttons_layout"
                 android:layout_alignParentBottom="true"
                 android:layout_height="wrap_parent"
                 android:layout_width="wrap_content"/>
    </RelativeLayout>


Neural networks - Difference between deep autoencoder and stacked autoencoder

Question: As I understand it, the only difference between them is the way the two networks are trained. Deep autoencoders are trained in the same way as a single-layer neural network, while stacked autoencoders are trained with a greedy, layer-wise approach. Hugo Larochelle confirms this in the comment of this video. I wonder if this is the ONLY difference, any pointers?
Answer: Autoencoders with multiple hidden layers are called stacked autoencoders or deep autoencoders.*
They are the same thing.
*See Hands-On Machine Learning with Scikit-Learn and Tensorflow by Aurélien Géron for a good overview of the different types of autoencoders.


How to replace second existing patteren in unix file

Question: I want to replace the second existence of the pattern in unix.
Input File:-
12345|45345|TaskID|dksj|kdjfdsjf|TaskID|12
1245|425345|TaskID|dksj|kdjfdsjf|TaskID|12
1234|25345|TaskID|dksj|TaskID|kdjfdsjf|12|TaskID
123425|65345|TaskID|dksj|kdjfdsjf|12|TaskID
123425|15325|TaskID|dksj|kdjfdsjf|12

Sample Output file:-
12345|45345|TaskID|dksj|kdjfdsjf|TaskID1|12
1245|425345|TaskID2|dksj|kdjfdsjf|TaskID3|12
1234|25345|TaskID|dksj|TaskID1|kdjfdsjf|12|TaskID2
123425|65345|TaskID3|dksj|kdjfdsjf|12|TaskID4
123425|15325|TaskID|dksj|kdjfdsjf|12

Answer: your example does not match your question,
so i'll only show how to replace every second match of the given pattern
use awk.  it's very powerfull tool for command line text processing
replace.sh as follow:
cat | awk -v search="$1" -v repl="$2" '
BEGIN {
        flag = 0
}
{
        split($0, a, search)
        len = length(a)
        for (f = 1; f < len; f += 1) {
                printf "%s%s", a[f], (flag % 2 == 0 ? search : repl)
                flag += 1
        }
        printf "%s%s", a[len], ORS
}
'

cat input.txt | ./replace.sh TaskID TaskID1


Ableton: keyboard shortcut for starting playing at beginning of song?

Question: In Ableton running on Mac, I'd like to use a keyboard shortcut to start playing the track from the beginning of the song, regardless of where the Arrangement Insert Marker (little downward pointing green arrow) is located.
I can hit spacebar twice to start over at the "beginning", but that only refers to the point where the Arrangement Insert Marker is.
Alternatively, it would also work there is a keyboard shortcut to change the Arrangement Insert Marker to the beginning of the song.
This would help speed up working on clips quite a lot.
Comment: https://www.ableton.com/en/manual/live-keyboard-shortcuts/#live-keyboard-shortcuts
Answer: The shortcut for "Move Insert Marker to Beginning" is Function+left arrow key


Tela preta no emulador android

Question: Eu estou tentando iniciar o emulador pelo android studio e genymotion mas nos dois fica uma tela preta no emulador:

Pode ser minha placa gráfica que é péssima, mas teria alguma forma de consertar isso? Ou algum outro emulador decente para desenvolvimento android?
Também tentei testar meus apps em um dispositivo físico, primeiro testei com o celular do meu uso e deu certo, depois tentei com um celular que comprei para isso (j5 metal) mas fica dando erro
C:\Users\MIDIASILK\Desktop\Junior\Android\curso-react-native\exercicios>react-n
tive run-android --deviceId 8031fe9d
Starting JS server...
Building the app...

> Task :app:bundleReleaseJsAndAssets
warning: the transform cache was reset.
Loading dependency graph, done.
bundle: Writing bundle output to: C:\Users\MIDIASILK\Desktop\Junior\Android\cur
o-react-native\exercicios\android\app\build\generated\assets\react\release\inde
.android.bundle
bundle: Done writing bundle output

FAILURE: Build failed with an exception.

* What went wrong:
java.io.IOException: Unable to delete directory C:\Users\MIDIASILK\Desktop\Juni
r\Android\curso-react-native\exercicios\android\app\build\intermediates\blame\r
s\release.
> Unable to delete directory C:\Users\MIDIASILK\Desktop\Junior\Android\curso-re
ct-native\exercicios\android\app\build\intermediates\blame\res\release.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4m 27s
35 actionable tasks: 16 executed, 19 up-to-date
Could not build the app, read the error above for details.

Running C:\Users\MIDIASILK\AppData\Local\Android\Sdk/platform-tools/adb -s 8031
e9d reverse tcp:8081 tcp:8081
Installing the app on the device (cd android && adb -s 8031fe9d install app/bui
d/outputs/apk/app-debug.apk
adb: failed to stat app/build/outputs/apk/app-debug.apk: No such file or direct
ry
Command failed: C:\Users\MIDIASILK\AppData\Local\Android\Sdk/platform-tools/adb
-s 8031fe9d install app/build/outputs/apk/app-debug.apk
Could not install the app on the device, read the error above for details.

Starting the app on 8031fe9d (C:\Users\MIDIASILK\AppData\Local\Android\Sdk/plat
orm-tools/adb -s 8031fe9d shell am start -n com.exercicios/com.exercicios.MainA
tivity)...
Starting: Intent { cmp=com.exercicios/.MainActivity launchParam=MultiScreenLaun
hParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } }
Error type 3
Error: Activity class {com.exercicios/com.exercicios.MainActivity} does not exi
t.

Rodei o mesmo comando no meu celular e funcionou.
Answer: Eu tive o mesmo problema. Eu acho que o problema é que o Android Studio gera esse app-debug.apk. Por algum motivo nesse esse diretório
android/app/build/output/apk
Mas esse diretório, possui diretórios filhos, debuge e release. É por isso que o react-native-cli da esse erro, pois não consegue encontrar o app-debug.apk que está no diretório debug.
Eu resolvi mudando o app-debug.apk para
android/app/build/output/apk
Answer: Resolvi desinstalando o Device Emulator e criando novamente.
Utilizei as mesmas configurações anteriores como Device e AVD.
Não descobri o porque desse erro mas tenho a sensação de ser algo relacionado ao meu processador AMD.

Tela preta no emulador android


How to print a 40 bit number in PHP using a 32 bit machine

Question: I'm trying to print a 40 bit number in php. But when using a Windows machine, it only allows for 32 bit integers which is causing my code echo the wrong result. Example of the code below:
function decoded_microchip_id($coded_string) {
     $manufacturer = substr($coded_string, 0, 3);
     $manufacturer = hexdec($manufacturer);
     $manufacturer = $manufacturer / 4;
     $device_id = substr($coded_string, 2, 11);
     $device_id = hexdec($device_id);
     $device_id = $device_id & 0x3fffffffff;
     echo $manufacturer.'.'.$device_id;
};

decoded_microchip_id('f58e29a43c67');

The correct output for the code above is: 982.60828171367
But in my 32 bit Windows environment I'm getting: 982.698629223
When testing the code in various PHP sandbox's the output varies as well.
Here is an example of a sandbox environment giving me the correct output:
http://sandbox.onlinephpfunctions.com/code/83cc28fd5314557e7a9d86d8061e1c8dfae4d1b7
And here is an example of an environment that produces the wrong output:
http://codepad.org/m2ygOgC6
Does anybody know a way around this issue or a solution.
Thanks.
Comment: And how do you think 8bit microcontrollers can handle 32 or 64 bit integers??.... by splitting!
Answer: The PHP function hexdec() works fine on 32-bit too. The documentations says it produces float numbers when the result doesn't fit in 32 bits.
It's interesting that 0x3fffffffff is also stored as a float number.
The culprit is the bitwise operator (&) that seems to produce an integer number. Converting its result to float doesn't help, the damage is already done.
This behaviour is documented:

both operands will be converted to integers and the result will be an integer.

A potential solution
You can try to split the input string in pieces that fit in 32 bits and use bitwise operators on them then use addition and multiplication to generate the final value (addition and multiplication convert the result to float if it cannot fit in 32 bits).
A concrete solution
A simpler solution for this situation is to convert the hex string to the binary representation of the number it encodes, extract the bits you need for each component then convert the values to decimal. No bit operations are involved in this case (except for the conversions but those seem to work correctly).
function decoded_microchip_id($coded_string)
{
    // Convert to binary
    $bin = base_convert($coded_string, 16, 2);
    // Split to 10/38 bits
    $manufacturer = substr($bin, 0, 10);
    $device_id    = substr($bin, 10, 38);
    // Convert to decimal
    $manufacturer = bindec($manufacturer);
    $device_id    = bindec($device_id);
    // Put pieces back
    return $manufacturer.'.'.$device_id;
}


Matrix Operation

Question: Let $x$ be a $n \times 1$ vector whose jth element is $x_j$. Show that $A = xx^{T}/x^{T}x$ and $B = I_n - A$ are symmetric idempotent matrices.
Note that $x^Tx$ is a scalar (real number)
Comment: What do you mean by $x$, $x'$ and In? Can you give some context, as well as what your thoughts on the problem are?
Answer: Notice that if $x\neq 0$ then $x^Tx\neq 0$ and then
$$A^T=\left(xx^T/x^Tx\right)^T=\frac{1}{x^Tx}\left(xx^T\right)^T=xx^T/x^Tx=A$$
so $A$ is symmetric and then $B$ is also symmetric, moreover we have:
$$A^2=\frac{1}{(x^Tx)^2}x(x^T x)x^T=\frac{1}{x^Tx}xx^T=A$$
so
$$B^2=(I-A)(I-A)=I-2A+A^2=I-A=B$$
and then $A$ and $B$ are idempotent matrices.
Answer: Since it is a little bit confusing to use $u v^T$ to represent the outer product of
a $n\times 1$ column vector $u$ with a $1\times n$ row vector $v^T$, let us
use an alternate notation $u \otimes v^T$ for such outer products.
Notice for any column vectors $a, b, c, d$, we have:
$$(a \otimes b^T)^T = (b \otimes a^T)
\quad\text{ and }\quad
(a \otimes b^T) (c \otimes d^T) = (b^T c) (a \otimes d^T)$$
These two equalities can be proved by expanding everything out
and one can check the matrix entries on both sides do match with each other.
Substitute $a,b,c,d$ by $x$ gives us:
$$
(x \otimes x^T)^T = (x \otimes x^T)
\quad\text{ and }\quad
(x \otimes x^T)^2 = (x^T x) (x \otimes x^T)$$
Divide the first equality by $(x^T x)$ and second by $(x^T x)^2$, we get
$A^T = A$ and $A^2 = A$, i.e. $A$ is a symmetric idempotent matrix.
As a consequence,
$$\begin{align}
& B^T = (I_n - A)^T = I_n - A^T = I_n - A = B\\
\text{ and }\quad &
B^2 = (I_n - A)^2 = I_n - 2 A + A^2 = I_n - 2 A + A = I_n - A = B
\end{align}$$
i.e. $B$ is also a symmetric idempotent matrix.

Matrix Operation


Having some problems with a horizontal navigation

Question: I have a django app that has a horizontal navigation. For some reason I am having problems creating a drop down menu.
Have a look at both of these images

The first image shows the horizontal navigation. On the left side of the image, there is a menu.

The second image shows when I hover over Storage orders (This is the only link that has a drop down menu.) For some reason the right hand side of the tab seems a bit off. This is because the length of the tab for storage, delivery and collection are different due to the number of words. I want to try to make all of these three tabs the same length if possible.
Another problem that I have is the left hand side menu moves to the right when I move my curser over storage orders.
base_menu.html

Home

Create quote/order

 Item Search

Storage orders

Delivery orders

Collection orders

Delivery list

Collection list

Export for invoicing

Backup data

Help

base.css
ul#toc {
    height: 2em;
    list-style: none;
    margin: 0;
    padding: 0;
}

ul#toc li{
    background:#ffffff url(../images/tab.png);
    float: left;
    margin: 0 1px 0 0;

}

ul#toc span {
    background: url(../images/tab.png) 100% 0;
    display: block;
    line-height: 2em;
    padding-right: 10px;
}

ul#toc a {
    color: #000000;
    height: 2em;
    float: left;
    text-decoration: none;
    padding-left: 10px;
}

ul#toc a:hover {
    background: url(../images/tab2.png);
    text-decoration: underline;
}

ul#toc a:hover span {
    background: url(../images/tab2.png) 100% 0;
    background-position: 100% -120px;

}

ul.subnav {
    float:left;
    display:none;
    position:absolute;
}

ul#toc li:hover .subnav {
    display:block;
}

EDIT: @Andres: If I make the change, you can see from the image below,  the drop down tab needs to be lowered a bit more. Also, the collection tab is missing as well, but the good thing is the left hand menu does not shift to the right.
Update @Andres: I have removed the  tag in the template has made the tab re-appear. Now using margin-top:10px seem to work. Now from the image below, I need to make sure my drop-down box can overlap the delivery header. And I think I may be done.
Answer: Try this:
ul#toc {
    height: 2em;
    list-style: none;
    margin: 0;
    padding: 0;
}

ul#toc li{
    background:#ffffff url(../images/tab.png);
    float: left;
    margin: 0 1px 0 0;
    position:relative;

}

ul#toc span {
    background: url(../images/tab.png) 100% 0;
    display: block;
    padding-right: 10px;
}

ul#toc a {
    color: #000000;
    float: left;
    text-decoration: none;
    padding-left: 10px;
}

ul#toc a:hover {
    background: url(../images/tab2.png);
    text-decoration: underline;
}

ul#toc a:hover span {
    background: url(../images/tab2.png) 100% 0;
    background-position: 100% -120px;

}

ul.subnav {
    float:left;
    display:none;
    position:absolute;
}

ul#toc li:hover .subnav {
    display:block;
}

since your ul.subnav class is still in the flow of things when it pops up it shifts things on the bottom, if you position it absolutely, relative to the parent li it should fix things up.
Comment: `@Andres:` Please look read the info above on the changes I have made.
Comment: Try adding "top:40px;" (adjust accordingly) to your "ul.subnav class" to bring it down and position as you see fit. Also, if you can post a link to the actual page it would be awesome, i can pinpoint all the changes exactly you need right away.
Comment: Just add "z-index:999" to your "ul.subnav" class and it should come up in top of everything.


I need help with a competition math problem please.

Question: I am a competition math student, and I was doing a practice test when I found this problem:
"The fourth degree polynomial equation $x^4 - 7x^3 + 4x^2 + 7x - 4 = 0$ has four real roots a, b, c and d. What is the value of the sum $1/a + 1/b + 1/c + 1/d$? Express your answer as a common fraction."
First of all, I don't think this polynomial can be factored, so I don't know how to find the reciprocals of the roots. I need help and any help would be appreciated! Note: When they say "Express your answer as a common fraction.", it means that the answer IS a fraction. I tried asking this question already, but I worded it differently, and they didn't get a fraction so I knew it was wrong. This is the link to my other question: Link
Comment: You may find [Vieta's formulas](https://en.wikipedia.org/wiki/Vieta%27s_formulas) useful.
Comment: Make the substitution $y=1/x$ and consider the quartic in $y$.
Comment: See [here](https://math.stackexchange.com/questions/3091605/solving-a-polynomial-with-grouping)
Comment: @J.W.Tanner It isn't a duplicate. Read my edit.
Comment: The answer there has been corrected now
Answer: The trick is to write
$$
\frac{1}{a}+
\frac{1}{b}+
\frac{1}{c}+
\frac{1}{d}=\frac{bcd+acd+abd+abc}{abcd}
$$
write $f(x)=x^4-7x^3+4x^2+7x-4=(x-a)(x-b)(x-c)(x-d)$ and use Vieta's  relations.
For example, by multiplying out we see at once that  $abcd=-4$ and $-(bcd+acd+abd+abc)=7.$
Answer: Suppose we have a polynomial $f(x)=a_nx^n+a_{n-1}x^{n-1}+\dots +a_0$ with roots $r_1,r_2,\dots, r_n$. We claim that the polynomial with roots $\frac{1}{r_1},\frac{1}{r_2},\dots,\frac{1}{r_n}$ is simply $g(x)=a_0x^n+a_1x^{n-1}+\dots + a_n$.  Why? Because if you observe that the roots of the polynomial $f(\frac{1}{x})$ are the reciprocals of the roots of $f(x)$, then our desired polynomial is $$\begin{align*}g(x)&=x^nf(1/x)\\&=x^n\left(\frac{a_n}{x^n}+\frac{a_{n-1}} {x^{n-1}}+\cdots+\frac{a_1}{x}+a_0\right)\\&=a_0x^n+a_1x^{n-1}+\cdots+a_n,\end{align*}$$
The desired polynomial can be found by simply 'reversing the coefficients' as shown above. Hence the polynomial with roots $\frac{1}{a},\frac 1b, \frac 1c,$ and $\frac 1d$  is $$-4x^4+7x^3+4x^2-7x+1$$ Applying Vieta's Formulae to this, we find that the sum of the roots is $-\frac{-7}{4}=\frac{7}{4}$.
Comment: Thanks! I got 7/4 too because my reasoning was that $x^4 p(1/x) = -4x^4+7x^3+4x^2-7x+1$ and the sum of the roots is $-7/-4=7/4$. I just wasn't 100% sure that you could do this.
Comment: @Spencer1O1 nice work! In the future, consider tagging your competition math questions with the tag [contest-math]
Comment: Okay! I tried to tag it with [competition-math], but it didn't exist. Thanks for the tip!


Fixing issue with program that calculates grade average with option of dropping lowest grade

Question: I need to create a program that calculates grade averages and provides the option of dropping the lowest grade. The program must allow the user to enter the number of students and number of grades per student. I keep getting "'int' object is not iterable" with respect to the "lowest" component. Please help.
def main():

    num_students=eval(input("Please enter the number of students you will have grades for: "))
    num_grades=eval(input("Please enter the number of grades per student: "))
    gcounter=0
    scounter=1
    drop=input("Do you wish to drop the lowest grade? Type yes or no: ")

    if drop=="no" or drop=="No" or drop=="n" or drop=="N":
        while scounter<=num_students:
            name=input("Please enter the student's name: ")
            grades_total=0
            while gcounter<num_grades:
                getgrade=eval(input("Enter grade: "))
                grades_total=grades_total+getgrade
                gcounter=gcounter+1

            print("The average grade for ", name, "is ", grades_total/gcounter)
            num_students=num_students-1
            scounter=scounter+1
            gcounter=0

    elif drop=="yes" or drop=="Yes" or drop=="y" or drop=="Y":
        while scounter<=num_students:
            name=input("Please enter the student's name: ")
            grades_total=0
            while gcounter<num_grades:
                getgrade=eval(input("Enter grade, including the lowest: "))
                lowest = min(getgrade)
                grades_total=grades_total+(getgrade-lowest)
                gcounter=gcounter+1

            print("The average grade for ", name, "is ", grades_total/(gcounter-1))
            num_students=num_students-1
            scounter=scounter+1
            gcounter=0
main()

Comment: `getgrade` is whatever was entered, not a list of grades, so taking the minimum doesn't make sense. Also `eval` is a dangerous choice here--you're accepting arbitrary user input. You're expecting either an int or a float, so cast to that.
Answer: Your issue is with the line lowest = min(getgrade). The min function expects to be passed an iterable argument, like a list or tuple. You're giving it a single number (assuming that what you typed in at the prompt). That can't work. You either need to put all the grades into a list first, then call min on it, or you need to do your checking of each grade differently (for instance, using < to test each grade against the previous minimum, which you'd probably need to initialize to something absurdly large, like float('inf')).
You certanly don't want to be subtracting the minimum value on every iteration. The simplest approach is to do that only at the end, after you've added up all the values (including the minimum):
        grades_total = 0
        lowest_grade = float('inf')                # initialize lowest_grade to infinity
        while gcounter < num_grades:               # this could be a `for` loop
            getgrade = int(input("Enter grade, including the lowest: "))
            grades_total += getgrade               # don't subtract minimum any more here
            gcounter += 1
            if getgrade < lowest_grade:            # check for minimum
                lowest_grade = getgrade
        grade_total -= lowest_grade                # subtract mimimum outside the loop

I'd also strongly recommend against using eval on user input, as that function would allow the user to type in any valid Python expression which your code would then run. You can use int to convert a string to an integer, usually, which it looks like is all you need. If you really do need to parse more complicated data structures like lists or tuples in one go, use ast.literal_eval from the standard library.
Comment: Would you please tell me what your solution is? I'm really confused and still don't understand what I need to do.
Comment: Alright, I've added some code. Making a list of grades might be a bit cleaner, but it would have involved changing more of the code. This approach (adding up and counting the values as you get them) works just fine.
Answer: Firstly, use ast.literal_eval instead of eval, as eval poses security risks.
Regarding your error, your error originates from these lines:
getgrade = eval(input("Enter grade, including the lowest: "))
lowest = min(getgrade)

The min function takes an iterable as input. If getgrade is an integer or not an iterable, e.g. tuple, list, set, then you can expect an error each time this line is reached.
You can correct this by asking for each grade one by one and forming a list, or have the user input a list such as "[55, 65, 70, 82]". This will have knock-on effects for your entire script, so you should decide how to approach your data types from the start.


Electric drum kit noise - cymbals only (Need advise to reduce noise)

Question: I have read lots of posts about electric drum noise especially in apartments, but these posts relate to the kick drum the the thump sound either upwards or downwards.
emphasized text
I have experienced complaints from neighbours because of the rubber cymbal noise. I have a roland kit with VH-11 and CY-12C cymbal pads.
Does anyone have any suggestions about reducing the noise on these?
Thanks,
Jack
Comment: I have heard of people taping a think cloth to it, not sure how that will affect the sensitivity of the pad, but it would probably work in a pinch.
Comment: You have some very thin walls. Long term, I'm afraid your best option is to look forward to your next move and hopefully you can find a place where a reasonable (IMHO) amount of noise won't sound so loud to your neighbors. Regarding your question, where do the complaining neighbors live? Below? Above? On the same level? Adjacent to the room where the kit is or two rooms over?
Comment: Yeah, I can hear people coughing from the next apartment so drums are  not welcome. The complaining neighbours live above (i am ground floor), but I have neighbours on all sides of the apartment.
Answer: For the kick pedal(s) you can try building a "floating floor."
I have seen people who take two pieces of board separated by an array of tennis balls (usually held in place by means of small holes or collars.
Put a mat on the floor, put the floating boards on that mat and another mat ion top. This raises everything by maybe 4 inches, disperses the downward forces across a wider surface area, has a dampening effect. All of this should reduce the transmission of noise through the floor from the physical action of the pedals.
If you want to make a big enough platform, your whole kit can be decoupled from the floor which will reduce noise from the movement of the kit "scaffolding."
The cymbals are more complicated in that any dampening will result in potential trigger sensitivity issues. Maybe try moving the kit away from the shared wall. A very thick duvet hung as a tapestry might work to reduce any mid to high frequency transmission through the shared wall.
Comment: The key seems to be (at the floor interface) a rug or mat and then some form of thick high density, heavy material and then the decoupling (tennis balls etc). I just came across one individual who made a box and filled it with sand. Very heavy
Comment: I will attempt the riser as that can't hurt to reduce some noise. As the cymbals are attached to the rack, there is probably some impact noise going through the floor as well.
Answer: A method I used on a kit at school years ago is to simply put any cloth, in my case felt, on the cymbal. cut a circular hole in your cloth to attach it to the cymbal then just hang it over the cymbal. It's does not create the best results of all but it does minimize the noise of the sticks on the cymbals. the thicker the cloth the more noise reduction but the less response on the electronic cymbals if you go too far.
It's cheap and easy and works quite well.


how to convert .raw file to .jpg or .png using python 2.7 in windows

Question: I want to convert .raw file to .jpg or .png using some plain python code or any module that is supported in python 2.7 in windows environment.
I tried rawpy, PIL modules.
But I am getting some attribute error(frombytes not found); because it is supported in Python3. Let me know if i am wrong..
In rawpy the RAW format is not supported.
I need some module or some code that will change .raw to either png or jpeg.
Comment: *".raw"* does not define a file - it may be a Nikon `NEF` file, a Canon `CR2` file, an Adobe `DNG` file or a pure raw, binary file which is no use to man or beast without knowing its dimensions, endianness, number of channels, interleave, compression etc.
Comment: Are you planning on updating your question in the light of my comment?
Answer: use PIL library
from PIL import Image

im = Image.open("img.raw")
rgb_im = im.convert('RGB')
rgb_im.save('img.jpg')

Answer: You can use the convert utility which comes with image magic.
convert -size 640x360 -depth 8 bgr:input.raw out.jpeg

-size -> WxH
bgr is the format of data. it can be rgb also.


Add > (greater than) sign to the end of the links with CSS

Question: Is there a way to add > to the end of all hrefs using CSS?
Answer: You can use the :after selector and the content property:
a:after {
    content: ">";
}

Note that pseudo-elements created this way are not part of the DOM and therefore you can't get a reference to them in JavaScript.
Comment: If the page contains named anchors and you don't want to add the `>` to those anchors, use `a:link:after, a:visited:after` instead.
Comment: Darn, I was 20 seconds off posting! +1
Comment: @BoltClock - Nice one, didn't think of that.
Comment: @Romario - I'm afraid not (http://www.quirksmode.org/css/contents.html#t15)... if you want to do that you may have to resort to JavaScript.


How does LinearNDinterpolator really work? The theory behind it?

Question:     from scipy.interpolate import LinearNDInterpolator
    import matplotlib.pyplot as plt
    import numpy as np

    x = np.array([1,1,5,6])
    y = np.array([1,5,5,5])
    z=[2,6,10,11]

    points = np.array(list(zip(x,y)))
    values = np.array(z)

    i=2
    j=4.5

    Linear = LinearNDInterpolator(points, values)
    r = Linear(i,j)
    print("Linear %s" %r)

    plt.scatter(x, y,c=z)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('y as a function of x')
    cbar = plt.colorbar()
    plt.show()

#This is a very simple code. But I want to know how LinearNDInterpolator is really working? And is the idea similar in 3d?
Answer: We can see in the documentation that this is a Piecewise linear interpolant. You can find a presentation of that here.
Also:

The interpolant is constructed by triangulating the input data with Qhull, and on each triangle performing linear barycentric interpolation.

About Qhull. And you can find an article about linear barycentric interpolation here.


Subtracting previous row to current row of timestamp datatype

Question: I need to subtract current REQ_START_DATE from ( previous ACTUAL_START_DATE + RUN_DURATION) in order to check the timing whether job is requested before completion of the previous execution.
Tried using below query:
WITH delay_in_start AS (
SELECT  LOG_ID, LOG_DATE, OWNER, JOB_NAME, REQ_START_DATE, ACTUAL_START_DATE,run_duration, ROW_NUMBER() OVER (PARTITION BY job_name ORDER BY req_start_date desc) RN
FROM dba_scheduler_job_run_details t
)
SELECT cast(A.req_start_date as date) - cast((B.ACTUAL_START_DATE + b.run_duration)  as date) Consumption, a.*, b.*
FROM delay_in_start A LEFT JOIN delay_in_start B
    ON B.JOB_NAME = A.JOB_NAME
    AND A.RN  = B.RN - 1
    where cast(A.req_start_date as date) > (cast(B.ACTUAL_START_DATE as date) + b.run_duration)

But not sure of the output.
Can someone help?
Comment: What are you not sure about? You haven't shown any sample data, current output or expected output, so we don't have much to go on. (Also, look at the lag function to look at the previous row, rather than using a subquery with row number; you may find it simpler.)
Comment: lag function doesn't help in date datatype. Since dba_scheduler_job_run_details  is a view for jobs and exists globally hence I didnt provided sample. My requirement is to just calculate req_start_date of job (last execution) shouldn't be lesser then the actual_start_date + run_duration of job (second last execution)
Comment: You're wrong about lag, but that's kind of a side issue. You still haven't said what you are not sure about. Have you just got `>` instead of `<` in your where clause, if you only want to see those that overlapped?
Answer: Based on your description, you seem to be comparing the wrong way around; your where-clause filter is looking for requested dates after the completion of the previous job, based on its actual start time and duration - not before.
So you can perhaps just change the logic to:
where cast(A.req_start_date as date) < (cast(B.ACTUAL_START_DATE as date) + b.run_duration)

I'm not sure why you're casting the timestamps to dates though; you're losing precision, which could mean you miss jobs that ran very close together (sub-second gap). On my test instance I see 23 records with those casts - all from ORACLE_APEX_MAIL_QUEUE - but 36 if I leave them as timestamps.
You can also use lag() instead of self-joining based on row number:
select lag_actual_start_date + lag_run_duration - req_start_date as consumption,
  t.*
from (
  select dba_scheduler_job_run_details.*,
    lag(actual_start_date)
      over (partition by job_name order by req_start_date) as lag_actual_start_date,
    lag(run_duration)
      over (partition by job_name order by req_start_date) as lag_run_duration
  from dba_scheduler_job_run_details
) t
where req_start_date < lag_actual_start_date + lag_run_duration
order by job_name, req_start_date;

Which gives the 'consumption' as an interval - positive as I've switched the terms round in that subtraction too.
The results currently include only the actual start date and duration from the previous row; if you wanted other fields then you could include lag clauses for those too. I would also avoid *, but I don't know which columns you are actually interested in, from either the current or previous row.
Answer:
lag function doesn't help in date datatype.

No, That's not right and you may be looking for something like this.
SELECT JOB_NAME,
  CASE
    WHEN REQ_START_DATE >= LAG ( actual_start_date + run_duration )
     OVER ( PARTITION BY JOB_NAME ORDER BY LOG_DATE )
    THEN 1
    ELSE 0
  END
FROM dba_scheduler_job_run_details;

Answer: Used below query to get the data of all the jobs whose differs in req_start_date and actual_start_date excluding those job's details which gets delayed because of previous job run delayed (i.e.  don't want to get alerted if the delayed start is due to previous run not completed)
and who is taking more than 60 secs
SELECT extract(DAY FROM(t.actual_start_date - t.req_start_date)) * 24 * 60 * 60 +
       (extract(hour FROM(t.actual_start_date - t.req_start_date))) * 60 * 60 +
       (extract(minute FROM(t.actual_start_date - t.req_start_date))) AS duration,
       t.*
FROM (SELECT d.*,
             lag(actual_start_date) over(PARTITION BY job_name ORDER BY req_start_date) AS lag_actual_start_date,
             lag(run_duration) over(PARTITION BY job_name ORDER BY req_start_date) AS lag_run_duration
      FROM dba_scheduler_job_run_details d) t
WHERE ((lag_actual_start_date IS NOT NULL AND req_start_date > lag_actual_start_date + lag_run_duration) OR -- For Jobs running at frequent time interval
      (lag_actual_start_date IS NULL AND actual_start_date > req_start_date))        -- For Jobs scheduled at single time interval
AND extract(DAY FROM(t.actual_start_date - t.req_start_date)) * 24 * 60 * 60 +
      (extract(hour FROM(t.actual_start_date - t.req_start_date))) * 60 * 60 +
      (extract(minute FROM(t.actual_start_date - t.req_start_date))) > 1
ORDER BY log_date DESC;


Fatal error: Call to undefined method DOMElement::item()

Question: The code crawls several URLs and it stops at some url with the following error:
 Fatal error: Call to undefined method DOMElement::item()

Why this error is showing up?
Answer: Probably because DOMElement doesn't have a method named item().


Solving recursion by analogy with a differential equation

Question: I came across this problem:

Let sequence $u_n$ be defined by its first term $u_0 > 0$ and $$\forall n \in \mathbb{N}, \quad u_{n+1} = u_n + \frac{1}{u_n}$$ Find an asymptotic formula for $u_n$.

I thought that we could solve it by analogy with the equation $$f' = \frac{1}{f}$$ which gives the asymptotic formula $u_n \sim \sqrt{2 n}$, and this is indeed the right answer.
More generally, is we take $u_0 > 0, \forall n \in \mathbb{N}, u_{n+1} = u_n + f(u_n)$, what would be the conditions on a continuous, positive, decreasing function $f$ such that the method of analogy with a differential equation gives the right asymptotic formula ?
Thanks a lot !
Comment: Considering this from the opposite perspective is interesting. If we have the differential equation $\frac{dy}{dx} = f(y)$ with initial condition $y(0) = y_0$, then applying [Euler's method](https://en.wikipedia.org/wiki/Euler_method) with step size $1$ gives us the approximation $y(n) \approx u_n$, where $u_n$ satisfies the recurrence $u_{n+1} = u_n + f(u_n)$ and $u_0 = y_0$. I suspect that your approach having the correct asymptotics is equivalent to the convergence some approximations from Euler's method to this differential equation's solution.
Answer: As is noted in the comment below, this answer is incorrect

Suppose that $y$ is a solution to the differential equation $y' = f(y)$, and $u_n$ solves the recurrence $u_{n+1} = u_n + f(u_n)$ with $u_0 = y(0)$.  By the mean value theorem, we find that for all $n$, there exists a $c \in [n,n+1]$ for which $y(n+1) - y(n) = y'(c).$ Because $f$ is decreasing, we have
$$
f(y(n)) = y'(n) \geq y(n+1) - y(n) \geq y'(n+1) = f(y(n+1)).
$$
Now, suppose that $w_n$ satisfies $w_{n+1} = w_n + f(w_n)$, and $w_0 = y(1)$.  We find inductively that $u_n \leq y(n) \leq w_n$. In particular, we we that if the inequality holds for $n = k$, then
$$
\begin{align}
w_{k+1} &= w_k + f(w_k) \geq y(k) + f(w_k) \geq y(k) + f(y(k))
\\ & \geq y(k) + [y(k+1) - y(k)] = y(k+1),
\end{align}
$$
and the inequality $y(k+1) \geq u_{k+1}$ can be seen similarly.
With that, we can conclude the following: if $f$ is such that the recurrence $u_{n+1} = f(u_n) + u_n$ has the same asymptotics for all $u_0 > 0$, then it follows that the asymptotics of the sequence $(y(n))_{n \in \Bbb N}$ generated from a solution to $y' = f(y)$ with $y(0) > 0$ are the same.
Comment: Hi, thank you for your answer but I think the inequality $y(k)+f(w_k) \geq y(k)+f(y(k))$ is wrong since f is decreasing and $w_k \geq y(k)$
Comment: @25laps Of course, good catch. I do suspect that this argument can be fixed, but I'll have to think about it


How to disable mod_pagespeed without having to reboot server?

Question: I have a centos 7 with mod_pagespeed installed, and whenever I want to disable mod_pagespeed momentarily I go to /root/rpmbuild/BUILD/etc/httpd/conf.d/pagespeed.conf and set below line to off
<IfModule pagespeed_module>
    ModPagespeed off

What happens is that it won't take effect at all. Pages will still be shown cached until I reboot the server.
Is there a way to not reboot?
thanks
Answer: Just restart only the web server.
service httpd restart

(or whatever method does that in your cleary non-standard web server install)


VMware detects wrong drive as C:\

Question: After installing SP2 to W2K3 straight after adding a second drive, my VM after restart is now detecting the 2 disks the wrong way around. I am getting "Operating System not found" and when I boot from a recovery disk it offers me the chance to log into "D:\Windows" - it should be C:!
What is the quickest way for me to get the VM detecting the drives in the correct order again so I can boot?
UPDATE:
Ultimately LukeR below is correct. I was able to do it from within "Edit Settings" on the individual hard drives rather than editing the vmx directly, but the SCSI order was the correct solution.
WHY did it happen? Because this was originally, months ago, a P2V server, and the P2V process had assigned C drive to SCSI 0:1 rather than 0:0. That was fine, right up to the point I added a second HDD, which ESX gave the ID 0:0. As soon as I rebooted, it decided 0:0 was the lowest and therefore primary partition, and tried to boot off that. All I had to do was switch the IDs around.
Comment: Yes, adding a second disk was the instigator of your problem.  It will always add on the lowest available scsi id, unless you specify otherwise.  For some reason (perhaps you originally had another disk that was removed due to resizing?) SCSI 0:0 was left unused.
Comment: One of my workmates says they have seen it before where a server that is put through P2V ends up with its HDD as 0:1 rather than 0:0. Something I will watch out for next time!
Answer: Check the .vmx file in the folder where your VM disk is held.
This holds configuration information for your Virtual Machine, you can edit it with a text editor. Shut down your VM first.
From one of my config files:
<code>scsi0:0.present = "TRUE"
scsi0:0.fileName = "Ubuntu.vmdk"
</code>
This represents the system disk in this particular VM.
If you have multiple disks, you should be able to edit these entries to the correct order.
Comment: I think you are absolutely right and came to the same likely conclusion literally seconds before reading your post! However I've found I don't have permission to edit or copy the vmx file location directly - arranging it now.
Comment: Good stuff. Glad you got it sorted.

VMware detects wrong drive as C:\


c# collection manipulation with Linq

Question: I have a collection in this format
IList<ReportRow> MyCollection

Where ReportRow is a
Dictionary<string, object>

So MyCollection might look like this:
    Id1 Id2 Value   Status  Entered
    123 2   56      New     50:01.7
    123 2   76      Old     50:23.0
    123 2   12      New     50:23.0
    127 3   54      Old     50:23.0
    127 3   77      New     59:23.0

...
Is there a way in Linq that I can do this:
What I need to do is for each Id1+Id2 combination I need to output the Value where Status is New and where the status is Old. There might be multiple New values for an Id1+Id2 combination so it should pick up the latest New record, using the Entered column to sort.
The new record will contain all the records plus 1 extra column like so:
    Id1 Id2 NewValue    OldValue    Entered
    123 2   12          76          50:23.0
    127 3   77          54          59:23.0

Any help with this would be great
Comment: How does it come that `ReportRow` contains 5 values (Id1, Id2, Value, Status, Entered) when it is `Dictionary`?
Comment: Can you post the Entity classes? Or the snippet of Linq that you using so far.
Answer: from row in MyCollection
group row by new { row.Id1, row.Id2 } into g
let lastNew = g.OrderByDescending(r => r.Entered)
               .FirstOrDefault(r => r.Status == "New")
let lastOld = g.OrderByDescending(r => r.Entered)
               .FirstOrDefault(r => r.Status == "Old")
select new {
   Id1 = g.Key.Id1,
   Id2 = g.Key.Id2,
   NewValue = (lastNew == null) ? null : (int?)lastNew.Value,
   OldValue = (lastOld == null) ? null : (int?)lastOld.Value,
   Entered = g.OrderByDescending(r => r.Entered).First().Entered
}

Answer: This should do it (or be close as this is off the top of my head)
collection.OrderByDescending(r => r.Value.Entered)
          .GroupBy(r => {r.Id1, r.Id2)
          .Select(g => new {
               Id1 = g.Key.Id1,
               Id2 = g.Key.Id2,
               NewValue = g.FirstOrDefault(v => v.Status == "New").Value ?? 0,
               OldValue = g.FirstOrDefault(v => v.Status == "Old").Value ?? 0,
               Entered = g.Last().Entered
           })

If you don't care for the dictionary string key you could do
collection.SelectMany(d => d.Value)
          .OrderByDescending(r => r.Value.Entered)
          .GroupBy(rr => {rr.Value.Id1, rr.Value.Id2)
          .Select(g => new {
               Id1 = g.Key.Id1,
               Id2 = g.Key.Id2,
               NewValue = g.FirstOrDefault(v => v.Status == "New").Value ?? 0,
               OldValue = g.FirstOrDefault(v => v.Status == "Old").Value ?? 0,
               Entered = g.Last().Entered
           })

c# collection manipulation with Linq


Second derivative of Brownian motion?

Question: My question is, we give a meaning to the following expression:
$$dX(t) = \mu(t,X(t))dt + \sigma(t,X(t))dW(t), \ \ X(0)=x.$$
where $W$ is a Wiener process.
This equation can be thought as
$$\frac{dX(t)}{dt} = \mu(t,X(t)) + \sigma(t,X(t))\frac{dW(t)}{dt}, \ \ X(0)=x.$$
Now, if I wanted to differentiate again in an ODE I would write something like:
$$\frac{d^2X(t)}{dt^2} = \mu'(t,X(t)) + \sigma'(t,X(t))\frac{d^2W(t)}{dt^2}, \ \ X(0)=x.$$
But, my question is, can we do this in Stochastic ODE's? Does the term $\frac{d^2W(t)}{dt^2}$ have a meaning? What would one do in this case? Any idea, literature, reference?
Thank you for your help!
Answer: what you can do is filtering first the Wiener process by a compactly supported  $C^k$ function (hence it is a low-pass filter), then differentiating at most $k+1$ times.
Answer: When you write
$$dX(t) = \mu(t,X(t))dt + \sigma(t,X(t))dW(t), \ \ X(0)=x.$$
this is an 'abuse of notation' and should be read as the equation
$$X(t)-x = \int_0^T\mu(t,X(t))dt + \int_0^T\sigma(t,X(t))dW(t)\qquad t\geq0.$$
This equation can't be solved pathwise since it would have no meaning. It has a more complex structure due to the stochastic integral $\int_0^T\sigma(t,X(t))dW(t)$ which is not differentiable in $T$.
Comment: Sure.. I see it, thanks a lot :)
Comment: "This equation can't be solved pathwise since it would have no meaning" This is unrelated to the question asked and is in fact false: for tons of functions $(\mu,\sigma)$, the SDE can very much be solved pathwise.

Second derivative of Brownian motion?


Get the reflection of a POINT M[row][col] on a SQUARE matrix M, of size N

Question: I have the following 7 x 7 matrix, which I'll name M. It has a value of 1 at M[2,2].
<code>       [[0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]]
</code>
If I rotate the matrix 180 degrees I would get the REFLECTION of the matrix, and 1 would be now at M[4,4].
<code>       [[0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]]
</code>
I'm looking for a formula to find the REFLECTION OF A POINT on a square matrix without doing the actual 180 degree rotation to get the result. A function to which I could pass f(M[2,2]), and get f(M[4,4]). This function should map M[row][col] to M[reflected_row][reflected_col] for ALL the points that could have a reflection on a SQUARE matrix of size N.
Thanks
p.s. I using python with numpy
Comment: You should ask this on Stack Overflow instead if you want the code for it. Or do you want a mathematical function?
Answer: A mathematical function that does the trick is simply
$$f:M_{i,j} \mapsto M_{N-i,N-j},$$
but perhaps you are looking for a function in Python that does this? In that case, either simply define it yourself or ask over at Stack Overflow.
Comment: Wow, that's what I was looking for. Does this function have a formal name after which it is known in the field? Thanks a lot!
Comment: @OantaWilliamRichard Glad it was helpful! Hmm, I don't know the name, perhaps it doesn't even have one - I just sat down with a drawing and found that this one would do the trick :)


How to change table direction in Apache word poi (XWPF)?

Question: I'm trying to use Apache poi word 3.8 to create word document in Persian/Arabic language.
My question is: how to change table direction in document? It means order of column in table(not text direction inside table cell).
For example:

In MS word we could change table property using:
Comment: Possible duplicate of [how change text direction(not paragraph alignment) in document in apache poi word?(XWPF)](http://stackoverflow.com/questions/38802115/how-change-text-directionnot-paragraph-alignment-in-document-in-apache-poi-wor)
Answer: If the whole table shall be bidirectional, then the org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr must contain bidiVisual set to ON.
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import java.math.BigInteger;

public class CreateWordRTLTable {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("Paragraph 1 LTR");

  paragraph = doc.createParagraph();

  //create table:
  XWPFTable table = doc.createTable();
  //set the table itself to bidi visual
  if (table.getCTTbl().getTblPr() == null) {
   table.getCTTbl().addNewTblPr().addNewBidiVisual().setVal(STOnOff.ON);
  } else {
   table.getCTTbl().getTblPr().addNewBidiVisual().setVal(STOnOff.ON);
  }
  //create first row
  XWPFTableRow tableRow = table.getRow(0);
  tableRow.getCell(0).setText("first cell");
  tableRow.addNewTableCell().setText("السلام عليكم");
  tableRow.addNewTableCell().setText("third cell");
  //Each cell contains at least a paragraph. Those can be set to support bidi.
  for (int col = 0 ; col < 3; col++) {
   paragraph = tableRow.getCell(col).getParagraphs().get(0);
   CTP ctp = paragraph.getCTP();
   CTPPr ctppr = ctp.getPPr();
   if (ctppr == null) ctppr = ctp.addNewPPr();
   ctppr.addNewBidi().setVal(STOnOff.ON);
  }

  //create CTTblGrid for this table with widths of the 3 columns.
  //necessary for Libreoffice/Openoffice to accept the column widths.
  //values are in unit twentieths of a point (1/1440 of an inch)
  table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
  for (int col = 1 ; col < 3; col++) {
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
  }

  //create and set column widths for all columns in all rows
  //most examples don't set the type of the CTTblWidth but this
  //is necessary for working in all office versions
  //values are in unit twentieths of a point (1/1440 of an inch)
  for (int col = 0; col < 3; col++) {
   CTTblWidth tblWidth = CTTblWidth.Factory.newInstance();
   tblWidth.setW(BigInteger.valueOf(2*1440));
   tblWidth.setType(STTblWidth.DXA);
   for (int row = 0; row < 1; row++) {
    CTTcPr cttcpr = table.getRow(row).getCell(col).getCTTc().getTcPr();
    if (cttcpr != null) {
     cttcpr.setTcW(tblWidth);
    } else {
     cttcpr = CTTcPr.Factory.newInstance();
     cttcpr.setTcW(tblWidth);
     table.getRow(row).getCell(col).getCTTc().setTcPr(cttcpr);
    }
   }
  }

  paragraph = doc.createParagraph();

  doc.write(new FileOutputStream("WordDocument.docx"));

 }
}


Suppose we have $N_0$ with $s_n\leq t_n$ for all $n>N_0$. Prove if $\lim_{n\to\infty}s_n=+\infty$, then $\lim_{n\to\infty}t_n=+\infty$.

Question:
Suppose there exists $N_0$ such that $s_n \leq t_n$ for all $n > N_0$. Prove if $\lim_{n\to\infty} s_n = +\infty$, then $\lim_{n\to\infty} t_n = +\infty$.

Having been exposed to analysis for the first time recently, I find it very easy to get lost down blind alleys and lose track of quantifiers, etc. As such I'm not entirely sure if my proof is valid. Here is my attempt at the proof:
Let $M > 0$. First we observe since $\lim_{n\to\infty} s_n = +\infty$, there must exist $N_1$ such that $n > N_1$ implies $s_n > M$. Let $N = N_0 + N_1$. Then, we see that $n > N$ implies $t_n \geq s_n$, and since we have $s_n > M$, it must be the case that $t_n \geq s_n > M$, and so $t_n > M$, which proves the limit in question.
Comment: Why was the question downvoted?
Comment: I guess you'd like someone to comment on your work above? It looks O.K. You could explain/justify a little more, in particular that you use the fact that $s_n$ is unbounded to show that $t_n$ is unbounded.
Answer: I think we have pick $N = \max (N_0, N_1)$ and then we have that $t_n \geq s_n$ for all $n \geq N$ and moreover, $t_n > M$ as desired.
Comment: Well, $N$ could be any integer greater than both $N_0$ and $N_1$ and OP's  choice of $N_0+N_1$ is also fine. I agree taking a max here is conventional, but as per limit definition it's not necessary.


How to use PAM to manage lockout policy for ssh public key authentication methods

Question: I have followed instructions on redhat on how to harden authentication on a linux server, but we only use SSH with public key auth. According to these instructions:
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/security_guide/chap-hardening_your_system_with_tools_and_services
Here is my /etc/pam.d/system-auth and /etc/pam.d/password-auth files, they are both the same actually:
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        required      pam_faildelay.so delay=2000000
auth        required      pam_faillock.so preauth silent audit deny=3 even_deny_root unlock_time=60
auth        sufficient    pam_unix.so nullok try_first_pass
auth        [default=die] pam_faillock.so authfail audit deny=3 even_deny_root unlock_time=60
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so

account     required      pam_faillock.so
account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so

With this config, I was hoping to achieve some kind of lockout message if user tries to authenticate with the wrong key after 3 tries for example. But no message about lockout pops up, and I have no way to tell if lockout policy is working or not. There is also the pam_tally2 module, but I don't see what difference it would make vs the pam_faillock module.
The logs show nothing except that root permission denied:
[some_user@ip-10-10-2-53 ~]$ cat /var/run/faillock/some_user
[some_user@ip-10-10-2-53 ~]$ cat /var/run/faillock/root
cat: /var/run/faillock/root: Permission denied

And I have tried to use the wrong key to ssh for some_user, and it does not seem to lock me out because I don't see anything in the faillock logs or any ssh message from where I try to ssh.
Answer: The problem is that you're trying to enforce these policies inside of the auth stack.
auth        required      pam_env.so
auth        required      pam_faildelay.so delay=2000000
auth        required      pam_faillock.so preauth silent audit deny=3 even_deny_root unlock_time=60
auth        sufficient    pam_unix.so nullok try_first_pass
auth        [default=die] pam_faillock.so authfail audit deny=3 even_deny_root unlock_time=60
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so

account     required      pam_faillock.so
account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     required      pam_permit.so

Public key authentication implemented within the SSH daemon itself bypasses the auth stack. (there's no PAM auth module being called to validate the submitted key, so it has to work that way) The sole exception is when you're running a customized configuration that requires success inside of keyboard-interactive as well. Since this is not the default, your auth stack is almost certainly being ignored during these authentications.
While the account stack is usually where you place restrictions on publickey-only logins, I don't believe that will work here as you would first have to succeed at authenticating in order for the PAM module to be called. If your PAM module isn't being called, it isn't able to increment a count with each failed login.
The only way I can see this working is if you adjust your sshd configuration to require keyboard-interactive authentication in addition to public key authentication. (you can use this Q&A as a starting point) That said, as JohnA points out it is debatable whether this would truly provide any value.
Answer: I'm pretty sure that you won't be able to use PAM in this capacity.  If the user does not have the ssh private key that corresponds to the ssh public key on the server, then they will not be able to authenticate.
The purpose of password failure lockout is to prevent brute forcing of the password on a user account.  If ssh key authentication is enforced, there is no user account password to take into account.
In the case of the password that is requested for ssh key auth, this is the password for the private key.  Failure to authenticate against the private key does not result in any authentication failure to the server.


Listar o dono do post e o último usuário que comentou. Mysql

Question: Eai galera, eu tenho a seguinte query abaixo, onde eu listo todos os posts, quantidade de comentários e o usuário que o criou, mas também queria listar o último usuário que comentou cada post, será que dá pra fazer tudo isso em apenas uma query?
<code>SELECT post.titulo, COUNT(comentario.codigo), autor.nome, MAX(comentario.codigo_usuario) FROM post JOIN comentario JOIN usuario autor JOIN usuario ON post.codigo_usuario = autor.codigo AND post.codigo = comentario.codigo_topico AND usuario.codigo = comentario.codigo_usuario GROUP BY post.codigo
</code>
Comment: Só uma observação, se for para usar JOIN, acho que fica mais interessante com a cláusula ON em vez de WHERE: `JOIN comentario ON post.codigo = comentario.codigo_post JOIN usuario ON ...`. Ou, se prefere mesmo o WHERE, não precisa de JOIN, separe as tabelas com vírgula `FROM post, comentario, usuario WHERE post.codigo`. Claro que você deve fazer como achar melhor, a sugestão é só no sentido de "padronizar", caso ache interessante.
Comment: Uma possibilidade seria, supondo que os comentários tenham ID em  ordem temporal usar um novo JOIN vinculando o MAX( comentario.id ) novamente à tabela comentários, e obtendo o ID do comentarista. Alternativamente, no MySQL dá pra usar o ORDER BY ... DESC para o GROUP pegar o ultimo de uma determinada tabela, mas não é garantido que isso funcionará em versões futuras
Comment: Irei utilizar ON então. Não entendi muito bem o que tu disse, não to conseguindo pegar o nome de quem criou o post e ao mesmo tempo pegar o nome do ultimo q comentou, e o ORDER BY eu vou utilizar para ordenar pelo nome do post.
Comment: Lembre-se que nada impede de fazer ORDER BY nome, post.id DESC, por exemplo (ordenando prioritariamente pelo nome, mas deixando o ID decrescente do post como 2º fator de ordenação). O ORDER BY pode aceitar várias expressões e/ou colunas diferentes separadas por vírgula.
Comment: Quanto a pegar os nomes separadamente, se ambos forem da tabela usuário, precisa dar JOIN duas vezes JOIN usuario AS autor ON... JOIN usuario AS comentarista ON ...
Comment: Não sabia que dava pra usar duas cláusulas no ORDER BY. Editei o post colocando como está a query, eu usei o MAX para pegar o codigo do ultimo usuario q comentou, mas como eu uso esse codigo para comparar com a tabela usuario(para pegar o nome)? Já que só da pra usar o MAX no select e não no ON
Comment: Conseguir fazer, coloquei um "usuario.codigo = (select max(codigo_usuario) from comentario where comentario.codigo_post = post.codigo" para fazer a comparação com o código do usuário. Valeu pela ajuda!
Answer: Dá pa fazer, precisas de ter um atributo do genero DATE ou DATETIME, que te guarda a data em que o post foi feito, tudo depende como tens construido a base de dados
Comment: Eu tenho um campo de data, mas não consigo imaginar como mudar esse select para listar somente o ultimo que comentou.


Create a graph of dominant frequencies at each point in time in signal?

Question: I have a signal that varies in frequency and amplitude, and I want to create a moving window that takes a number of samples, finds out the "dominant frequency" in the window using FFT, and stores the frequency in another vector, before moving the window one step until the entire original signal has been analyzed.
This is what I have come up with so far, but the resulting graph looks very weird, so it's not working the way I want it to...
Fs = 200; % Samples per second
samples = 100; % Window size (samples)

freq = zeros(samples,1); % Output vector, starting with zeroes

% Move the window along the signal, starting at "samples" offset
for x = samples+1:1:length(signal)
    % Get samples from signal in the "window"
    windowFreq = signal(x-samples:x);

    % Perform FFT
    myFFT = fftshift( fft(windowFreq) );

    % Store "dominant frequency" from the FFT
    freq(x) = max(myFFT);
end

plot(freq);

Comment: Yes an uncomplicated way of doing it is multiplying with something that is close to 0 at the edges but close to 1 in the middle and some smooth curve in between.
Comment: Max is not defined for complex values and fft returns coefficients according to the complex exponential definition of the Fourier Transform giving complex coefficients.
Comment: What you want to do is maybe [~,idx] = max(abs(myFFT)); freq(x) = idx; because it is not the value of the max of abs but the index where the max of abs occurs.
Comment: And except for that you may also want to window the signal with some function that decays to 0 at the edges so that any discontinuity jump from the edges does not contaminate the spectrum.
Comment: @mathreadler Thanks! How can I make that kind of window function? Do you mean the amplitude of the signal in the window should "fade out" at the edges? Right now I get a maximum frequency of 0 most of the time...
Comment: If you want your code to be robust with respect to noise, you'll need to use dynamic programming in the spectrogram for finding the path (constrained to have slow frequency variation) in the spectrogram maximizing the energy.
Answer: I have found few problems in your approach.

Moving window FFT should only be used for constant
frequency signals (if number input samples remains the same):
The input of FFT should be an integer number of cycles of the base frequency and the dominant frequency should be one of the harmonic of the base frequency. Now if the frequency is varying with each moving window, the number of input samples to FFT should also vary. Instead of going further into details, I will illustrate this concept with the following example:
nbSamples = 100;
samplingFrequency = 5000;
cycleEnd = 0.020;
time = linspace(0, cycleEnd, nbSamples);
windowFreq = sin(2*pi*50*time);
myFFT = fftshift(fft(windowFreq));
fshift = (-nbSamples/2:nbSamples/2-1)*(samplingFrequency/nbSamples);
powershift = abs(myFFT).^2/nbSamples;
dominatingFreq = max(fshift(1, find(powershift == max(powershift))))

Here you will get the dominatingFreq equals to 50 hz, which is correct. Now change the signal frequency to 60 hz without changing the cycleEnd and samplingFrequency. The results will be incorrect. You need to change the values of sampling frequency and cycleEnd to 6000 hz and 0.0167 seconds respectively to get correct results (you can also change the number of samples given that it's an integer).
What if dominating frequency is an inner-harmonic?
In your example the base frequency is 2 hz.$$baseFrequency = \frac{samplingFrequency}{NumberOfSamples}$$If the dominating frequency is an inter-harmonic (not an integer multiple of base frequency), it will not be clearly present in the output.
Few bugs in your code
freq(x) = max(myFFT) is not the frequency (its frequency strength at a given frequency). Use instead max(fshift(1, find(powershift == max(powershift)))) to get highest positive dominating frequency. Minor remarke: Index of frequency starts from 100 in your code.

I can't provide you an exact solution to your problem but you can try to use an enhanced version of DFT for this specific case. Otherwise you can also have a look at least squares base algorithm which is known to free from obligation of integer number of input cycles.
I hope that helps.


Realizar um cálculo de valores anteriores em coluna no R

Question: Gostaria de montar uma coluna de acordo com o resultado de 2 linhas de uma outra coluna, segue a fórmula abaixo, não faço ideia de como montar isso no R ou no Python e gostaria de uma colaboração de vocês.
Dando um exemplo no Excel
                coluna 1   coluna 2
      célula D2 - 558,8       1
      célula D3 - 584,3       1
      célula D4 - 603,3   =SE(D4-D2>=D2*0,02;1;SE(D4-D2<=-D2*0,02;-1;0))

E assim sucessivamente...
Answer: Aqui está uma solução em R base, vetorizada com sign.
n <- nrow(dados)
inx <- seq_len(n)[-(1:2)]
dados$col2 <- 1
dados$col2[inx] <- sign(dados$col1[inx] - 1.02*dados$col1[inx - 2])

Dados de teste
col1 <- c(558.8, 584.3, 603.3)
dados <- data.frame(col1)

Answer: Talvez isso te ajude, utilizando dplyr
Data frame de teste
dados <- data.frame(coluna_1 = c(558.8, 584.3, 603.3))

A lógica
library(dplyr)

dados <- dados %>% mutate(coluna_2 = case_when(
  coluna_1 - lag(coluna_1, n = 2) >=  lag(coluna_1, n = 2) * 0.02 ~ 1,
  coluna_1 - lag(coluna_1, n = 2) <=  (-lag(coluna_1, n = 2)) * 0.02 ~ -1,
  T ~ 0
))
dados$coluna_2[1:2] <- 1

Com mutate criamos uma coluna nova chamada coluna_2, o case_when serve para fazer algo quando uma condição é aceita, o lag serve para dar um atraso, neste caso damos um lag de 2 que seriam duas linhas acima. O T ~ 0 é quando nenhuma condição foi encontrada então preenchemos com 0.

Obs: Como o calculo é feito voltando duas linhas os primeiros resultados vão ser zero, pois não tem como calcular.

Uma possibilidade em Python utilizando o pandas
import pandas as pd

dados = pd.DataFrame({'coluna_1': [558.8, 584.3, 603.3]})

dados.loc[dados['coluna_1'] - dados['coluna_1'].shift(2) >= dados['coluna_1'].shift(2) * 0.02, 'coluna_2'] = 1
dados.loc[dados['coluna_1'] - dados['coluna_1'].shift(2) <= -dados['coluna_1'].shift(2) * 0.02, 'coluna_2'] = -1
dados['coluna_2'].iloc[0:2] = 1
dados.fillna(0)

Comment: Muito obrigado pela aula, me ajudou muito, teria alguma maneira de deixar os dos primeiros itens com o valor 1?
Comment: @RoneyWesleyGalan, boa tarde! Como os dois primeiros valores não entram nas condições de preenchimento do restante, podemos colocar 1 de forma arbitrária. Atualizei o código para resolver essa questão. Se as condições sempre forem atingidas, você pode colocar o fill_na ou o T ~ iguais a 1 pois serão os unicos resultados faltantes. Exemplo: `fill_na(1)` ou em R `T ~ 1` Abraço!
Comment: Muito obrigado!! Me ajudou demais, um dia chego nesse nível expert rsrs.
Comment: @RoneyWesleyGalan, por nada! precisando estamos ai! Com certeza vai chegar! Abraço!!!


Finding the average intersection line for multiple planes

Question: I have some planes in 3D space, which in theory should all intersect at the same line.
Each plane is calculated by taking 3 measured points. However there is some error in the measurement of these points.
So in practice, the planes do not all intersect at the same line.
How can I get the "average" intersection line for all these planes?
I could just intersect each plane with each other plane, and average the lines. However, when two planes have almost the same orientation, a small error in their measurements will result in a huge error in their calculated intersection. So I would be magnifying the measurement error when calculating the average intersection this way.
Is there a fairer way to calculate the common intersection line?
Comment: Weight the intersection lines with a small value for *same orientation planes* and a bigger one for *orthogonal planes*... Or eliminate intersections of *near parallel planes*.
Comment: Yes, weighting each individual line should work, thanks! I am curious if there is some mathematical justification for the exact weight, i.e. if I weight each line by [angle-between-the-planes-in-rad]² would I get the best fit result, or is there some other optimal value for the weight.
Comment: I thought about it..but have no good answer on this. You have to manage both the error model and the angle between planes. I think you mustn't not use linear function, use some fast growing function, an exponential-like? Really favor orthogonals. All of this depend on the number of planes, etc.
Comment: Take the dot product to get the cosine of the angle between the normals of the planes, and subtract abs(this) from 1. This should give you ~0 when the planes are nearly parallel and ~1 when perpendicular. Then to adjust for the fact that reasonable values above zero still give sufficient accuracy, take some large root of this value, e.g. 10th root or something.
Comment: Perhaps only consider the "best" sample lines? That is, for each plane, find the the one other plane most orthogonal to it, and consider only that line. If you have `n` planes you will end up with `n` lines, possibly not all unique. Average those. In any event I would recommend you come up with a variety of representative test cases and try several approaches to see which produces the "best" results.
Answer: I think what you need is not averaging but an algorithm which detects outliers (i.e. bad intersections lines) and discards them.
One standard algorithm doing this is the random sample consensus (RANSAC). But for be able to use it you would have to define some kind of distance between lines, which should be possible to do in a meaningful way.
Another possibility to find the inlier (i.e. good intersection lines) is the Hough transform. In this algorithm, the whole parameter space of lines is subdivided into cells. A calculated intersection line "votes" for the cell which contain the parameters of this intersection line. The parameter cell with the most votes wins. One can refine the result by calculating the average line from all lines which voted for the winning cell.


How to find number of partitions in a DataFrame using Python in spark And how to create Partitions in a DataFrame with Python in spark

Question: I have a DataFrame named df and I want to find out that can I create partitions while we read data into a DataFrame
AND
I also want to understand how can we find the number of partitions in a DataFrame.
I have searched multiple answers which show the following
df.rdd.getNumPartitions() but by default it is returning 1 only.
I tried coalese() and repartition to change the number of partitons.
Please help
Answer: While reading any file as a dataframe using DataFrameReader, we don't have option to specify number of partitions. Here You can read about default number of partitions which will get created while reading, or change the partitions while reading file as RDD.
Using repartition() you can increase/decrease number of partitions but using coalesce you can just decrease number of partitions.
You might have missed reassigning repartitioned dataframe to variable back again that's why previous partition is getting displayed.
df = spark.read.csv('file.csv')
df = df.repartition(10) # reassign to any variable. dataframes are immutable
# Now check number of partitions
df.rdd.getNumPartitions()


Is Postfix a SMTP server?

Question: Last couple of weeks I was trying to setup a hMailServer on windows, but there were some problems so I decided to give a unix-based solution a try.
I am running a roundcube webmail and Ubuntu with postfix and dovecot. Inbox work fine with IMAP but I am not able to send any emails via SMTP.
I always get
Error SMTP (554): Unable to add recipient "email@example.com" (5.7.1 <firstname.lastname@example.com>: Relay access denied)

So what I understand from the postfix settings it only accepts emails for specified list of domains (that is for the domains it lists the emails for). But I need to direct Roundcube to some SMTP server that can deliver email to all domains.
Am I using a wrong SW or is it just misconfigured?
alias_database = hash:/etc/aliases
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
home_mailbox = Maildir/
mydestination = dynapos.cz,sweetparadise.cz, ubuntu.mshome.net, localhost.mshome.net, localhost
myhostname = mail2.sweetparadise.cz
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
readme_directory = no
relayhost =
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = no
virtual_alias_domains = hash:/etc/postfix/virtual_domains
virtual_alias_maps = hash:/etc/postfix/virtual

Comment: Configure your clients to use smtp authentication
Comment: You're using exactly the right software.
Answer: You need to allow your Postfix to accept relay mails from Windows Server(s) (220.127.116.11 & 18.104.22.168 in this case).

Add the following content in /etc/postfix/main.cf:

smtpd_relay_restrictions = permit_mynetworks, check_client_access hash:/etc/postfix/check_client_access, reject_unauth_destination

Setup /etc/postfix/check_client_access with the following

126.96.36.199         OK
188.8.131.52         OK

Run postmap hash:/etc/postfix/check_client_access to generate hash map for Postfix.
Run postfix reload to reload configuration.

Then try it again.

Is Postfix a SMTP server?


Getting an error when I try to add variable on Query on my php 7 platform

Question: I'm trying add limit  & offset as variables on a sql in php application
code looks like this:
<code>$bind[':limit'] = $limit;
$bind[':offset'] = $offset;

$sql= 'SELECT id, monkeys '.
      'from monkeyisland mi ' .
      'left join monkeyland ml '
      'on mi.id = ml.id ' .
      'LIMIT :limit OFFSET :offset ';

$result = $query->run($sql,$bind);
</code>
the error message saying:
syntax error  check Mariadb server version for the right syntax
to use near ''100' OFFSET '0''
is there a different way to right this query variables? Thanks for help in advance
Answer: Why are you using bind?
you can add the variables directly
<code>$sql= 'SELECT id, monkeys '.
  'from monkeyisland mi ' .
  'left join monkeyland ml '
  'on mi.id = ml.id ' .
  'LIMIT ' .$limit. ' OFFSET ' .$offset;

$result = $query->run($sql);
</code>
The above query should return the same values of the variables!


Import item and delete old item only

Question: Import or update if item is exists in MySQL table.
Sample import:
Jon | 12
Marie | 17
Delia | 10
Megan | 2

In MySQL table:
Jon | 12
chrtalie | 23

How delete record if not exists in Sapmle - chrtalie | 23?
It's about more than 2000 item`s.
Answer: I see two options:

Clear the table before the import.
Import into a temporary copy of the original table, and merge the two tables manually:

Create an empty copy of the original table
Import into the copy
Delete from the original table the entries that are not in the copy
Update the entries in the original table that are in the copy
Add in the original table the entries that are only in the copy
Drop the copy table

Import item and delete old item only


Método privado em Classe JAVASCRIPT

Question: Como definir um método privado em uma classe JavaScript de forma a tornar o método msg_privada como privado (não visível externamente) sem alterar o padrão de notação?
O método msg_privada deve ser acessado apenas pelo objeto da classe e não externamente.

class TesteVisibilidade{

    // método público
    msg(input_msg){
      this.msg_privada(input_msg);
    }

    // método privado
    msg_privada(input_msg){
      alert('msg privada: ' + input_msg);
    }
}

let t = new TesteVisibilidade();
t.msg('Olá mundo!'); // emite alerta: "msg privada: Olá mundo!"
t.msg_privada('deveria dar erro!'); // Não deveria ser acessível (deveria resultar em ERRO)
Comment: Veja se essa resposta de outra pergunta te ajuda: https://pt.stackoverflow.com/questions/328202/class-privada-em-javascript/328721#328721
Comment: https://pt.stackoverflow.com/questions/428641/como-definir-atributos-privados-em-uma-fun%c3%a7%c3%a3o-construtora-utilizando-javascript
Comment: Isto responde à sua pergunta? [Como definir atributos privados em uma função construtora utilizando javascript](https://pt.stackoverflow.com/questions/428641/como-definir-atributos-privados-em-uma-fun%c3%a7%c3%a3o-construtora-utilizando-javascript)
Answer: Nas versões mais novas da linguagem, você pode declarar campos e métodos privados em uma classe. É uma funcionalidade que já possui um bom suporte dos browsers e engines atuais.
Basta colocar o prefixo # antes do nome:

class TesteVisibilidade {
    // método público
    msg(input_msg) {
        this.#msg_privada(input_msg);
    }

    // método privado
    #msg_privada(input_msg) {
        alert('msg privada: ' + input_msg);
    }
}

let t = new TesteVisibilidade();
t.msg('Olá mundo!'); // emite alerta: "msg privada: Olá mundo!"

// qualquer tentativa de usar o método privado fora da classe dá erro
// t.msg_privada('erro!'); // ERRO!
// tentando chamar com o prefixo
// t.#msg_privada('erro!'); // ERRO!

Repare que o método foi declarado como #msg_privada: o # no início indica que é privado. Vale notar que o prefixo # também é necessário ao se chamar o método: this.#msg_privada(etc...). E como esperado, qualquer tentativa de usar o método privado fora da classe dará erro (com ou sem o prefixo, nenhum funciona).

Para quem está se perguntando "Por que não usaram a palavra-chave private em vez do #?", a resposta está aqui (houve uma discussão a respeito, com argumentos para ambas as opções, mas no fim o # venceu).
Answer: Sem alterar o padrão de notação não é possível, você pode utilizar o typescript que adiciona vários conceitos de linguagens tipadas (Mas seu método não será private realmente, só que o typescript irá reclamar que você está tentando acessar um parametro/método privado, mas quando gerar seu javascript, poderá acessa-lo normalmente), ou usar o iife no js para criar um escopo para sua função/classe, exemplo utilizando o iife:

(function(root){

 const camelCase = (nome) => nome.substring(0, 1).toUpperCase() + nome.substring(1, nome.length);

 class Pessoa {
  constructor (nome) {
   this.nome = nome;
  }

  get nomeCamelCase () {
   return camelCase(this.nome);
  }

 }

 root.Pessoa = Pessoa;

})(window);

//Não tenho acesso ao camelCase diretamente, somente ao Pessoa que adicionei no window
const nome = new Pessoa('jonathan').nomeCamelCase; // "Jonathan"
console.log(nome);
console.log(Pessoa);
console.log(camelCase);

Método privado em Classe JAVASCRIPT


In scala, use reflection on a case class classtag to find the companion object's apply method

Question: This is related to the following question, but since it concerns a distinct and salient issue, I'm asking it as a follow up: Support generic deserialization from a List[(String, Any)] in Scala
How can I use reflection to find the methods of the companion object for a ClassTag? Specifically, I'm trying to call the apply method of a case class' companion object reflectively to construct an instance of a case class.
Answer: Could this answer help you?
Here is an example for scalaVersion := "2.11.1"
import scala.reflect.runtime.{universe => u}

def companionMembers(clazzTag: scala.reflect.ClassTag[_]): u.MemberScope = {
  val runtimeClass = clazzTag.runtimeClass
  val rootMirror = u.runtimeMirror(runtimeClass.getClassLoader)
  val classSymbol = rootMirror.classSymbol(runtimeClass)
  // get the companion here
  classSymbol.companion.typeSignature.members
}

case class MyClass(value: Int)

val applyMethods =
  companionMembers(scala.reflect.classTag[MyClass])
  .filter { m => m.isMethod && m.name.toString == "apply"}

println(applyMethods)

prints
Scope{
  case def apply(value: scala.Int): MyClass
}

Comment: Yes, something like this works ok. I ended up using `private val apply = ctag.runtimeClass.getDeclaredMethods.find(m => "apply".equals(m.getName)).get`.


Json error with xamarin

Question: My environment is Android and i use Xamarin for do my project.
I have a problem with my connection to server, for that i use Json my error is :
`Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2. at Newtonsoft.Json.Linq.JObject.Load`

so my code app side is :
public async Task Login (string user_email, string user_password)
{
var content = new Dictionary<string, string> { {
"user_email",
user_email
},
{
"user_password",
user_password
}
};
String str = await ProcessPOST ("/api/login", content);
JObject data = JObject.Parse (str);

        if (data ["success"] != null)
            return (string)data ["success"];
        throw new Exception ((string)data ["error"]);
    }

and server side is :
So login
public function login() {
if ($this->method == "POST") {
if ($this->_data("user_email") && $this->_data("user_password")) {
$u_dao = new UserDAO();
$users = $u_dao->executeSelect("WHERE user_email = :user_email", array("user_email" => $this->_data("user_email")));

            if (!isset($users[0]))
                return $this->_response(array("error" => "User not found"), 403);

            $user = $users[0];
            if ($user && crypt($this->_data("user_password"), $user->user_password) == $user->user_password) {
                $token = bin2hex(openssl_random_pseudo_bytes(16));
                $user->user_token = $token;
                $u_dao->update($user);
                return $this->_response(array("success" => $token));
            }
            return $this->_response(array("error" => "Bad login"), 403);
        }
        return $this->_response(array("error" => "Missing data"), 500);
    }
    return $this->_response(array("error" => "Wrong method"), 405);
}

and code of _response
protected function _response($data, $status = 200) {
header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
return json_encode($data);
}

and now of _requestStatus
private function _requestStatus($code) {
$status = array(
200 => 'OK',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Internal Server Error',
);
return ($status[$code]) ? $status[$code] : $status[500];
}

and when i try to connect my web service is online , but i forget to said when i have error like "Missing Data" i haven't error of JObject but when i have success i have error.
so i show to all two str one of error:
"{\"error\":\"Missing data\"}"

and one of succes:
"''{\"success\":\"db035db78a9f1e64d71c83bcbb45ffa5\"}"

i want to said thanks to all people which help me . And i'm sorry for my bad english but i'm french .
i hope to be clear but if u have question u can ask them.
Answer: I don't see any necessary use for Json.net here. I would simplify and just check if the response contains "success" or "error".

Json error with xamarin