Generalizing fields to more than two operations: Are these definitions equivalent?

Question: See the previous question Can a "generalized field" with three operations be infinite?
We have a set $S$, and $n$ operations $\times_0,\times_1,\times_2,\cdots,\times_{n-1}$ on $S$. Each operation $\times_k$ is commutative, is associative, has an identity $e_k\in S$, and distributes over the previous operation $\times_{k-1}$. Also, the identities are all distinct. Denote $S_k=S\setminus\{e_0,e_1,e_2,\cdots,e_{k-1}\}$ (understanding that $S_0=S$, etc.). The whole structure is called an $n$-field if it has some further properties.
Given the above properties, are (some combinations of) the following further properties equivalent?
$(1)$ Each $\times_k$ is invertible in the sense that, for any $a\in S_k$, there exists $b\in S$ such that $a\times_kb=e_k$.
$(2)$ Each $\times_k$ is invertible in the sense that, for any $a\in S_k$, there exists $b\in S_k$ such that $a\times_kb=e_k$.
$(3)$ Each identity is null with respect to the higher operations; for any $k<l$ and any $a\in S_k$, $e_k\times_la=e_k$.
$(4)$ Recursively, both of the structures $(S_0,\times_0,\times_1,\cdots,\times_{n-2},e_0,e_1,\cdots,e_{n-2})$ and $(S_1,\times_1,\times_2,\cdots,\times_{n-1},e_1,e_2,\cdots,e_{n-1})$ are $(n-1)$-fields. (And a $1$-field is an abelian group.)
$(5)$ All $(n-1)$ of the structures $(S_k,\times_k,\times_{k+1},e_k,e_{k+1})$ are fields. (Or if $n=1$ the structure is an abelian group.)

Clearly $(2)$ implies $(1)$, and $(1)$ and $(3)$ together imply $(2)$. Ideally, I want $(1)$ alone to imply all the others.
To prove $(4)$ for the second structure (the first is easy), we'd only need to show that $S_1$ is closed under $\times_1,\times_2,\cdots,\times_{n-1}$; that is, if $a\neq e_0\neq b$, then $a\times_kb\neq e_0$. But this follows from $(3)$ and invertibility.

