Locus Similar Triangle

Question: ABC is a triangle and XY is variable straight line parallel to AC meeting BC and BA in X, Y respectively.  If AX and CY meet at P find the locus of P.
Answer: Construction: Through P, draw MN parallel to AC meeting BC, BA at M and N respectively.

For some reasons, ⊿YNP ~⊿YAC. Therefore, $NP = AC. \frac {YN}{AY}$.
Similarly, we have $PM = AC. \frac {XM}{XC}$.
By intercept theorem, $\frac {YN}{AY} = \frac {XM}{XC}$.
∴ $NP = PM$ implying that P is the midpoint of the side NM of ⊿BNM.
Different sets of X,Y (i.e. X', Y' say) will generate the corresponding P' of N'M' of ⊿BN'M'.
∴ The locus of P is the median from B to AC.
Answer: First, I assume you want the intersection between $CY$ and $AX$, because $XY$ and $CY$ intersect at $Y$.
The answer in this case is the "mediane"-line from $B$ to the middle point of $AC$.
Proof. The construction is invariant under affine transformations:
Given $A,B,C$ not colinear, the parallel $XY$ to the edge $AC$, is determined by the ratio of the lenghts $AY/AB$.
Given any other three points $a,b,c$ there is a unique affine map $f$ so that $f(a)=A,f(b)=B,f(c)=C$. Points $X,Y$ corresponds to $X=f(x)$ and $Y=f(y)$ and the proportions are preserved: $AY/AB=ay/ab$ and $CX/CB=cx/cb$.
So, you can solve the problem with an equilateral triangle, for which you see immedately that the locus of the $p$'s is the $b$-median line. Since the $b$-median line is defined as the line that joins $b$ with the midpoint of $ac$, and since the proportions of lengths are preserved by affine maps, then $f(b$-median line$)=B$-median line.
Comment: you can also prove it directly, without use of affine by making use of similar triangles
Comment: I want a mathematical proof I know we can use this but I wanna know the school proof
Comment: what I gave is a mathematical proof, what do you mean by "I want a mathematical proof"?
Comment: Actually I want a simple proof which is applicable at school level because the unique affine map I can't understand what it is.
Comment: If you want a proof with "similar triangles" just drow any line L passing through $P$ and crossing both AC and XY in points s,t respectively. Then note that by using similar triangles you see in the picture, you can prove that the ratio As/sC is the same as Yt/tX (note the "switch" of the orders). Then note that the median line gives you As/sC=1. So it is an admissible line. This implies that $P$ passes trhoug the median line. Since this holds for any $P$ the locus of $P$'s is the median line
Comment: Could you please be more generous and explain this answer it seems simple
Comment: this is not a matter of generosity: is a lack of pictures!
Comment: So you could just post a new answer please
Comment: @user3650050 thanks for asking to write a new answer...
Answer: Let L be a line through $P$ that crosses both $AC$ and $XY$.
Let $S=L\cap AC$ and $T=L\cap XY$. Triangles $SCP$ and $PTY$ are similar, so are $ASP$ and $PXT$ and the ration of lengths is given by $SP/PT$.
In particular $$\frac{AS}{SC}=\frac{XT}{TY}$$
Since the ratio $AS/SC$ runs from $0$ to $\infty$ as $L$ change among the lines crossing $AC$ and $XY$, there is a line such that the ratio is $1$.
Now, choose $L$ so that such ratio is $1$. Then $L$ is the $B$-median of $ABC$. Therefore $P$ belongs to the $B$-median of $ABC$. But this holds true for any such $P$. Therefore the locus of $P$'s is contained in the $B$-median of $ABC$.
Conversely you easlily see that in fact the $P$'s cover the whole median line.

Locus Similar Triangle


Spark Scala - How to explode a column into multiple rows in spark scala

Question: I have a dataframe like this
+----------+-------------+
|A         |Devices      |
+----------+-------+------
|house1    |[100,101,102]|
|house1    |[103,104]    |
+----------+-------------+

And I want to explode the column 'Devices' into multiple rows. My final dataframe should look like this
+----------+--------+
|A         |Devices |
+----------+--------+
|house1    |100     |
|house1    |101     |
|house1    |102     |
|house1    |103     |
|house1    |104     |
+----------+--------+

The schema of the table is
 root
  |-- A: String (nullable = true)
  |-- Devices: array (nullable = true)
  |   |-- element: String (containsNull = true)

I tried doing this but it is showing error (UnresolvedAttribute in $"Devices")

