Is there a way to alias a specific interface ip?

Question: I've got a VCS running on debian as prod server, and due to some hypervisor issues it had to be rebooted/migrated/updated several times in the past week.
Because i'm running my app using docker containers, i can't just pass localhost for it to connect to my local postgres, so i'm using the ens2 ip instead.
ens2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.12.174.3  netmask 255.255.255.254  broadcast 10.12.174.3
        inet6 fe80::dc1c:14ff:fe51:5002  prefixlen 64  scopeid 0x20<link>
        inet6 2001:bc8:4740:205::1  prefixlen 127  scopeid 0x0<global>
        ether de:1c:14:51:50:02  txqueuelen 1000  (Ethernet)
        RX packets 37139  bytes 4801851 (4.5 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 39791  bytes 35291408 (33.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

But with every reboot that ip changes, and i have to manually go and change it in env vars so my app can reach the db again, which i'm sure you'll agree is not very practical.
So here is my question: is there a way to automatically assign an alias, pretty much like localhost, to this specific interface?
I guess i could still try and parse the ifconfig output but i'd rather ask first for an actual solution
Thanks for your time guys
Answer: Could always use:
alias ip="hostname -I"

Comment: Regarding -I, per the manual `Do not make any assumptions about the order of the output.`  A robust script would parse the results to see which is IPv4 and which is IPv6.
Comment: Yeah i could `cut` the ip out of this easily but then it's tricky is to keep it up to date in `/etc/hosts` every time it changes... I was rather wondering about a "legit" way to refer to a given interface
Answer: DNS.
Maintain a record for the application to use, perhaps appdb.prod.example.org. As this is a service name, consider creating a CNAME to the host currently running it.
Update a name in DNS each time a host gets an IP.  For example, AAAA record called container1.example.org containing 2001:bc8:4740:205::1. How exactly to do this depends on your numbering scheme and DNS configuration.  Static IPs can be entered as soon as they are allocated. DHCP hooks can be used to update DNS. And there exists software to watch every interface for IP changes and do an nsupdate, such as  autoddns.

Do not use ifconfig on Linux, not for new scripts. It has been obsolete for at least 11 years.
Comment: Oh wow, 11 years. That's a lot  I feel a little bit outdated here. I'll have a look to this autoddns, it sounds like what i need, thank you !
Comment: In addition, I gave the other examples like static and DHCP to show this depends on your address allocation methods and DNS environment.


Solving for x values of polynomial with known y

Question: I am trying to solve for the x values with a known y. I was able to get the polynomial to fit my data, and now I want to know the x value that a chosen y would land on the curve.
import numpy as np

x = [50, 25, 12.5, 6.25, 0.625, 0.0625, 0.01]
y = [0.00, 0.50, 0.68, 0.77, 0.79, 0.90, 1.00]

poly_coeffs = np.polyfit(x, y, 3)

f = np.poly1d(poly_coeffs)

I want to do 0.5 = f and solve for the x values.
I can solve this in WolframAlpha by typing:
0.5 = -9.1e-6*x^3 + 5.9e-4*x^2 - 2.5e-2*x + 9.05e-1

The real x value is ~26
Answer: In [1]: from numpy.polynomial import Polynomial as P

In [2]: x = [50, 25, 12.5, 6.25, 0.625, 0.0625, 0.01]

In [3]: y = [0.00, 0.50, 0.68, 0.77, 0.79, 0.90, 1.00]

In [4]: p = P.fit(x, y, 3)

In [5]: (p - .5).roots()
Out[5]:
array([ 19.99806935-37.92449551j,  19.99806935+37.92449551j,
        25.36882693 +0.j        ])

Looks like the root you want is 25.36882693.
Answer: You can solve the equation f(x) - y = 0 using np.roots. Consider the function:
def solve_for_y(poly_coeffs, y):
    pc = poly_coeffs.copy()
    pc[-1] -= y
    return np.roots(pc)

Then you can use it to solve your polynomial for any y you want:
>>> print solve_for_y(poly_coeffs, 0.5)
[ 19.99806935+37.92449551j  19.99806935-37.92449551j  25.36882693 +0.j        ]
>>> print solve_for_y(poly_coeffs, 1.)
[ 40.85615395+50.1936152j  40.85615395-50.1936152j -16.34734226 +0.j       ]

Comment: Your method appears to modify `poly_coeffs`, so the second call to the method will actually give the wrong answer, i.e. it's solving for `y = 1` for `x` in a different polynomial than the original one.
Comment: @Amit: Yes, my bad. I thought that function parameters are passed by value, and it seems to be true only for immutable types. Since `np.array` is mutable, it is passed by reference. I'll edit the post, thank you.


Parametric Equation for Great Circle

Question: So I've been doing a lot of searching and haven't found exactly what I'm looking for.  My math skills are a bit rusty, so I haven't had luck deriving this on my own.
What I'm looking for is an equation (or set of equations) where I can plug in starting and ending spherical coordinates, plus a percentage (ie [0,1]) and output spherical coordinates of some point in between (ie, progress along a great circle).
The idea is basically to chart the progress of a plane between two cities and draw it on a globe or map.
Inputs:

lat1,lon1
lat2,lon2
r (radius)
p (progress, from 0->1)

Output:

lat_x,lon_x (point in-between)
Comment: See [this question](http://math.stackexchange.com/q/45293/11619) for some ideas. Once you figure out the initial compass direction [Clairaut's relation](http://en.wikipedia.org/wiki/Clairaut%27s_relation) probably also helps.
Comment: I appreciate the suggestion.  What I'm really looking for is an equation already derived that I can plug numbers into.  Haven't had a luck deriving anything on my own...
Answer: Ok, so I found what I was looking for at Ed Williams' awesome Aviation Formulary:
Given (lat1,lon1), (lat2,lon2), and progress fraction f=[0,1]
d = acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2))
A = sin((1 - f) * d) / sin(d)
B = sin(f * d) / sin(d)
x = A * cos(lat1) * cos(lon1) + B * cos(lat2) * cos(lon2)
y = A * cos(lat1) * sin(lon1) + B * cos(lat2) * sin(lon2)
z = A * sin(lat1) + B * sin(lat2)
lat_f = atan2(z, sqrt(x^2 + y^2))
lon_f = atan2(y,x)
Comment: @user2469 I don't think that's right. At f=0, we are at lat1,lon1. At f=1, we are at lat2,lon2. If you past 1, you will continue along the same great circle, and eventually you will come around to lat1,lon1 again. Exactly how far you need to go for that to happen depends on how far apart the point 1 and point 2 are.
Comment: @DoVanHoan No, f=2 would be the same as f=0 and f=1. Basically, f=2 would be looping around the circle twice (720 degrees), which is the same as looping once (360 degrees) or not at all (0 degrees). Now, if you set f to an imaginary number, you might have something.
Comment: Does this formula automatically always choose the shorter direction on the great arc?
Comment: What happens if I set $f$ not in [0,1]. For example $f$ = 2, would I get the point outside great circle and have double the length of great circle?
Comment: What happens if I set f to an imaginary number? I couldn't figure out how this would happen.
Comment: @barrycarter What happens if one set f to an imaginary number?
Comment: @j13r Yes, looks like it does. I made a toy on Geogebra based on this answer that you can play around with: https://www.geogebra.org/3d/vzgctb98
Comment: Verified at least for a simple case by copying these commands more or less directly into matlab (using cosd instead of cos etc).
Answer: Perhaps the most succinct and easiest answer is (as quoted from here)

You are given two points $u$ and $v$ on the unit sphere. Think of them as position vectors $\vec u$ and $\vec v$ . It is easy enough to calculate cross products. Calculate $\vec w = (\vec u \times \vec v)\times\vec u$. Then $\vec w$ and $\vec u$ are unit vectors perpendicular to each other and in the plane of the circle. So a parameterization of the circle is $$\vec R (t)=\vec u \cos t+\vec w \sin t.$$

Correction: $\vec w$ is only a unit vector if $\vec u$ and
$\vec v$ are perpendicular.
Comment: I have seen another paremeterization as R(t) = u * sin(th0(t)) / sin(th) + v * sin(th1(t)) / sin(th), with th being the total angle between u and v, th0 the angle between u and R and th1 the angle between R and v. Though probably related, I still don't see how this expression can be deduced from the one above.
Comment: What happens if I set $f$ not in [0,1]. For example $f$ = 2, would I get the point outside great circle and have double the length of great circle?

Parametric Equation for Great Circle


Load runner Java applet recording

Question: I'm recording finacle 10.x application using vu 12.02.. When I click on Login button I am getting error:

could not perform login.. applet not loaded properly.

Same error I am getting without installing Java when I was trying to login with browser only, but now I have install JRE 1.7 and I am able to login with browser. But still I am getting error when I start recording.
Answer: Check out whether you are using 32 bit Java or 64 bit java.  It makes a difference when your VUGEN is a 32 bit component and is running in the Windows on Windows 32 Subsystem and your Java is running in the 64 bit subsystem

Load runner Java applet recording


Prove that the interior of the boundary of an open or closed set is empty.

Question: Let $X$ be a topological space, $A\subset X$ and $B=Fr(A)$.
I have two questions.

How do you prove that if $A$ is open or closed, then $B^\circ=\emptyset$?
Why can this not be proven for a set that is both open and closed?
Comment: Just to be clear, what is your definition of boundary?
Comment: @Exodd. $ Fr(A)=\overline{A}\cap \overline{(A^c)} $
Comment: By your definition, $Fr(X) = Fr(\emptyset) = \emptyset$, so even if $A$ is both open and closed,  the interior of $B$ is empty..
Answer: $$(Fr(A))^\circ=(\overline{A}\cap \overline{A^c})^\circ=(\overline{A})^\circ\cap (\overline{A^c})^\circ=A^\circ\cap (A^c)^\circ=A^\circ\cap (\overline{A})^c=\emptyset$$
Comment: It's not necessarily true that $\operatorname{int}\operatorname{cl}A=\operatorname{int}A$: consider the set $A=(0,1)\cup(1,2)$ in $\Bbb R$.


How can I configure Symantec Endpoint Protection Agent to allow access to windows shares?

Question: I'm having some difficulties exposing a standard windows file share on a Windows Embedded Standard 2009 device that is running Symantec Endpoint Protection Agent 5.1.
I'm using simply file sharing to expose a particular directory. That share is visible locally on the machine and externally visible when I disable the endpoint protection agent.
I've added a rule (and moved it to the to ensure priority) allowing all hosts access on TDP ports 137,138,138,445 and another rule allowing UDP access on ports 137,138,139. When I try to connect, two  endpoint protection dialogs pop up saying:
<code>Traffic has been blocked from this application: NWLINK2 IPX Protocol Driver (nwlnkipx.sys)
Traffic has been blocked from this application: IPv6 driver (tcpip6.sys)
</code>
I'm not using IPv6 anywhere.
Interestingly, I discovered a workaround in that I can white-list all traffic from the subnet the device is on, which meets my needs, but I'm still curious as to why my original approach wasn't successful.
Can anyone suggestion a reason why the above endpoint protection rules won't allow me to access windows file shares on the device?
Answer: Solution : http://service1.symantec.com/support/ent-security.nsf/854fa02b4f5013678825731a007d06af/684e821eb0b394f8882575070060f2a4?OpenDocument

To manually enable clients to browse for files and printers

In the client, in the sidebar, click Status.
Beside Network Threat Protection, click Options > Configure Firewall Rules.
In the Configure Firewall Rules dialog box, click Add.
On the General tab, type a name for the rule and click Allow this traffic.
On the Ports and Protocols tab, in the Protocol drop-down list, click TCP.
In the Remote ports drop-down list, type 88, 135, 139, 445.
Click OK.
In the Configure Firewall Rules dialog box, click Add.
On the General tab, type a name for the rule and click Allow this traffic.
On the Ports and Protocols tab, in the Protocol drop-down list, click UDP.
In the Remote ports drop-down list, type 88.
In the Local ports drop-down list, type 137, 138.
Click OK.
To manually enable other computers to browse files on the client
In the client, in the sidebar, click Status.
Beside Network Threat Protection, click Options > Configure Firewall Rules.
In the Configure Firewall Rules dialog box, click Add.
On the General tab, type a name for the rule and click Allow this traffic.
On the Ports and Protocols tab, in the Protocol drop-down list, click TCP.
In the Local ports drop-down list, type 88, 135, 139, 445.
Click OK.
In the Configure Firewall Rules dialog box, click Add.
On the General tab, type a name for the rule and click Allow this traffic.
On the Ports and Protocols tab, in the Protocol drop-down list, click UDP.
In the Local ports drop-down list, type 88, 137, 138.
Click OK.

Somehow I missed that during my initial searching. The version I'm using (5.1) didn't match the steps exactly, but once I implemented the rules, I was able to access my share.
I basically ended up creating 4 rules rather than the one that I was trying to do as well as adding the rules for port 88 (according to wikipedia this is Kerberos, which seems a little odd). Once this was done I was able to access my share as intended..


Why does this variadic C function not print the first argument?

Question: I am trying to make a variadic function in C with stdarg.h, and I followed this tutorial and wrote the code exactly as he did: https://www.youtube.com/watch?v=S-ak715zIIE. I included the output in the code. I cannot figure out why the first argument is not printed, and also, why are there zeros printed at the end? I am beyond confused. Thanks!
#include <stdio.h>
#include <stdarg.h>

void printNums(int num, ...) {
    va_list args;
    va_start(args, num);

    for (int i = 0; i < num; i++) {
        int value = va_arg(args, int);
        printf("%d: %d\n", i, value);
    }

    va_end(args);
}

int main() {
    printNums(5, 2, 3, 4);
    return 0;
}

/*
Output:
0: 2
1: 3
2: 4
3: 0
4: 0
*/

Comment: `printNums(5, 2, 3, 4);` This promises `5` more arguments to `printNum`, but only `3` follow, and the number of arguments itself (`num` in `printNums`) is never printed.
Comment: If you look at the code, you'll see that the first parameter is the amount of numbers that follow it. To use the `va_*` macros you need to have at least one non-`...` parameter, and must know how many parameters to expect (and their types), so there's no way around it.
Answer: va_start's first argument is the last parameter that isn't variadic.  So num holds the 5, and the rest hold the variadics:
#include <stdio.h>
#include <stdarg.h>

void printNums(int num, ...) {
    va_list args;
    va_start(args, num);

    printf("%d: %d\n", 0, num);
    for (int i = 1; i <= num; i++) {
        int value = va_arg(args, int);
        printf("%d: %d\n", i, value);
    }

    va_end(args);
}

int main() {
    printNums(5, 2, 3, 4);
    return 0;
}

0: 5
1: 2
2: 3
3: 4
4: 0
5: 0

also, why are there zeros printed at the end? I am beyond confused. Thanks!

Because of this line:
    for (int i = 1; i <= num; i++) {

You pass the value 5 as num to printNums().  In the for loop you act as though it describes the number of variadic arguments to read, but it doesn't - you passed 3 variadics, not 5.  The last 2 calls to va_start therefore yield undefined behavior, since you've read past the end of valid variadic arguments.  It's just mere chance that you happen to get 0 here - it could be some other random value.
Note that there is no way with mere variadic macros to know how many arguments were passed.  Nor is there a way to assert their type.  You can assume their type and specify their length at runtime if you wish:
$ ./t3
0: 5
1: 2
2: 3
3: 4

#include <stdio.h>
#include <stdarg.h>

void printNums(int num, ...) {
    va_list args;
    va_start(args, num);

    for (int i = 0; i < num; i++) {
        int value = va_arg(args, int);
        printf("%d: %d\n", i, value);
    }

    va_end(args);
}

int main() {
    printNums(4, 5, 2, 3, 4);
    return 0;
}

Variadic functions are primarily valuable when writing functions like printf, where unknown types and quantities of arguments are required (see the example from the man page)  Using passing a list of known types would be more conveniently accomplished by passing an array and count int:
$ cat t.c
#include <stdio.h>

void printNums(int count, int* nums) {
    for (int i = 0; i < count; i++) {
        printf("%d: %d\n", i, nums[i]);
    }
}

int main() {
    int nums[] = {5,2,3,4};
    printNums(4, nums);
    return 0;
}

that just doesn't make a very good video about variadics :P
Comment: using `int nums[] = {5,2,3,4};` the number of elements is known at compile time and you do not need to give *4* by yourself as a literal in `printNums(4, nums);` with the risk to have it wrong if the number of element is changed, be lazy and let the compiler count for you, also making your code more robust
Comment: in this case that's true, but `printNums()` doesn't know whether its true for any given array, so it needs to know the size.
Comment: sure, I just say to replace `4` by `sizeof(nums)/sizeof(*nums))` to have `printNums(sizeof(nums)/sizeof(*nums)), nums);` allowing to send the right number even you add/remove value in the initialization list
Comment: only if the array is full though.
Comment: it is full by definition because its number of elements is determined by its initialization


Math induction, how does it work?

Question: I'm reading a book(concrete Mathematics) and it uses a lot the concept of 'Math induction'.
Thought I've been reading tutorials and examples about it, I'm still unable to understand it, the last 'basic' example I was reading is(my questions are the ones highlighted):
Prove $1+2+...+n=\frac{n(n+1)}{2}$
Then it indicates:

Step 1: Show is valid for n=1: $1=\frac{1(1+1)}{2}=\frac{2}{2}=1$
Step 2: Inductive step, assume is valid for n=k:

$1+2+...+k=\frac{k(k+1)}{2}$ //why do I need to substitute n by k? to me is exactly the same as doing nothing, I could work with n+1 instead

Step 3: Prove is valid for $n=k+1$, and the demo is:

$1+2+...+\color{red}{(k+1)}=(1+2+...+k)+\color{red}{(k+1)}$
= $\frac{k(k+1)}{2}+k+1$
= $\frac{k(k+1)+2(k+1)}{2}$
= $\frac{(k+1)(k+2)}{2}$//How is getting this from the previous equation???????
= $\frac{(k+1)[(k+1) + 1]}{2}$
Any help is appreciated, this 'basic thing' is driving me nuts.
Comment: $k(k+1) + 2(k+1) = (k+2)(k+1)$ is just basic factorization.
Comment: I mean, I could answer most of these questions, but I don't honestly think they will really elucidate anything. I would check out a intro to induction on google to help you out
Comment: @RushabhMehta As I mentioned, I've been through many examples (most of them showing exactly the same) and still don't get it
Answer: The principle of induction is based in the Axioms of Peano, an Italian mathematician. It states that, if a set X is such that $1 \in X $ and every successor of X is also an element of X, that is: $s(X) \in X$, then this set is the set of natural numbers!
The idea is quite intuitive: if every successor of a number is in a set, and the set contains the first of numbers (1), then it must have its sucessor as an element (2), and the successor of successor (3) and so on.
Then what you do is that you actually don't substitute n for k. You test the validity of the expression for n=1. And then you check if the formula holds for a k+1 (successor), assuming it works for a given k.
So, you could actually work with $n$ and $n+1$. It's just a matter of mathematical rigour! :)
For your second question, how you get that from the equation, it's factorization.
Comment: I'm not sure the first paragraph is much help to the OP, nor do I think they care too much about rigour at this point that they're trying to get basic induction!

Math induction, how does it work?


SQL Question: Getting Datediff in days elapsed for each record in a group

Question: Given this table:

How can I get the datediff in days between each status_date for each group of ID_Number?  In other words I need to find the number of elapsed days for each status that the ID_Number has been given.
Some things to know:

All ID_Number will have a received_date which should be the earliest date for each ID_Number (but app doesn't enforce)
For each ID_Number there will be a status with a corresponding status_date which is the date that the ID_Number was given that particular status.
The status column doesn't always necessarily go in the same order every time (app doesn't enforce)
All ID_Number will have a closed_date which should be the latest date (but app doesn't enforce)

Sample output:
So for ID_Number 2001, the first date (received_date) is 2009-05-02 and the next date you encounter has a status of 'open' and is 2009-05-02 so elapsed days is 0.  Moving on to the next date encountered is 2009-05-10 with a status of 'invest' and the elapsed days is 8 counting from the prior date.  The next date encountered is 2009-07-11 and the elapsed days is 62 counting from the previous date.
Edited to add:
Is it possible to have the elapsed days end up as a column on this table/view?
I also forgot to add that this is SQL Server 2000.
Comment: I added all the columns to my answer to replicate the original table with a new column of days. It is null when there is no closed_date.
Answer: What I understand is that you need the difference between the first status_date and the next status_date for the same id and so on up to the closed_date.
This will only work in SQL 2005 and up.
;with test as (
    select
        key,
        id_number,
        status,
        received_date,
        status_date,
        closed_date,
        row_number() over (partition by id order by status_date, key ) as rownum
    from @test
    )
select
    t1.key,
    t1.id_number,
    t1.status,
    t1.status_date,
    t1.received_date,
    t1.closed_date,
    datediff(d, case when t1.rownum = 1
                then t1.received_date
                else
                    case when t2.status_date is null
                        then t1.closed_date
                        else t2.status_date
                    end
            end,
            t1.status_date
         ) as days
from test t1
left outer join test t2
on t1.id = t2.id
    and t2.rownum = t1.rownum - 1

This solution will work with SQL 2000 but I am not sure how good will perform:
select *,
    datediff(d,
        case when prev_date is null
            then closed_date
            else prev_date
        end,
        status_date )
from (
    select *,
        isnull( ( select top 1 t2.status_date
          from @test t2
          where t1.id_number = t2.id_number
            and t2.status_date < t1.status_date
          order by t2.status_date desc
          ),received_date) as prev_date
    from @test t1
) a
order by id_number, status_date

Note: Replace the @Test table with the name of your table.
Comment: I have modified the results based on the sample output you added to your question.
Comment: Ugh.  It looks like this will be pretty ugly to implement in sql2000 which is information I forgot to add to my original post.
Comment: @GregD: Is the KEY column always going to be continuous for each ID_Number?
Comment: The KEY column is an identity column and is auto incrementing.  Having said that, there is no guarantee that the identity column will always be in order with anything else.  These are really funky dates added in as an afterthought in this app and there are no business rules on them.
Comment: @GregD: I added a SQL 2000 compatible query, but I am not sure how good it will perform against big tables.
Answer: Some sample output would really help, but this is a guess at what you mean, assuming you want that information for each ID_Number/Status combination:
select ID_Number, Status, EndDate - StartDate as DaysElapsed
from (
    select ID_Number, Status, min(coalesce(received_date, status_date)) as StartDate, max(coalesce(closed_date, status_date)) as EndDate
    from Table1
    group by ID_Number, Status
) a

Answer: The tricky bit is determining the previous status and putting it on the same row as the current status. It would be simplified a little if there were a correlation between Key and StatusDate (i.e. that Key(x) > Key(y) always implies StatusDate(x) >= StatusDate(y)). Unfortunately, that doesn't seem to be the case.
PS: I am assuming Key is a unique identifier on your table; you haven't said anything to indicate otherwise.
SELECT  Key,
        ID_Number,
        (
        SELECT  TOP 1 Key
        FROM    StatusUpdates prev
        WHERE   (prev.ID_Number = cur.ID_Number)
            AND (   (prev.StatusDate < cur.StatusDate)
                OR  (   prev.StatusDate = cur.StatusDate
                    AND prev.Key < cur.Key
                    )
                )
        ORDER BY StatusDate, Key /*Consider index on (ID_Number, StatusDate, Key)*/
        ) PrevKey
FROM    StatusUpdates cur

Once you have this as a basis, it's easy to extrapolate to any other info you need from the current or previous StatusUpdate. E.g.
SELECT  c.*,
        p.Status AS PrevStatus,
        p.StatusDate AS PrevStatusDate,
        DATEDIFF(d, c.StatusDate, p.StatusDate) AS DaysElapsed
FROM    (
        SELECT  Key,
                ID_Number,
                Status,
                SattusDate,
                (
                SELECT  TOP 1 Key
                FROM    StatusUpdates prev
                WHERE   (prev.ID_Number = cur.ID_Number)
                    AND (   (prev.StatusDate < cur.StatusDate)
                        OR  (   prev.StatusDate = cur.StatusDate
                            AND prev.Key < cur.Key
                            )
                        )
                ORDER BY StatusDate, Key
                ) PrevKey
        FROM    StatusUpdates cur
        ) c
        JOIN StatusUpdates p ON
            p.Key = c.PrevKey


How to represent an empty IntSet in Haskell?

Question: As the title asks, how would I represent an empty IntSet?
For example, I know that an empty list is represented as []. I know that IntSet has type [(Int, Int)], and I was wondering what an empty IntSet would look like. I suppose it's not [()], nor [(,)].
Thanks!
Comment: `IntSet` has not *per se* type `[(Int, Int)]`. Exactly what is the semantics of this representation?
Comment: Or if, as it appears, you're actually using lists of pairs rather than "actual" `IntSet`s, then of course an empty intset is simply represented by the empty list, `[]`.
Comment: Do you mean an `IntSet` from [`Data.IntSet`](https://hackage.haskell.org/package/containers-0.6.2.1/docs/Data-IntSet.html) ?
Answer: If you have defined
type IntSet = [(Int, Int)]

as implied in the question (but why? what is the other Int for?), then the empty list is an empty IntSet:
empty :: IntSet
empty = []

Indeed, the empty list is an empty list of any type, including of the type [(Int, Int)].


Slow sql query despite indexes

Question: i'm stuck with a performance of a simple sql query.
Query:
SELECT * FROM company
        WHERE
        (IDCompanyMain in (ID1, ID2...) or IDCompany in (ID1, ID2...))
        and Network="XXX";

There are indexes on each field and ca 10M rows.
Each query has 1 to 100 ids.
Each query needs >4 seconds! if i remove one of the conditions, results are ready in miliseconds.
EXPLAIN says, mysql uses network index and has ca 5M rows in question. If try to force certain index(USE or FORCE), no index is used.
What i am doing wrong?
EXPLAIN:
id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
'1', 'SIMPLE', 'company', 'ref', 'PRIMARY,UNetwork_ID,IIDCompanyMain,INetwork', 'INetwork', '98', 'const', '5270286', 'Using where'

Comment: can you please run the same query with EXPLAIN prefix and post the explain result?
Comment: i added explain
Answer: Only one index is being used - for the Network column.
Due to the OR clause, indexes for IDCompanyMain and IDCompany cannot be used. You'd have to do two separate queries for each of these conditions and then join the results together:
(SELECT * FROM company WHERE IDCompanyMain in (ID1, ID2...) and Network="XXX")
UNION
(SELECT * FROM company WHERE IDCompany in (ID1, ID2...) and Network="XXX")

For optimal querying performance, you'd need two compound indexes - (Network, IDCompanyMain) and (Network, IDCompany)
Answer: the EXPLAIN result says only the Network field index is used in the check (see key column), making the check being run against over 5 milion rows and that's why it's so slow.
You should consider creating an index that uses both fields in the index, the indexes you have only index 1 field per index.
see this for example:   CREATE INDEX index_1 ON t1 (c1, c2);
so in your case:
CREATE INDEX maincompany_network ON company (IDCompanyMain, Network);
CREATE INDEX company_network ON company (IDCompany, Network);

then EXPLAIN again to see if it improved your rows column.
I advised creating two indexes one for network and maincompany and another: network and company, becasue that's how your OR is going to be evaluated.

Slow sql query despite indexes


Why is persistence context called persistence context?

Question: Why is persistence context called persistence context?
Is it context because it acts as a stepping stone until the object is permanently stored in db?
(Because context is a dynamic feeling from where to where rather than a static feeling?)
Answer: A context in computing terms is defined as follows:

In computer science, a task context is the minimal set of data used by a task that must be saved to allow a task to be interrupted, and later continued from the same point.
Context_(computing)

A persistence context is a specific context relating to database persistence. Just like any other context it will store required state relating to database persistence.

Is it context because it acts as a stepping stone until the object is permanently stored in db?

JPA works with transactions, sometimes this can appear hidden if using web frameworks that automatically begin and end the transaction for an http request. The persistence context will act as a kind of cache during a transaction storing any database reads. Any updates made are also saved to the context until the transaction is finished or you manually flush, at which point they will be persisted to the database.


Proving that the point spectrum of the right shift operator on $\mathscr{l}^2(\mathbb{Z})$ is empty.

Question: How can I prove that no series $x\in\mathscr{l}^2(\mathbb{Z})$ of the form $$\forall i\in\mathbb{Z}: x_{k-1}=\lambda x_k$$
exists other than the zero sequence?
In particular I want to prove that the point spectrum of the right shift operator $$R:\mathscr{l}^2(\mathbb{Z})\rightarrow\mathscr{l}^2(\mathbb{Z})$$ $$\forall i\in\mathbb{Z}:x_i\mapsto x_{i-1}$$
is empty. I did this for $\mathscr{l}^2(\mathbb{N})$ already but can't prove the first statement, which I think i need for the $\mathscr{l}^2(\mathbb{Z})$ case.
Answer: Suppose there exists some $\lambda \in \mathbb{C}$ such that $\lambda \in \sigma_{pt} (R)$. Then, for some nonzero sequence $x \in l^2 (\mathbb{Z})$, $$Rx = \lambda x \leftrightarrow x_{n-1} = \lambda x_n \forall n \in \mathbb{Z} .$$
Let's then divide this into cases. First, suppose that $| \lambda | \geq 1$. In this case, the above equation can be rewritten as $$\frac{x_{n-1}}{x_n} = \lambda \rightarrow \left\vert \frac{x_{n-1}}{x_n} \right\vert = |\lambda| \geq 1.$$ However, this is a contradiction, since the terms of a sequence in $l^2(\mathbb{Z})$ must vanish as $n \rightarrow \pm \infty$.
The second case follows a similar argument. Suppose $|\lambda| < 1$. Then, $$\left\vert \frac{x_{n-1}}{x_n} \right\vert = |\lambda| \leftrightarrow \left\vert \frac{x_{n}}{x_{n-1}} \right\vert = \frac{1}{|\lambda|} > 1.$$ The contradiction follows as before.
Thus, there is no nonzero sequence $x \in l^2 (\mathbb{Z})$ such that $R x = \lambda x$ for some $\lambda \in \mathbb{C}$.
Answer: A representation of this operator is multiplication by $e^{ix}$ on $L^{2}[-\pi,\pi]$ with inner product
$$
           (f,g) = \frac{1}{2\pi}\int_{-\pi}^{\pi}f(t)\overline{g(t)}dt.
$$
This is because $\{ e^{inx} \}_{n=-\infty}^{\infty}$ is an orthonormal basis of $L^{2}[-\pi,\pi]$, and
$$
            e^{ix}\sum_{n=-\infty}^{\infty}f_n e^{inx}=\sum_{n=-\infty}^{\infty}f_{n-1}e^{inx}.
$$
A multiplication operator $M_{a}f=a(x)f(x)$ on $L^{2}$ cannot have an eigenvalue unless what you're multiplying by ('a' in this case) is equal to a constant on a set of non-zero measure because
$$
                 0 = \|(M_{a}-\lambda I)f\|^{2}=\int_{-\pi}^{\pi}|a-\lambda|^{2}|f|^{2}dx \\
             \implies |a-\lambda||f| = 0\;\; a.e.
$$


Help With Intra-Application Drag and Drop -- Cocoa

Question: Okay, I've got a custom class called "Task", which represents a task to be done.  I've got an NSMatrix which acts as a calendar.  I want the user to be able to drag an icon from an nscollectionview (I've had no trouble setting up the nscollectionview) onto a cell in the nsmatrix, thereby assigning that task to that day.  I just can't seem to get the nsmatrix to respond to the drag or the drop at all.
I've implemented the method:
<code>- (BOOL)collectionView:(NSCollectionView *)cv writeItemsAtIndexes:(NSIndexSet *)indexes toPasteboard:(NSPasteboard *)pasteboard
{
    [pasteboard declareTypes:[NSArray arrayWithObject:TASK_UTI]  owner:self];
    NSUInteger index=[indexes firstIndex];
    Task* task=[[cv content] objectAtIndex:index];
    NSData* taskData=[NSKeyedArchiver archivedDataWithRootObject:task];
    [taskData retain];
    BOOL success=[pasteboard setData:taskData forType:TASK_UTI];

    return success;
}
</code>
in my nscollectionview delegate as shown above.
I've sent [self registerForDraggedTypes:[NSArray arrayWithObjects:TASK_UTI, nil]] in my NSMatrix subclass (called "Calendar").
I've implemented the methods:
<code>- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
- (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender
</code>
in my Calendar (NSMatrix subclass) class.
Some debugging shows that the NSMatrix/Calendar object is not even running the dragging methods above.  What gives?
Comment: "I've sent [self registerForDraggedTypes:[NSArray arrayWithObjects:TASK_UTI, nil]] in my NSMatrix subclass…" Are you sure about that? What method did you send it from? Did you use `NSLog` to prove that that code ran?
Comment: I ran it in the -awakeFromNib method, and yes, i ran NSLog
Code:
NSLog(@"Registered Drag types:%@", [[self registeredDraggedTypes] description]);
With this result:
2010-01-11 18:54:59.963 Planner[48548:a0f] Registered Drag types:(
    "com.yourcompany.YGPlannerTask"
)
Answer: Did you define your Calendar class to implement dragging destination protocol?
Comment: What exactly do you mean? I wrote in the question that I implemented the 3 methods:
- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
- (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender
Is there something else I have to do?
Comment: My bad. I knew something was missing (but wasn't quite sure so I went for the guess). Here's the thing that you're missing (excerpt from apple documentation:
===
To receive drag operations, you must register the pasteboard types that your window or view will accept by sending the object a registerForDraggedTypes: message, defined in both NSWindow and NSView, and implement several methods from the NSDraggingDestination protocol
===
Whole drag'n'drop guide is here: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/DragandDrop/DragandDrop.html
Comment: I did send it that message, see comment above
Comment: I've spent hours poring over the drag n' drop guide, with no success.
Maybe there's something wrong with my UTI??
Answer: First off, you should use your own domain name, not "com.yourcompany", in the UTI.
Second, did you export the UTI in your Info.plist?
Comment: Thanks.  I do think the problem is with the UTI, but the Apple Docs haven't helped me at all.  They don't make it clear on how to set up your own UTI.  I've tried exporting it in my info.plist, but I'm not sure I did it right.  Could you explain EXACTLY what I need to do to set up my own UTI?
Comment: I've checked it out, the problem is for sure the UTI--Everything works if I change the "TASK_UTI" to "NSPasteBoardStringType" in all the places.
Comment: Joe Atkin: From the chapter I linked to: "In addition to declaring the UTI string, the declaration can contain any of the following properties…" implying that only the UTI itself is required. If that's not working, you should edit your question to include the declaration.


How to do an update + join in PostgreSQL?

Question: Basically, I want to do this:
update vehicles_vehicle v
    join shipments_shipment s on v.shipment_id=s.id
set v.price=s.price_per_vehicle;

I'm pretty sure that would work in MySQL (my background), but it doesn't seem to work in postgres. The error I get is:
ERROR:  syntax error at or near "join"
LINE 1: update vehicles_vehicle v join shipments_shipment s on v.shi...
                                  ^

Surely there's an easy way to do this, but I can't find the proper syntax. So, how would I write this In PostgreSQL?
Comment: vehicles_vehicle, shipments_shipment? That's an interesting table naming convention
Comment: Postgres syntax is different: http://www.postgresql.org/docs/8.1/static/sql-update.html
Comment: @CodeAndCats Haha...it does look funny doesn't it? I think I was using Django at the time, and the tables are grouped by feature. So there would have been a view `vehicles_*` tables, and a few `shipments_*` tables.
Comment: Some care should be taken if the join is performed on a *non-unique column*. This may lead to a [non deterministic outcome](https://stackoverflow.com/a/75592208/4808122).
Answer: The UPDATE syntax is:
[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table [ [ AS ] alias ]
    SET { column = { expression | DEFAULT } |
          ( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...]
    [ FROM from_list ]
    [ WHERE condition | WHERE CURRENT OF cursor_name ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

In your case I think you want this:
UPDATE vehicles_vehicle AS v
SET price = s.price_per_vehicle
FROM shipments_shipment AS s
WHERE v.shipment_id = s.id

Or if you need to join on two or more tables:
UPDATE table_1 t1
SET foo = 'new_value'
FROM table_2 t2
    JOIN table_3 t3 ON t3.id = t2.t3_id
WHERE
    t2.id = t1.t2_id
    AND t3.bar = True;

Comment: @ted.strauss: The FROM can contain a list of tables.
Comment: If the update relies on a whole list of table joins, should those be in the UPDATE section or the FROM section?
Comment: coming from mysql it's unintuitive that the same join used for `select` won't also `update` just by adding a `set` phrase  :(   still - the syntax for this is probably easier for a newcomer to sql to master.
Comment: @WEBjuju my thoughts exactly, converting a select statement into an update requires an additional step with this method which is inconvenient. The syntax is also not quite as intuitive this way (in my opinion).
Comment: I got an error with the alias in the update line; I removed it and there was NOT an error.
Comment: I have no idea how many times I have visited this answer. Wish I could update it more than once.
Answer: The answer of Mark Byers is the optimal in this situation.
Though in more complex situations you can take the select query that returns rowids and calculated values and attach it to the update query like this:
with t as (
  -- Any generic query which returns rowid and corresponding calculated values
  select t1.id as rowid, f(t2, t2) as calculatedvalue
  from table1 as t1
  join table2 as t2 on t2.referenceid = t1.id
)
update table1
set value = t.calculatedvalue
from t
where id = t.rowid

This approach lets you develop and test your select query and in two steps convert it to the update query.
So in your case the result query will be:
with t as (
    select v.id as rowid, s.price_per_vehicle as calculatedvalue
    from vehicles_vehicle v
    join shipments_shipment s on v.shipment_id = s.id
)
update vehicles_vehicle
set price = t.calculatedvalue
from t
where id = t.rowid

Note that column aliases are mandatory otherwise PostgreSQL will complain about the ambiguity of the column names.
Comment: Not sure why, but the CTE version of this query is way way faster than the "plain join" solutions above
Comment: I really like this one because I'm always a tad nervous with taking my "select" off the top and replacing it with an "update," especially with multiple joins.  This reduces the number of SQL dumps I should have to do before mass updates. :)
Comment: The other advantage of this solution is the ability join from more than two tables to get to your final calculated value by using multiple joins in the with / select statement.
Comment: This is awesome. I had my select crafted and like @dannysauer, I was scared of the conversion. This simply does it for me. Perfect!
Comment: Your first SQL example has a syntax error. "update t1" cannot use the alias from  the t subquery, it needs to use the table name: "update table1". You do this correctly in your second example.
Comment: This was a lifesaver, regular UPDATE/FROM with a join was running indefinitely on my table and this ran in no time!
Comment: regardless of method (join or cte) i have:
SQL state: 55000
Detail: Views that do not select from a single table or view are not automatically updatable.
seems like it should be simple/common operation
Comment: Just to emphasise: the column aliases must be present on the columns within the CTE, not the outer query. I had forgotten those alliances and it wasn't working, once I added them I went to the moon
Comment: It's also possible to JOIN any number of tables without a subquery (see accepted answer).  If you have a SELECT, you just replace FROM with UPDATE, take the first JOIN and make it a FROM clause (moving the ON condition into the WHERE clause), and then the rest of the JOINs can stay as is.
Answer: Let me explain a little more by my example.
Task: correct info, where abiturients (students about to leave secondary school) have submitted applications to university earlier, than they got school certificates (yes, they got certificates earlier, than they were issued (by certificate date specified). So, we will increase application submit date to fit certificate issue date.
Thus. next MySQL-like statement:

UPDATE applications a
JOIN (
    SELECT ap.id, ab.certificate_issued_at
    FROM abiturients ab
    JOIN applications ap
    ON ab.id = ap.abiturient_id
    WHERE ap.documents_taken_at::date < ab.certificate_issued_at
) b
ON a.id = b.id
SET a.documents_taken_at = b.certificate_issued_at;

Becomes PostgreSQL-like in such a way
UPDATE applications a
SET documents_taken_at = b.certificate_issued_at         -- we can reference joined table here
FROM abiturients b                                       -- joined table
WHERE
    a.abiturient_id = b.id AND                           -- JOIN ON clause
    a.documents_taken_at::date < b.certificate_issued_at -- Subquery WHERE

As you can see, original subquery JOIN's ON clause have become one of WHERE conditions, which is conjucted by AND with others, which have been moved from subquery with no changes. And there is no more need to JOIN table with itself (as it was in subquery).
Comment: How would you join a third table?
Comment: You just `JOIN` it as usual in the `FROM` list:
```FROM abiturients b JOIN addresses c ON c.abiturient_id = b.id```
Comment: @AdrianSmith, you can't use JOIN in UPDATE itself, but can use it in UPDATE's `from_list` clause (which is PostgreSQL's extension of SQL). Also, see notes about joining tables caveats on the link you provided.
Comment: @Envek - You can't use JOIN there alas, I just checked. https://www.postgresql.org/docs/10/static/sql-update.html
Comment: @Envek can you give a from_list example with multiple joins as well ? a to b might not be direct link, sometimes c is there too and then we have to do a.c_id = c.id and c.b_id = b.id , to connect a and b.
Answer: For those actually wanting to do a JOIN you can also use:
UPDATE a
SET price = b_alias.unit_price
FROM      a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value'
AND a.id = a_alias.id;

You can use the a_alias in the SET section on the right of the equals sign if needed.
The fields on the left of the equals sign don't require a table reference as they are deemed to be from the original "a" table.
Comment: Considering this is the first answer with an actual join in (and not inside a with subquery), this should be the real accepted answer. Either that or this question should be renamed to avoid confusion whether postgresql supports joins in update or not.
Comment: It should be noted that according to the documentation (https://www.postgresql.org/docs/11/sql-update.html), listing the target table in the from clause will cause the target table to be self-joined.  Less confidently, it also appears to me that this is a cross-self-join, which may have unintended results and/or performance implications.
Comment: Just FYI, I tried this and the number of rows updated was different than the number of rows returned from the select query with same join and where clauses.
Comment: I tried this with CockroachDB on a test env and it updated every record in the table regardless of `JOIN` and `WHERE` conditions.
Answer: For those wanting to do a JOIN that updates ONLY the rows your join returns use:
UPDATE a
SET price = b_alias.unit_price
FROM      a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value'
AND a.id = a_alias.id
--the below line is critical for updating ONLY joined rows
AND a.pk_id = a_alias.pk_id;

This was mentioned above but only through a comment..Since it's critical to getting the correct result posting NEW answer that Works
Comment: @FlipVernooij With the addition of the last line in the answer, `AND a.pk_id = a_alias.pk_id`, *there is no cross-join here* and the answer *is* valid. The link and reference to Ben's comment can only lead readers to a wild goose chase and a complete waste of their time, trying to understand what you are referring to.
Comment: @FlipVernooij When posting a comment referring to a link, please be specific about the part of the link being reference and/or quote the part, unless the entire link applies or the applicable portion of the link is *very* obvious. In this case there is nothing whatsoever obvious about what you are referring to at the link referenced, This leaves all of us bewildered, after wasting time searching the documentation linked and returning with the question, "*What side-effects??*"
Comment: I tried this one, and it seemed to be working https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-update-join/
Answer: Here we go:
UPDATE vehicles_vehicle v
SET price = s.price_per_vehicle
FROM shipments_shipment s
WHERE v.shipment_id = s.id;

Simple as I could make it.
Comment: @mpen I can confirm that it updates all records to one value.  it does not do what you would expect.
Comment: @littlegreen You sure about that? Doesn't the `join` constrain it?
Comment: Why is some of this answer's text cross-out?
Comment: From an earlier revision. Apparently it didn't work so I crossed it out. I'll delete it now.
Comment: I found the similar one in a blog https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-update-join/ and it seems like working as expected. @AdamGordonBell
Answer: To add something quite important to all the great answers above, when you want to update a join-table, you may have 2 problems:

you cannot use the table you want to update to JOIN another one
Postgres wants a ON clause after the JOIN so you cannot only use where clauses.

This means that basically, the following queries are not valid:
UPDATE join_a_b
SET count = 10
FROM a
JOIN b on b.id = join_a_b.b_id -- Not valid since join_a_b is used here
WHERE a.id = join_a_b.a_id
AND a.name = 'A'
AND b.name = 'B'

UPDATE join_a_b
SET count = 10
FROM a
JOIN b -- Not valid since there is no ON clause
WHERE a.id = join_a_b.a_id
AND b.id = join_a_b.b_id
a.name = 'A'
AND b.name = 'B'

Instead, you must use all the tables in the FROM clause like this:
UPDATE join_a_b
SET count = 10
FROM a, b
WHERE a.id = join_a_b.a_id
AND b.id = join_a_b.b_id
AND a.name = 'A'
AND b.name = 'B'

It might be straightforward for some but I got stuck on this problem wondering what's going on so hopefully, it will help others.
Answer: WORKS PERFECT!!!
POSTGRE SQL - UPDATE With a JOIN
BELOW CODE - Check the positioning of columns and IDs as below:
If you place it exactly as below, then only it will work!
---IF you want to update This table1 using table2

UPDATE table1
SET attribute1 = table2.attribute2
FROM table2
WHERE table2.product_ID = table1.product_ID;

Answer: Here's a simple SQL that updates Mid_Name on the Name3 table using the Middle_Name field from Name:
update name3
set mid_name = name.middle_name
from name
where name3.person_id = name.person_id;

Answer: The link below has a example that resolve and helps understant better how use update and join with postgres.
UPDATE product
SET net_price = price - price * discount
FROM
product_segment
WHERE
product.segment_id = product_segment.id;

See: http://www.postgresqltutorial.com/postgresql-update-join/
Answer: First Table Name: tbl_table1 (tab1).
Second Table Name: tbl_table2 (tab2).
Set the tbl_table1's ac_status column to "INACTIVE"
update common.tbl_table1 as tab1
set ac_status= 'INACTIVE' --tbl_table1's "ac_status"
from common.tbl_table2 as tab2
where tab1.ref_id= '1111111'
and tab2.rel_type= 'CUSTOMER';

Answer: To UPDATE one Table using another, in PostGRE SQL / AWS (SQL workbench).
In PostGRE SQL, this is how you need to use joins in UPDATE Query:
UPDATE TABLEA set COLUMN_FROM_TABLEA = COLUMN_FROM_TABLEB FROM TABLEA,TABLEB WHERE FILTER_FROM_TABLEA = FILTER_FROM_TABLEB;

Example:

Update Employees Set Date_Of_Exit = Exit_Date_Recorded , Exit_Flg = 1 From Employees, Employee_Exit_Clearance Where Emp_ID = Exit_Emp_ID

Table A - Employees Columns in Table A - Date_Of_Exit,Emp_ID,Exit_Flg Table B is - Employee_Exit_Clearance Columns in Table B - Exit_Date_Recorded,Exit_Emp_ID
1760 rows affected
Execution time: 29.18s
Answer: Some care should be taken if the join is performed on a non-unique column. I.e. the result of the join produces  more values that can be used in the update.
Some RDMS raise an exception is this case, but PostgreSQL apparently performs the update with a non deterministic outcome.
Example
Tested on 14.1
create table tab as
select * from  (values
(1,'a'),
(2,'b')
) t(id, att);

We use a CTE where the id = 1 id giving two possible values for the update. Using the order by in the CTE we get a different results.
with t as (
select * from  (values
(1,'c'),
(1,'d')
) t(id, att)
order by 2   /* Based on this order different update is performed */
)
update tab
set att = t.att
from t
where tab.id = t.id

With the ascendig order the column is updated to the value of d (highest value)
id|att|
--+---+
 1|d  |
 2|b  |

while using a descending order in the CTE the column is updated to the value of c (lowest value)
id|att|
--+---+
 1|c  |
 2|b  |

The moral of the story always check if the join produce a unique result.
The relevant part of the documentation

When using FROM you should ensure that the join produces at most one output row for each row to be modified. In other words, a target row shouldn't join to more than one row from the other table(s). If it does, then only one of the join rows will be used to update the target row, but which one will be used is not readily predictable.
Answer: --goal: update selected columns with join (postgres)--
UPDATE table1 t1
SET    column1 = 'data'
FROM   table1
       RIGHT JOIN table2
               ON table2.id = table1.id
WHERE  t1.id IN
(SELECT table2.id   FROM   table2   WHERE  table2.column2 = 12345)

Answer: The first way is slower than the second way.
First:
DO $$
DECLARE
  page int := 10000;
  min_id bigint; max_id bigint;
BEGIN
  SELECT max(id),min(id) INTO max_id,min_id FROM opportunities;
  FOR j IN min_id..max_id BY page LOOP
    UPDATE opportunities SET sec_type = 'Unsec'
    FROM opportunities AS opp
    INNER JOIN accounts AS acc
    ON opp.account_id = acc.id
    WHERE acc.borrower = true
    AND opp.sec_type IS NULL
    AND opp.id >= j AND opp.id < j+page;
    COMMIT;
  END LOOP;
END; $$;

Second:
DO $$
DECLARE
  page int := 10000;
  min_id bigint; max_id bigint;
BEGIN
  SELECT max(id),min(id) INTO max_id,min_id FROM opportunities;
  FOR j IN min_id..max_id BY page LOOP
    UPDATE opportunities AS opp
    SET sec_type = 'Unsec'
    FROM accounts AS acc
    WHERE opp.account_id = acc.id
    AND opp.sec_type IS NULL
    AND acc.borrower = true
    AND opp.id >= j AND opp.id < j+page;
    COMMIT;
  END LOOP;
END; $$;

Answer: In case you don't have the value in one column but instead had to calculate it from the other table (in this example price_per_vehicle from shipments_shipment).
Then assuming that shipments_shipment has price and vehicle_id columns the update for a specific vehicle could look like this:
-- Specific vehicle in this example is with id = 5
WITH prices AS (
    SELECT SUM(COALESCE(s.price, 0)) AS price_per_vehicle
    FROM shipments_shipment AS s
    WHERE s.vehicle_id = 5
)
UPDATE vehicles_vehicle AS v
SET v.price = prices.price_per_vehicle
FROM prices
WHERE v.id = 5

Answer: EDIT: do not use, execution time increases quadratically
It's a pity that the runtime is so bad, because the syntax was very elegant.
I'm leaving this answer up to save others from going down this path.

This answer is different from the rest because
you don't have to repeat the join condition.

You join once in the FROM clause
and the WHERE clause checks that rows from X are present in (X as X_joined join Y).

As a result this works with natural joins, which is very nice.
Example query
Say that you have a table shipment that you want to augment with information from table vehicle, and both tables have a column vehicle_id so you can use NATURAL JOIN.
---- DO NOT USE, quadratic runtime ----

EXPLAIN UPDATE shipment
SET shipment.speed = vehicle.average_speed
FROM
    shipment s_joined NATURAL JOIN vehicle
WHERE
    -- This is the magic condition
    -- (EDIT: ... it probably causes the quadratic runtime, too)
    shipment = s_joined
    -- any further limitations go here:
    AND shipment.destination = 'Perth'

Minimal working example
-- A table with shipments, some with missing speeds
create temporary table shipment (
    vehicle_id varchar(20),
    cargo varchar(20),
    speed integer
);
insert into shipment values
    ('cart', 'flowers', 60),
    ('boat', 'cabbage', null),
    ('cart', 'potatos', null),
    ('foot', 'carrots', null);

-- A table with vehicles whose average speed we know about
create temporary table vehicle (
    vehicle_id varchar(20),
    average_speed integer
);
insert into vehicle values
    ('cart', 6),
    ('foot', 5);

-- If the shipment has vehicle info, update its speed
---- DO NOT USE, quadratic runtime ----
UPDATE shipment
SET   speed = vehicle.average_speed
FROM  shipment as s_joined natural join vehicle
WHERE shipment = s_joined
      AND shipment.speed is null;

-- After:
TABLE shipment;
┌────────────┬─────────┬───────┐
│ vehicle_id │  cargo  │ speed │
├────────────┼─────────┼───────┤
│ cart       │ flowers │    60 │ <- not updated: speed was not null
│ boat       │ cabbage │       │ <- not updated: no boat in join
│ cart       │ potatos │     6 │ <- updated
│ foot       │ carrots │     5 │ <- updated
└────────────┴─────────┴───────┘

Answer: If you want to check whether your joins are proper or not you can run your update query in transaction, using this you can run select query on original table which gives you exactly those results which you are looking for, and after confirmation you can finalize the query.
BEGIN;
-- Begin the transaction

UPDATE schema.village vill
SET wst_id = vill_view.wst_id_023::INT, --if you want to cast the column type
    wst_dist = vill_view.wst_dist_023::numeric --if you want to cast the column type
FROM schema.village_view vill_view
WHERE vill.id = vill_view.id::double precision; --if you want to cast the column type

-- Verify the result
SELECT * FROM schema.village

-- ROLLBACK; -- if your query fails or fills that something is wrong you can reverse the all updates and table will remain as original
-- COMMIT -- if you fills all are good (no return to original table once commited)


Separar valores vindo de uma variavel

Question: Ola amigos preciso separar valores de uma variavel recebo os valores assim:
-4.08768, -63.141322 23/04/2017 22:00:00

preciso dos valores separado cada um com uma variavel tipo assim:
-4.08768, -63.141322
23/04/2017
22:00:00
Preciso enviar via post para meu sistema mais nao estou conseguindo separar alguem da essa forca ai para separar isso exemplo:

<?php
$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";
echo $variavel;
?>
Answer: $variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";

Primeiro retiramos o espaço depois da virgula para depois fazermos um explode com espaço de modo a não separar a latitude da longitude
$variavel=str_replace(", ",",",$variavel);

O explode
$partes = explode(' ',$variavel);

$coordenadas=$partes[0];
$data=$partes[1];
$hora=$partes[2];

E finalmente recolocamos o espaço após a virgula na variável $coordenadas
$coordenadas=str_replace(",", ",",$coordenadas);

A saída será
echo $coordenadas; //-4.08768, -63.141322
echo $data; //23/04/2017
echo  $hora; //22:00:00

Juntando tudo:

$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";
$variavel=str_replace(", ",",",$variavel);
$partes = explode(' ',$variavel);
$coordenadas=$partes[0];
$data=$partes[1];
$hora=$partes[2];
$coordenadas=str_replace(",", ",",$coordenadas);

echo $coordenadas;
echo $data;
echo  $hora;

exemplo- ideone

O mesmo resultado se obtém da seguinte forma:

$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";

$partes = explode(' ',$variavel);

$latitude=$partes[0]; //-4.08768,
$longitude=$partes[1]; //-63.141322
$data=$partes[2]; //23/04/2017
$hora=$partes[3]; // 22:00:00

$latLong=$latitude." ".$longitude; // -4.08768, -63.141322

exemplo - ideone
Answer: Use um explode para fazer a separação da forma que precisar ex:
$params = explode(',', $row['variavel']);
$lat = $params[0]; //-4.08768
$lon = $params[1]; //-63.141322 23/04/2017 22:00:00
$val = $params[2]; //0

$saida = $lon.','.$val.','.$lat;

Answer: Utilizando preg_split, você informa o pattern regex para que a string seja dividida:
$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";

$split = preg_split("/\b\s/", $variavel);

var_dump($split);

Dessa forma, retornará um array com três posições:
array(3) {
  [0]=>
  string(20) "-4.08768, -63.141322"
  [1]=>
  string(10) "23/04/2017"
  [2]=>
  string(8) "22:00:00"
}

Veja o exemplo no ideone

Separar valores vindo de uma variavel


Testing whether a matrix of trig values is positive definite.

Question: I just want to check that the matrix below is not positive definite:
$$\begin{bmatrix}\cos(\theta) & -\sin(\theta) \\\sin(\theta) & \cos(\theta)\end{bmatrix}$$
I think that it is not because the upper left 1*1 determinant is just $cos(\theta)$ and this is not positive for every value of $\theta$
Is this correct?
Comment: It's positive-definite for _some_ values of $\theta$. Mainly, for $\theta$ between $-\pi/2$ and $\pi/2$.
Comment: more generally $\cos \theta > 0 \Rightarrow \theta \in \left ( 2n\pi-\pi/2,2n\pi+\pi/2 \right )$
Answer: You'll just have to see that this is a rotation and then go back to the definition of definiteness. $R_\theta$ is positively definite if $u\cdot R_\theta u>0$ for all $u\ne 0$. Now we have thhat $u\cdot R_\theta u=|u|^2\cos\theta > 0$ for all $u\ne 0$ if and only if $\cos\theta > 0$.


Why do minimal polynomial have coefficients in the integral closured ring?

Question: I'm reading the following theorem:

My question is, why are $a_i$s in $A[\alpha_1...\alpha_n]$?
Comment: I suggest you write a complete answer answering your question.
Comment: The as are the result of evaluating the elementary symmetric functions on the alphas.
Comment: I guess I know the answer now...how stupid I am...
Answer: There's an $\sigma$ sending $\alpha$ to $\alpha_i$ fixing $K$, hence $\alpha_i$ are integral over $A$ since $\alpha$ is, the rest is easy.


Force Image module to regenerate thumbs

Question: I am using the Image module along with ImageGallery to make galleries in Drupal 6. I now have some 'holes' in my gallery where Image can't find the thumbnails, so they need to be regenerated. How do I force that to happen? Have tried clearing caches and running update.php, but I still have the holes. Am I missing something?
Answer: Probably the easiest way is to just go to the ImageCache Styles page and re-save the style. Don't make any changes just hit save.
You could also just delete all the thumbnails out of the image_styles folder in your files/ directory.

Force Image module to regenerate thumbs


Extension of Hölder continuous function

Question: Let $f:[0,c] \rightarrow \mathbb R$ be Hölder continuous with constant $M>0$ and power $p \in (0,1)$ and satisfies $f(0)=f(c)$. Let $g:[0,2c] \rightarrow \mathbb R$ be given by:
$$
g(x)=f(x) \ \ \textrm{for} \ \ x \in [0,c]
$$
and
$$
g(x)=f(x-c) \ \ \textrm{for} \ \ x \in [c,2c].
$$
Then $g$ is Hölder continuous with the same power but I don't know if constant $M$ is the same.
I try in this way. Let $x,y \in [0,2c]$, $x<y$. It is obvious that if $x,y \in [0,c]$ or $x,y \in [c,2c]$ then $|g(x)-g(y)|\leq M |x-y|^p$. For $x\in [0,c]$, $y\in [c,2c]$ we have
$$
|g(x)-g(y)| \leq |g(x)-g(c)|+|g(c)-g(y)| =|f(x)-f(c)|+|f(0)-f(y-c)|\leq M [(x-c)^p+(y-c)^p]\leq M 2^{1-p} (c-x+y-c)^p= M 2^{1-p} |y-x|^p.
$$
(I have  used inequality: $2^{p-1}(u^p+v^p)\leq (u+v)^p$ for $u,v \geq 0$, $p\in (0,1)$, which follows from concavity of $[0,\infty) \ni t\mapsto t^p$.)
Does constant $M 2^{1-p}$ can be improved to $M$ ?
Thanks
Answer: Suppose $f(x) = x^p$ for $0 \le x \le \epsilon$ and $f(x) = -(c-x)^p$ for $c-\epsilon \le x \le c$, which (at least if $c$ is large enough and you define $f$ suitably on $[\epsilon, c-\epsilon]$) has constant $M=1$.  Then taking $x=c+\epsilon$, $y=c-\epsilon$,
$$ |g(x) - g(y)| = 2 \epsilon^p =  2^{1-p} |x-y|^p$$
and you can't get rid of the $2^{1-p}$.

Extension of Hölder continuous function


Estimando o tempo de resposta de um servidor usando Python ou regex

Question: Criei um ambiente virtualizado com um servidor Apache (rodando em Debian) e várias máquinas atacantes rodando Debian também. Foi utilizado o VMware Workstation.
IP do servidor: 192.168.91.5
Tenho arquivo de dump (PCAP) coletado com o tcpdump. Há alguma forma de estimar (ou calcular) o tempo de resposta do servidor a cada 60 segundos?
Os IPs dos atacantes são da forma 192.168.91.X
Exemplo de arquivo PCAP:

Arquivos PCAP de exemplo:
https://ufile.io/hfqp4
Tentei usar tcprstat mas o resutado sempre dá zero, o que sem dúvidas, está errado:
tcprstat -r semAtaques.pcap -f '%n\n' -p 80 -t 1 -n 0

Answer: Você pode tentar usar libs prontas pra isto, encontrei duas:
pypcapfile
Para instalar use o pip:
pip install pypcapfile

Um exemplo de uso:
from pcapfile import savefile
testcap = open('1.pcap', 'rb')
capfile = savefile.load_savefile(testcap, verbose=True)
print capfile

pcap-parser
Para instalar use o pip:
pip install pcap-parser

Ele funciona por linha de comando (o que pode ser aproveitado), exemplo simples:
parse_pcap 1.pcap

A lista dos outros comandos estão em https://pypi.python.org/pypi/pcap-parser
Comment: Obrigado! Este parece que não gera estatísticas! Estou tentando entender pq tcprstat está dando sempre zero!
Comment: Estou testando também este:  http://yconalyzer.sourceforge.net/
Comment: yconalyzer não consegui instalar
Comment: eu não entendi como conseguir o tempo de resposta!
Answer: Conseguir resolver utilizando um programa free:
Response Time Viewer for Wireshark:
http://www.solarwinds.com/free-tools/response-time-viewer-for-wireshark
Ele fornece, dentre outras coisas, o tempo de resposta da aplicação e da rede!


Choosing an electro-acoustic guitar

Question: I am an amateur guitarist and want to buy an electro-acoustic guitar. I tried a lot of them, but two just struck my heart: Fender CD-100CE and Fender CD-60CE. I am confused about the significant differences between the variety!
What should look for when buying an electro-acoustic guitar for the first time?
Comment: Have you looked at guitars other than Fenders? Not that Fenders aren't great, but you should try out some other brands as well.
Comment: Welcome to the Site. I had to edit your question a bit, because the kind of question you asked was [off topic here](http://meta.music.stackexchange.com/questions/631/may-i-ask-for-product-reviews-or-is-it-considered-a-shopping-question), since it was pretty much a shopping question.
Answer: There are many things to consider when buying any guitar. Here are my important factors:

price
action/playability
construction materials
sound when plugged in
sound when unplugged (I play almost always plugged in, so this is less important)

Takamine have a great range of cheap guitars that sound amazing and have great playability. Check out the D series.
Comment: I would completely agree about the action needing to be right
Comment: Honestly @Unknown, it's almost the most important thing for me.
Answer: Have you looked at the Fender website?

CD-100CE; and
CD-60CE.

There are only three differences, according to the Specs tab:

The 100 has mahogany back and sides, whereas the 60 is nato;
The 100 has a satin finish to the body and neck, whereas the 60's is gloss; and
The 100 has a rosewood headstock veneer, which the 60 doesn't.
Answer: Basically, there are four criteria:

Does it sound good?
Does it feel good?
Does it work good?
Does it look good?

The first is most important. Go by your own ears, but be aware that as a new player, your ears are not well-developed. If you only intend to play by yourself or accompanying a singer, then test it in a quiet environment, but if you're going to play with others, then play in context of other instruments and see if it's frequencies work with other instruments. An A/E guitar in an otherwise electric band functions essentially as a tuned snare or hi-hat, so a nice solid bass will be wasted in context. You will want to try both acoustic and through an acoustic amp or PA system.
Feeling right can come to several things. Does the guitar have a thin/thick/narrow/wide neck? Is the glossy finish sticky to your hands? Is the action high? Some of this can be corrected by a setup, but some of it can't.
Turn the tuners. They should move smoothly. Move the pots up and down, looking for scratchy pots. You're talking inexpensive in-production instruments, so I doubt there will be issues, but if there are, tell the store's staff and choose another instrument.
Fernando on SNL used to say "It is better to look good than to feel good", but it is better for guitars to sound good than to look good. I wouldn't play a guitar covered with pinup stickers in church, and I might not play a sunburst Strat in an 80s glam metal cover band, and the aesthetic choices for low-end Fender acoustics are few, but it is an area of choice. More importantly, a floor model might have nicks and scratches and cracks. Often they mean nothing, but they might mean repair bills or replacement costs later. If you're buying new, you shouldn't have to worry about blemished instruments; unless it's the one, put it back on the wall and try another.
You might worry about solid wood vs laminate. A solid top is a nice thing, but, unless I'm wrong about the context, it shouldn't be a worry.
Good luck and happy playing!
Comment: +1, great answer. I would take issue with the "tuned snare" part -- it's true, but only if the guitar is played in a certain style.

Choosing an electro-acoustic guitar


Impossible to change DNS records in .DE domain

Question: I've being trying to change DNS records in a .DE domain (waverocker.de), but it's impossible! I have the same domain as .ORG and as .CH and no problem there, but with .DE version it's impossible.
Always gives back an "error while updating domain name: Nameserver error". I'm checking with https://zonemaster.net and the only red error that I get it's that my IP refers to multiple nameservers.
How can I change my DNS records in this .DE domain? Why it works fine with other domains but not with .DE?
Answer: Have a look at DeNIC's Nameserver Predelegation Check.
Short version: your DNS servers for waverocker.org don't actually allow querying waverocker.de.
Comment: I've just checked and I've got these errors:
Warning 102 Provided glue records not applicable (NS)
waverocker.de IN NS vps139700.ovh.net /22.214.171.124

Error 107 Insufficient diversity of nameserver's IP addresses (# expected, # found)
2
1

Warning 102 Provided glue records not applicable (NS)
waverocker.de IN NS ns1.juanandjuan.com /126.96.36.199
Answer: You are trying to use a single server in two different NS records for the same domain, and using the same server twice is against IANA Technical requirements for authoritative name servers.
NS1.JUANANDJUAN.COM.    IN      A       220.127.116.11
VPS139700.OVH.NET.      IN      A       188.8.131.52

Minimum number of name servers
There must be at least two NS records
  listed in a delegation, and the hosts must not resolve to the same IP
  address.
Network diversity
The name servers must be in at least two
  topologically separate networks. A network is defined as an origin
  autonomous system in the BGP routing table. The requirement is
  assessed through inspection of views of the BGP routing table.

Your .org, .ch and .net has three nameservers, of which one has a different IP address:
Name Server: SDNS2.OVH.NET
Name Server: VPS139700.OVH.NET
Name Server: NS1.JUANANDJUAN.COM

sdns2.ovh.net.          IN      A       220.127.116.11

But, this server doesn't meet other requirement by not answering authoritatively (nor at all) for the queries: it simply isn't aware of waverocker.org / .net / .ch / .de at all.

Answer authoritatively
The name servers must answer authoritatively
  for the designated zone. Responses to queries to the name servers for
  the designated zone must have the "AA"-bit set.
This will be tested by querying for the SOA record of the designated
  zone with no "RD"-bit set.

There are two possible reasons for this to work with the other TLDs than .de:

The tests for them were made before the sdns2.ovh.net stopped to work as a secondary.
The .de might be more strict with the IANA requirements. The difference could be e.g. that it doesn't do a single test for each condition alone: there are two different IP addresses and two of the NS records are working because the single DNS server is answering authoritatively. However, the overall condition doesn't meet the requirements and there could be tests for that.

What to do?

Get a working secondary and test it answers authoritatively for all your domains.
Remove the duplicate record and only refer to 22.214.171.124 once.


Is it possible to create a template (tpl) file for comment view mode?

Question: I created a new view mode for comments called "cool", as shown in the image below (click the image for full size):

I created comment--cool.tpl.php and added it to my theme template folder.
Based on the question about Custom tpl for view mode for all contenty type, I also need to add a pre-process to my theme. I tried:
  function MyThemeName_preprocess_comment(&$vars) {
  $vars['theme_hook_suggestions'][] = 'comment__' . $vars['view_mode'];
  }

But I get an error "Undefined index: view_mode"
Seems like comments preprocess doesn't have view_mode as an argument. So I guess it's not possible to create a tpl for comments? OR is there another way?
Answer: With take look at  Template Comment Preprocess You find out that you just need use  $vars['elements']['#view_mode'] instead of $vars['view_mode'].


Retrieving just the joined entities from Core Data

Question: I have a movie showtimes entity which has a one-to-one relationship to a movie entity. The inverse (movie -> movie showtime) relationship is a one-to-many relationship. If a movie is deleted, the associated movie showtimes will also be deleted, but if a movie showtime is deleted the associated movie will stay. (Not sure how much of that is relevant but wanted to clarify the situation as much as I could)
Now, is there a way to query Core Data to get only the unique movies for which I have showtimes?
Is it possible to select from the movie showtimes and somehow restrict the results to just the associated unique movies? Or would selecting from the movie entity bring back only the movies with a matching row in the movie showtime entity?
Answer: Taking your questions in turn:

Now, is there a way to query Core Data to get only the unique movies for which I have showtimes?

You could use a predicate to select movies where the count of showtimes is greater than zero:
"showtimes.@count > 0"

Is it possible to select from the movie showtimes and somehow restrict the results to just the associated unique movies?

If you have (courtesy of your first query) an array (say scheduledMovies) of movies which have showtimes, then you can fetch the associated showtimes using a predicate like this:
 "movie IN %@", scheduledMovies

Or would selecting from the movie entity bring back only the movies with a matching row in the movie showtime entity?

If you fetch movies, then you will get ALL movies, unless you specify a predicate as per your first question.  But if you fetch showtimes, you can get an array of the associated movies using key value coding with the key:
"@distinctUnionOfObjects.movie"

The resulting array will not have any movies with no showtimes.  (The first part of this key removes any duplicates, since several showtimes might have the same movie).
Answer: Sure. Write a fetch request on Movie with no restrictions, and you'll get all Movie instances.
Comment: Thanks, although I was after just movies with showtimes against them (apologies if I didn't make that clear).
Comment: Okay, in the end I wrote a fetch request to pull in movies with the predicate of there having to be a matching showtime entity, i.e. !(ANY(showtime) = Nil) seemed to do the trick. Is this the best way of doing this?


event phase -Capture phase in flex

Question: I read a document, capture phase is check for the event from target to root node. means buttoncontrol to panel container like....
Application
<code>  Panel
    TitleWindow
        Button
</code>
But i have 2 panels under the same application container and 2 panels have a button controls and events.
So now the flash player from where and which event will check first ?
thanks,
ravi
Answer: IIRC, it uses the parent property in each of the components to work out the stack to send the event through. So it will be the relevant child for the way down the stack.

event phase -Capture phase in flex


Executar comando em JS usando string

Question: Tenho um comando para pegar o tamanho do meu json, mas preciso usar uma string para indicar qual objeto quero pegar o tamanho:
var comando = data.result[0][0].'Pedidos'.length;

o erro que me da é esse:
Uncaught SyntaxError: Unexpected string
Comment: talvez você pode acessar como um datatable em c#. data.result[0]["Pedidos"].length;
Comment: Ou tentou utilizar sem apóstrofos? data.result[0][0].pedidos.length ?
Comment: Podes dar um exemplo desse JSON?
Comment: Essa string é fixa, ou está numa variável? Se for fixa, por que não fazer simplesmente `data.result[0][0].Pedidos.length`?
Answer: Assumindo que seu data possui uma estrutura tipo:
{                                 // data
    "result":[                    // data.result
        [                         // data.result[0]
            {                     // data.result[0][0]
                "Pedidos":[...]   // data.result[0][0].Pedidos
            },
            ...
        ],
        ...
    ]
}

Você pode obter o tamanho do array "Pedidos" da seguinte forma:
data.result[0][0]['Pedidos'].length;

Onde 'Pedidos' poderia estar também em uma variável:
var x = 'Pedidos';
data.result[0][0][x].length;

Todo objeto JavaScript pode ter suas propriedades acessadas como se fosse um array associativo:
objeto.campo == objeto["campo"]

Answer:
var comando = eval("data.result[0][0].Pedidos.length");

ou como preferir
var variavel = "pedidos";
var comando = eval("data.result[0][0]."+variavel+".length");

Executar comando em JS usando string


Showing $\text{Aut}(\mathbb{Q})$ is the trivial group and calculating $\text{Aut}(\mathbb{Q}(\sqrt{2}))$

Question: For a field $K$ let $\text{Aut}(K)$ denote the group of all automorphisms $f:K\to K$.
How can one show that $\text{Aut}(\mathbb{Q})$ is the trivial group and how to calculate $\text{Aut}(\mathbb{Q}(\sqrt{2}))$ ?
Comment: For the first, you can show that as $1\mapsto 1$ under any automorphism, then any automorphism fixes each $n\in \mathbb{N}$ by additivity, then $1/n$ by reciprocity and then $n/m$ by multiplicity.
Answer: Hint: If $f$ is an automorphism of $\mathbb{Q}$, $f$ has to map every element to itself. (why?)
If $f$ is an automorphism of $\mathbb{Q}(\sqrt{2})$, $f$ fixes every element of $\mathbb{Q}$, meaning $f$ is determined by what it maps $\sqrt{2}$ to.
Answer: Suppose $\varphi$ is an automorphism of $\mathbb{Q}$: we know that it has to fix 0 and 1, and so it fixes the integers by linearity, and hence it fixes $\mathbb{Q}$ by the fact that it's a field homomorphism.
Now, if $\sigma$ is an automorphism of $\mathbb{Q}(\sqrt{2})$, it has to fix $\mathbb{Q}$ by the above, and so as $\mathbb{Q}(\sqrt{2})$ is a $\mathbb{Q}$-vector space, $\sigma$ is determined by what it sends $\sqrt{2}$ to. Bear in mind that $\sigma(\sqrt{2})^2 = 2$...


how to add one month in a raw date coming from oracle using PHP only?

Question: Let's say I have this date, e.g.:
12-DEC-14 11.55.51.000000000 AM

and then I assigned it to variable, let's say:
$date = '12-DEC-14 11.55.51.000000000 AM';

Now the question is, how do I add 1 month or 2 months or so to that $date using only
php, without using any oracle sql date functions, just pure php,
because I will save the result to oracle db table in that same format.
The result should be like, e.g.:
$nextmonth = '12-JAN-15 11.55.51000000000 AM';

Then that's the time I can save that $nextmonth in the table column. So how ?
Answer: You can use DateTime classes in this case, load that date and define its format. Then after creating the datetime object, adjust it to your x number of months, then present it again with the original format.
$input = '12-DEC-14 11.55.51.000000000 AM';
$date = DateTime::createFromFormat('d-M-y h.i.s A', $input);
$next_month = clone $date;
$next_month->modify('+1 month');
echo strtoupper($next_month->format('d-M-y h.i.s A'));

Comment: how bout the succeeding 9 zeroes ?, won't that cause any errors in oracle if I just append it like e.g `echo strtoupper($next_month->format('d-M-y h.i.s.000000000 A'));`
Comment: @sasori of course you can do that also, whats the column data type anyway?
Comment: it's a `TIMESTAMP(6)` , but the format is exactly like this inside that column `12-DEC-14 11.55.51.000000000 AM`
Comment: @sasori i don't know if that fractional seconds will bear its weight on insertion, but have you tried it?
Comment: not yet, am still building my code,I will test the saving of data later. thanks for the help :)
Answer: This is probably only a very long comment rather than a real answer, but some of your comments let me think we have an instance of XY problem here:

it's a TIMESTAMP(6) , but the format is exactly like this inside that column 12-DEC-14 11.55.51.000000000 AM
how bout the succeeding 9 zeroes ?, won't that cause any errors in oracle if I just append it like e.g echo strtoupper($next_month->format('d-M-y h.i.s.000000000 A'));

A TIMESTAMP(6) store a date-time information (a "point in time"). It hasn't any "format" par se. TIMESTAMP are great data type, as they allow you to easily perform calculation on data and time with a great precision at DB level such as "adding one month".
But, without explicit request from your part, a default format is used to convert timestamps from and to strings.
Maybe your real issue is that Oracle try to implicitly convert your string to timestamp using its standard format. Usually, it is a far better idea to explicitly convert data type yourself. From the documentation:

Oracle recommends that you specify explicit conversions, rather than rely on implicit or automatic conversions, for these reasons:

[...]
implicit conversion depends on the context in which it occurs and may not work the same way in every case. For example, implicit conversion from a datetime value to a VARCHAR2 value may return an unexpected year depending on the value of the NLS_DATE_FORMAT parameter.

Please note that above statement is true for TIMESTAMP too, as the "standard" format is user-definable using NLS_TIMESTAMP_FORMAT.
The PHP documentation has a similar warning:

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

As a personal suggestion, I would say that you should never rely on implicit date/timestamp conversion, as any change of the relevant configuration settings at DB-level or for the current session will break your code.

So, depending the way you insert your value, using an explicit format might be as simple as wrapping the bind variable in a proper TO_TIMESTAMP(....) call:
// query the original data
$q = oci_parse ($connection ,
                "INSERT INTO ....
                        VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");

$q = oci_parse ($connection ,
                "INSERT INTO ....
                        VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");

Coming back to your initial question: "how to add one month in a raw date" " I will save the result to oracle db table in that same format data type" , this should be as simple as adding 1 month when inserting the value:
$q = oci_parse ($connection ,
                "INSERT INTO ....
                        VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF')
                                + INTERVAL '1' MONTH, other_columns...)");


php namespace alias and the choice of words for directories - can we name a directory as global?

Question: I am having more trouble with namespacing when comes to the choice of words after this question I made earlier,
use \global\Conan as Cimmerian;

error message,

Parse error: syntax error, unexpected 'global' (T_GLOBAL), expecting
  identifier (T_STRING) in C:\wamp..

So that's no way you can name a directory as global in this situation?
Comment: A list for the meaning of the `T_xxx` tokens is available here: http://www.php.net/tokens - You also might find the error messages reference useful: [Reference - What does this error mean in PHP?](http://stackoverflow.com/q/12769982/367456)
Comment: Thanks for the links, hakre.
Answer: global is a reserved keyword in PHP, so cannot be used as an identifier.
See the List of Keywords in the PHP manual.
Although namespaces are not specifically mentioned on that page, they would cause the same problems as class names, in that the parser will not know what to do when it encounters the keyword - hence the error you are seeing.


In a commutative, Noetherian ring, $d(A/J) = d(A/{J^{m}})$

Question: Let $R$ be a commutative, Noetherian ring.
Let $d$ be a dimension function: for each finitely generated $R$-module $M$, we assign a natural number, or zero, such that for every $N \leq M$ a submodule we have $d(M) = \max\{d(N), d(M/N)\}$.

Let $J \triangleleft R$ be an ideal and let $m \in \mathbb{N}$. How
  does it follow that $d(A/J) = d(A/{J^{m}})$?

So far, I think that if we assume that $d$ is invariant under isomorphisms (if $M_1 \cong M_2$ then $d(M_1) = d(M_2)$, which isn't technically given), we get that $d(A/J^m) = \max\{d(A/J),d(A/J^m/A/J)\} \geq d(A/J)$, since for any $m \geq 1$ we have $J^m \leq J$ and so $A/J$ is isomorphic to a submodule of $A/J^m$. How do you get the other direction?
Some useful facts that may be relevant:

The set of minimal prime ideals over $J$ is finite and non-empty.
There are primes $I \subset P_i$ s.t $P_1P_2\cdots P_n \subset I$.
If $M$ is a finitely generated $R$-module then setting $I = \mathrm{Ann}_R(M)$ we get that $R/I$ is isomorphic to an $R$-submodule of $M^n$ for $n$ the number of generators of $M$.

The first two facts follow from $R$ being Noetherian. The third from commutativity as well.
Answer: Partial answer:
I'll assume that more precisely the condition is that if
$$0\to M'\to M\to M''\to 0$$
is a short exact sequence of modules over $R$ (commutative, Noetherian) with $M$ finitely generated, then $d(M)=\max\{d(M'),d(M'')\}$. This addresses the isomorphism vs set theoretic equality problem that the original statement had.
I suspect the claim in the question is false, but I can't come up with a counterexample, so I'm leaving this partial answer here. Mostly the problem is that I can't think of a function $d$ which has the desired property, so if the OP has one, adding that context to the question would be really helpful.
This is a weird property. First consider a direct sum. $M\oplus N$. $d(M\oplus N)=\max\{d(M),d(N)\}$, which implies that $d(M^n)=d(M)$, so in particular, $d(R^n)=d(R)$. However, if $M$ is finitely generated, then there is a surjection $R^n\to M$ for some $n$, which implies that $d(M)\le d(R^n)=d(R)$. Thus $d(R)$ is an upper bound on all the "dimensions" of modules over $R$. (I put dimensions in quotation marks, because this behaves very differently from the notions of dimension that I am familiar with.)
Now if $I$ is an ideal of $R$, then $d(R)=\max\{d(I),d(R/I)\}$, which means that one of $d(I)$ or $d(R/I)$ equals $d(R)$. If $d(R/I)=d(R)$, then since $R/I$ is a quotient of $R/I^m$ for all $m\ge 1$, we have $d(R/I)=d(R)\le d(R/I^m)\le d(R)$, so $d(R/I)=d(R/I^m)=d(R)$ in this case.
In the other case, $d(R/I)<d(R)$, and $d(I)=d(R)$. This is the case in which we could falsify the claim in the question, because if $d(I^m) < d(R)$, $d(R/I^m)=d(R)$, then there is no clear contradiction.
However, I can't think of any examples of functions $d$ which have the desired property, so I don't have a counterexample at hand.
Comment: thanks for the partial answer - I agree this is weird. Unfortunately I don't have an example on hand, I'll look further into my notes. Indeed the direct sum property you mentioned is strange, I came upon it too..


Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'

Question: I am new to Android Studio, I am getting this error everytime I try to sync the project with gradle. For instance I am providing reference to three files.
1) Project level build.gradle File
plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.myfirstapp"
        minSdk 24
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

2) Gradle Scripts build.gradle file
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
        mavenLocal()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0-RC2"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

3) gradle-wrapper.properties
#Fri Nov 05 11:37:25 IST 2021
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

I am on Windows 10 with Android Studio Arctic Fox 2020.0.1 Patch 3
The Complete Error Message Which I get is
Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'. Received status code 405 from server: Method Not Allowed

Comment: Works fine for me. Smells like a firewall problem.
Comment: chrylis Do you have a solution ?
Comment: Step 1: Post a complete error message, particularly including the part that probably says something like "connection timed out".
Comment: Yeah I added the complete error message
Comment: Chrylis I have added the complete error message at the end of the question, Now can you please provide me with a solution because I am not able to get started with android studio. It's my first project afterall.
Answer: well , as it seems alright I can only guess its a connection issue .
Try using this link https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom with a browser to make sure you can connect to google .
if you can reach the site then you ll probably need to use proxy/vpn .
and the way to do so is downloading psiphon and navigate to the setting , set local port for 1234 for example.
Then go to Users/%USERNAME%/.gradle and add gradle properties , with the following
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=1234

systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=1234

Comment: Yes I can connect to dl.google.com successfully and yeah I think I need a proxy let me try your suggestion.
Comment: Still getting the same issue, also tried adding the proxy.
I can download .jar file when pasting the link on the browser but on android studio getting this error.
Comment: This was a valid response with the android version at that time , try to set the HTTP proxy settings in Android Studio: From the menu bar, click File > Settings (on macOS, click Android Studio > Preferences). In the left pane, click Appearance & Behavior > System Settings > HTTP Proxy. The HTTP Proxy page appears.
the proxy should be as the answer suggested after connecting with psiphon.
Comment: the problem for me was that cruel maintainer of maven repository now return 404 instead of 403 when you have an ip ban so I waisted many hours not knowing what was going on


Set Image using getAbsolutePath()

Question: I'm trying to use custom gallery and trying to get the selected images and would like to display it in listview
This is what I'm trying to do:
if (extras != null) {
        for (int i = 0; i < fetchList.size(); i++) {
            Bitmap originBitmap = null;
            filepath = fetchList.get(i);
            newStringList.add(filepath);

            imgfilename = filepath.substring(filepath.lastIndexOf("/") + 1);
            Uri selectedImage = Uri.fromFile(new File(filepath));
            File myFile = new File(selectedImage.getPath());
            myFile.getAbsolutePath();
            Toast.makeText(MainActivity.this,myFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
            listimage.setImageBitmap(myFile.getAbsolutePath());
            myStringList.add(imgfilename);
            arrayAdapter = new ArrayAdapter<String>(
                    this,
                    R.layout.custom_textview, R.id.listtext,
                    myStringList);
            lv.setAdapter(arrayAdapter);
            arrayAdapter.notifyDataSetChanged();
        }
 }

Now my question is how do I set the image to the image view using this path ?
If I use this  listimage.setImageBitmap(myFile.getAbsolutePath()); I couldnt see the image.
Path I'm getting is : /storage/emulated/0/
Answer: Pls try this way,
File imgFile = new  File("/sdcard/Images/test_image.jpg");

if(imgFile.exists()){

    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

    myImage.setImageBitmap(myBitmap);

}

Hope this will help you.
Comment: No the app is crashing by getting this error
Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
Comment: This means you are trying to set null bitmap in the image view. From your code i can see that you are getting path as /storage/emulated/0/ while it should be  /storage/emulated/0/. As you can see in my answer it has complete path till image.jpg file.
Answer: Try this
private AQuery aq = new AQuery(activity);

File imgFile = new File(filepath);
aq.id(imageView).image(imgFile, false, 300, new BitmapAjaxCallback() {
                        @Override
                        public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {
                            iv.setImageBitmap(bm);
                        }
                    });

Set Image using getAbsolutePath()


Tem como colocar um spinner em função a outra spinner só como imagem?

Question: Sou novato no Android Studio e queria fazer dois spinners. Um que estaria por exemplo carros,motos e quando selecionada a opção o outro aparecesse as imagens com os nomes dos carros ( caso selecionada carros ) ou motos ( caso selecionado motos)
Comment: Pergunta respondida. O foco do site é esclarecer dúvidas referentes principalmente a erros. Quando você estiver fazendo e estiver em dúvidas coloque o código que você fez e o erro que apresenta e mais pessoas irão te ajudar :D
Answer: Primeira situação - preencher o segundo spinner após a seleção da informação no primeiro:
Para isso você pode utilizar o OnItemSelectedListener(). Seria algo mais ou menos assim:
<code>spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        //seu código aqui }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        //seu código aqui  }

});
</code>
Segunda situação - fazer o spinner aparecer imagens:
Você precisará, para isso, fazer um layout customizado para o seu spinner. Tem um tutorial disso nesse link para facilitar para você: https://www.codingdemos.com/android-custom-spinner-images-text/


Eclipse Junit '-ea' VM Option

Question: In eclipse preferences
<code>Windows > Preferences > Java > Junit
</code>

What effect does the "Add '-ea' to VM args ...." checkbox option actually have on the new junit launch config?
Answer: It enables the JVM to honour assertions
Comment: +1 note: the Java-in-built assertations are not the junit ones ... I do not recommend to use those in-built assert statements. instead do unit testing
Comment: @Karussell Assertions and unit tests serve different purposes. When writing unit tests, you should use the junit assert functions. Inside your regular code, you should use the assert keyword if you want to test invariants and other conditions (which is a good idea).

Eclipse Junit '-ea' VM Option


Is it possible to use a view as a field in another view?

Question: I have two views. First one is an unformatted view from a content type, and second one is a table view of most viewed from the same content type. Now I want to show both of these views in a page without using panel module. Is there any way to attach these views?
thanks.
Answer: The title of your question and the body of your question seem different to me.
To use the results of a view as a field in another view, you would use Views Field View.
To display two views at the same time, make one a page display and the other an attachment display attached to the page display.
Comment: I have problem with both ways. when I use Views Field View, the table view show completely in my boxes. and when I add an attachment, if I set its format as Table, my Page display also change to Table, and when I set my page format to Unformatted, it affects on attachment display, But I need to different format here. What should I do to separate their Format style?
Comment: o! With setting display just for page and attachment I could make them to show different!


Showing convergence of integrals does not imply pointwise convergence

Question: Can somebody verify that this counter example shows that
$\int\limits_{a}^b|f_n(x)-f(x)|dx\rightarrow 0\implies f_n(x)$ converges pointwise to $f(x)$
is not true?
Counter example:
Let $f_n:[1,2]\rightarrow\mathbb R$ be define by $f_n(x) =\frac{nx+2}{nx+1}$
and define $f:[1,2]\rightarrow\mathbb R$ by $f(x)\equiv1$
EDIT: Does this work on [0,2] rather than [1,2]
Comment: No, $f_n\to 1$ uniformly on $[1,2]$
Comment: Maybe try $f_{n}(x)=nx$ when $0\leq x\leq 1/n$ and $f_n(x)=1$ when $1/n<x\leq 1$ on $[0, 1]$. Use $f(x) = 1$ on $[0, 1]$ as the function it converges to. (The function can be easily modified to fit $[1,2]$. I leave that to you.)
Answer: No, your example doesn't work, note that $$ f_n(x) = \frac{nx+2}{nx+1}=1 + \frac{1}{nx+1}$$
and therefore
$ |f_n(x) - 1| = \frac{1}{nx+1} $, and
$$ \|f_n  - 1\|_{\infty} = \max_{x\in[1,2]}\frac{1}{nx+1} = \frac1{n+1} \to 0 $$
which means $f_n\to 1$ uniformly. Hence for your sequence, we have the limit $f=1$, $f_n\to f$ pointwise, and $\int_1^2 |f_n - f| \to 0$.
Your example does indeed work for the region $[0,2]$ (or $[0,1]$, for that matter.) I'll leave the proving of that to you :)
Comment: would the counter example work on [0,2], as then it would not converge pointwise?
Comment: @Loobear23 oh, it looks like yes!