My linked question proves that $(1)$ implies the others in the case $n=3$, and shows that no $n$-field exists for $n>4$ provided that it's true for $n=4$. So let's focus on $4$-fields, and assume property $(1)$.
We know that the sub-structure $(S_0,\times_0,\times_1,\times_2,e_0,e_1,e_2)$ is a $3$-field, which implies, for all $a\in S$,
$$e_0\times_0a=e_1\times_1a=e_2\times_2a=a,$$
$$e_0\times_1a=e_0\times_2a=e_0,$$
$$a\neq e_0\implies e_1\times_2a=e_1.$$
The last two lines are property $(3)$ for this sub-structure. To complete $(3)$, we need to consider the final operation $\times_3$:
$$e_0\times_3a\overset?=e_0,$$
$$a\neq e_0\overset?\implies e_1\times_3a=e_1,$$
$$e_0\neq a\neq e_1\overset?\implies e_2\times_3a=e_2.$$
For the last one, defining $x=e_2\times_3a$ and using the given algebraic laws,
$$e_2\times_3a=(e_2\times_2e_2)\times_3a=(e_2\times_3a)\times_2(e_2\times_3a),$$
we see that $x=x\times_2x$ is its own square. If $x\in S_2$ (meaning it's not $e_0$ or $e_1$), then it's $\times_2$-invertible, and dividing gives $e_2=x$. If instead $x=e_0$ or $e_1$, then
$$a=a\times_3e_3=a\times_3(e_3\times_2e_2)=(a\times_3e_3)\times_2(a\times_3e_2)=a\times_2x,$$
so we get $a=a\times_2e_0=e_0$, or $a=a\times_2e_1=e_1$, a contradiction. Therefore $x=e_2\times_3a=e_2$.

In fact we can prove $(2)$ from $(1)$, at least in the case $n=4$. We already know that $\times_0,\times_1,\times_2$ are invertible on their respective spaces $S_0,S_1,S_2$. It remains to consider $a\in S_3$: is its $\times_3$-inverse $b$ also in $S_3$? Suppose contrarily that $b=e_0$, $e_1$, or $e_2$. Then, from the known properties of $3$-fields, $b=b\times_2b$, and thus
$$e_3=a\times_3b=a\times_3(b\times_2b)=(a\times_3b)\times_2(a\times_3b)=e_3\times_2e_3;$$
but $e_3\in S_2$ is invertible; dividing gives $e_2=e_3$, a contradiction. So we must have $b\in S_3$.
Answer: From the discussion near the end of the linked question, the $\times_1\times_2$ structure must be a field with characteristic not $2$; that is, $e_2\times_1e_2\neq e_1$. So the $\times_1$-inverse of $e_2$ (let's call it $x$) is not $e_2$ itself. Also
$$e_2\times_1x=e_1,$$
$$e_2\times_1e_1=e_2\neq e_1,\quad e_2\times_1e_0=e_0\neq e_1,$$
which shows that $x$ is not $e_1$ or $e_0$. This leaves us with $x\in S_3$.
Since $(-1)\cdot(-1)=1$ in any field, we have $x\times_2x=e_2$:
$$e_2=x\times_2x=(x\times_3e_3)\times_2(x\times_3e_3)=x\times_3(e_3\times_2e_3).$$
Let $y$ be the $\times_3$-inverse of $x$. It was shown in the OP that $y$ must be in $S_3$ (which is a subset of $S_2$) and that anything in $S_2$ is absorbed by $e_2\times_3y=e_2$. Multiplying the above equation by $y$, we find that
$$e_2\times_3y=x\times_3y\times_3(e_3\times_2e_3)=e_3\times_3(e_3\times_2e_3)$$
$$e_2=e_3\times_2e_3.$$
Now consider an arbitrary element $a\in S_2$:
$$a\times_2a=(a\times_3e_3)\times_2(a\times_3e_3)=a\times_3(e_3\times_2e_3)=a\times_3e_2=e_2.$$
In any field, the equation $a\cdot a=1$ has only two solutions, $a=\pm1$; that is, $a=e_2$ or $a=x$. Therefore, $S$ must have exactly $4$ elements. (In particular, $x=y=e_3$.)

Since any $n$-field is also a $k$-field for any $k<n$ (just ignore the operations $\times_k,\cdots,\times_{n-1}$), it follows that there are no $n$-fields for $n>4$.
But there is an odd surprise in the case $n=|S|=4$: the structure is not unique, and in fact $(1)$ does not imply $(3),(4),(5)$.
$$\begin{array}{c|cccc}\times_0&e_0&e_1&e_2&e_3\\\hline e_0&e_0&e_1&e_2&e_3\\e_1&e_1&e_0&e_3&e_2\\e_2&e_2&e_3&e_0&e_1\\e_3&e_3&e_2&e_1&e_0\end{array}\qquad\begin{array}{c|cccc}\times_1&e_0&e_1&e_2&e_3\\\hline e_0&e_0&e_0&e_0&e_0\\e_1&e_0&e_1&e_2&e_3\\e_2&e_0&e_2&e_3&e_1\\e_3&e_0&e_3&e_1&e_2\end{array}$$
$$\begin{array}{c|cccc}\times_2&e_0&e_1&e_2&e_3\\\hline e_0&e_0&e_0&e_0&e_0\\e_1&e_0&e_1&e_1&e_1\\e_2&e_0&e_1&e_2&e_3\\e_3&e_0&e_1&e_3&e_2\end{array}\qquad\begin{array}{c|cccc}\times_3&e_0&e_1&e_2&e_3\\\hline e_0&e_0&e_0&e_0&e_0\\e_1&e_0&\mathbf{e_0}&e_1&e_1\\e_2&e_0&e_1&e_2&e_2\\e_3&e_0&e_1&e_2&e_3\end{array}$$


Discrete Math - Counting Integer Solutions to Inequality

Question: I'm trying to find the number of integer solutions to

$x + y + z + w \le 20$ where $x \ge 1$, $y \ge 2$, $z \ge 3$ and $w \ge 4$.

So far I did $x-1 + y-2 + z-3 + w-4 \le 10$. I believe if it were to be equal to $10$ then there would be ${13\choose10}=286$ solutions but I'm not sure if I did that correctly or how to count with the inequality without overcounting. Any help would be greatly appreciated!
Comment: What you've written looks correct to me. The usual trick with an inequality is to introduce an extra variable whose job is to take up all the slack: $x+y+z+w+v=20$ with $v\ge0$
Answer: Nicely done. You are right, for $10$ is how you are saying. Now, what about for $9$? $8$? In general, just add
$$\sum _{i=0}^{10}\left ( \text{# of solutions to }a+b+c+d=i\right ),$$
where $a=x-1,b=y-2,\cdots$ This is equivalent to construct a variable $e\geq 0$ such that
$a+b+c+d+e=10$ as hinted by Jaap Scherphuis in the comments.
Both results will be the same and the connection of the formulas comes from the Hockey-Stick identity.


ADB | Having troubles with device connection

Question: I am working flashing a custom ROM on a new device. Through a bit of research, I've found that I am able to completely circumvent the need to port Clockworkmod by simply using UniFlash on my Windows based laptop. From there, I am left with needing to port the ROM I desire, Cyanogenmod 12, to my device.
I've come to learn that I do not need to build from source, rather I can tailor an existing recovery to fit my device. I am unsure if that is true, so that may need to be cleared up. I went ahead and installed ADB and found a porting guide on the Cyanogenmod Wiki. This is where I am running into problems. I do not seem to have ADB permissions for my device.
When attempting to grab my build.prop, I get this return:
user@mypc:~$ adb pull /system/build.prop
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
error: insufficient permissions for device

After realizing my computer may not see the device, I tried to see which were connected:
user@mypc:~$ adb devices
List of devices attached
????????????    no permissions

It seems I do not have any access to the device at all. USB Debugging is connected, it is a rooted device, and it is set show as a USB Storage. I'm sure if I can at least get this fixed, I should be able to find my way through the rest of the guide myself.
Thank you for any help I can receive!
EDIT 01-
So, I decided to do more digging, and I guess I needed to START the server as super user, and not just run commands in super user.
After running this command, I was able to use my others with permission:
    user@mypc:~$ sudo adb start-server
Now, I am running into a problem in which my device is offline:
user@mypc:~$ adb pull /system/build.prop
error: device offline

After referring to this (set up device for development (?????? no permissions)) thread, I seem to get a new response:
user@mypc:~$ adb pull /system/build.prop
error: device not found

I feel it's safe to say I should remove 51-android.rules from my ~/rules.d/.
Edit 02:
It seems I have answered my own question with research. I guess I just needed to update to the newest version because Android 4.2+ requires bridge authorization to complete tasks, and my version did not know to do that! I was successfully able to pull my build.prop!
Comment: even i used to have the same issue. then i have tried by selecting the adb device from the DDMS solved my issue...........
Comment: As a friendly note @Methamphetadreams, this is a Q and A site. You will get more help if you stick to asking direct questions without adding lots of back-story that is completely unrelated to what you are trying to solve. Hence my rather brutal edit of your question, sorry.
Comment: I apologize for the inconvenience.
Comment: Try restarting the adb server on your pc with sudo.
Comment: I did fix the problem using @hoomi 's answer!
Answer: The reason is that when you connect the USB device it shows a popup asking if you want to allow your pc access the device. You have to accept that manually from the device.
Something like this
http://www.gihosoft.com/android-recovery/img/allow-usb-debugging.png
Comment: I wish I would have looked at this a bit before my research because you were totally correct! I found this through many links, and your answer would have lead me much quicker. Thank you!
Comment: Now, to begin my long journey of porting this ROM. v.v
Comment: Can you make this as your answer? :)
Comment: Done! I hope that helps your reputation go up! I'm unsure who marked it down.


Does anybody know how should I use animatedline in order to draw me an orbit immediately?

Question: This is the main code
%%%%%%%%%%%% Valori pentru Rcsc

%%%%Pozitiile si vitezele pe cele 3 axe

y0(1,1)=   743322.3616  ;
y0(2,1)=   -6346021.219 ;
y0(3,1)=     -3394131.349 ;
y0(4,1)=     5142.38067;
y0(5,1)=   4487.44895   ;
y0(6,1)=     -7264.00872;
%%%% Timpul

tspan=[0 :864];

%%%% Masa(kg) si aria suprafetei satelitului (m^2)

m =    217 ;         %320;
A =   1.2;             %8;

%%%% Metoda Runge-Kutta de ordin 4

h=1;
y = zeros(6, tspan(end)/h);
y(:,1) = y0;

for i=1:(tspan(end)/h)
    H=sqrt(y(1,i)^2+y(2,i)^2+y(3,i)^2);
    k_1 = proiectia(tspan(i), y(:,i), H, m, A, y(4:6, i));
    k1=double(k_1);
    k_2 = proiectia(tspan(i)+0.5*h, y(:,i)+0.5*h*k_1, H, m, A, y(4:6, i));
    k2=double(k_2);
    k_3 = proiectia((tspan(i)+0.5*h), (y(:,i)+0.5*h*k_2), H, m, A, y(4:6, i));
    k3=double(k_3);
    k_4 = proiectia((tspan(i)+h),(y(:,i)+k_3*h), H, m, A, y(4:6, i));
    k4=double(k_4);

    y(:,i+1) = double(y(:,i) + (1/6)*(k1+2*k2+2*k3+k4)*h);

end

%%% Distanta satelitului
Rcsc = ((y(1,:).^2 + y(2,:).^2 + y(3,:).^2).^0.5);
n=50;
%plot(tspan,Rcsc)
 %% Textured 3D Earth example
%
% Ryan Gray
% 8 Sep 2004
% Revised 9 March 2006, 31 Jan 2006, 16 Oct 2013

%% Options

space_color = 'k';
npanels = 180;   % Number of globe panels around the equator deg/panel = 360/npanels
alpha   = 1; % globe transparency level, 1 = opaque, through 0 = invisible
GMST0 = []; % Don't set up rotatable globe (ECEF)
%GMST0 = 4.89496121282306; % Set up a rotatable globe at J2000.0

% Earth texture image
% Anything imread() will handle, but needs to be a 2:1 unprojected globe
% image.

image_file = 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Land_ocean_ice_2048.jpg/1024px-Land_ocean_ice_2048.jpg';

% Mean spherical earth

erad    = 6371008.7714; % equatorial radius (meters)
prad    = 6371008.7714; % polar radius (meters)
erot    = 7.2921158553e-5; % earth rotation rate (radians/sec)

%% Create figure

figure('Color', space_color);

hold on;
 orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow

% Turn off the normal axes

set(gca, 'NextPlot','add', 'Visible','off');

axis equal;
axis auto;

% Set initial view

view(0,30);

axis vis3d;

%% Create wireframe globe

% Create a 3D meshgrid of the sphere points using the ellipsoid function

[x, y, z] = ellipsoid(0, 0, 0, erad, erad, prad, npanels);

globe = surf(x, y, -z, 'FaceColor', 'none', 'EdgeColor', 0.5*[1 1 1]);

%% Texturemap the globe

% Load Earth image for texture map

cdata = imread(image_file);

% Set image as color data (cdata) property, and set face color to indicate
% a texturemap, which Matlab expects to be in cdata. Turn off the mesh edges.

set(globe, 'FaceColor', 'texturemap', 'CData', cdata, 'FaceAlpha', alpha, 'EdgeColor', 'none');

What I wanna do is that when I run the script a figure with the Earth should appear, and while the positions are being caluclated by the runge kutta algorithm it should upload the orbit in real time. But now the figure appears only after the Rk algorithm is being calculated till the end of tspan and the orbit from the figure is already uploaded without intermediate points. What should I do? I've seen on github that others use animatedline and drawnow.
I was thinking about
 orbit=animatedline;

    addpoints(orbit,y(1,:),y(2,:),y(3,:));
    drawnow
    end

But where should I put this line exactly?  if I put it in the rk loop it doesn't work and if I put it
% Create figure
figure('Color', space_color);
%%
orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow

it first displays a figure with the orbit but not by intermediate points and then a different figure with the Earth ,while the orbit and the Earth should be in the same figure.
Comment: Why can't you plot within your Runge-Kutta loop, using the normal `plot` function (and `drawnow`)?
Comment: Hi, I've done that and this is the result: https://ibb.co/niKJ9m  The  orbit is well described but it keeps drawing from 0 to where the point(x,y,z) is .After all the values are being represented, the line from 0 dissapears and it only remains the curved line(the orbit). Do you have any ideea why does it plot that line from 0 while is on the Runge Kutta loop?
Answer: You are using animatedline in a wrong way.
The line:
orbit = animatedline;

should be placed before the loop that calculates the points, and the lines:
addpoints(orbit,y(1,i),y(2,i),y(3,i));
drawnow

should be placed within it, to add one (or several) points to the line on each iteration. But, a better approach, would be to first calculate all the orbit and then use a loop for the animation. This way you have more control over the rate of the animation. Here is a small example using your case:
orbit = animatedline;
for k = 1:size(y,2)
    addpoints(orbit,y(1,k),y(2,k),y(3,k));
    drawnow
end

Alternative option
Don't use animated line just keep updating the data in the plot. Here is a simple workout for this:
% create a sphere with earth map on it:
set(gcf,'Color','k')
earth = imread('earth.jpg');
[X,Y,Z] = sphere(50);
warp(-X,Y,-Z,earth)
axis off
view(-46,17)

% set an animation of a simple orbit:
Nframes = 100; % number of steps in the orbit
% calculation of the orbit:
orb = linspace(-pi,pi,Nframes);
x = cos(orb).*1.5;
y = sin(orb);
hold on
% plot the whole orbit invisible, just for setting the axes limits:
tmp = plot(x,y,'Color','none');
p = plot(x(1),y(1),'LineWidth',3,'Color','m'); % plot the first step
hold off
for k = 1:numel(orb)
    p.XData = x(1:k); % update the data of the plot
    p.YData = y(1:k);
    pause(0.05) % delay
end

The result:


How to free up a rusty trombone slide?

Question: I just bought a crap old trombone for $50. It has a few dings, but sounds fine. The problem is that the slide is slightly rusty (little fleck marks on the inner slide, I can't see inside the outer slide), and so it doesn't move very freely.
Is there any way to clean something like that up? I've had a bit of a go at it with a trumpet snake, but I think the bristle just dodge the rust flecks, and don't do much. My only other plan is to lube it up ridiculously, and then just move it repeatedly until the rust wears off, but I don't know if that's even viable. Any ideas?
Comment: Is this for real?! Google "rusty trombone" and then add the trumpet snake and lube... this question's suddenly way off-topic!
Comment: There's some good info on general slide maintenance here: http://www.edwards-instruments.com/trombone/maintenance/slide_care.php.  That doesn't cover repair (rust removal) though, and I'd be cautious to recommend anything since some solutions can take the lacquer off / damage the instrument further.
Comment: HAHAHA!! That's hilarious. I didn't know about that before, I promise. This question is real, and should be taken literally! :D
Comment: @JohnLBevan: there's lacquer on the inside of the slide??
Comment: The inside of the slide is not laquered, but the warning to "be careful" is worth heeding so you don't mess up the outside of your instrument.
Answer: If it sounds OK and the instrument seems in otherwise good shape, it MAY be worth reconditioning.
The first thing to try is to grab a real trombone snake; the bore of a trombone is a bit wider than most of a trumpet, and you want a brush that's wider than that bore in order to make a dent on any oxidation build-up in the slide. Follow these instructions: http://www.brassstages.com/acrobat/tromboneslidecare.pdf. Since you know there's oxidation in the slide, you may use vinegar instead of water as the cleanser for the inside of the slide tube. If there's any visible oxidation on the chrome-plated slide that doesn't come off with some vigorous rubbing with a soft cloth, the chrome has given way and the brass underneath is pitted; you'll need to get the slide tubes re-chromed to regain that smooth action (and it's unlikely to be worth the cost unless you really like the sound of the horn). Also, when lubing a trombone slide, you typically use something thicker than trumpet valve oil; usually the stuff's somewhere between valve oil and tuning slide grease. The thicker it is, the smoother it'll be, but the more resistance to movement it will have. There's a happy medium to be found; try Vaseline as a cheap starting point, mix in a little valve oil to thin it, and if you can't find a consistency you like, hit your local music store for the real stuff.
If that doesn't smooth out the slide, the outer slide tube is probably severely pitted. If that's the case the entire horn's probably garbage, but to save your $50 you can try polishing the bore. Head to the hardware store and pick up some brass polish, some rags and a few Scotch-Brite pads (not the sponges; we're talking the thin green pads). Now, you'll make several "bore swabs"; cut a few pieces of the rag and tie a string around em, to create a wad that will fit tightly into the bore. Make that string long so you can fish it all the way through, and you might want to put a small weight on it. Then, put a liberal amount of brass polish on the wad of cloth and pull it through the slide, going both ways. Repeat until you can't feel the swab catching on any part of the tube. If that takes longer than you're willing to wait, you can fashion another swab using more of the cloth with an outer layer of the Scotch-Brite pads. This swab will really scour the inside of the pipe, so I would not use it too much or you could mess up the interior diameter of the bore by enough to cause air leakage (ruining the instrument).
Once the inside of the bore feels smooth when you run the swab through it, rinse and swab it out well, then apply a liberal amount of slide grease to a clean swab and pull it through to make sure the inner tube surface has a good protective layer of grease. Finally, you'll want to get all the gunk out of the water key.
If you can't seem to get it smoothed out and you think you're wearing it out, you can take it to a repair ship and have it professionally reconditioned. Be aware that doing this will likely cost much more than the instrument did and may cost more than it is worth in good working order.

How to free up a rusty trombone slide?


open() method doesn't open specified .txt file

Question: I am made a file where i can reference functions and i thought that it would be fun to make a program to add text to the file, and when i try to open the file, it doesn't show any errors, but when i go and check the file there's nothing there.
My code:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
    vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
    if vseb_funk == "končano":
          break
    else:
        funk += "\n    "+vseb_funk

mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)

Don't pay attention to the variable names and strings, as that's not important.
Also I am using replit if that's important.
I have no idea why it doesn't work.
i have tried mark = open("test.txt", "w") but same story.
Answer: you need to add this line to your code
mark.close()

or what you can do I replace this part of the code
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)