Df.withColumn("c", explode(split($"Devices","\\,")))
Comment: You shouldn't need the split function. Your strings dont have commas
Comment: Yes, Thanks @OneCricketeer! I updated the question
Comment: Thanks @OneCricketeer. I am able to find the answer using explode(columnName)
Answer: Df.select(col("A"),explode(col("devices"))

Using this I am able to find the required answer
Comment: The `$`  should work, but you need to `import spark.implicits._`


Display Date of the timestamp from the input field use only IST result should be in p tag in javascript

Question: Display Date of the timestamp from the input field use only IST result should be in p tag (example: timestamp of 1382086394000 must have a output --> Tue Jul 29 45766 12:43:20 GMT+0530 (India Standard Time)

function showDate(){
    //Start Your code here

}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Static Template</title>

TimeStamp<input type='text' id='in1' name='tstamp' oninput='showDate()'>

Comment: Welcome to Stack Overflow. If you're looking for solutions to homework questions, you've to show your effort, problem you're facing and expected result.
Answer: Use the Javascript Date Function

function showDate(){
    //Start Your code here
    const timestampEntered = Number(event.currentTarget.value);
    result.textContent = new Date(timestampEntered).toString();

}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Static Template</title>

TimeStamp<input type='text' id='in1' name='tstamp' oninput='showDate()'>


std::thread gives "thread" is not a member of "std" error in C++ Builder 6

Question: I tried to use std::thread like this, but it gave me a "thread" is not a member of "std" error: (stdio.h is included)
std::thread thread_obj(makeFile, 512, MEGABYTE, "file");

Answer: std::thread was introduced in C++11 in 2011. However, C++Builder 6 was released in 2002, thus it predates C++11 by almost a decade. C++Builder 6 only supports C++98, hence the error.
C++11 support was first added in C++Builder XE4, which was released in 2013. And XE4 supported C++11 only under 64bit development - 32bit support for C++11 wasn't added until several versions later.
So, you need to upgrade to a modern version of C++Builder if you want to use modern C++ features.
Comment: I see, is there an equivalent for it in C++98?
Comment: @furybowser no, there is nothing like `std::thread` in C++98. So, you will have to either 1) derive a new class from BCB6's own `TThread` class, or 2) use the Win32 API `CreateThread()`, or 3) use a 3rd party wrapper like `pthreads`, etc. The real question is - why are you using a compiler/IDE that is over 20 years old?


Finding Lyapunov function to show origin is stable

Question: Consider the system
\begin{cases} \dot{x}=-2y+yz \\ \dot{y}=x-xz \\ \dot{z}=xy \end{cases}
I need to find a Lyapunov function of the form $V(x,y,z)=ax^2+bx^2+cz^2$ to show that the origin $(0,0,0)$ is Lyapunov stable. How do I choose the constants $a,b,c$?
 I need $V(0,0,0)=0$, which is true and $V(x,y,z)>0$ is any neighbourhood of the origin, which is true as long as $a,b,c>0$.
 Then $\dot{V}(x,y,z)=2ax\dot{x}+2by\dot{y}+2cz\dot{z}=-4axy+2axyz+2bxy-2bxyz+2cxyz$.
 I can take $b=c$ to get $\dot{V}(x,y,z)=-4axy+2axyz+2bxy$.
 What should I do next?
Answer: Instead of imposing $b=c$ just collect the similar terms in the expression $\nabla V\cdot X$ you have just computed so that you just need to solve the non-singular linear system:
\begin{cases}
-4a+2b=0 \\
2a-2b+2c=0.
\end{cases}
At this point you will get infinitely many Lyapunov functions indexed by $a\in\mathbb{R}$ for instance and you can conclude.
Comment: I see, so the origin is Lyapunov stable if and only if $\dot{V}(x,y,z) \leq 0$ and in my case I have $\dot{V}(x,y,z) = 0$.
Comment: @wwinters57 when $\dot{V}(x,y,z) \leq 0$ the system would be asymptotically stable, which is a stronger notion of stability than [Lyapunov stability](https://en.wikipedia.org/wiki/Lyapunov_stability#Definition_for_continuous-time_systems).
Comment: I think it is the other way round: the system is Lyapunov stable if $\dot{V}(x,y,z) \leq 0$ for all points in a neighbourhood of $(0,0,0)$ and it is asymptotically stable if $\dot{V}(x,y,z) < 0$.
Comment: If you just need stability showing that there exists a $V$ s.t. $\nabla V \cdot X =0$ is enough.


libvirt qemu/kvm migration problem

Question: I am using kvm and libvirt on my Dell server. Now i am trying to migrate one virtual machine from a physical server to another. However, I failed everytime.
In virsh on physicalServer1, I typed:
virsh # migrate virtualmachine1 qemu+ssh://username@physicalServer2/system
error: operation failed: migration to 'tcp:physicalServer2:49163' failed: migration failed

Then I searched FAQ part on libvirt.org. It says:
error: operation failed: migration to '...' failed: migration failed

This is an error often encountered when trying to migrate with QEMU/KVM. This typically happens with plain migration, when the source VM cannot connect to the destination host. You will want to make sure your hosts are properly configured for migration (see the migration section of this FAQ)

I managed to ssh physicalServer2 from a shell on virtualmachine1 so the above red part did not explain my failure.
I also open ports on physicalServer2, iptables -L shows following information:
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT udp -- anywhere anywhere udp dpt:domain
ACCEPT tcp -- anywhere anywhere tcp dpt:domain
ACCEPT udp -- anywhere anywhere udp dpt:bootps
ACCEPT tcp -- anywhere anywhere tcp dpt:bootps
ACCEPT udp -- anywhere anywhere udp dpt:domain
ACCEPT tcp -- anywhere anywhere tcp dpt:domain
ACCEPT udp -- anywhere anywhere udp dpt:bootps
ACCEPT tcp -- anywhere anywhere tcp dpt:bootps
ACCEPT tcp -- anywhere anywhere state NEW tcp dpts:49152:49215

Chain FORWARD (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere 192.168.122.0/24 state RELATED,ESTABLISHED
ACCEPT all -- 192.168.122.0/24 anywhere
ACCEPT all -- anywhere anywhere
REJECT all -- anywhere anywhere reject-with icmp-port-unreachable
REJECT all -- anywhere anywhere reject-with icmp-port-unreachable
ACCEPT all -- anywhere 192.168.122.0/24 state RELATED,ESTABLISHED
ACCEPT all -- 192.168.122.0/24 anywhere
ACCEPT all -- anywhere anywhere
REJECT all -- anywhere anywhere reject-with icmp-port-unreachable
REJECT all -- anywhere anywhere reject-with icmp-port-unreachable

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

The /var/log/libvirt/qemu/virtualmachine1.log on physicalServer2:
2011-05-06 13:37:30.708: starting up
LC_ALL=C PATH=/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin QEMU_AUDIO_DRV=none /usr/bin/kvm -S -M pc-0.14 -enable-kvm -m 2048 -smp 1,sockets=1,cores=1,threads=1 -name openjudge-test -uuid a8c704bc-a4f9-90db-3e57-40e60b00aac1 -nodefconfig -nodefaults -chardev socket,id=charmonitor,path=/var/lib/libvirt/qemu/virtualmachine1.monitor,server,nowait -mon chardev=charmonitor,id=monitor,mode=readline -rtc base=utc -boot c -drive file=/media/nfs/virtualmachine1.img,if=none,id=drive-ide0-0-0,format=raw -device ide-drive,bus=ide.0,unit=0,drive=drive-ide0-0-0,id=ide0-0-0 -drive if=none,media=cdrom,id=drive-ide0-1-0,readonly=on,format=raw -device ide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0 -netdev tap,fd=20,id=hostnet0 -device rtl8139,netdev=hostnet0,id=net0,mac=00:16:36:8a:22 :a0,bus=pci.0,addr=0x3 -chardev pty,id=charserial0 -device isa-serial,chardev=charserial0,id=serial0 -usb -vnc 127.0.0.1:2 -vga cirrus -incoming tcp:0.0.0.0:49163 -device virtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x4
char device redirected to /dev/pts/0
2011-05-06 13:37:30.915: shutting down

The /var/log/libvirt/qemu/virtualmachine1.log on physicalServer1 is empty.
Both physical servers are using Ubuntu 11.04. The libvirt and kvm used are installed by apt-get. The libvirt version is 0.8.8.
Comment: where is the VM's image? does both of the servers have access to this image and sees it on the same path? does physicalServer2 have full rw access to the image?
Comment: also, make sure that the libvirt user can ssh to the physicalServer2 (have the server's rsa key in its known_hosts, and better to have ssh keys setup for libvirt users)
Comment: I'd also try to get rid of firewalls completely, as a test
Answer: Make sure you have TCP 49152-49261 open between the hosts and the hostnames for each in either DNS or each other's /etc/hosts files.  For some reason KVM migration works off of hostname rather than IP address.
Answer: Make sure both host servers are on the same physical switch (or VLAN).

libvirt qemu/kvm migration problem


How to display content type name on related image?

Question: I have create one content type[article] with two by default field i.e. title and body.
In body summary part we have contain one image on left side and description on right side.
I want display the content type name on that image which is show in summary part.
Please help
Answer: 1) In FIELDS add Content Type as a field and check mark exclude from display.
2) Make sure Content Type is ABOVE Body field, other wise you will not get Content Type token as a replacement pattern.
3) Click on your Body field and in REWRITE RESULTS, checkmark override output of this field.
Then use the replacement patterns.

The above is for Drupal 8, in Drupal 7 it would be [type_1] [body__summary]
You can add html if you need ex:
[type_1]
 [body__summary]

Bonus: You could remove the image from Summary Part and instead add an image field to your content type. Then add your image as a
  field to your view. Then when you REWRITE RESULTS you can add the image there
  [type_1][field_image][body__summary]

PS: Next time tell us which Drupal version you are using!


Physical components of a third-order tensor

Question: Aris' book Vectors, Tensors, and the Basic Equations of Fluid Mechanics describes how to convert between covariant, contravariant, and physical components of vectors and tensors.
For example, in chapter 7 he defines the covariant metric tensor as:
$$g_{ij} = \sum_k \frac{\partial y^k}{\partial x^i}\frac{\partial y^k}{\partial x^j},$$
where $y^i$ are Cartesian coordinates and $x^i$ are curvilinear coordinates. The contravariant metric tensor is defined through the identity:
$$g^{ij}g_{jk} = g_{kj}g^{ji} = \delta_i{}^k = \delta^i{}_k.$$
He then uses these metric tensors to convert covariant and contravariant vectors and tensors to their physical components. For example the physical components of $\mathbf{A}$ are denoted by $A(j)$:
$$A(j) = \sqrt{g_{jj}}A^j\qquad \text{(no summation on $j$)}$$
For orthogonal coordinates, where $h_i = \sqrt{g_{ii}}$, the conversion of tensors to physical components is:
$$T(ij) = \frac{h_i}{h_j}T^i{}_j\qquad \text{(no summation on $i$ or $j$)}$$
$$T(ij) = \frac{h_j}{h_i}T_i{}^j\qquad \text{(no summation on $i$ or $j$)}$$
$$T(ij) = h_ih_jT^{ij}\qquad \text{(no summation on $i$ or $j$)}$$
$$T(ij) = \frac{1}{h_ih_j}T_{ij}\qquad \text{(no summation on $i$ or $j$)}$$
He then says that for non-orthogonal coordinates the form is similar to the first one above:
$$T(ij) = \sqrt{\frac{g_{ii}}{g_{jj}}}T^i{}_j\qquad \text{(no summation on $i$ or $j$)}$$
and you can determine the conversion of other tensors by raising/lowering the indices of the tensor on the right-hand-side using the metric tensor, such as:
$$T(ij) = \sum_m\sqrt{\frac{g_{ii}}{g_{jj}}}g^{im}T_{mj}\qquad \text{(no summation on $i$ or $j$)}$$
This explanation is sufficient for me to determine these conversions for all second-order tensors. How do I determine the physical components of a third-order tensor?
$$T(ijk) = ?$$
EDIT:
Aris provides this description of physical components:
Comment: Could you elaborate on what is meant by "physical components"?
Comment: @Muphrid I've updated the question to include Aris' definition of physical components. Basically if the vector represents velocity, what is the form of the vector with each element having correct units?
Comment: Would the downvoter please explain why this is not a good question so that I can improve it or move it to a more appropriate forum?
Answer: As you have already pointed out one can compute the physical component of a contravariant vector using
$$A_{(i)} = h_{(i)} A^i$$
For a covariant vector we have
$$A_{(i)} = h_{(i)} g^{i j} A_j \overset{\text{orthogonal coordinates}}{=} \frac{1}{h_{(i)}} A_i$$
This "transformation" can also be extended to tensor of arbitrary rank
$$ T_{(i_1,..,i_n,j_1,..,j_m)} = \frac{h_{(i_1)}\cdot ... \cdot h_{(i_n)}}{h_{(j_1)}\cdot ... \cdot h_{(j_n)}} {T^{i_1,..,i_n}}_{j_1,..,j_m}$$


The Standard seems to support (the snippet below compiles) a static data member having the same type as the class itself

Question: Where specifically is this covered in the Standard? I found §9.2/10: Non-static (9.4) data members shall not have incomplete types. In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C., but this doesn't seem to directly support the issue at hand.
#include <iostream>
struct A{
    int i;
    static A a;
};

A A::a{10};

int main() {
    std::cout << A::a.i << '\n';
}

Comment: I think that is because when you *declare* `a` it has an incomplete type but since it is a static variable the compiler does not need to know its size until its *definition*, which occurs when the type `A` is well defined and complete.
Comment: I particularly like `struct A { static A a; } A::a;` :)
Answer: C++11 9.4.2/2:

The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void.
Comment: @AJMansfield: Presumably, you understand "The declaration of a static data member in its class definition"; that's the `static A a;` declaration in the example. It's just a declaration, not a definition - there needs to be a separate definition outside the class definition (`A A::a{10};` in the example). Being a declaration, the type doesn't have to be complete - it can be a class type that's been declared but not fully defined, as `A` is at that point. (The last bit just says that it can't have type `void` - not relevant here).
Comment: Could you add a little bit of explanation of exactly what this means? Not sure I understand it entirely.
Comment: @AJMansfield The OP asked where in the standard incomplete types are allowed as `static` data members.  MikeSeymour found the quote that says that `static` data members can have (non-void) incomplete types at declaration.  Is there something else in particular you don't understand?
Comment: He quoted _the_ holy Standard, no explanation necessary.


Java 9, Hibernate and java.sql/javax.transaction

Question: I've tried to "upgrade" a project using Hibernate to Java 9, but I am having problems getting the module to function properly.
The relevant part of my module-info.java looks like this:
module test {

    ...

    requires java.base;
    requires hibernate.core;
    requires javax.transaction;
    requires java.sql;

}

and the relevant dependencies in my POM are

org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec, 2.0.0.Alpha1
org.hibernate:hibernate-core, 5.2.12.Final
javax.transaction:javax.transaction-api, 1.2

The problem is, if I run the program, I get a NoClassDefFoundError for javax.transaction.SystemException. I looked into this, and quite obviously, my module is missing a requires on javax.transaction.
So I add a module dependency on javax.transaction-api. I then go on and attempt to run the program again - now I'm missing java.sql.SQLException.
Here is what I am having a problem with: if I add a dependency on the module java.sql, which contains this class, I end up with a conflict:

module reads package javax.transaction.xa from both java.sql and javax.transaction.api

java.sql and javax.transaction.api contain different packages, and have one in common (javax.transaction.xa), but I require all of them.
How do I deal with this? Is there something simple I am missing?
Comment: Seems similar to a [linked comment](https://stackoverflow.com/questions/47852809/java-9-java-lang-classnotfoundexception-java-sql-sqlexception-in-spring-boot-a#comment82696084_47852809) and a relevant [reply from Alan](https://stackoverflow.com/questions/47852809/java-9-java-lang-classnotfoundexception-java-sql-sqlexception-in-spring-boot-a#comment82698260_47852809)
Comment: There's a MR of JSR 907 in progress (https://www.jcp.org/en/jsr/detail?id=907) to fix this. Once that is fixed then I would expect a new version of the JTA API artifact to be published with the right module name and also exporting only javax.transaction.
Answer: Use version 1.3 instead of 1.2 of javax.transaction-api, in this version javax.transaction.xa has been removed.
Maven dependency:
<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>javax.transaction-api</artifactId>
    <version>1.3</version>
</dependency>


Notes in an A13 chord

Question: Does an A13 chord include the 11th?  Here's why I'm asking... If you google this chord for piano, sometimes the third (C#) is omitted and sometimes the 11th (D) is omitted -- but sometimes they are both included.  In a theory video I watched a chord played as A - G - B - D - F#  (Gmaj7/A) was referred to as an A13sus.  This makes sense if the D (the 11th) is not included in a "standard" A13.  But if it is, I'm confused as to why it is referenced this way.
Answer: Theoretically speaking, thirds are stacked sequentially, until the quoted one is reached.
So, 1, 3, 5, 7, 9, 11, 13 are the notes that 'should' go into a 13th chord. That 13th chord is generally going to be a dominant 13th, so the 7th part will be m7, (b7). So, note-wise on C: C E G Bb D F A.
There are potential clashes here, with notes being so close (in name). When kept away from each other, as in more than an octave apart, the clashes can be avoided. C E G is the basic major triad. C E G Bb is dominant 7th. C E G Bb D is dominant 9th.
The F (11th note) is often omitted, but the 13th is pretty important - it's the one that names the chord ! In busier chords, it's often the 5th that gets left out - there are shades of that note frequency in the root. The root generally stays - it names the chord - although guitarists playing alongside a bass player can usually leave that out. The 3 has to be there - defining major or minor.
It's established that most chords with a number attached that's larger than 7 keep that 7th not. BUT - that 7th note here is b7, as it is NOT a major 7th type chord.
As said previously, the F gets left out, and the D can too. On guitar (I know it's only a theory question!) leaving out the D and F still constitute a 13th chord. I work on the premise that 7+6=13, so with the b7 and the 13 notes on board, along with the basic triad, it works on guitar - where some notes are not easily reachable. On piano, the voicing is all important, making sure, if indeed you want to play all notes, that where they're played is taken into account.
I suppose this is another bit of theory that really needs the practical to make it make sense!

Notes in an A13 chord


Type families causes ambiguous variable error

Question: Use case: I'm writing a game in a ghcjs frontend and a backend that use essentially the same state so that I can encode the rules of the game on both sides and communicate with changes in state.  To that end a gamestate would look like
data GameState = GameState {
  gameTurn :: Int,            -- | Everyone sees
  gamePhase :: GamePhase,     -- | this
  boardState :: BoardState,   -- | stuff
  -- a lot more stuff everyone can see, followed by
  usHand :: [Card],
  ussrHand :: [Card]
}

Where each player is represented by us and ussr.  Each player has a hand and from the server perspective it is omnicient, and knows every card in both player's hands.  But from the us player's perspective, gamestate looks more like this
data GameState = GameState {
  -- public stuff
  usHand :: [Card],
  ussrHand :: Int
}

That is, he can see his own hand, but he can only see how many cards his opponent has.  An observer sees even less.  The rules of the game are complex and there are a lot of things that can happen so it'd be great to encode the rules once, such that rules which affect a player's hand, such as dealing new cards, forcing a player to show a card of a type, etc, would affect each hand in the way that is appropriate depending who they are.  To that end, I ended up writing the following using type families, which doesn't work
{-# LANGUAGE  TypeFamilies, RankNTypes #-}
module Test where

data Card = Card
data BoardState = BoardState
data GamePhase = GamePhase
data Country
data Player = PUS | PUSSR

data US
data USSR
data Observer
data Server

data Private = Private Int
data Public = Public [Card]

class HandType a where
  type USHand   a :: *
  type USSRHand a :: *
  toUS :: Public -> USHand a
--   toUSSR :: Public -> USSRHand a -- TODO

instance HandType Server where
  type USHand Server = Public
  type USSRHand Server = Public
  toUS (Public cs) = Public cs

instance HandType US where
  type USHand US = Public
  type USSRHand US = Private
  toUS (Public cs) = Public cs

instance HandType USSR where
  type USHand USSR = Private
  type USSRHand USSR = Public
  toUS (Public cs) = Private (length cs)

instance HandType Observer where
  type USHand Observer = Private
  type USSRHand Observer = Private
  toUS (Public cs) = Private (length cs)

data GameState a = GameState {
  gameTurn :: Int,            -- | Everyone sees
  gamePhase :: GamePhase,     -- | this
  boardState :: BoardState,   -- | stuff

  usHand :: USHand a,
  ussrHand :: USSRHand a
}

data Event a =
    PlaceInfluence Player Int Country -- | Most plays don't affect
  | PlayCard Player Card              -- | either hand
  | DealCards (USHand a) (USSRHand a) -- | This one does

-- Works
obsEvents :: [Event US]
obsEvents = [PlayCard PUS Card, PlayCard PUSSR Card, DealCards (Public [Card]) (Private 3)]

-- Works
serverEvents :: [Event Server]
serverEvents = [PlayCard PUS Card, PlayCard PUSSR Card, DealCards (Public [Card, Card]) (Public [Card])]

-- The server must send out the gamestate modified for the player's consumption.
-- serverToPlayerGS :: GameState Server -> GameState a
serverToPlayerGS (GameState turn phase bs us ussr) =
  GameState turn phase bs (toUS us) undefined -- | <- Doesn't work (line 75)

-- serverToPlayerEvent :: Event Server -> Event a
serverToPlayerEvent (PlaceInfluence p amt c) = PlaceInfluence p amt c
serverToPlayerEvent (PlayCard p c) = PlayCard p c
serverToPlayerEvent (DealCards us ussr) =
  DealCards (toUS us) undefined -- | <- Doesn't work (line 78)

The error on both lines 75 and 78 are both something along the lines of
Couldn't match expected type 'USHand a'
            with actual type 'USHand a0'
NB: 'USHand' is a type function, and may not be injective
The type variable 'a0' is ambiguous
Relevant bindings include
  serverToPlayerGS :: GameState Server -> GameState a
    (bound at src/Test4.hs:74:1)
In the fourth argument of 'GameState', namely '(toUS us)'
In the expression: GameState turn phase bs (toUS us) undefined

Or if I omit a type declaration
Could not deduce (USHand a0 ~ USHand a1)
from the context (HandType a1,
                  USHand a1 ~ USHand a,
                  USHand t ~ Public)
  bound by the inferred type for 'serverToPlayerGS':
             (HandType a1, USHand a1 ~ USHand a, USHand t ~ Public) =>
             GameState t -> GameState a
  at src/Test4.hs:(74,1)-(75,45)
NB: 'USHand' is a type function, and may not be injective
The type variable 'a0' is ambiguous
Expected type: USHand a
  Actual type: USHand a0
When checking that 'serverToPlayerGS' has the inferred type
  serverToPlayerGS :: forall t a a1.
                      (HandType a1, USHand a1 ~ USHand a, USHand t ~ Public) =>
                      GameState t -> GameState a
Probable cause: the inferred type is ambiguous

I see some other answers on the site that are similar, but I'm not sure how the fixes explained would ultimately lead to the answer I'm hoping for, which is a way to write serverToPlayerGS and serverToPlayerEvent in ways that typecheck and are useful.
Answer: The problem is that your type family is not injective: knowing that USHand a is Private for instance doesn't tell you exactly what a is: it could be USSR but it could also be Observer because both instances declare:
type USHand USSR = Private
type USHand Observer = Private

Because the function toUS has type Public -> USHand a, the a has to be somehow guessed and we just saw that it was not possible.
In order to fix this, you are going to need to introduce proxies. A proxy is a simple data type defined as:
data Proxy a = Proxy

If you have a function f :: F a for which Haskell is not able to guess the a, you can turn it into an f :: Proxy a -> F a in order to be able to specify at the call site which a you mean by writing for instance f (Proxy :: Proxy Int) in the case where you want a to be Int.
You'll need scoped type variables because the a you'll use with toUs will come from the type annotation of your function. So you should add these two lines at the top of your file:
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Proxy

And then change the type of toUS from Public -> USHand a to:
toUS :: Proxy a -> Public -> USHand a

Don't forget to add a dummy argument _ to all your instance declarations of toUs. Finally, you can patch your definition of serverToPlayerGS like so:
serverToPlayerGS :: forall a. HandType a => GameState Server -> GameState a
serverToPlayerGS (GameState turn phase bs us ussr) =
  GameState turn phase bs (toUS (Proxy :: Proxy a) us) undefined

Comment: @mindreader, Yes that's the `TypeApplication` extension. It will land in GHC 8, which already has a release candidate available. https://ghc.haskell.org/trac/ghc/wiki/TypeApplication
Comment: That totally works.  Thanks a lot!  Also I heard that a future release of ghc the Proxy type may not be necessary.  Does anyone have any references to any info regarding that?


Elementary Problem: Opposite and Adjacent Seem to Change From Problem to Problem

Question: I've read two or three answers here but I suppose I need the idiots guide with paper and crayons to explain it to me.  I can't seem to tell which is opposite and which is adjacent on each problem.  I assume that adjacent is directly below hypotenuse but apparently not.
Any advice is appreciated.  The attached picture is just one many instances of me getting it wrong.

Here is the logic I have read to use:
Answer: Opposite and adjacent are referenced relative to the angle you are taking the trig value of. Each acute angle is part of a leg (that would be the adjacent side), and across from (not adjacent to) the other leg (that would be the opposite side).
Comment: I still don't understand.  I would post more pictorial examples but the Aleks program I use forced me to change subjects because I got so many incorrect.  Thanks for the time regardless.
Comment: @ArkhamAngel Put your feet at M and look through the interior of the triangle. The triangle's side at your hand is adjacent to the angle you stand at, and the far side is opposite to the angle.
Answer: Let us try this picture:
You stand at a position and place a ladder against a wall.
The ladder you place is the hypotenuse.
The wall you face is the opposite side.
The ground you stand on is the adjacent side.
Apply this to your case:
You stand at M (angle M ) ,you place a ladder ML ( hypotenuse) against a wall NL ( opposite side) and you stand on ground MN(adjacent side).
Then the correct answer follows.
Comment: This clicked. Thanks.
Comment: I though it clicked, but (I think I'm using your steps here) why is this wrong now?  [link](https://imgur.com/a/vYSq8Zj)
Comment: You stand at A, your ladder is AB, the wall is BC, the ground is AB. So, cos A = ground/ladder=15/17.
Comment: Thanks for the time.  Sometimes I wonder why I am so stupid at this stuff. Working on not being consistently stupid..
Comment: You are outreaching for help showing that you are a good student eager to learn. You can check this site https://www.mathsisfun.com/links/d-10up-algebra.html for basic maths topics. A lot on fundamental trigs.  Let me know if you need extra help.
Comment: The answer was in my face the whole time but I have so low confidence that I was assuming I just didn't have the brains to figure it out.  It tells you the angle in the question... just like you alluded to.
Comment: Try the exercises in Mathisfun, it gives you answer and explanation. You can redo many times. This will help you master the tipic and build up confidence.
Answer: I think you're assuming that Opposite and Adjacent have something to do with the short and long sides of a right-triangle.  (i.e. you're assuming something like "Cosine=Long/Hypotenuse" based on the one defined example.)
But actually Opposite/Adjacent are relative terms (like right/left) that depend on which non-right angle is being asked about.  The "Adjacent" side is "the non-Hypotenuse side that touches the Angle" and "Opposite" is "the far side that doesn't touch the Angle".
In your answers, you were essentially giving cosL=40/41, tanL=9/40, and sinL=9/41 instead of the cosM, tanM, and sinM the book was asking for.
Angle "Theta" in the example is Angle "L" in the problem; the problem set is asking about Angle "M".
Comment: How does one determine which side is the Angle?
Comment: OK, the answer was staring right in my face the whole time.. I feel really dumb sometimes.  it's asking to find tanA cosA sinA A is the angle.
Answer: If you're interested in the angle at a vertex $V$ of a right triangle, the adjacent side is the side that goes $V$ to the vertex with the right angle, and the opposite side is the side that goes from the vertex with the right angle to the vertex I haven't mentioned yet.


Linear Regression with dependent variables

Question: I want to create a linear regression model using two variables, var $a$ and var $b$, and the coefficients are $w$ and $(1-w)$ respectively.
So the output dependent variable $Y =  wa + (1-w)b$.
I am not sure how to approach this. Please suggest.
Comment: What in particular are you not sure of?
Answer: The approach is quite simple: algebra. Just to be clear: $w$ meaning weight is the coefficient term to be estimated from regression. Correct?
The linear expression reduces to $$ Y  = w (a-b) + b$$. I am assuming this all has a normal error term or some other rationale for using regression. Anyway, the constant term "b" can be handled with an offset term. And you must create a new variable "c" as "a-b" so that the linear model just adjusts for c and offset(b) and possibly no intercept term.
Answer: @AdamO has the right idea. Your setup can be dramatically simplified with some algebra.
$Y = wA + (1-w)B$
Implies that
$Y = w(A-B) + B$
Which in turn implies
$Y-B = w(A-B)$
Assuming you have some errors in there (and maybe a constant?) you should have:
$Y-B = c + w(A-B) + e$
This regression can be run very simply. In R:
y_less_b = y-b
a_less_b = a-b
mod = lm(y_less_b~a_less_b)
mod_no_constant = lm(y_less_b~a_less_b-1)

And all the summary stats apply.
If you wanted $w \in [0,1]$, and that regression doesn't put it there, then a) rethink whether it needs to be in $[0,1]$, and/or b) project it to the nearest point in that set (either 0 or 1). Broadly speaking, if it belongs in $[0,1]$, its extremely likely to be estimated in that region once you have even a mediocre sample size -- unless your error variance is off the charts.
Answer: Here is a Python 3D fitter using your equation with some test data. This example has a 3D scatter plot, a 3D surface plot, and a contour plot.
import numpy, scipy, scipy.optimize
import matplotlib
from mpl_toolkits.mplot3d import  Axes3D
from matplotlib import cm # to colormap 3D surfaces from blue to red
import matplotlib.pyplot as plt

graphWidth = 800 # units are pixels
graphHeight = 600 # units are pixels

# 3D contour plot lines
numberOfContourLines = 16

def SurfacePlot(func, data, fittedParameters):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)

    matplotlib.pyplot.grid(True)
    axes = Axes3D(f)

    x_data = data[0]
    y_data = data[1]
    z_data = data[2]

    xModel = numpy.linspace(min(x_data), max(x_data), 20)
    yModel = numpy.linspace(min(y_data), max(y_data), 20)
    X, Y = numpy.meshgrid(xModel, yModel)

    Z = func(numpy.array([X, Y]), *fittedParameters)

    axes.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=1, antialiased=True)

    axes.scatter(x_data, y_data, z_data) # show data along with plotted surface

    axes.set_title('Surface Plot (click-drag with mouse)') # add a title for surface plot
    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label
    axes.set_zlabel('Z Data') # Z axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems

def ContourPlot(func, data, fittedParameters):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    x_data = data[0]
    y_data = data[1]
    z_data = data[2]

    xModel = numpy.linspace(min(x_data), max(x_data), 20)
    yModel = numpy.linspace(min(y_data), max(y_data), 20)
    X, Y = numpy.meshgrid(xModel, yModel)

    Z = func(numpy.array([X, Y]), *fittedParameters)

    axes.plot(x_data, y_data, 'o')

    axes.set_title('Contour Plot') # add a title for contour plot
    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    CS = matplotlib.pyplot.contour(X, Y, Z, numberOfContourLines, colors='k')
    matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) # labels for contours

    plt.show()
    plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems

def ScatterPlot(data):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)

    matplotlib.pyplot.grid(True)
    axes = Axes3D(f)
    x_data = data[0]
    y_data = data[1]
    z_data = data[2]

    axes.scatter(x_data, y_data, z_data)

    axes.set_title('Scatter Plot (click-drag with mouse)')
    axes.set_xlabel('X Data')
    axes.set_ylabel('Y Data')
    axes.set_zlabel('Z Data')

    plt.show()
    plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems

def func(data, w):
    a = data[0]
    b = data[1]
    return w*a + (1-w)*b

if __name__ == "__main__":
    xData = numpy.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
    yData = numpy.array([11.0, 12.1, 13.0, 14.1, 15.0, 16.1, 17.0, 18.1, 90.0])
    zData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.0, 9.9])

    data = [xData, yData, zData]

    initialParameters = [1.0] # same as scipy default values in this example

    # here a non-linear surface fit is made with scipy's curve_fit()
    fittedParameters, pcov = scipy.optimize.curve_fit(func, [xData, yData], zData, p0 = initialParameters)

    ScatterPlot(data)
    SurfacePlot(func, data, fittedParameters)
    ContourPlot(func, data, fittedParameters)

    print('fitted prameters', fittedParameters)

    modelPredictions = func(data, *fittedParameters)

    absError = modelPredictions - zData

    SE = numpy.square(absError) # squared errors
    MSE = numpy.mean(SE) # mean squared errors
    RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
    Rsquared = 1.0 - (numpy.var(absError) / numpy.var(zData))
    print('RMSE:', RMSE)
    print('R-squared:', Rsquared)