with this code:
with open("test.txt", "a") as mark:
   mark.write("\n" + ime_funk + "\n" + funk)

Answer: A file write in python does not happen untill you call file.flush(). This is usually called automatically when you close the file but in your example you are never closing the file. Try:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
    vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
    if vseb_funk == "končano":
          break
    else:
        funk += "\n    "+vseb_funk

mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
mark.close()

or even better try using the with statement:
with open("test.txt", "a") as mark:
    mark.write("\n" + ime_funk + "\n" + funk)

this way close() is called automatically


What is the music theoretical basis for this chord transition?

Question: I've got a song on the piano, which I've been learning for years now and for which I just recently decided to actually dive into a chord analysis.
Early on in the piece, there's this climactic build of chords that transitions into the next portion of the song and goes: D-D-?-Dm7-Dm7-Gm-(start of next portion with a D)
The problem is that I just can't figure out the question mark chord. It contains C#, E, F, and A, making it kinda like a Dsus2 over A except without the D...
That seems odd, so I could use some help identifying what the chord is, and what sense it makes from a music theory perspective!
Image of the phrase for added context:
Comment: Music theory is talking about musical practices. The title makes it sound like there was such a thing as _THE_ music theoretical basis for the chords, as if there was one Correct Way of talking about it or looking at it. :) And of course, it would follow that other ways must be incorrect or wrong. I disagree with this implication. There are many ways of thinking about it and talking about it.
Comment: piggybacking off of @piiperiReinstateMonica - music theory is based off of music, not the other way around. While you can certainly use theory as a creative jumping off point, the only actual rule that music has to follow is that people like it or find it interesting.
Comment: Related: https://www.youtube.com/watch?v=eXqNyWehVEQ
Answer: Your chord is a combination of an A/C# and a Dm chord. I wouldn't give it a name. The composer wants the whole passage to sound like it continues to hammer out Dm chords, but they also want the chromatic movement of the descending bass. Hence both the F-A of the Dm and the C#-E of the A. You can call this a "poly-chord", or consider both the C# and the E as passing tones between the Dm and the Dm/C chords.
Answer: It's Dm A/C# Dm7/C with the F5 held during the change through A/C#.
With C# and E in the outer voices and an A included it has all the tones and movement of Dm: i V6, and I think that progression sounds out pretty clearly.
You could call the F5 a non-chord tone, perhaps a pedal or a sort of suspension.
To make the point about Dm: i V6 cleared just play the F5 as G5 and the progression will become a clear Dm: i V6/5. To play F5 or G5 in an inner voice doesn't really obscure the main harmony that much.
Another way to look at it is a progression simply of Dm Dm7/C where the non-chord tones are the C# and E which would be called passing tones.
Comment: @MitchellFaas, not the scale, the _key_. Scale and key are not synonymous.
Comment: Thanks for the response! Could you elaborate a little on what the notation `Dm: i V6` means? I haven't seen it before.
Comment: That's Roman numeral analysis, Roman numerals assigned to each of the scale degrees which are the roots of chords. https://en.wikipedia.org/wiki/Roman_numeral_analysis
Comment: I see, so the "Dm: ..." just indicates that you're talking about the Dm scale here? (This was my confusion ^^)
Answer: It's an A maj aug 5.
https://en.wikipedia.org/wiki/Minor_sixth
That part is just bouncing between a Dm and A maj. The F is just carrying over to the the Dm7.
Comment: By looking only at the notes one could call it an A+. Except that it has both E and F, and F is not an aug 5, it's a minor 6. But that ignores the harmonic function. The whole function of that C# is to go to C natural, as a chromatic bass line. Calling it an A chord of any stripe -- and therefore having somesort of dominant function -- misses that.


is there an equivalent to the COUNTIFS function of Excel in Stata?

Question: I have data about investments, organized by name of investor:
(firmname), company(companyname) and year of investment (roundyear).
How can I create a variable which count number of observations for each
investor (firmname) which happened in the 10 years prior to current investment?
I tried
bys firmname: egen exprience= count (roundyear < roundyear[_n]  & roundyear> roundyear[_n]-10 )

but it does not work.
I know how to do it in Excel but since the size of data is very big, it takes plenty of
time to do it.
The data look like this:
 firmname, companyname, year
 f1, c2, 1990
 f1, c2, 1999
 f1, c3, 1991
 f1, c3, 1992
 f1, c3, 1993
 f1, c4, 1990
 f1, c4, 1993
 f1, c4, 1994

Answer: The documentation for egen warns you not to make references to _n.
See Stata - Moving Finite Product for the principle that the sum for the last so many time units is the difference between two cumulative sums.
However, I suspect that you should go straight to
http://www.stata-journal.com/sjpdf.html?articlenum=pr0033
to see some technique with detailed examples.
Comment: Thank you, reading the document helped me to solve the problem, by the way thank you as well for the lesson about names.


Is there a relationship between the response and predictors?

Question: I have been reading Introduction to statistical learning and I was going through Multiple Linear Regression. This is the topic that Im reading

 As i was further reading I encountered an equation that Im not able to understand. Below is that equation

It further say that,

Please try to explain explain the above mentioned problem as simple as possible.
Answer: This method is called comparing the full and reduced model. Let's say for example, we have four variables and we want to check out if the fourth variable is significant or not. The NULL hypothesis is $\beta_4=0$. What you're doing is comparing the FULL model $\beta_1+\beta_2+\beta_3+\beta_4$ to a REDUCED model it.i.e.$\beta_1+\beta_2+\beta_3$.
If there is a significant difference between the two then clearly $\beta_4$ added something over and above the REDUCED model. In which case we reject the null hypothesis and conclude $\beta_4\neq0$. Also, instead of just testing $\beta_4$, i can test $\beta_3$ AND $\beta_4$ at the same time by comparing the FULL model of $\beta_1+\beta_2+\beta_3+\beta_4$ to a REDUCED model of $\beta_1+\beta_2$, and so on. That's why the authors are indexing it as $q$ and $p$ because either $q$ or $p$ can go up to any length.
The F test basically takes the residual sums of squares of the reduced model and subtracts the the residual sums of squares of the full model, and then compares it (through division) to the residual sums of squares of the full model. (after appropriately dividing each of them by the appropriate degrees of freedom). Remember, residual sums of squares is a measure of how well/unwell the model fit, because the residual is what's left over after you subtract your predicted value from your observed value.
Comment: There is nothing clear about $\beta_4$ from a non statistically significant result. And $p>\alpha$ is not the same as $\beta_4=0$. In fact, based on what we know of the world, $\beta_4\neq0$, since most variables are always related, even if trivially.
Comment: fair enough, good point, I have concluded the null hypothesis which i shouldn't have. What i should have said was that if the two models are significantly different from each other then $\beta_4$ IS adding something significant from the reduced model. Thanks for the tip I'll edit the answer.


How can I improve the accuracy of my logistic regression code, which tests the accuracy using the 10-fold cross-validation technique?

Question: How can I improve the accuracy of my logistic regression code, which tests the accuracy using the 10-fold cross-validation technique? I have implemented this code using glmfit and glmval. The desired accuracy is somewhat higher and it requires the parameters to be found using maximum likelihood estimator. Also, when I run this code in MATLAB, I get the following error

Warning: X is ill conditioned, or the model is overparameterized, and some coefficients are not identifiable. You should use caution in making predictions. In glmfit at 245 In LR at 8

The code is:
function LR( X,y)
y(y==-1)=0;
X=[ones(size(X,1),1) X];
disp(size(X,2));
indices = crossvalind('Kfold',y,10);
for i = 1:10
    test = (indices == i); train = ~test;
    b = glmfit(X(train,:),y(train),'binomial','logit');
    y_hat= glmval(b,X(test,:),'logit');
    y_true=y(test,:);
    error(i)=mean(abs(y_true-y_hat));
end
accuracy=(1-error)*100;
fprintf('accuracy= %f +- %f\n',mean(accuracy),std(accuracy));
end

Comment: I am voting to leave this open. The question contains code, but isn't really about code.
Answer: The MATLAB error tells you what is going on - at least possibly - you have either too many variables or some that are creating  partial or complete separation. So, you need to remove some variables.
How to improve the fit? Sorry, but without a lot more information, this is going to be guesswork but my guess is that the only way to improve your fit will be go get more data or better variables or a better model.


Can not display contents of Arraylist n JTable

Question: I can't figure this out (have been trying to fix this for the past 2-3 hours).
I would like to display the contents of an arraylist, but they do not appear in the table and also there are NO errors, they simply do not appear. Here is my code:
private class examinations{
private int id;
private int candidate_id;
private String date;
private String exam;
private String examNumber;

public examinations(int id, int student_id, String date, String exam, String examNumber) {
    this.id = id;
    this.student_id = student_id;
    this.date = date;
    this.exam= exam;
    this.examNumber= examNumber;
}

public ArrayList ListExams(){
    ArrayList<exams> list = new ArrayList<exams>();

    return list;
}

public void addRollToTable(){
    DefaultTableModel model = (DefaultTableModel)tableExams.getModel();
    ArrayList<exams> list = ListExams();
    Object rowData[] = new Object[5];
    for(int i = 0; i < list.size(); i++) {
        rowData[0] = list.get(i).id;
        rowData[1] = list.get(i).student_id;
        rowData[2] = list.get(i).date;
        rowData[3] = list.get(i).exam;
        rowData[4] = list.get(i).examNumber;

        model.addRow(rowData);
    }
}

}
I tested this loop and the variables coming out of the other list are there, so a System.out.println(list.get(i).exam); will display the correct thing i typed. However the table will NOT display whatever I add in the rowData. It gives, again, no errors. Let me show you the DefaultTableModel code. This code is in the private void initComponents() of my class...
    Object [][] data = {};
    String[] columnNames = {"Id", "Student_Id", "Date", "Exam",
    "Exam_number"};
    tableExams= new javax.swing.JTable();

    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    tableExams.setModel(model);
    tableExams.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
    jScrollPane4.setViewportView(tableExams);

I've been reading this: DefaultTableModel Class Overview But I still can't find where I am going wrong... Could anyone give a tip?
Answer: First of all learn and use Java naming conventions:

Classs names SHOULD start with an upper case character. Can you show me a class in the JDK that does not?
Method should should NOT start with an upper case character. Again, can you show me a method in the JDK the does?

Learn by example and don't make up your own conventions.

so a System.out.println(list.get(i).exam); will display the correct thing i typed

I don't know how this is possible. Your code is as follows:
a) First, you retrieve the ArrayList from the "listExams() method.
ArrayList<exams> list = ListExams();