Remote Drush Commands Not Found

Question: I'm using a new host for my website and I requested drush access to my site. They said it's all set and told me to run drush commands as such $ ../drush/drush command
I test it out with $ ../drush/drush status and everything works as it should.
The problem comes when I try to run drush commands remotely via my alias file. Everytime time I drush @remote I get drush: not found
I even set path-aliases to point specifically at %drush and %drush-script.
Is there something I'm missing?
Answer: If you use, '%path-aliases', either specify the full path to Drush, or ensure that the Drush that you are calling (e.g. drush) is on your PATH.
Example:
$aliases["mysite"] = array (
  'uri' => 'mysite.org',
  'root' => '/path/to/drupalroot',
  'remote-host' => 'myisp.com',
  'remote-user' => 'www-admin',
  'path-aliases' =>
  array (
    '%drush-script' => '/home/myuser/drush/drush',
  ),
);

If setting the PATH in your .bashrc, always do so at the very top of the file.  It is common for boilerplate (host-provided) .bashrc files to have a line somewhere in the middle that exits prematurely when not in interactive mode -- and Drush makes remote Drush calls non-interactively in most instances.

Remote Drush Commands Not Found


Football score swapping: is it ok?

Question: I'm developing a football application. A two-legged tie looks like this:
TeamA  1:0  TeamB
TeamB  4:2  TeamA
<sum of goals 3:4, sum of wins 1:1, winner TeamB>

Is it easy to understand? The sum is actually calculated diagonally, and the order of sums corresponds to the first leg (match).
May I rearrange all this so that it would be understandable and correct? May I fold the first two lines like following?
TeamA 1:0, 2:4 TeamB

Or it is untraditional and weird to swap the score this way?
There may be objections that this question should be moved to User Experience site, but the question is more about how is right, rather than how is more convenient.
Comment: Someone must have had that problem before. Did you check [what they came up with](http://en.wikipedia.org/wiki/2014%E2%80%9315_UEFA_Champions_League#First_qualifying_round)?
Comment: Before reading the last note I was about to suggest you to post on UX.SE.
Answer: What's important isn't the format per se; it could pretty much be formatted anyway you see fit (that is, with regards to design and user-friendliness). The way I see it, you can do it anyway you want - just as long as it's clear which team was the home team in each game.
You probably already know this, but for a reader who's new to football; the two-legged tie is often determined on the number of away goals, when each team has won one game each and the goal difference is the same. This makes it very important that it is clear which team was the home (and away-) team in each game.
Apart from that, you should simply find a good looking way of presenting the scores :)

Football score swapping: is it ok?


Informatica. How to reject whole source file if source and target have duplicates

Question: I have a mapping which compares target with source. In expression there is a condition which checks if there are duplicates. How can I stop whole data flow if condition returns true? DD_Reject does not work as it only rejects one record.
Comment: Does this help? https://network.informatica.com/thread/6853
Comment: do you want to stop the whole flow if source has duplicates ? Or you want to reject duplicated data and process rest? or you dont want to process any data if it exists in both source and target
Answer: To stop the flow use the available Expression Transformation ABORT function. This will NOT rollback the already process rows though. If you need that as well, then two sessions will be needed, one to check the duplicates, another to perform the actual load, linked with SUCCEEDED condition.
Start -> s_check_duplicates -succeeded-> s_load_data


Cannot start NFS: Not starting NFS kernel daemon: no support in current kernel

Question: I installed NFS on a new Debian7 install. I did:
apt-get install nfs-kernel-server

add folder to share to /etc/exports: /home/share *(rw,sync,no_root_squash)
service nfs-kernel-server start

But after this I get this error:
[warn] Not starting NFS kernel daemon: no support in current kernel. ... (warning).

I googled for this, but didn't find the solution yet. Some say the check /proc/config.gz, but I haven't this file in /proc
Comment: Please provide the output of `uname -a`.
Comment: uname -a gives: Linux h2523591.stratoserver.net 3.2.41-042stab111.12 #1 SMP Thu Sep 17 11:38:20 MSK 2015 i686 GNU/Linux
Answer: Maybe the NFS module is not loaded. Try modprobe nfs and restart the nfs service.
Comment: Tried modprobe nfs, but get this error: libkmod: ERROR ../libkmod/libkmod.c:554 kmod_search_moddep: could not open moddep file '/lib/modules/3.2.41-042stab111.12/modules.dep.bin'
Comment: Your kernel modules directory seems to have some problem. Try `depmod -a`, then retry with `modprobe nfs`
Comment: depmod -a gives: ERROR: could not open directory /lib/modules/3.2.41-042stab111.12: No such file or directory
FATAL: could not search modules: No such file or directory
Comment: You had serious problems with your installed kernel. Try to uninstall and reinstall it via `apt-get`
Answer: In addition to the answer of shodanshok and the comments:

It seems your hosting provider removed the nfs modules in the version you've installed. Maybe they want to prevent that users exporting "by accident" their / or /home to the public internet.
Not sure if this is a dedicated, virtualized or containerized server and if you're able to switch to / install a different kernel: If so, install a vanilla Debian kernel, otherwise, speak to the support of your hoster.
Comment: it is a vps. Maybe better try with samba, I thought nfs was simple, but for me costs me too much time and fustration. Thanks for help!


0/0 time signature?

Question: In a piece my brother is playing there's a weird time signature - it looks like a zero over a zero: a 0/0 time signature. It seems that the bars have 5/4 in them (probably not 10/8, but could be as far as I'm concerned). It is stated that the bars are played in tempo rubato.
Any idea what it is?

Adding a similar example...
Answer: 0/0 time signature can be used to denote free time, with an irregular number of beats per bar.   A large X as time signature is also sometimes used.
Comment: I have seen "senza misura" to indicate that also.

0/0 time signature?


Como criar uma expressão Lambda com Group by e Order By

Question: Estou com problemas em criar um sentença Lambda com Group by e Order By Juntos.
Como agrupo pela coluna Escopo e IDEscopo, e ordenar pelo IDEscopo.
Segue Sentença.
 public static List<Escopos> EscoposCalCliente(int IDCalCLiente)
        {
            using (entidadesIUS entidades = new entidadesIUS())
            {
                return entidades.Escopos.Where(e => e.CALClientes.Any(cc => cc.IDCALCliente == IDCalCLiente)).
                ToList().
                GroupBy(es => new {.IDEscopo, es.IDEscopo }).
                SelectMany(esc => esc.OrderBy(escp => escp.IDEscopo));
            }
        }

Answer: Não vejo necessidade no seu exemplo de usar GroupBy e OrderBy. Apenas o OrderBy faz todo o trabalho.
    public static List<Escopos> EscoposCalCliente(int IDCalCLiente)
    {
        using (entidadesIUS entidades = new entidadesIUS())
        {
            return entidades.Escopos
                .Where(e => e.CALClientes.Any(cc => cc.IDCALCliente == IDCalCLiente))
                .OrderBy(es => es.IDEscopo)
                .ToList();
        }
    }


Differences in SVM performance

Question: Why would a polynomial SVM have better performance than a linear SVM but the same performance as a radial SVM?
Answer: If the performance with a linear kernel is bad, it means the data is not separable in input space (assuming a classication context). The feature spaces induced by more complex kernels (such as polynomial or RBF) can lead to linear separability.
The feature space of an RBF kernel is more complex than both linear and polynomial (in fact, both linear and degree-2 polynomial are degenerate versions of RBF). Hence, if a polynomial kernel can make the data separable, an appropriate RBF kernel can too.
Comment: I agree with this nice answer by Marc.

Differences in SVM performance


how to add namespace to route file using custom generators

Question: I am generating certains controllers using rails generators, it is working as expected.
However, how can i add namespace based routes in my route file
something like

  namespace :api do
    namespace :v1 do
     get resource_one, to: resource_one_index
     get resource_two, to: resource_two_index
    end
  end

I see the following in the documenation under the route section route "resources :people" but i am not sure how to add namespace routing.
Thanks.
Comment: `route "resources :people", namespace: 'api/v1'` maybe? I'm not sure the method can handle more then one level of block nesting though. https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-route
Answer: route "resources :people", namespace: ["api", "v1"]

from your generator leads to result:
route  namespace :api do
            namespace :v1 do
              resources :people
            end
          end

(at least for Rails 7)


Use keywords from dataframe to detect if any present in another dataframe or string

Question: I have two problems: First is...
I have one dataframe with category and keywords like this:
  Category                   Keywords
0    Fruit            ['apple', 'pear', 'plum', 'grape']
1    Color            ['red', 'purple', 'green']

Another dataframe like this:
              Summary
0        This is a basket of red apples. They are sour.
1        We found a bushel of fruit. They are red.
2        There is a peck of pears that taste sweet.
3        We have a box of plums.

I want the end result like this:
      Category                                            Summary
0    Fruit, Color     This is a basket of red apples. They are sour.
1           Color     We found a bushel of fruit. They are red.
2    Fruit, Color     There is a peck of green pears that taste sweet.
3           Fruit     We have a box of plums.

Second is...
I should be able to check if a string contains any of the keywords, and if true then output a list of appropriate categories.
Example:  sample_sentence = "This line contains a red plum?"
output:
result_list = ['color','Fruit']

EDIT: Its kind of similar but not same.Use this for reference: How do I assign categories in a dataframe if they contain any element from another dataframe?
EDIT2:
I also have another version of first dataframe like this:
  Category                   Filters
0    Fruit  apple, pear, plum, grape
1    Color        red, purple, green

Answer: You can use list comprehension to achieve this:
Dataframe set-up:
df1 = pd.DataFrame({'Category': {0: 'Fruit', 1: 'Color'},
 'Keywords': {0: 'apple,pear,plum,grape', 1: 'red,purple,green'}})
df2 = pd.DataFrame({'Summary': {0: 'This is a basket of red apples. They are sour.',
  1: 'We found a bushel of fruit. They are red.',
  2: 'There is a peck of pears that taste sweet.',
  3: 'We have a box of plums.'}})
df1['Keywords'] = df1['Keywords'].str.split(',')

Code:
df2['Category'] = (df2['Summary'].str.split(' ').apply(
    lambda x: list(set([str(a) for y in
                        x for a,b in
                        zip(df1['Category'], df1['Keywords']) for c in
                        b if str(c) in #Or you can use: "if str(c) == str(y)" or "if str(c).lower() == str(y).lower()"
                        str(y)]))).str.join(', '))
df2

Output:
Out[1]:
                                          Summary      Category
0  This is a basket of red apples. They are sour.  Fruit, Color
1       We found a bushel of fruit. They are red.         Color
2      There is a peck of pears that taste sweet.         Fruit
3                         We have a box of plums.         Fruit

a, b and x iterate through rows (vertically). c and y iterate through lists within rows (horizontally). In order to start iterating through lists horizontally, you first need to iterate through rows vertically. That is why we have all of these variables (see image). You can use zip to simultaneously iterate through two or more columns of the first dataframe.
Comment: Thanks a lot for your effort @David. Your explanation with the image clarifies a everything.
Comment: Thanks for the quick response @David Erickson. I am getting the following error: "'float' object is not iterable" I am pretty sure I don't have any float values in my data.
Comment: I have updated my question with another version of first dataframe to make things easier.
Comment: @Brussel I threw str in front of everything. I would guess you have an integer somewhere in your sentence column.
Comment: Mistake was on my side. I rectified the float problem. Thanks a lot for the solution David. You made my day. It would be much helpful if you could give more explanation for your solution so anybody with similar problem can tailor your solution to their problem. Also I see that your solution matches substring, a whole word match would be awesome.
Comment: @Brussel it matches substring because keyword is Apple and word in sentence is apples. I'll try to add more explanation later.
Comment: @Brussel you can just change this part of the code: `if str(c) in str(y)` to `if str(c) == str(y)`. That looks for a direct match. You can also match case insensitively with: `if str(c).lower() == str(y).lower()`


Python's Pytest.mark equivalent for non-test code

Question: The Pytest testing framework has this nice feature, where you can mark tests with certain attributes, for example:
import pytest
@pytest.mark.webtest
def test_startup():
   pass

Then, using the pytest command line, you can preform actions only on functions/tests with certain marking:
i.e: pytest -m webtest will only run webtest marked code. There are also command line to query all the tests with certain marker, etc.
My question is, is there an equivalent library which does this for just regular code? For example:
@mark.refactor
def foo():
   pass

# Or #
@mark.todo("Specifying a todo comment which can be grammatically queried later")
def bar():
   pass