b) But in the "listExams()" method all you do is create an empty ArrayList.
ArrayList<exams> list = new ArrayList<exams>();

So you are missing the logic that actually adds data to the ArrayList.
Based on the logic provided, you don't even need the ArrayList. Just take the data from the Examination class and add it to the TableModel:
Object rowData[] = new Object[5];
rowData[0] = id;
rowData[1] = student_id;
rowData[2] = date;
rowData[3] = exam;
rowData[4] = examNumber;
model.addRow(rowData);

For a different solution you could create a custom TableModel to hold your "Examination" objects. Check out Row Table Model for a step-by-step example of how this can be done.
Comment: The problem isn't really in the fact that i am creating an empty array, because even when I put object in there, and as I said, they all return a result when I do the print test. The issue is they do not show on the table. I created a custom table model, still, they don't show, but when I do `System.out.println(model.getRowCount())`, it prints "1" (butthe table doesn't display the 1 row i added). There are no errors, just like before.
Comment: Post a proper [mcve] that demonstrates the problem.
Comment: @SkyMage You were asked to post your example demonstrating the problem. I can't possibly guess what you are doing wrong. If your method has a reference to the TableModel of the visible JTable, then the addRow(...) method will work.
Comment: Ok so let me just wrap it all up - The problem is that whenever I want to add a row in this table, but when passing the values from ANOTHER JFrame, it does not display the new record.
Here: [link] (https://image.prntscr.com/image/HXHLZg84SbCJYKk_0HSAlA.png)
Comment: I guess you really don't want help. An image tells us nothing. Without a proper [mcve] you are on your own. We don't have time to guess what you are doing. So what you need is a simple JFrame with a JTable  and a button. When you click the button you add a row of hard coded data to the table. Learn how this basic process works and then apply the knowledge to your real application. This will take 20-30 lines of code to test so it will be easy for us to help is you still have a problem.
Answer: OK, I solved it, even though this was just a work around, I'd accept it.
All I did was use this.setVisible(false) and then entered the information in the other JFrame. Clicking add, i make an object of the first JFrame, passed all the variables, used this.dispose() and then called .setVisible(true) to return to the table, which displayed the information. LOL that was a long testing and re-writing of code to actually realize it was something that small...
I am sorry, I did not know where the actual problem was, and yeah thanks a lot for that simple suggestion there camickr. I tried it in the same JFrame and it worked, then I tried it between 2 JFrames and I realized the JFrame with the table DID NOT update the table. repaint() also didn't work. You quite literally helped me out with that small tip, which is all i needed. THANKS!!!!!!
Comment: (1-) No, this is NOT a solution. A table will automatically repaint itself when the data in the TableModel is changed. You still have some fundamental design problem. Also, you should NOT be using a second JFrame. Application should only have a single JFrame. For child windows you should be using a JDialog to prompt for Exam information. `and yeah thanks a lot for that simple suggestion there camickr.` - then that is the answer that should be "accepted", or at least a simple "thank yout" to acknowledge the time spent helping.


wpf dynamic window

Question: I am trying to create a window to act as a switch board for testing an application I'm working on, and having two problems doing so.
The first problem is trying to set the size & margin of buttons that need to be added to a stack panel dynamically. In XAML, the properties look like this:
<StackPanel Name="_mainStackPanel" >
    <Button Height="Auto" Width="Auto" Margin="10,10,10,5" >Do Something</Button>
</StackPanel>

The second problem is trickier. I want the switch board window to have a status bar with an exposed property, like so:
<StatusBar BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Left">
    <TextBlock Name="_statusBar" Foreground="Black" TextWrapping="Wrap">blah</TextBlock>
</StatusBar>

public string Status {
        get { return _statusBar.Text; }
        set { _statusBar.Text = value; }
}

In a test case I'm working through, I just want each button to display it's text content in the status bar when it's clicked. Invoking the click gets a NullReferenceException...
I'm using the command pattern to tell the button what to do when it's clicked. Here's the code in the switch board window where commands are turned into buttons:
private void _addButtons() {
        foreach (var cmd in _commands)
        {
            var b = new Button
                    {
                        Content = cmd.DisplayText,
                        // height = "Auto" double.NaN ?
                        // width = "Auto"
                        // margin = "10,10,10,5
                    };
            var command = cmd;
            b.Click += ((sender, args) => command.Execute());
            _mainStackPanel.Children.Add(b);
        }
    }

And here is the setup in my "test" (I am not asserting anything, just firing up the gui and seeing if it works):
[TestFixture]
public class SwitchBoardTests
{
    private SwitchBoardView _switchboard;
    private Application _app;

    [SetUp]
    public void SetUp() {
        var commands = new List<IDisplayableCommand> {
                                                         new StatusCommand("Hello...", _switchboard),
                                                         new StatusCommand("Good Bye...", _switchboard),
                                                     };
        _switchboard = new SwitchBoardView(commands);
    }

    class StatusCommand : DisplayCommand
    {
        private readonly SwitchBoardView _view;
        public StatusCommand(string message, SwitchBoardView view) : base(message) {
            _view = view;
        }
        public override void Execute() { _view.Status = DisplayText; }
    }

    [Test]
    public void Display() {
        _app = new Application();
        _app.Run(_switchboard);
        //_switchboard.Show();
    }

}

I am just learning WPF, so any best practices that might come out of solving these two issues would be most welcome!
Cheers,
Berryl
Answer: For your dynamic adding of buttons, you could make an ItemsControl instead of a StackPanel and bind the ItemsSource to your list of things to create buttons for (ObservableCollection). You'll also need a DataTemplate to define the ItemsTemplate for your list so that each item appears as a button with the margin and command attribute you want.
Here is a good example of binding an ItemsControl to a template
WPF: Example of ItemsControl bound to an ObservableCollection

wpf dynamic window


Example of two spaces with same cohomology ring but different homotopy group

Question: I want to find example of two spaces with same cohomology ring but different homotopy group.
I know spaces with same homotopy groups but different homology groups and vice versa. But currently I have not found example of spaces with same cohomology ring but different homotopy group. Thanks!
Comment: Any homology sphere and the actual sphere.
Comment: @MikeMiller  I am sorry, could you explain more about that? Thanks.
Comment: @MikeMiller I get your point, but I still can not find a homology sphere...... Could you please give an example?
Answer: Mike's example in the comments is fine, but here is a simply connected example.
Let $X$ denote the homogeneous space $U(3)/U(1)^2$ where $U(1)^2$ sits in $U(3)$ as matrices of the form $\operatorname{diag}(z,w,1)$ and let $Y$ denote $S^2\times S^5$.  I claim that the cohomology rings of $X$ and $Y$ are isomorphic, but that $\pi_4$ distinguishes them.
To compute the cohomology ring of $X$, note that there is an intermediate subgroup $U(1)^2\subseteq U(2)\subseteq U(3)$ giving rise to a homogeneous fibration $$U(2)/U(1)^2\rightarrow U(3)/U(1)^2\rightarrow U(3)/U(2).$$
Using the fact that $U(2)/U(1)^2 \cong S^2$ and $U(3)/U(2) = S^5$, we see that $U(3)/U(1)^2$ has the structure of an $S^2$ bundle over $S^5$.  From the Gysin sequence, this is easily enough to show that that cohomology ring of $U(3)/U(1)^2$ is isomorphic to that of $S^2\times S^5$.
Now, from the fibration $U(1)^2\rightarrow U(3)\rightarrow X$, we get an LES in homotopy groups.  Since $U(1) = S^1$ has vanishing higher homotopy groups, this implies $\pi_k(X)\cong \pi_k(U(3))$ for any $k\geq 3$.  Further, since $U(3)$ is diffeomorphic (but not Lie isomorphic) to $SU(3)\times S^1$, $\pi_k(X)\cong \pi_k(SU(3))$.  Then, according to this paper by Mimura and Toda, $\pi_4(SU(3)) = 0$, so $\pi_4(X) = 0$.
On the other hand, $\pi_4(Y)\cong \pi_4(S^2)\times \pi_4(S^5)\cong \mathbb{Z}_2\times \{0\}$.
Comment: An analogous argument shows $Sp(3)/Sp(1)^2$ has cohomology ring isomorphic to that of $S^4\times S^{11}$.  In his thesis, Kamerich shows that $\pi_{10}$ distinguishes these spaces.  Also, I'm curious if there are lower dimensional examples of closed simply connected manifolds with isomorphic cohomology rings and different higher homotopy groups.


How do I combine arbitrarily-ranked lists?

Question: Look, I know the basic answer is either "you don't" or "you need much more information". I strongly suspect that there isn't a fully rigorous way to do this. That said, I am still hopeful there is a reasonably good way, because my specific use case doesn't need full rigor. On to the actual question:
I have about a thousand items, some of which are "bad". There are three orthogonal measures of badness, and I can get a ranked list of items by each measure of badness. I need a filter that ranks the overall baddest items, based on the three individual rankings. I can access the metric values, but they are orthogonal to each other and not readily normalizable.
The good news is that a combined list would be interpreted by humans. It does not need perfect rigor. It does need to provide reasonable confidence to its users, so frequent "surprising" results are bad.

Strict ordering is not critical, though the order should not be chaotic.
It's fine if small changes swap #3 and #4; it is not fine if small changes swap #3 and #600.
An item that is high badness in one list should be high overall.
For example, if the starting lists are:
<code>   1. Ape            1. Fish           1. Fish
   2. Bat            2. Heron          2. Heron
   3. Cat            3. Cat            3. Cat
   4. Gorilla        4. Lynx           4. Mouse
     ...              ...               ...
 500. Fish         500. Ape          500. Ape
</code>
Then the ending list should probably have Fish as #1, Ape, Heron, and Cat next (no opinion on which order is correct), then Bat. Any algorithm which generates a similar answer is good.

Finally, if there truly is no generalizable solution, that's also useful to know. I remain hopeful that isn't the case.
Comment: your comment that "*if the ranks for a left-handed corkscrew are 1,601,601; the average is 401, when it should come out somewhere near the top*" implies you know/understand some things that are *not at all obvious* from your post. *We* cannot supply - or likely even correctly guess at - this knowledge.
Comment: To elaborate on what @Glen_b has written, it will probably work to have some kind of function of the ranks that does what you want to do. This will need to be designed in such a way that it achieves what you want, for which reason we need to understand what you want (it may well be that it is enough if you yourself understand it properly, as this is at least half the work done). Just computing the average was my fist guess, but you could of course also take the best rank, or compute a weighted average with the best rank having double weight.
Comment: What do you mean by "orthogonal"? What exactly do you mean by "not readily normalizable"? What's wrong with just averaging the three values (if for some reason this doesn't work with the metric values, you could average the ranks)?
Comment: The values are, roughly, a count of one kind of event, a duration, and a unitless numerical measure. the unitless measure could normalize to a scale from 1-10 (or whatever), but the difference between "2" and "3" would not be the same a "6" and "7". Averaging the ranks might work, but is probably not ideal: if the ranks for a left-handed corkscrew are 1,601,601; the average is 401, when it should come out somewhere near the top.
Comment: I imagine you can at least explain some sense of what you'd seek instead in more depth.
Comment: @Glen_b That's a fair point, and it may be that this is too poorly formed to be answerable. Let me take another crack at describing what success would look like.
Comment: What do you mean by generalizable?
Comment: @fectin there's a whole family of power means $\overline{{x}^p}^{1/p}$, which include as special or limiting cases harmonic means and geometric means. For example, the harmonic mean of (1,601,601) is about 3 while the geometric mean is about 70. At the same time the harmonic mean of (1,1,601) is about 1.5 and the geometric mean is about 8.4. Beyond power means there's other generalized means, $t^{-1}\left(\,\overline{t(x)}\,\right)$, for some strictly monotonic $t$. Perhaps there's a power mean or some other generalized mean that suits you?
Comment: Specifically perhaps a power mean with $p<-2$ (say) might be close to what you seek? $p$ at $-2$ would place Bat a bit better than Cat, but $-3$ places it lower. Alternatively, something based on the highest rank (i.e. the minimum of the ranks), with ties broken by the next best rank for each item.
Answer: From your example it seems that you want to weight the top ranks heavily. 500-1-1 is ranked higher in your view than 3-3-3, and even 1-500-500 should still be rated high.
What about this: Rank accoording to top rank (i.e., anything that has a rank 1 comes first, then anything that has rank 2 but not 1 and so on. Among those having a rank 1, two rank 1 are better than one, and if there are still ties not resolved in this way, sort according to the next best rank. This will give Fish-Ape-Heron-Bat-Cat in your example. I do realise you want Cat above Bat, but it's really hard to arrange this if also you want Ape high up based on a single rank 1; unless you treat rank 1 essentially different from the later ranks.
Comment: This is a reasonable answer. I'm going to leave it unaccepted for a while in hopes that a better answer appears, but this may well be the best available. Thanks for playing along with my admittedly vague constraints.


How do you show that $\lim_{(x,y)\to(0,0)} \frac{xy}{x^2+y}$ doesn't exist?

Question: I have to prove that this limit doesn't exist.
$$\lim_{(x,y)\to(0,0)} \frac{xy}{x^2+y}$$
I tried this parametrization: $\begin{cases} x = t \\ y = mt^\alpha\end{cases}$
obtaining as result that the previous limit in this specific case would be equivalent to
$$\lim_{t\to0} \frac{mt}{t^{2-\alpha}+m}$$
which would be null for each value of $\alpha,m$.
Using a polar coordinate system doesn't seem effective too.
How do I prove that this doesn't exist?
Comment: **Hint:** note that along the path $y=-x^2$,  the function does not exist at all. Along paths close to that, bad things should also happen.
Comment: Damn you're right, how didn't I see that?
Answer: Let $y=-x^2+x^4$.  Then,
$$\frac{xy}{x^2+y}=-x^{-1}+x$$
What happens now?
Comment: @Salahamam_Fatima Yes, I have edited before you sent the comment.
Comment: that's a nice $\pm \infty$
Answer: As an alternative to the solution by Mark Viola, note that

for $x=t \quad y=t \quad t\to 0 \implies \frac{xy}{x^2+y}=\frac{t^2}{t^2+t}=\frac{t}{t+1}\to0$
for $x=t \quad y=t^3-t^2 \quad t\to 0 \implies \frac{xy}{x^2+y}=\frac{t^4-t^3}{t^2+t^3-t^2}=\frac{t^4-t^3}{t^3}=t-1\to -1$
Comment: @Bafforasta the first one is trivial (you can choose many of them, as also x=0 or y=0) for the second the trick is to try with a path for which the principal term of denominator cancel out (that's also the strategy used by Mark); in this case x^2+y=0 leads to $x=t$ and $y=-t^2$; then we add a higher order term to $y$ in such way that the denominator is not exactly =0, that is $y=-t^2+t^3$. This strategy often leads to different limits.
Comment: A question from a complete beginner: how did you select exactly this path among all the possible ones? Is there some way to spot it?
Answer: If $y=\frac {x^2}{x-1} $, the limit is
$$\lim_{(x,y)\to (0,0)}\frac {xy}{xy}=1$$
but if $x=\sqrt {y} $, it gives
$$\lim_{(x,y)\to (0,0^+)}\frac {\sqrt {y}}{2}=0.$$
So, the limit cannot exist.
Answer: Let $$m=\frac{xy}{x^2+y}$$
Then $$m(x^2+y)=xy$$ so $$y=\frac{mx^2}{x-m}$$
For any $m$ we have an equation of a curve, which meets $(0,0)$ and on which the expression $\frac{xy}{x^2+y}$ is constant, equal $m$. This way there are infinitely many paths leading to the origin, each of which results in a different limit $m$.
Hence the limit does not exist.


How to retrieve data from database using webservices (JAX - RS) in eclipse using Java

Question: I have done inserting a record into database but I don't know how to retrieve it.
My code is:
Account.java:
package com.fetch;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;

public class Account implements Serializable
{
  @Id
  private long id;

  @Column(name="NAME")
  private String name;

  public Account()
  {

  }

  public Account(int id, String name)
  {
     this.id = id;
     this.name = name;
  }

  public long getId()
  {
     return id;
  }

  public void setId(long id)
  {
     this.id = id;
  }

  public String getName()
  {
     return name;
  }

  public void setName(String name)
  {
     this.name = name;
  }
}

MyAccount.java:
package com.fetch;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

@WebService()
@Entity
@Table(name = "CUSTOMER")
@Path("/user")
@NamedQuery(name="loginquery", query="select ID,NAME from CUSTOMER")
public class MyAccount
{
   private Account ac;
   public MyAccount()
   {
     // TODO Auto-generated constructor stub
     ac = new Account();
   }

   @POST
   @Path("/fetch")
   @WebMethod(operationName = "insert")
   public String insert(@FormParam("name") String name)
   {
      try
      {
         Class.forName("com.mysql.jdbc.Driver");
         Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");

         String query = "insert into CUSTOMER"+"(NAME) VALUES"+"(?)";
     PreparedStatement st = con.prepareStatement(query);
         st.setString(1,name);
     st.executeUpdate();
      }
      catch (Exception e)
      {
         System.out.println(e.getMessage());
      }
      return"Record inserted successfully";
   }
  public Account getAc()
  {
     return ac;
  }
  public void setAc(Account ac)
  {
     this.ac = ac;
  }
}

insert.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert</title>

    <form action="rest/user/fetch" method="POST">

            Name : <input id="name" name="name" />

        <input type="submit" value="Add" />
            <input type="submit" value="Retrive" />
    </form>

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
   <display-name>FetchAndInsert</display-name>
   <servlet>
      <servlet-name>REST Servlet</servlet-name>
      <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
      <init-param>
         <param-name>com.sun.jersey.config.property.packages</param-name>
         <param-value>com.fetch</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>REST Servlet</servlet-name>
      <url-pattern>/rest/*</url-pattern>
   </servlet-mapping>
</web-app>

How to retrieve the data from the database when the user clicks on the retrieve button, and display all the records in another HTML form?
Please give suggestions on how to do it.
In my application, when the user clicks the retrieve button it is performing the insert operation.
But I want is, when the user clicks it should go to the another page and display the data in table from database.
Can anybody tell the mistake what I have done, and give suggestions for finding solution for it and how to display the dynamic table in other page when the user clicks the retrieve button?
Comment: Can anyone give suggestions for doing it with an example
Answer: Finally I have done it, Now I am able to perform both insertion and retriving of data from database using jersey(JAX - RS) webservices and able to display it in a html page.
Account.java:
package com.fetch;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;

public class Account implements Serializable
{
    @Id
    private long id;

    @Column(name = "NAME")
    private String name;

    public Account(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

MyAccount.java:
package com.fetch;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.Entity;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@WebService()
@Entity
@Path("/user")
public class MyAccount
{
    @POST
    @Path("/fetch")
    @WebMethod(operationName = "insert")
    public String insert(@FormParam("name") String name)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
            String query = "insert into CUSTOMER"+"(NAME) VALUES"+"(?)";

            PreparedStatement st = con.prepareStatement(query);
            st.setString(1,name);
            st.executeUpdate();
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        return"Record inserted successfully";
    }

    @GET
    @Path("/retrive")
    @Produces("text/html")
    @WebMethod(operationName = "retrive")
    public String retrive()
    {
        ResultSet rs = null;
        String details = "";
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");

            String query = "select ID,NAME from CUSTOMER";

            PreparedStatement st = con.prepareStatement(query);
            rs = st.executeQuery();

            details = "";
            details = details + "
";
            details = details + "
Id 	" +
                                    "Name 	" + "
";
            while (rs.next())
            {
                details = details + "
" + rs.getInt("ID") + "	" +
                                        "" + rs.getString("NAME") + "
";
            }
            details += "
";
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        return details;
    }
}

insert.html:
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert</title>

    <form action="rest/user/fetch" method="POST">

            Name : <input id="name" name="name" />

        <input type="submit" value="Add" />
    </form>
    <form action="rest/user/retrive" method="GET">
        <input type="submit" value="Retrive" />
    </form>

my web.xml is:
 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>FetchAndInsert</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>REST Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.fetch</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>REST Servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

Answer: Jersey doesn't provide any sort of HTML templating. You need to forward your response to a jsp page or use Ajax to fetch the data and lay it out on the page.
Comment: Can you give an example for it.By using the above example
Comment: There are many examples out there of combining jersey and jsp look at: http://blog.docuverse.com/2009/08/04/using-jsp-with-jersey-jax-rs-implementation/ if you want to use Ajax you probably should start with jquery
Comment: I can understand little bit form the given http://blog.docuverse.com/2009/08/04/using-jsp-with-jersey-jax-rs-implementation/
Can you give clear explaination for creating it using my application.
Comment: It's all pretty clear in that example you need to return a viewable in your response which directs the user to your jsp page which will have your object in the model.
Comment: There is no clear explaination in it, only some part is explained like the web.xml and about the responses, there is no code for jsp for displaying the table from database.
Comment: Oh that's a whole different question.. Look at the standard jstl tags for that.


Complex Number inqualities

Question: Although the inequalities are not defined on complex numbers. But does the inequality $x < 4 + 5i$  be said to possess any solutions ? Where $ i = \sqrt{-1}$.
Comment: maybe u can say 3+5i
Comment: all numbers with same imaginary part , but i am not sure
Comment: You can define the inequality individually to $Re(z)$ or $Im(z)$ or maybe even to $mod|z|$ but i don't think your case will make sense.If you define $x$ as a complex number. And if you define it to be real number, they have different domains.
Comment: Then what about the inequalities like x^2 + x < -3  ?  Do inequalities like these also possess solutions ?
Answer: The impossibility for $\mathbb{C}$ to be an ordered field is a general result of fields theory.

An ordered field $F$ is a field with a total order relation $\le$
  compatible with the field operations. This means that $\forall a,b,c
> \in F$ : $$ a \le b \Rightarrow a+c \le b+c $$ $$ 0\le a \,,\; 0 \le b
> \Rightarrow 0 \le ab $$

We can show that this definition is equivalent to:
There exists a subset $\mathcal{P} \subset F$ such that:

$\forall a,b \in  \mathcal{P}$ we have  $a+b \in  \mathcal{P}$ and $ab
> \in  \mathcal{P} $  (closure property)

and

$\forall a \in  A$ only one of these relations hold: $ a \in
> \mathcal{P}$, or $ a=0$ , or $-a \in  \mathcal{P}$  ( trichotomy
  property)

From this two properties we can easely see that : $1 \in \mathcal{P}$ and $\forall a \in F\,,\,a \ne 0  \Rightarrow (-a)^2=a^2 \in \mathcal{P}$, so:
a field can not be an ordered field if it contain an element $i$ such that $i^2=-1$.
Note that this does not means that we can not ghive any order on $\mathbb{C}$.  As an exeple we can define the lexicographical order:
$$
x=a+ib \le y=c+id \iff (a<c)\; \lor\; (a=c \land b\le d)
$$
whith wich we can solve inequalities as $x< 4+5i$, but this order is not compatible with the operations in $\mathbb{C}$.
Comment: Then what about inequalities like x^2 + x < -3  ?

Complex Number inqualities


$A\rightarrow B$ and $\Pi x:A.b(x)\in B$

Question: I have a question about the following two formulas (where both $A,B:\textsf{Prop}$ and $x$ is not a free variable in $B$):
$$A\rightarrow B\quad\quad\quad\Pi x:A.b(x)\in B$$
where $b(x)\in B$ is a membership type (equivalent to $\textsf{Id}(b(x),b(x),B)$ using the notation of identity type) indicating that $b(x)$ is an inhabitant of $B$. It appears to me that they are equivalent. From $\Pi x:A.b(x)\in B$, by the elimination rule of $\in$, it is easy to deduce $\Pi x:A.B$, which is in fact equivalent to $A\rightarrow B$. So we have the following:
$$(\Pi x:A.b(x)\in B)\rightarrow(A\rightarrow B)$$
But what about the other direction? Thanks in advance!
Comment: NuPRL is rather different from MLTT. The former is based on types being partial equivalence relations on a fixed semantic domain. So typing is propositional, and terms can have many types. By contrast, in MLTT, terms have essentially one intrinsic type, and the identity type is only well defined for terms known to have that given type. Just copying similar looking things from one to another won't necessarily make sense.
Comment: I think your answer makes sense. NuPRL only factors in in that $x =_T y$ in NuPRL is *not* the same thing as $Id_T(x,y)$ in Martin-löf type theory, so one can't just copy something from NuPRL and replace equality with the MLTT identity type.
Comment: You should probably say what type theory this is supposed to be. For instance, in Martin-löf type theory, it doesn't make much sense to consider the identity type to be a 'membership type', because it must already be the case that $b(x) : B$ in order for $\mathsf{Id}_B(b(x),b(x))$ to even be a well-formed type.
Comment: @DanDoel I am using Constable's Computational Type Theory, which is a variant of MLTT. That definition comes from their NuPRL, $t\in T$ is an abbreviation of $t=_Tt$ or $Id(t,t,T)$.
Comment: @EminiJask do you have a constructor for identity types like $\operatorname{refl}$ available? (the introduction rule for $\operatorname{refl}$ in the ML type theory I know is that, if $C$ is a type and $c:C$, we can judge $\operatorname{refl}_c:\operatorname{Id}(c,c,C)$)
Comment: Right, it's the same thing. Since the membership type $c\in C$ is just an abbreviation of $Id(c,c,C)$, they have the same inference rules.
Comment: @DanDoel I'm not familiar with NuPRL unfortunately, and a quick google search didn't reveal much information. does the answer I gave below still make sense in that context?
Answer: Let me expand a bit on Dan Doel's point. In Martin-Löf type theory, to make a judgement that $\operatorname{Id}(b(x),b(x),B)$ is a type, you need to have already judged that $b(x)$ is of type $B$. In particular, for $$\prod_{x:A}\operatorname{Id}(b(x),b(x),B)$$ to be a type, you need to know that we can deduce $b(x):B$ from $x:A$. This means you must assume that $\lambda x.b(x)$ is a term of type $A\rightarrow B$ for your question to even make sense. If we do assume this – ie, if we assume that we have already judged $\lambda x.b(x):(A\rightarrow B)$ – then we can solve your problem, but it's perhaps a slightly unsatisfying solution:
In Martin-Löf type theory, we have the "reflexive" constructor for identity types, which I will denote $\operatorname{refl}$. The introduction rule for $\operatorname{refl}$ is that, if $C$ is a type and we have judged $c:C$, then we can judge $\operatorname{refl}_c:\operatorname{Id}(c,c,C)$. If you have this construction in your type theory, then $\prod_{x:A}\operatorname{Id}(b(x),b(x),B)$ in fact always holds, with a proof given by the term $\lambda x.\operatorname{refl}_{b(x)}$. Since we know $b(x):B$ for any $x:A$, it is clear that this will be well-typed. If you wish, we can then construct a proof of $$(A\rightarrow B)\rightarrow\prod_{x:A}\operatorname{Id}(b(x),b(x),B),$$ simply by considering the term $\lambda f.\lambda x.\operatorname{refl}_{b(x)}$.  Conversely, we can construct a proof of  $$\prod_{x:A}\operatorname{Id}(b(x),b(x),B)\rightarrow (A\rightarrow B)$$ by the term $\lambda g.\lambda x.b(x)$; since we already know $\lambda x.b(x):(A\rightarrow B)$, this will be well-typed.
If this is the answer you're looking for, great! However, there's not much "moral" content in it, as the terms we construct don't ever use their first arguments. This is why I'm not sure if we're understanding your question correctly.
Comment: Thanks a lot! :-) Have a good night!
Comment: Yes, I have the same doubt because the first argument is not used. But it appears that we can take it to be a theorem, even though it is mainly due to the presupposition of the well-formedness of $Id(b(x),b(x),B)$, right?
Comment: @EminiJask yep, exactly! :) the two terms given above provide a proof
Comment: Let me ask a further question. Let $\Gamma\vdash f: A\rightarrow B$. In this case, if we follow the above reasoning, we can actually reach $\Gamma\vdash(\lambda x)\textsf{refl}(f(x)):\Pi x:A.\textsf{Id}(f(x),f(x),B)$. Is that right?
Comment: @EminiJask exactly!! :)


If $A= \begin{pmatrix} -4 & 1\\ 3 & 2 \end{pmatrix}$ find $f(A)$ if $f(x) =x^2 - 2x+3$

Question: If $A= \begin{pmatrix} -4 & 1\\ 3 & 2 \end{pmatrix}$ find $f(A)$ if $f(x) =x^2 - 2x+3$.
Actually while solving for $f(A)$, my teacher said to change $3$ into $3I$ where $I$ is an identity matrix, so that matrix can add up but I am still confused about how can an integer change into the matrix and what is its significance?
Comment: Welcome to MSE. Please include your question in the body of the question, instead of putting it only in the title.
Comment: Do you mean $\begin{bmatrix} -4&1 \\ 3&2\end{bmatrix}$?
Comment: Where did "7" come from?  Do you mean replace $3$ by $3I$?
Answer: I agree ... arbitrarily changing a number into a matrix doesn't make much sense, and you're right to question it.
In my opinion, the problem is just poorly written, and you shouldn't worry about that. The function $f$ is pointless, and doesn't need to be mentioned at all. What the problem is really asking you to do is calculate $A^2 - 2A + 3I$, and I expect you know how to do that.
Comment: Changing a number into a matrix seems to be a convention used in, for example, the Cayley-Hamilton theorem. (If $P(X) = X^2 + 1$ is the characteristic polynomial, then $P(A) = A^2 + I$.) This notation can be confusing for first-timers, as was for me. But as for the OP's question, this is just a definition/conventional issue. There is a way of thinking about such things via isomorphisms.
Comment: Yeah, I know it's a convention. But it's a convention that deserves some explanation. Telling a beginner to just interchange numbers and matrices willy nilly  is inviting confusion, and I think the OP is right to question it.


Probability density function / maximum likelihood for correlating sequence

Question: I have a stream that contains two consecutive identical sequences, each of length $N$. These sequences have a ideal autocorrelation property. So I want to have the probability density function over $2N$ samples. So before the sequences, the pdf $f(x)$ for the examined vector $[x_1,\ldots,x_{2N}]$ is just a multiplikation of statistically independent values
$$f(x_1,x_2,\ldots,x_{2N})=\prod_{k=1}^{2N} f(x_k).$$
For the case of the correlating values of the consecutive identical sequences: How can it be simplyfied (since they are not statistically independent anymore)?
$$f(x_1,x_2,\ldots,x_{2N}) = ?$$
Thank you
Answer: $f(x_1,x_2,\ldots,x_{2N})=f(x_1)f(x_2|x_1)f(x_3|x_2,x_1)\ldots f(x_{2N}|x_{2N-1},x_{2N-2},\ldots,x_2,x_1)$


Pine script : Just text always on the corner top

Question: I would like to add text and keep it at the top right of the chart all the time.
It will be a sort of 4-line checklist.
This text is assigned to an indicator.
How can I do this?
Thank you in advance for your help.
Here the problem of the col on the left side.
Thanks
Answer: You can use table.new function.
https://www.tradingview.com/pine-script-reference/v5/#fun_table{dot}new
<code>//@version=5
indicator("table.new example")
var testTable = table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, border_width = 1)
if barstate.islast
    table.cell(table_id = testTable, column = 0, row = 0, text = "Open is " + str.tostring(open))
    table.cell(table_id = testTable, column = 1, row = 0, text = "Close is " + str.tostring(close), bgcolor=color.teal)
</code>
Comment: Thanks so much.  Works perfectly

Have a good day
Comment: Hi again,

Finally, i have a little problem with this code.

I have a col on the left side.

How can I remove this ?

Thanks
Comment: pls provide more info about problem


Probability Proof. $P(A | B) = P(A | B^c)$

Question: Be A,B are independent envents, if and only if
$P(A|B) = P(A|B^c)$
I know that
$P(A) = P(A∩B) + P(A∩B^c)$
and $P(B)= 1- P(B^c)$ So...
$\frac {P(A∩B)}{P(B)} = \frac {P(A∩B^c)}{P(B^c)}$
hence
$(1-P(B)) P(A∩B) = P(B)P(A∩B^c)$
$P(A∩B)=P(B)P(A|B^c)$ (this change is not very clear to me)
But i can't see how continue...
Thanks for the time :)
Comment: There are some flaws in your calculation. Can you find them?
Answer: Some corrections for your working:
$$\color{red}(1-P(B) \color{red})(P(A∩B) = P(B)P(A∩B^c)$$
$$P(A∩B)=P(B)P(A|B)$$
Now let's work on the question:
$$(1-P(B))(P(A∩B) = P(B)P(A∩B^c)$$
$$P(A \cap B) - P(B)P(A\cap B)=P(B)P(A \cap B^C)$$
which is equivalent to
$$P(A \cap B) = P(B)(P(A\cap B)+P(A \cap B^C))$$
Try to simplify the last line.
Answer: You have done it correctly till :- $$(1−P(B))P(A∩B)=P(B)P(A∩B^c)$$ Just try to convince yourself by some Venn diagrams that $$P(A∩B^c) = P(A)-P(A∩B)$$ Replace this in your equation and you will get $P(A∩B) =P(A)P(B)$ which proves their independence.


Issues with PHP INSERT form

Question: So I'm trying to get this php code to display a textarea and submit button so a user can submit a bio that gets inserted into a db. I have a few issues with this code:

For some reason, the text area is filled with the actual form HTML instead of just a blank box, so it shows as:
<form action='page-bio.php' method='post'>
    <textarea name='author_bio' value=<input type='hidden' name='hidden' value=
    <input type='submit' name='update' value=update
</form>.

I'm using wordpress, so this is a php template, but I am wondering if this code will properly get the current user and insert the user's bio into the user's bio field in the database? I have a feeling it won't, but I can't tell because I still can't get the submit button to display.

<?php
    $con = mysql_connect("localhost","XXXX","XXXX");
    if (!$con){
        die("can not connect: " . mysql_error());
    }
    mysql_select_db("i5412",$con);

    // Get the current user's info
    $current_user = wp_get_current_user();

    if(isset($_POST['update'])){
        $UpdateQuery = "UPDATE wp_usermeta SET author_bio='".$_POST['author_bio']."'WHERE
        user_id=$current_user and author_bio='".$_POST['hidden']."'";
        mysql_query($UpdateQuery, $con);
    }

    $sql = "SELECT * FROM wp_usermeta";
    $myData = mysql_query($sql,$con);
    while($record = mysql_fetch_array($myData)){
        echo "<form action='page-bio.php' method='post'>";
        echo "<textarea name='author_bio' cols='10' rows='10' value=" . $record['author_bio'];
        echo "<input type='hidden' name='hidden' value=" . $record['author_bio'];
        echo "<input type='submit' name='update' value=update";
        echo "</form>";
    }
    mysql_close($con);
?>

Comment: You forgot to close almost all the form element tags.
Comment: `echo "" . $record['author_bio'] . "";`
Comment: `echo "";`
Comment: `echo "";`
Comment: @ThinkDifferent Please delete your comments now that you've sent an answer.
Answer: you forgot to close half of the input tags such as echo "<input type='submit' name='update' value=update"; where you missed the ending >
Comment: I don't know who downvoted your question but this is most certainly the cause, but please add some code sample.
Comment: If I add the whole code, wouldn't he just copy+paste it and not learn anything as opposed to getting him in the right direction and letting him solve it and therefore learning something?
Comment: I appreciate you comment Limiter, but I've been spending countless hours trying to learn which I want to do. And there is a lot ahead of me and sometimes I just need to get something to work so I don't lose heart. This code almost works but now issue 2 I mentioned is as I feared: this is a wordpress template called from a WP page and it does not accept $current_user = wp_get_current_user(); That is, when i leave wordpress for this php page, it does not keep the current user variable i suppose, so this might be another dead end for using php insert with wordpress :(
Comment: @Limiter I know exactly what you mean, but you know, there are people who don't read properly and just downvote because of "too short", "doesn't provide sample", etc.
Answer: You need to change the following lines:
echo "<textarea name='author_bio' cols='10' rows='10' value=" . $record['author_bio'];
echo "<input type='hidden' name='hidden' value=" . $record['author_bio'];
echo "<input type='submit' name='update' value=update";

To
echo "<textarea name='author_bio' cols='10' rows='10'>" . $record['author_bio'] . "</textarea>";
echo "<input type='hidden' name='hidden' value='" . $record['author_bio']. "'>";
echo "<input type='submit' name='update' value='update'>" ;

Issues with PHP INSERT form


How to write a rule for 'After sending email'?

Question: I have to write a rule for the event 'After sending email'. How can I do that?
For example there are three users user1, user2, user3. I need to enable a flag on a content type after admin sending email to those three users.
Comment: Not a trivial task - you'll probably need to write your own mailsystem which extends the default one to invoke a custom action whenever mail is sent. You can use `hook_action_info()` to define the action, but I doubt anyone will write the whole thing for you so probably best you have a go yourself, and come back with specific problems :)
Comment: My bad, you can implement [`hook_mail_alter()`](https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_mail_alter/7) and fire a custom action from there. Quite a small job
Answer: There is no Rules Event like "*after sending eMail". However, you can create a Rules Component for sending an eMail. For a sample of such Rules Component, refer to the answer to "Rule to store user's last post date and scheduled rule based 30 day reminder".
If you then "invoke this Rules component" any time a rule has to send an eMail, you basically created the equivalent of the Rules Event you're asking for. All that's left to do is to expand that Rules Component with additional Rules logic that you want to happen "after sending eMail" (... as in your question).


Accidentals in divisi parts

Question: I've got a trumpet part which is divisi (upper and lower part on one staff). The upper part starts with a F, which has an accidental sharp in front of it. The 3rd note of the lower part is a F as well... Does the accidental also apply to this note?
Comment: Possible duplicate of [Does an accidental apply to all octaves?](https://music.stackexchange.com/questions/49717/does-an-accidental-apply-to-all-octaves)
Comment: Can you post a photo of the measure in question? It is hard to give an answer based on the information here.
Comment: @AlbrechtHügli I disagree.  The parts are written into the same staff just to save page space. They are completely separate - you wouldn't have a violinist play an accidental just because the clarinet had one in the score!
Comment: @ Carl: we even don't know whether this F# is an accidental or a key sign  (what my assumption is)  as long we can't see a copy. I'm asking about the style because this would be the only explanation that there could be such strange voicing.
Comment: Yes, I agree with Carl and user45266. My point is that I've met here too many beginners that didn't know such elementary things as the meaning accidentals and key signature  and the difference of them. So we can only assume what it could be: an typo, an error of the composer/arranger or a misunderstanding of the OP's knowlede,  as long we don't have more information. So far I assume the latter  - unless this isn't music of 20th century like e.g. Bartok, Stravinsky, Lloyd Webber or Schönberg and Co. :)
Comment: normally yes, but it would be clear if you told at least what style this piece is in ...
Comment: @AlbrechtHügli It does say "accidental", meaning not in the key signature.
Comment: I've seen instances in choral music/Barbershop music where the bass and baritone parts are written on the same staff and an accidental (Yes, accidental, not key signature) appears in the bass part at the beginning of a measure and the baritone part is given the same note at the end of the measure without an accidental. Given that two different people are singing the two different parts, I would expect the baritone to get a courtesy accidental whether or not he is to sing the same note as the bass, That doesn't always happen and produces ambiguity. I am not answering the original question, but
Answer: Best practice is to put the accidental in both parts.  We could argue the point in polyphonic keyboard music.  But this is actually two seperate PLAYERS.  Tell them both!
I'm assuming the two F notes are in the same octave.  If not, the rule is clear.  An accidental only affects the octave it's in.   But, nonetheless, a cautionary natural where it ISN'T required would be sensible.
Comment: This is definitely best practice, but it's very possible that the publisher/composer wasn't following best practices in this case.
Comment: An accidental only affects the octave it's in. This is correct. But I would like to know the composer's name. Either there should be notated a  Gb in the upper voice or - that would be nice  of him - a (natural ) F in the 3rd. ...
Answer: A "divisi" score is just a way to reduce the amount of paper used.  If the same two parts were written as "Horn 1" and "Horn 2" there would be no question that the accidental only applies to the part it's written into.
Therefore, divisi parts follow only their own accidentals, just as they follow only their own slur/staccato, dynamics, etc.
Comment: Theoretically yes, but far too many composers/copyists/publishers get it wrong. Usually it's clear what's intended. Unfortunately sometimes it's not.
Answer:
The upper part starts with a F, which has an accidental sharp in front of it.

My assumption is: this is not an accidental but a key sign that says: we are in major G or minor e (trumpet setting!). If you have other parts for C-instruments with one flat in front (after the clef) or Eb-Horns with 2# (F# and C#) this answer is the right one:
The key sign applies to all parts.
Comment: How can you say that without seeing the actual score?
Comment: Because I want to see the proof :) I've written it in my commentaries below the question. Ok. My opininion is my assumption.
Comment: We actually do know that it is NOT a key signature sharp, because the OP did write that it is an accidental sharp.
Comment: Yes, we no nothing. We don't know anything about OP, nothing about the sheet notation, nothing about the title of the piece, nothing  about the composer, nothing about the style.

Accidentals in divisi parts


NSString containing parentheses ()

Question: Just start learning obj c and iOS and NSstring drive me crazy,
NSString *iTunesSongURL;

value of iTunesSongURL is
I just want to join two strings
NSLog(@"%@", [NSString stringWithFormat:@"%@%@",  iTunesSongURL, @"&at=sdsdgsd"]);

But result is like
(
    "https://itunes.apple.com/us/album/im-yours/id277635758?i=277635828&uo=4"
)&at=sdsdgsd

But I want the result like
    "https://itunes.apple.com/us/album/im-yours
/id277635758?i=277635828&uo=4&at=sdsdgsd"

I spend lot of time on it but can't figure out small things. Any help
Comment: @downvoter: Why down vote? No solutions works for me given bellow
Comment: as I checked your debugger and come to know that iTunesSongURL is NSArray. So let me edit my answer.
Answer: Try this:-
NSString *iTunesSongURLString = iTunesSongURL.firstObject

NSLog(@"%@",[NSString stringWithFormat:@"%@&at=sdsdgsd",  iTunesSongURLString]);

Explanation:-
%@ means dynamic value is passing to strig. In your case, iTunesSongURL is the only dynamic string. &at=sdsdgsd is static string so put it directly in double quotes.
Comment: yes working, Thanks. Manny question in my mind but will study later more about it.
Comment: not compiled, .firstObject is not valid for NSString
Comment: Declare iTunesSongURL as NSArray
Answer: Your object iTunesSongURL is an array. You should write it as below
NSLog(@"%@", [NSString stringWithFormat:@"%@%@",  [iTunesSongURL objectAtIndex:0], @"&at=sdsdgsd"]);

Comment: I declared `iTunesSongURL` as NSString, How it became array?
Comment: As you show in the image in the log 'iTunesSongURL' is NSArray, so Chetan's answer should work if it's NSArray
Comment: As @Pyro said, the image you uploaded shows  'iTunesSongURL' as an array.
Answer: First u need to declare :
NSArray *iTunesSongURL;

retrieve the response in the array and use
 NSLog(@"%@", [NSString stringWithFormat:@"%@&at=sdsdgsd",[iTunesSongURL objectAtIndex:0]]);

Comment: you forgot to add  ]  after 0 .          objectAtIndex:0]]);

NSString containing parentheses ()


Técnicas para levantar requisitos e escrever casos de uso

Question: Faz um tempo vi um curso do Lynda.com chamado "Foundations of Programming: Object Oriented Design" e o cara do curso deu uma lista de 5 passos para criar um modelo de domínio:

Coletar requerimentos
Descrever o sistema (com casos de uso)
Identificar os objetos principais
Identificar as relações entre os objetos principais
Fazer um diagrama de classes

Até aí tudo bem, gostei muito da forma que ele propõe para fazer o modelo de domínio, mas eu ainda estou com bastante dúvida na coleta de requerimentos e na descrição do sistema com casos de uso. Existem técnicas para um programador que trabalha sozinho fazer isso com sucesso? Existem também exemplos reais?
Digo isso porque eu trabalho na maioria com aplicativos web e intranets, mas os exemplos que eu achei até agora são sobre caixa eletrônico de banco e coisas do tipo. São coisas interessantes, mas queria ver algo mais próximo do que eu trabalho, pra poder me basear.
Comment: Sugiro que você dê uma lida no Project Management Body of Knowledge, também conhecido como PMBOK. A etapa da coleta de requisitos é só uma pequena parte entre as 10 áreas de conhecimento que um projeto pode possuir. O pouco que você absorver de lá já é um grande passo para os projetos que você tocar futuramente.
Comment: Obrigado pela sugestão @rodrigorigotti, vou dar uma olhada sim. Esse livro é focado em equipes ou para um programador sozinho também serve?
Comment: Na verdade o PMBOK tem como público alvo o gerente de projetos, mas qualquer um pode ser gerente de projetos do seu próprio projeto. :) Boa sorte!
Comment: (Quatro anos depois...) Procure cursos online de UML como por exemplo na Udemy.com, alguns deles são focados em aplicações web.
Answer: A teoria é linda, se não fosse teoria.
na prática

nunca se consegue coletar todos os requisitos de um sistema no começo dele, porque o uso do sistema leva os usuários a refletirem sobre novos usos, sem contar com o fato de que eles se lembram de novos detalhes.
abordagens "ágeis" vão tentar te vender a idéia de que você pode grudar no cliente e ir extraindo interativamente os requisitos, negociando a cada delivery um conjunto de funcionalidades que "agregue valor" (coff coff). Eu acho bastante questionável que um cliente tope pagar por iterações sem saber o que ele vai ter ao final de um determinado prazo, talvez daí a grande maioria dos contratos ainda se manterem de escopo fechado. Acho igualmente questionável que o cliente tenha a disponibilidade de participar do projeto como a agilidade advoga, mas vale tentar. Na prática, clientes sentem que adivinhar o que ele quer faz parte do pacote que ele está pagando, afinal, é o tempo dele.

Dado que sistema nenhum começa a ser desenvolvido sem uma noção mínima inicial de escopo, e dado que a abordagem de tentar coletar o máximo de especificação desde o começo não seja perfeita pela natureza dinâmica da engenharia de software e dado que as abordagens ágeis vendem a idéia correta de que o cliente deve considerar o software como um serviço de desenvolvimento e não como um produto que custa X para ficar pronto com preço definido desde o início, o que nos resta?

Identificar logo no início quais são as funcionalidades MAIS IMPORTANTES e focar nelas desde o começo, pelo fato de que se você atrasar (e vc provavelmente vai), fica mais fácil o projeto sobreviver se as funcionalidades principais forem implementadas desde o início
Obter do cliente comprometimento quanto aos requisitos, formalizando-os sempre que possível e priorizando, de forma que vc tenha alguma moeda de negociação (vc vai precisar)
Obter desde o início os critérios de aceite do sistema, que são mais importantes e definem melhor o que o sistema deve realmente fazer do que a especificação inicial. Na verdade, se vc puder focar no critério de aceite como o critério onde o projeto e os pagamentos acabam desde o início do projeto, tanto melhor. Caso contrário, indica que seu cliente não sabe bem o que quer e que o projeto deve ser encarado como um serviço e não como um produto.

UPDATE - só complementando, vc pediu técnicas. A técnica mais importante é saber ouvir. E depois de uns bons anos, eu percebi que o melhor livro que eu conheço para ensinar empatia e a saber ouvir é este livro, que embora não pareça poder ser aplicado a engenharia de software, eu acho perfeitamente possível. http://www.amazon.com/How-Talk-Kids-Will-Listen/dp/1451663889
Answer: Concordo com o Leo em que a teoria é diferente da prática, sendo que a resposta toda é muito boa.
Teoria vs Prática
Temos que tomar cuidado.
Muitas teorias são criadas para depois serem implementadas e testadas na prática. Pode ser que funcionem ou não.
Mas no caso da Engenharia de Software, o que ocorre em geral é o inverso. Muito da teoria veio da observação da prática ou emprestado de outras áreas de conhecimento, tais como procedimentos de fábricas ou gerenciamento de projetos.
O problema é que essas coisas não funcionam da mesma forma, afinal não se desenvolve um software da mesma forma que se fabrica um automóvel em linhas de produção ou se constrói um prédio.
Analogias
Embora não sejam perfeitas, muitas analogias com essas outras áreas nos ajudam a entender o que estamos fazendo.
Da mesma forma, um passo-a-passo como o descrito na pergunta não consiste numa regra fixa a ser seguida, mas numa abstração do que realmente é feito.
Em outras palavras, não é como num livro de receitas ou um manual de montagem onde você executa cada passo e obtém o produto final. Pense na teoria de Engenharia de Software sobre uma tentativa de explicitar ou descrever o que muitas vezes fazemos sem mesmo entender.
Exemplo
Suponha que você teve uma ideia para um sistema interno para sua empresa que vai melhorar um determinado processo.
Você vai até o responsável pela área e faz algumas perguntas para entender como realmente as coisas funciona.
Depois volta para sua mesa e escreve um texto dizendo o que o sistema poderia fazer para efetivamente melhorar o processo.
Então você volta para falar com o responsável e explica sua proposta, isto é, como você pretende fazer o trabalho dele mais fácil ou efetivo, economizar esforço, diminuir erros, ou qualquer coisa nessa linha.
Imagine que ele gostou da ideia e lhe diz que ficaria grato em trabalhar com você para tornar isso real.
Nesse ponto você volta para sua mesa e gasta um ou dois dias esboçando melhor sua ideia, criando modelos das telas, talvez modelando o banco de dados e, no fim, monta um pequeno protótipo bem simples,
Agora você chama o responsável e mostra o que fez. Imagine que ele gostou, acha que está no caminho certo e apenas dá algumas dicas sobre alguns detalhes que ficariam melhor de um outro jeito.
Finalmente, você despenderia mais uma ou duas semanas para melhorar o protótipo, polir a interface, colocar alguma segurança e disponibilizar a primeira versão do produto.
O responsável então começa a usar com sua equipe, verifica que o resultado foi positivo e a partir daí ele vai começar a solicitar algumas melhorias, pequenos ajustes e novas funcionalidades para melhorar ainda mais o ganho obtido.
Explicação
Tudo o que descrevi acima tentando não usar termos técnicos é exatamente como poderia funcionar um projeto usando os mesmos passos descritos na pergunta, mas com juma abordagem ágil.
Note que mesmo no projeto ágil você tem a análise de requisitos, descrição do sistema em estórias de usuário, pensar nos objetos que vão compor a solução e fazer esses objetos funcionarem.
As principais diferenças são:

Talvez não seja necessário gastar muito tempo fazendo diagramas a não ser que isso seja relevante para o seu entendimento do problema
No processo ágil não se tenta descobrir tudo o que o sistema deve fazer para sempre e sempre, mas focar numa ideia inicial que resolve o problema mais crítico, testar se isso funciona, receber o feedback do usuário e iterar novamente, isto é, voltar ao primeiro passo para criar uma nova versão do sistema melhor e com mais funcionalidades
O foco é em atender as necessidades do cliente e não simplesmente em criar um modelo computacional e diagramas bonitos

Considerações
Use os conceitos da Engenharia de Software para entender os princípios do desenvolvimento de software e então use as técnicas de engenharia ou de gerenciamento que contribuam para melhorar o seu trabalho.
Às vezes, quando o ambiente de trabalho é caótico, é recomendável adotar algum modelo de desenvolvimento existente. Mas, em geral, o ideal é não tentar seguir um livro-texto e sim adaptar os métodos disponíveis que sejam relevantes no seu caso para então tentar fazer um trabalho mais efetivo.
O que não der certo deve ser simplesmente descartado. Por exemplo, eu recomendo você tentar fazer um diagrama de classes simples, sem gastar muito tempo pensando em absolutamente todos os possíveis relacionamentos e atributos. Depois de um tempo você vai perceber o quanto esse diagrama foi útil ou não e, no próximo ciclo vai ter mais segurança para decidir isso.


Multiple hostnames for a Synology NAS in local network

Question: Is it possible to set up a Synology DS918+ NAS (which is just a Linux system) to be accessible via

http://diskstation.local and
http://laura.local

at the same time? I have set up a reverse proxy on my NAS that routes to a different server in a docker container when you access it via laura.local than when you access it via diskstation.local
Answer: Synology offer DNS Server package:
https://www.synology.com/en-global/dsm/packages/DNSServer
You can configure it for local resolution and  let it forward everything else to an external DNS (e.g.: your provider DNS)
https://robpickering.com/configuring-synology-for-forward-and-reverse-internal-dns-resolution/
In the master zone you can add many entries you need that resolve your hosts and point to NAS IP:
diskstation.local -> your NAS IP
laura.local -> your NAS IP

Remember also to configure the router or the server that offering DHCP in your local network in order to provide your Synology NAS as DNS server.
In this way you don't need to create a host entry in each device in your local network
Answer: It is possible if you can add entries in your DNS server for the .local zone.
Another alternative is to add entries to /etc/hosts (Mac / Unix) or to C:\Windows\System32\drivers\etc\hosts.txt where you map the host names to IP addresses. This operation has to be done on every client computer where you want to use the hostname.
Comment: I want that host to be accessible from all computers and phones in my network, not just the ones i set up /etc/hosts for and I don't own a DNS server
Comment: You need a DNS server to set up mapping between names and IP addresses. Your NAS unit might have one, your router might have one. You need to research it yourself.


Sql Server Reporting services

Question: Can we merge two cells of two different rows while designing a report in SSRS???
Answer: It depends on the version of SSRS you are using.  You can only merge across columns in SQL Server 2005.  But with SQL Server 2008 you can merge across columns and rows.
That being said, you can place a table within a table in both versions which can provide the illusion of merged rows.  Add a table to the report that and select a value to group on.  Add the group on value to the first column in the grouping header.  In the second column of the grouping header insert another table.  Add to that table the values and details that correspond to the grouping value that you wanted to merge rows across.
Answer: I don't think so, SSRS will process rows sequentialy.
Your best bet would be to create a view or a temporary table and then create a report using that as the source.
Answer: No, you cant. What you can, is mimic this with absolute positioned text field. The problem with such text fields is that not all exports works correctly.

Sql Server Reporting services