Then I could run a command line or script to get all the functions marked todo or refactor and get their info.
I tried to look online but couldn't find any matching libraries for this use case.
Thanks.
Comment: Is there a functionality you want that couldn't be covered by something simple like using comments and `grep`?
Comment: I could use grep and mark functions using comments, but: A. it is not platform agnostic, B. hard to add metadata to the results (line number, function name, commiter, filename, last modified etc')
Comment: regarding running only tests with a specific marker, the Django framework has a `tag` decorator (https://docs.djangoproject.com/en/stable/topics/testing/tools/#tagging-tests) but you probably wouldn't want to use a complete framework just for this functionality...
Answer: After I couldn't find any answers, A buddy of mine wrote a python library that achieves this.
It is available here on github.
For example:
@marker.todo("still need to figure this out")
def func():
    print("hello world")

@marker.known_issue
def func2():
    print("hello world")


Restarting without a teacher

Question: A couple of years ago, I stopped practicing the piano due to school and other commitments. At that stage, I had recently passed my ABRSM grade 5 and grade 5 theory, and was starting to practice a couple of grade 6 pieces.
I've managed to get a digital piano for my house next year, so I will be able to play again. However, I still don't think I will have time for lessons.
Do you think I will be able to make reasonable progress without a teacher? I can still read music fairly well, still have good coordination of my hands, and can still play most of the pieces that I could back in the day.
What would be my best way forward without a teacher?
Thanks
Comment: You really want a teacher for piano, there are real concerns if you start practicing wrong technique.
Comment: Are you sure you wouldn't be able to take some intensive courses, maybe just e.g. 4 weeks in a roll a year? Having a teacher surely helps! Then just one thing concerning the articulation: record yourself, replay the recordings, compare to some professional (or even good youtuber) recordings of the pieces.
Answer: I stopped playing piano at about the same stage as you (Grade 5) when I was a teenager and had lots of exam stress. I went back to it about ten years later without a teacher and it's one of the best things I've ever done. It was wonderful just to play again, but the freedom of being able to play whatever I liked and know I was doing it just for my own enjoyment completely changed my attitude to music. I now play more difficult pieces far more proficiently, compose my own music, and most importantly enjoy playing in a way I never did when I had a teacher breathing down my neck.
By contrast, my brother gave up the violin at about the same time as me, and similarly went back to it about a decade later. He went to a teacher, but the new teacher was so unpleasant that the experience put him off ever playing again.
On the other hand, if you're focused on making progress, particularly if you mean that in the sense of taking more grades, then a good teacher will almost certainly help, and if you have any worries about where to start or getting into bad habits then a few refresher lessons might not be a bad idea. I found that I was very rusty at first, but after a few weeks of playing everything just sort of clicked and my fingers remembered what they were doing.
The lack of a teacher has certainly led me into bad habits, particularly in the way I practice. I play what I like, and what I feel like, whenever I like, for as long (or as short) as I like, just to enjoy playing it and without a particular focus on improving my technique, which is a terrible attitude to have ;)
My general advice to most people in most situations is (quite hypocritically) to get a good teacher, but time and money are often in short supply, and sometimes good teachers aren't all that easy to find either. I wouldn't advise a beginner to try to learn without a teacher, but grade 5 is a reasonable level of proficiency, and with grade 5 theory you should be able to read just about any music and understand the basics of harmony. The most important thing is to get back to playing, and enjoying, music in whatever way fits in with your life now.
The best way to go about it depends very much on you. I started off by going back through my old exam pieces and then picking up music I liked in second hand shops. Finding music to play is so much easier now with so much of the classical repertoire available for free on imslp. You can try to approach things systematically and identify your strengths and weaknesses, or you can just play what you like. I worked my way through Czerny, but then I like etudes. The trickiest thing I found was identifying music that was sufficiently challenging to be rewarding without being too difficult and time-consuming to tackle. The biggest revelation I had was when I realised that the music I enjoyed playing wasn't the music I liked listening to.
Good luck, and do yourself a favour: ditch that digital for an acoustic the first chance you get!
Comment: Thanks for all the pointers! I was thinking of using my old grade books as a starting place for getting back into it. I'm going to get in contact with my old teacher who was brilliant but unfortunately doesn't teach any more, and see if he can help me with a practice routine/schedule.

I do have an acoustic at home but my student accommodation at university is pretty tight on space, so I'll have to stick to the digital for now!
Answer: It depends on your goals. If you're planning to do ABRSM theory and piano practical exams again (eg. Grade 6, 7 and 8), it's more ideal to have a teacher to give you feedback about what areas you need to improve on. Having said that, it is possible to make a reasonable progress without having frequent lessons from a teacher. So if you're planning to do ABRSM, you can learn by yourself , but I stressed the importance of having a teacher to give you some feedback. But if you're restarting because it's a hobby, there are many ways you can progress without a teacher.
When it comes to learning both the piano and music theory by yourself, the best way forward is finding detailed resources that suit your needs and goals. I can't stress this enough because when you are learning music by yourself, there isn't anyone to guide you. Thus, you have to hunt for good resources to ensure that you are learning the correct techniques, and that you are learning efficiently.
There are 3 main resources for any self-learners today - Books, Online learning tools, and Music streaming. The best way to teach yourself piano is to gather the best resources available and make full use of them.
1. Books
There are many different books on piano techniques out there, but check out Czerny's etudes and exercises.
2. Online learning tools
With today's advanced technology, we can now learn music from the comfort of our homes. There are many tutorial videos and online schools that provide quality music lessons for self-learners like yourself.
3. Music Streaming
One part of learning music that we tend to overlook is exposing ourselves to different music genres. With Youtube and Spotify so readily available, you can listen to most music genres that you enjoy listening to. So be sure to listen to different genres written by various composers - who knows, you might even feel inspired to play music from a genre that you never even thought of!
And of course, be ready to work smart and hard, and really make time for piano practices and theory.
Answer: First you need to realize that Grade 6 - Grade 8 piano is equivalent to a Music Degree minus some subjects in solfege singing, composing, ethnic instruments and software usage.
The focus of playing Grade 6 pieces (or beyond) is to achieve what the composer had intended when he composed the piece. In order to do that, one will need to have a good grasp of the style of a given composer through listening to recordings, study the history and life of the composer and apply techniques that highlights the mood of the piece.
For example, when playing a Debussy piece, the control of pedal and the touch are quintessential to get the dreamy and floating effect. One cannot apply the same techniques when playing a Chopin waltz obviously. (A teacher's guidance is crucial at this stage, techniques and stylistic performance is not something that one can learn by him/herself.)
So as you can see, there is a vast gap of standard between Grade 5 and Grade 6 given the amount of time that you have to invest in researching in order to play well (much like an assignment) and you will also need to take into account the time you'll need to practice.
In terms of timing, I think now is not the best time to pursue your piano in the sense of advancing to ABRSM Grade 6. It will be like studying for a double degree - way too demanding and stressful. Instead, focus in your academic and take your time to work on improving your theory, analyzing pieces, finger strengths and agility.
P.S: Liberty Park had given some great suggestions that you should consider.

Restarting without a teacher


Get number of results from Search Action on Zapier

Question: I build zap using zapier, which performs "Find Person" Action on Pipedrive crm (the question is relevant to search in any integration)
The result returned from the search is a single object. (Contrary to what might be expected - an array of objects)
My goal is to know how many records returned from the search (I mean the list length actually), and use that information to perform various actions later in the Zap.
How can this be done?
how my zap currently looks
Thanks
Answer: Zapier searches are designed to resolve a piece of info (like an email) into a single record from an external service (like a "Contact"), so it's working as expected here.
I'm not sure the official integration will return the data you want here, but you can write a custom integration that has an action like "Count People Matching Search", which could return that data for you.
There's info about building a custom integration here: https://platform.zapier.com/


How to make a child divs wider than the scrollable parent

Question: I am trying to make a child div overflowing the parent div.  But the parent div needs to be scrollable.
See here: https://jsfiddle.net/20o4uysj/2/
<code>.container {
  width: 200px;
  border: 1px solid #d8d8d8;
  border-radius: 6px;
  height: 250px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 20px;
}

.extended {
  background: #f7f7f7;
  border: 1px solid #d8d8d8;
  border-radius: 4px;
  padding: 10px;
  width: 400px;
}
</code>
This is what I am trying to get:

It seems to be a though mission.
Haven't found any solution for this issue.
Comment: I don't think you can get exactly that (where the parent div keeps the same width throughout) using only HTML/CSS. Is a bit of Javascript acceptable?
Answer: If you want to use the normal flow then the answer of jeremy-denis is correct.
But you'll see that when you add a position: absolute; at your extended class that it will create the look you want. It allows for the element to flow outside of it's parent because it's taken out of the regular flow. Of course this means the rest of the flow of the other elements along with their positions get messed up as well.
Then that problem you could fix with Javascript but it will probably be a pain in the butt!
Answer: unfortunately like your container have an overflow-y : auto it's not possible
the spec implementation don't allow to have an overflow-x visible in addition to an overflow-y auto or scroll
see more details here
CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue


how to switch from light to dark theme in ipyvuetify?

Question: I'm using ipyvuetify in a Jupyter Python environment to create an interactive dashboard for my end-user.
I would like to create an interactive toogle btn that switch vuitify.theme.dark from True to False
When I test this behaviour in voila with the following code :
import ipyvuetify as v

v.theme.dark = True

#validate the selected data
v.Container(children=[
    v.Btn(color='primary', children=[
        v.Icon(left=True, children=[
            'mdi-square'
        ]),
        'Click me'
    ])
])

Only the surrounding of the Btn component have a dark background, the rest of the page keeps the voila light background.
A trick could be to add the ?voila-theme=dark at the end of my url but then it's not dynamic anymore.
Is there a way to change both the voila and ipyvuetify theme ? or to force the ipyvuetify background to occupy all the screen ?
Comment: There is a related [open issue](https://github.com/voila-dashboards/voila/issues/464) on Voilà project, unfortunately without update since its opening in Nov 2019.
Comment: the issue has not been closed but the solution have been implemented: if you add "voila-theme=dark" as an option in your url then the theme is changed
Comment: Maybe this issue does not exist when using the [voila-vuetify](https://github.com/voila-dashboards/voila-vuetify) template. Although it seems to be broken [recently](https://github.com/voila-dashboards/voila-vuetify/issues/43), so I could not try it.
Answer: Changing the body background color
With Voilà (default) lab template, the background surrounding the ipyvuetify application appears to be the HTML body background, so a workaround is to apply the background color of the ipyvuetify theme to the body background. Ipyvuetify-v.1.6.2 background colors are #fff in the light theme and #121212 in the dark theme (from vuetify.min.css-v2.2.26).
The background color can be modified by adding an internal CSS in an HTML


Passivity of a dynamical system

Question: Let a dynamical system , in particular a RLC circuit. I want to study the passivity of this.
In general the notion of $\textbf{passivity}$ comes out form the statics physics for which by a mathematical point of view it can be said that a static system $y=h(t,u)$ is said to be passive if $u^Ty\geq 0$ (for instance let a resistor and let $u=V$, $y=I$, it is passive since $VI\geq 0$).
Now it is possible to extend the notion of passivity to the dynamical system in the sense that follows with an example:
let a RLC circuit for which the energy absorbed by
the network over any period of time $[0, t]$ such that is greater than or equal to the change in
the energy stored in the network over the same period; that is,
$$\int_{0}^{t}u(s)y(s)ds\geq V(x(t)-V(x(0))$$ where $V(x)=\frac{1}{2}Lx_1^2+\frac{1}{2}Cx_2^2=\text{Total energy stored in the network}$, with $x_1=I_L$ and $x_2=V_C$.
My book indicates that the inequality above it is a matter of passitivity in the sense that this is due by the fact that the total energy stored by the network is greater than the variation of this in the period $[0,t]$.
$\textbf{My problems:}$
$1)$ It is true to think about the term $\int_{0}^{t}u(s)y(s)ds$ (that is the integral of the power flows the network over the period $[0,t]$) $\textit{equal to the energy stored in this period}$?
$2)$I can't understand the fact that the total energy stored by the network is greater than the variation of this in the period $[0,t]$ indicates dissipation of energy.
Can you help me please?
Answer: I'll answer the questions first and proceed to my explanations after.

The integral term tells you how much work you perform on the system. In principle, if there are no losses of any sort, then this is precisely equal to the change in the system's energy. Of course, energy is relative. You can always view $E(0)$ has being no energy stored and then you could view that integral as the amount of energy the system stores over that period.

Briefly, the integral tells you exactly how much energy you've put into the system. If the constraint $$V(t) - V(0) \leq \int_{0}^{t} u(s) y(s)\,ds$$ is satisfied, it is telling you that the system is not going to magically increase in energy greater than the amount you are applying. That is, you can strictly bound the growth of the system's energy using your input and, in particular, force it to decrease if you like!

It helps to consider a physical example. Consider the position of a particle $x(t) \in \mathbb{R}^3$ with mass $M$ and velocity $v(t) \in \mathbb{R}^3.$ We will take the output of the system to be $y(t):= v(t).$ The energy of the cart (there is no potential energy here) is $$E(t) = \frac{1}{2} M v(t)\cdot v(t) = \frac{1}{2} M y(t)\cdot y(t).$$ Suppose we could apply an input force $u(t) \in \mathbb{R}^3.$
In this case, with no potential energy, we know that the work is the change in kinetic energy. The work induced by the applied force $u(t)$ is the integral of the applied force inner producted with the velocity. That is, $$W(t) = \int_{0}^{t} u(t) \cdot v(t)\,dt = \int_{0}^{t} u(t) \cdot y(t)\,dt.$$ As discussed, we have that the change in kinetic energy is the work (because of a lack of potential energy) so we get the relation $$E(t) - E(0) = W(t) = \int_{0}^{t} u(t) \cdot y(t)\,dt.$$
The kinetic energy is energy the object we wish to control has (the particle) that is "stored" in the sense that the system has energy it can lose. What happens if there is friction or some other force that "steals" energy from the system? We must have $$E(t) - E(0) \leq W(t) = \int_{0}^{t} u(t) \cdot y(t)\,dt.$$
Why? Suppose we did positive work $W(t) > 0$ over this period. This would be equivalent to adding energy into the system, such as adding force in the direction of motion making the particle move faster. If it was the case that $E(t) - E(0) < W(t)$ then somehow, although we added some $W(t)$ amount of energy, we don't see it in $E(t),$ implying some was stolen through losses. You can see a similar argument in the case $W(t) < 0.$
Of course, if you do satisfy the equality (as in the above example), you of course don't have any internal losses but it still is a useful property for a system to have. It implies that you can essentially determine how much the energy the system gains or loses by your input $u(t).$
Back to your example, the question you must ask yourself --- if you seek the intuition --- is what is the work in a circuit? We have that power $P(t)$ is the derivative of the work, $$P(t) = \frac{dW}{dt}(t).$$ We know the instantaneous power of an ideal linear circuit is $$P(t) = I(t) V(t)$$ where $I(t)$ and $V(t)$ are the instantaneous current and voltage respectively measured from the single input to the single output. Solve for $W(t),$ $$W(t) = \int_{0}^{t} I(t) V(t)\,dt = \int_{0}^{t} u(t) y(t)\,dt$$ and we have that the change in energy, the work, is the integral in question!
Hope this helps.
Comment: Wonderful! Last question: I am not english mother toungue so I am not sure that I have undestrood completely athe meaning of a term...the integral representes the "stored" energy by the circuit, does it means energy $\textbf{accumulated}$ by the circuit?
Comment: The integral represents the net work put into the circuit over a period. So yes, I believe accumulated is accurate.
Comment: Thanks a lot again! You have clarified all my doubts in an excellent way!

Passivity of a dynamical system


Absolute value of integral

Question: I think it is well know that
$$\left|\int f \right| \leq \int\left| f\right|$$
for some complex valued function $f$. This is normaly proven by writting it as an complex exponent, but can it be proven using only the fact that the integral is positive (i.e. positive functions give positive integrals)?
Answer: Maybe prove more generally: if $\|\cdot\|$ is a norm on $\mathbb R^n$, then
$$
\left\|\int_X f(x)\,d\mu(x)\right\|\le \int_X\|f(x)\|\,d\mu(x)
$$
where $f \colon X \to \mathbb R^n$ is $\mu$-measurable.
Of course you do not use "complex exponent" to do it.

Absolute value of integral


Spivak, Chapter 10, "Differentiation", problem 9: Rate of change of distance between moving particles. Is the solution manual solution incorrect?

Question: Spivak, Chapter 10, "Differentiation", problem 9.

Particle A moves along the positive horizontal axis, and particle B along the graph of $f(x)=-\sqrt{3}x, x \leq 0$. At a certain time, A
is at the point (5,0) and moving with speed 3 units/sec; and B is at a
distance of 3 units from the origin and moving with speed 4 units/sec.
At what rate is the distance between A and B changing?

The solution I came up with is similar to the solution manual solution, but it seems we disagree on certain signs which leads to different results. My result is that the distance is changing at a rate of $-\frac{5}{14}$ units/sec (ie it is decreasing), and the solution manual says the distance is increasing at $\frac{83}{14}$ units/sec.
Given that the vertical distance is certainly decreasing, and that since horizontally both particles are moving to the right the relative speed must be smaller than 3 units/second, it seems to me that the result $\frac{83}{14} \approx 5.92$ units/sec is incorrect.
Here is my solution
Everything in this problem is analyzed at a single point in time. The variables below are all functions of time, though I will omit the time parameter.

Initial Position of Particle B
$$D_{BO}^2=x_B^2+y_B^2$$
$$y_B=-\sqrt{3}x_B$$
$$D_{BO}^2=x_B^2+3x_B^2=4x_B^2\tag{1}$$
$$9=4x_B^2$$
$$x_B=\frac{3}{2}$$
$$\implies y_B=-\frac{3\sqrt{3}}{2}$$
Rates of Change of B's Coordinates
$$y_B(t)=-\sqrt{3}x_B(t)$$
$$y_B'=-\sqrt{3}x_B'$$
Here is a tricky part regarding signs. If we take the square root of $(1)$ then
$$D_{BO}=2x_B\tag{2}$$
Note that $D_{BO}$ is a distance, so it must be positive. $x_B$ on the other hand is actually negative. But $(2)$ is actually incorrect, it should be
$$D_{BO}=2|x_B|$$
$$=\begin{cases} -2x_B, x_B<0 \\ 2x_B, x_B \geq 0 \end{cases}$$
But in our single point in time we are in a situation where $x_B<0$. In this scenario, we have
$$D_{BO}'=-2x_B'$$
Note that $D_{BO}'=-4$ because particle B is moving towards the origin.
$$-4=-2x_B'$$
$$x_B'=2$$
$$\implies y_B=-2\sqrt{3}$$
These derivatives make sense: $x_B$ is increasing from a negative value towards $0$, and $y_B$ is decreasing from a positive value.
Rate of Change of Distance Between the Two Particles
$$D = \sqrt{y_B^2+(x_A-x_B)^2}$$
Note that since $x_B$ is negative, I am subtracting from $x_A$ to get difference in x-coordinate between the particles.
$$D'=\frac{y_By_B'+(x_A-x_B)(x_A'-x_B')}{\sqrt{y_B^2+(x_A-x_B)^2}}$$
We have the values of all these variables at the time we are considering. If we plug them in we get
$$D'=-\frac{5}{14}$$
Thus the distance between the particles is decreasing at a rate of $\frac{5}{14}$ units/sec.
Is this correct (ie is the solution manual wrong?)
Comment: "Particle B moves along the graph, $f(x)=-\sqrt{3}x, x \leq 0
$". I don't know why you chose the direction of $B$ to be towards the origin, but in my understanding, the initial position of $B$ is at the origin and it is moving away from the origin along the curve, $f$. So, your $D'_{BO}$ should be positive while $x'_{B}$ will be negative.
Comment: You can save a great many steps by exploiting the fact that the line meets the $y$ axis at an angle of $\frac \pi 6$, so that cosine law for the triangle takes the form..

$$ D^2 = a^2+b^2+ ab $$
Answer: The solution is not incorrect, it merely assumes that B is moving northwest, not southeast.


What is meant by "Define a relation"?

Question: In my book

Ques. Let A= {1,2,3}, B= {2,3,4}. Define a relation R from A to B by R= {(a,b) : b= a+1}.
  i) Write R in roster form.
  ii) Write domain, range, codomain.

Answer is given as-

Ans. i) R= {(1,2), (2,3), (3,4)}
  ii) Domain = A, Range= B, Codomain= B

I am confusion by "Define a relation R from A to B..."
Y1. Is this asking us to define relation R? Then how do we define relation R (because it already is defined in the question as R= {(a,b) : b= a+1} ).
Y2. Or is it a way to say " Defined is a relation R from A to B by R= {(a,b) : b= a+1}"?
If Y2 is correct, then why do we use this language "Define a relation" instead of "Defined is a relation R from A to B" or "Relation R is defined from A to B"?
Thanks for your help
Comment: "Define a relation ... by" in math terminology means "We are telling you that the definition of the relation ... is."
Comment: @steve "Define relation R" sounds like they are asking us to define relation R.
Answer: When a book or problem says "Define relation R by..." followed by a description of the relation, what is meant is "Consider the relation R which is defined as follows:...".
The question is not asking you to define a relation, it is telling you "This is the relation we are concerned with." So your Y2 is the correct interpretation.
You can quibble a bit with the use of the imperative case ("Define R" rather than saying
"Let R be a relation defined by" but you must admit that the second way of saying it is more wordy.
Comment: In a way, the author is telling you to define $R$, but is telling you exactly how to do it, so that you and the author are "on the same page," so to speak, later. Other mathematical language for this same thing are "Let $R$ be the relation defined by ..." or "Suppose $R = \dots$. I can see how "Define" sounds more like an instruction than the others, but you get used to it.
Comment: "Let R be ..." is imperative also.
Comment: Thanks. That "Define relation R" kept confusing me, I thought it is asking to define R (which is already defined, so how do we even define again? Lol). Thanks for your answer. You made it very clear. Thanks.
Comment: @steve Why is the author telling us to define R when they define it afterwards themselves?
Comment: It's just the way mathematics is traditionally written, that's all.
Answer: Technically they are asking you to define it, but they are also telling you exactly how (by giving you an explicit description). Mathematical texts can read like recipes: "Define this thing. Put the things you have together in that way. Observe the result."
The idea of phrasing it this way is that when someone has found an argument that allows them to reach some conclusion, they want to share their argument with the rest of the world. So they write up the steps, and you are supposed go through it on your own and verify that you get the same result they do by following their "recipe" (also known as a "proof"). And after that, it's only natural that exercises adopt a very similar language to full proofs.
Comment: *"technically they are asking you to define it, but they are telling you exactly how"* then how do you define it again when they have already defined the relation? Like in the main question, R is already defined as R = {(a,b) : b =a+1)}, so how to define R again?
Comment: There is no "again". Think of a step in a baking recipe: "Add egg whites by cracking the eggs one by one, separating the yolk from the white and storing it into the batter carefully" They are not telling you to first add the egg whites, and then crack eggs to make more egg whites and then add those too. They are telling you to add whites, then they explain how the whites are to be produced and added.
Comment: It's the same here. "Define a relation $R$ by $R=\{(a,b):b=a+1\}$" is not first telling you to define a relation $R$, then telling you that there is a second relation called $R$ with pairs $(1,2), (2,3)$ and $(3,4)$. It's telling you to define a relation, that the relation is to be called $R$, and then it tells you what exactly that relation is supposed to be (namely the relation with the pairs listed above).
Comment: @AneSa They aren't defining it. They are telling _you_ to define it, and then they are telling you _how_ you should define it / what you should define it as.

What is meant by "Define a relation"?


Proper subfield in algebraic closed field of finite field

Question: Let $p$ be a prime number and $\mathbb{F}_{p^n}$ denote the finite field with $p^n$ elements. Note that $\overline{\mathbb{F}_p} = \cup_{n\geq 1}\mathbb{F}_{p^n}$ is the algebraic closed field of $\mathbb{F}_p$.
I am wondering if every proper sub-field of $\overline{\mathbb{F}_p}$ is finite.
Comment: Well, @Cpc , as long as both formulas give you an algebraically closed field, the two formulas are equivalent. I don't think that OP meant for "$\Bbb F_{p^n}$" to be a particular, chosen finite field.
Comment: Your main question was already answered. But I want to point out that forming that union is a little bit problematic. For example, if $\Bbb{F}_4=\Bbb{F}_2[x]/\langle x^2+x+1\rangle$ and $\Bbb{F}_8=\Bbb{F}_2[x]/\langle x^3+x+1\rangle$ what does $\Bbb{F}_4\cup\Bbb{F}_8$ mean even? When you add $\Bbb{F}_{16}=\Bbb{F}_2[x]/\langle x^4+x+1\rangle$ to the mix you run into the problem that there are two different embedding of $\Bbb{F}_4$ into that, and to form the union you need to pick one of them. I explained one way of sidestepping such issues [here](https://math.stackexchange.com/a/824137/11619).
Comment: Recheck the algebraic closure.  You want $\overline{ \Bbb F}=\bigcup_m\Bbb F_{p^{nm}}$.
Comment: @Cpc See my updates.
Comment: (cont'd) That approach is, in a way, based on having the union transformed into a direct limit (which is less problematic set theoretically). Using the sequence of factorials as extension degrees makes it a nested union, which at least to me feels simpler still.
Answer: You're asking whether the algebraic closure of a finite field has any subfields that are not finite as sets.
You may know that $\Bbb F_{p^n}\subset\Bbb F_{p^m}$ if and only if $n|m$, and if this happens, the field extension degree is $[\Bbb F_{p^m}:\Bbb F_{p^n}]=m/n$. Granting this, even if you didn't know it before, consider the union of the fields $k_\ell=\Bbb F_{p^{2^\ell}}$. You see that $k_\ell\subset k_{\ell+1}$, with $[k_{\ell+1}:k_\ell]=2$, so that we have an ascending chain of $2$-extensions of the prime field $k_0=\Bbb F_p$.
Then, according to the principle at the beginning of the preceding paragraph, $\Bbb F_{p^3}$ is not contained in any $k_\ell$. In particular, $\bigcup_\ell k_\ell$ is an infinite field not equal to the algebraic closure.
Comment: You're right.   I found the result.  It would have to be the algebraic closure of the prime subfield.   And that can be shown to be $\bigcup_n\Bbb F_{p^n}$.  Thanks.


Seeking recommendations on resolving sporadic network connectivity latency for Notes client

Question: I have Domino servers in geographically disperse data centers in the U.S.
Sometimes when I open an NSF on one of those servers the connection times out then when I open the NSF again it connects immediately.
This has been going on for years and during that time I have upgraded and changed my own internet connection and moved servers to different data centers.  Of course I have direct connection documents using fixed IP addresses.  When I do a Notes client Trace nothing is out of the ordinary.
My business partner experiences the same thing from an entirely different city and different ISP but to the same servers.
Never have any trouble connecting to the HTTP server, just over port 1352.
Does anyone have any recommendations on a process to determine what is causing this problem?
Comment: Try putting the path to the server in the hosts file.
Comment: Good thinking.  Done.  Will see how it fares.
Comment: No joy.  I added entries to hosts but the same issue happened again.  Thanks though.
Answer: Any chance to get a VPN from your machine directly to the server? There are "security solutions" that drop packages, connections, ...
Using a VPN, you can rule out issues with the network on the way there.
Comment: Was able to test this yesterday and I think that is the issue.  If I establish a VPN connection and then set up connection documents to use the internal IP address there seems to be no unusual pausing to connect to the server.  After switching back today the pause is back.  The only real difference in these two scenarios is that the server firewall is not engaged when using the VPN connection to that server.  That also seems to jive historically.  I can live with this scenario now that I am pretty confident in the cause.  Thanks very much.  Great suggestion.
Comment: Yup.  I'll give that a shot.
Answer: I haven't had this problem, so I'm not sure if this helps.
In the Notes Client. File -> Preferences -> Notes Ports
Select TCPIP and click the Options... button. Change the timeout value to something higher.
Comment: Another good idea!  Trying it.
Comment: This has stopped the failure but I am trying Simon's suggestion below because even though I have stopped getting the "Can't connect" message after bumping timeout to 30, it still clearly needs more time sometimes.  Thanks!
Answer: We also had this poblem, the only fix we found was this:

Add the following to the windows registry
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters
Add 'new DWord value': KeepAliveTime
value (decimal): 60000

Hope this will help
for more background info see:

http://www-01.ibm.com/support/docview.wss?uid=swg21686965
Answer: It is a very broad question and there is no one single answer.
First you can use the following in the notes.ini
<code>CONSOLE_LOG_ENABLED=1
DEBUG_THREADID=1
CLIENT_CLOCK=3
</code>
(maybe 30 for CLIENT_CLOCK)
This will generate console logs in the IBM_TECHNICAL_SUPPORT folder which will track response times/traffic.
Look for parts that reference high ms numbers and check the related information. If you want to post any related lines here I can look at it (make sure to remove any confidential information from log line!)
I'd also recommend reviewing the following.
http://www-01.ibm.com/support/docview.wss?uid=swg27008849
Also you should mention what version of Notes+Domino you are using, as there have been performance improvements across versions (eg. Managed mail replicas).
Comment: Thanks Simon.  I have updated my notes.ini and did a quick baseline to see what a normal time looks like.  I am running 8.5.3 servers and clients on whatever latest FP was.  Pretty much the same problem though over all versions.  Will update later.
Comment: I added these settings and have been examining the log file when the delay in opening the NSF occurs.  One time it took 21,000+MS to open after the console log file said "Server not responding" and then it opened the NSF.  By following Tommy suggestion to increase the TCIP port timeout I think the NSF opens after the long delay instead of just giving me the client error message indicating the server was not responding but that doesn't really indicate where the problem is.  If I could figure out a rhythm to it but it just seems so random.
Comment: [16FC:0013-1094:alarm] (OPEN_SESSION: 31 ms)
[16FC:0013-1094:alarm] 538 ms. [138+294=432] (Session Closed)
[16FC:0002-1700]  [16FC:0002-1700] (158-4579 [158]) OPEN_DB(CN=XXX/O=XXX!!mail\XXX.nsf): 21301 ms.
[138+0=138] (Remote system no longer responding)
[16FC:0002-1700]  [16FC:0002-1700] (159-4601 [159]) OPEN_DB(CN=XXX/O=XXX!!mail\XXX.nsf): (Connect to XXX/xxx: 140 ms) (Exch names: 0 ms)(Authenticate: 0 ms.)
Comment: [16FC:0002-1700] (OPEN_SESSION: 30 ms)
[16FC:0002-1700] (Opened: REP862579C2:00190929) 37 ms. [138+294=432]
[16FC:0002-1700]  [16FC:0002-1700] (160-4601 [160]) SERVER_AVAILABLE_LITE(CN=XXX/O=XXX): 79 ms. [30+86=116]
Comment: It seems fine because it connects in 31 ms and then a little later, nothing has changed and maybe five minutes has passed, then the whole no longer responding thing.  Maybe the issue really is with the network at the server. Server log shows no issues and no lapses. There is a firewall infront of these servers but, as I said, that has always been the case and during the course of three years this server has been moved from one data center to another with the same results.

This is not a huge issue. Just inconvenient. If I could locate the issue though I would feel better about it.
Comment: Leyrer's response is the best way to proceed at this point.
Comment: Only thing I can add is if you are getting it consistently on the same database, then it may be corruption, design issue. For example a badly designed view.


Show $f: l^2 \rightarrow l^1$, defined by $f(\{x_n\}) = \{x_n/n\}$, is uniformly continuous

Question: Let $f$ be a function defined  on   $\ell^{2}$ to $\ell^1$ by $f(x) =(x_n/ n)$. Show $f$ is uniformly continuous.
My attempt at the proof:
Let $\{a_n\}$ and $\{b_n\}$ be sequences in $\ell^2$
Let $\varepsilon > 0$, choose $\delta = 6\varepsilon/\pi^2$.
Then $d(f((a_n),(b_n)))= \left(\sum_{n=0}^\infty ({a_n-b_n\over n})^2\right)^{0.5} \le \left(\sum_{n=0}^\infty {(a_n-b_n)^2\over n^2}\right)^{0.5} \le
\left(\sum_{n=0}^\infty {(a_n-b_n)^2}\right)^{0.5} \left(\sum_{n=0}^\infty ({1 \over n^2})\right)^{0.5}$...
After some more typing, I end up with $|a_n-b_n|\cdot\delta$, which I then sub delta and get $\varepsilon$.
Does this show that f is uniformly continuous?
Comment: I think you may have formatting issues.
Comment: $f$ is uniform continuous, but your calculation is just not correct, starting from the first equality. What is $d(f(a_n), (b_n)))$?
Comment: @JohnMa I think it may be referring to the distance between f(an), and f(bn) in the l2 metric
Answer: Hint: If $X,Y$ are normed linear spaces and $T:X\to Y$ is a bounded linear map, then $T$ is not just uniformly continuous, it is Lipschitz, with Lipschitz constant equal to $\|T\|,$ the operator norm of $T.$ So we only need to show $f: l^2 \to l^1$ is a bounded linear operator. Wait! We don't even know yet that $\{a_n\}\in l^2 \implies f(\{a_n\})\in l^1.$ There is a very well known inequality that shows that. Once you have that, the fact that $f$ is bounded and linear is simple.


How to render a view in a form

Question: I am building a configuration form in an admin menu.  I'll have some input fields inline at top, and below, a table of data.  I'd like to render a view of the data in the table so it can handle the paging, etc.
How can I access the view and render it?
Comment: I am not clear with the question, but if you want to show view with table then you can check the display setting in view.  If you look at the code of render() function it is calling the drupal_render() function only but it will show the top level elements as well.
Comment: I modified my post.  I want to render a view in the #markup field in my form.
Answer: Use view_embedd_view function and you will get the view.
$output = views_embed_view($viewName,$display_id);
print $output;

How to render a view in a form


Getting bad request error on forn submission in react

Question: This the component I created. I can get the contact in console but throws error on submission. I can post the data through Postman; the problem occurs when I submit the form. Where is the error in the handlesubmit function?
import axios from 'axios';
import React, { useState } from 'react';

const ContactForm = () => {
  const [contact, setContact] = useState({
    firstName: '',
    lastName: '',
    phoneNumber: '',
    email: '',
    message: '',
  });

  function handleChange(e) {
    setContact({ ...contact, [e.target.name]: [e.target.value] });
  }

  function hanhdleSubmit(e) {
    e.preventDefault();
    console.log(contact);

    axios
      .post('http://localhost:8080/contact', contact)
      .then((response) => {
        console.log('Response after post api', response.data);
      })
      .catch((error) => {
        console.log('Error while post api', error);
      });
  }

  return (

      <form onSubmit={hanhdleSubmit} noValidate>

            <input
              type="text"
              placeholder="First Name"
              value={contact.firstName}
              name="firstName"
              onChange={handleChange}
              autoComplete="off"
            />

            <input
              type="text"
              placeholder="Last Name"
              value={contact.lastName}
              name="lastName"
              onChange={handleChange}
              autoComplete="off"
            />

            <input
              type="tel"
              placeholder="Phone Number"
              value={contact.phoneNumber}
              name="phoneNumber"
              onChange={handleChange}
              autoComplete="off"
            />

            <input
              type="email"
              placeholder="Email"
              value={contact.email}
              name="email"
              onChange={handleChange}
              autoComplete="off"
            />

            <textarea
              placeholder="Please type what you are looking from us?"
              value={contact.message}
              name="message"
              onChange={handleChange}
            />

            <button type="submit">Submit</button>

First Name:{contact.firstName}

Last Name:{contact.lastName}

Phone Number:{contact.phoneNumber}

Email:{contact.email}

message:{contact.message}

      </form>

  );
};
export default ContactForm;

This is the error I'm getting:
{
  "timestamp": "2020-12-04T18:32:39.945+00:00",
  "status": 400,
  "error": "Bad Request",
  "message": "",
  "path": "/contact"
}

Comment: In the onChange youre setting the value to { ...contact, [e.target.name]: [e.target.value] }` Should that be ` { ...contact, [e.target.name]: e.target.value }` The post is sending the values wrapped in brackets...
Comment: Yes worked it for me  Zsolt,thanks a lot for your replay
Answer: I think it's the syntax of the body sent to the backend, the second parameter of your axios.post should be an object :
axios
      .post('http://localhost:8080/contact', contact)

should be
axios
      .post('http://localhost:8080/contact', { contact })

Comment: let me know if this was the issue
Comment: its not  Marc ,i have tried it before submitting its becauseset Contact({...contact, [e.target.name] : [e.target.value] })  i was putting [] in e.target.name .thanks for your reply.


Image set cardinality vs set cardinality

Question: Suppose $S$ is the set of natural numbers $= \{1,2,3,4, \ldots\}$.
Consider the function $n^2 - n$
Does the image set $f(S)$ have the same cardinality as $S$?
I want to say no because the function is not a bijection, yet for every element in $S$, the function will produce an output.
Comment: By definition if u have a function $f:S \rightarrow f(S)$ then it is always a surjection since the very definition of  $f(S)$ is the image set! i.e. every point in $f(S)$ is landed by some point in $S$. Of course this can change if you decidedly change the codomain to some set larger than $f(S)$. So in any case if you already established surjectivity, it remains to show injectivity. If you have both, then we say both the domain and codomain have same cardinality.
Comment: Why do you think it is not a bijection?
Comment: Sets $A, B$ have the same cardinality iff there $exists$ at least one  bijection $\psi:A\to B.$ When $A$ is not finite, this does not preclude that there may  another function  $f:A \to B$ that is injective or surjective but not  bijective.
Comment: sorry, instead lets consider the function f(x) = 2x. This function is injective, but not surjective. But does f(S) have the same cardinality as S?
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Answer: To answer your question, we consider the function $f:S\rightarrow f(S)$ where $S$ is the set of natural numbers and $f(n)=n^2-n$ for all $n\in S$.
As per my comment above, this construction is always surjective. It thus remains to show injectivity. Suppose we have $n,m\in S$ such that $f(n)=f(m)$, i.e. $n^2-n=m^2-m$. Rearranging we have $(n-m)(n+m-1)= 0$.
Since $n$ and $m$ are both at least of value 1, then $n+m-1$ cannot be 0. So $n-m=0$ and so $n=m$. The function is injective and thus bijective. i.e. $S$ and $f(S)$ have the same cardinality.