java-akka : sending back message to grandparent

Question: I have created 3 levels of actors.
Level 1 is the supervisor actor. Supervisor actor will trigger message to Level2 actor and will also take action based on the responses back from the child actors (Level1 and Level2) based on the type of message received.
Below is the code of supervisor
if (message instanceof OutBoundDataExportDTO) {
    // This to trigger query processor

    OutBoundDataExportDTO data = OutBoundDataExportDTO.class.cast(message);
    LOGGER.info("Received:  " + data.toString());
    ActorRef ruleInstExportActor = actorSystem
        .actorOf(Props.create(OutboundsQueryActor.class, applicationContext)
        .withRouter(new RoundRobinPool(5)));
    ruleInstExportActor.tell(data, getSelf());

} else if (message instanceof TaskCompleteMsg) {
    TaskCompleteMsg taskCompleteMsg= TaskCompleteMsg.class.cast(message);
    taskService.update(taskCompleteMsg);
}

In Level 2 actor, the work is delegated to some Processor. This processor will spawn another actor (Level3 actor). Now, I need to return the response of taskcomplete from Level3 actor back to Level1 actor (supervisor actor) for it to take action based on the response.
Below is the sample code of Level2 actor:
if (message instanceof Level1ActorMessage) {
     OutboundQueryProcessor queryProcessor =  queryProcessorFactory
         .getQueryProcessor(queryName);
     response = queryProcessor.executeQuery(templateId, queryData, task);

} else if (message instanceof Level3ActorTaskCompleteMsg) { // This is the response from Level 3 actor, once it has completed
    ActorRef parent = getContext().parent(); // This gives me the   parent(Level2)
    // How do i send it back to its parent
    // parent.tell(returnResponse, parent);
}

How can I send the response back from 3rd level actor (child) to grandparent (1st level).
Comment: Please post more detailed questions here
Comment: Please provide the relevant codebase so that it is easier to understand what is going on. Also, what have you tried in the same regard?
Answer: In your code snippet for Level2 actor:
if (message instanceof Level1ActorMessage) {
    OutboundQueryProcessor queryProcessor = queryProcessorFactory.getQueryProcessor(queryName);
    response = queryProcessor.executeQuery(templateId, queryData, task);

} else if(message instanceof Level3ActorTaskCompleteMsg){// This is the response from Level 3 actor, once it has completed
    ActorRef parent = getContext().parent();// This gives me the   parent(Level2)
    //How do i send it back to its parent
    //   parent.tell(returnResponse, parent);
}

You have the line ActorRef parent = getContext().parent();// This gives me the   parent(Level2) which gives you the ActorRef for Level2's parent i.e. Level1, which is the grandparent of Level3.
So if you want to tell Level1 that Level3 has completed then in Level2 actor you can either use:
parent.tell(message, getSelf());

which will pass the Level3ActorTaskCompleteMsg on to Level1 and the sender will be Level2 or you could use:
parent.forward(message, getContext());

which will forward the Level3ActorTaskCompleteMsg to Level1 and the sender when Level1 will be Level3 i.e. it's grandchild.
Either way you will have achieved the goal of sending the Level3ActorTaskCompleteMsg from Level3 to it's grandparent at Level1.
See http://doc.akka.io/docs/akka/snapshot/java/untyped-actors.html#Forward_message
Comment: Hi nickebbitt, for some reason , this line `ActorRef parent = getContext().parent();`  gives me the reference of Level2 actor(See the comment section after that line). I think that is because the message received is from Level3 actor and its parent will be Level2 actor. Now, i dont have a way to get reference of Level2's parent.
Comment: If you are definitely in Level2 actor, and Level2 was created by Level1 one then this isn't possible, Level2 cannot be the parent of itself. Where the message was sent from is irrelevant, the ActorRef for the sender of a message comes from getSender()


How to trigger electronic sounds on stage

Question: Maybe this question is a little bit amateur but I am new to electronic music. I have seen a lot of bands like Coldplay that, despite they are only 4 members, they have lots of electronic sounds live that no one of the 4 members seems to be playing them.
For example, you can see an example in this video. At 1:02 an electronic melody starts playing. How is this achieved? Is the guy with the computer just triggering it at the exact time? That seems really difficult to do... Or is it all part of one big track and everyone is just playing with a metronome?
Thank you.
Answer: Sometimes it's the drummer, sometimes someone is offstage, sometimes there are entire songs programmed and they all have click tracks in their in-ear monitors, and sometimes it's a combination of those things.
There are so many controllers available now and so many kinds of software that the possibilities are manifold. Drum pads or sensors, foot controllers, even guitar note to midi conversion software can all be used for all kinds of triggers and synchronization.
Many acts have racks of music servers off stage running different effects, synthesizers, and pre-recorded tracks. What's interesting is some of the most synth heavy bands actually create more organic sounding performances. Nine Inch Nails is on record as using Apple Mainstage for software synths and effects while also using totally analog, pieced together custom synth racks and other tools that make their performances really breathe.
If you can dream up a crazy idea for your live show, and you're willing to do the research on what's available and how to use it, and you have a bit (or a lot) of money to throw around, you can do almost anything these days.

Regarding the video linked in the question:

They all have in-ear monitors and are probably playing with a click
The drummer has a Roland Octopad trigger pad device
They have an entire DJ who can literally spend all his time triggering and syncing samples (as necessary) (this is almost definitely where the pre-recorded content is coming from)
Some "live" music videos actually have additional parts overdubbed after the performance (oh yeah, it's totally "cheating" but whatever makes the money is what happens)

From comments:

In case it was the drummer, does he just hit a pad and the melody starts playing? How can you be sure the melody will be on tempo?

Three ways (at least) a drummer might trigger something:

a pad
a drum trigger attached to a real drum or cymbal
a foot controller of some kind.

Synchronization can be handled in different ways:

Musicians can be given a click that matches the backing track, they can just play along with the backing track if they are good enough and the track is clear enough
The backing track can be made to speed up and slow down to follow the
musicians
The backing can just be sample that doesn't play at a certain tempo
and is repeatedly triggered and plays once for a short time.
Comment: In case it was the drummer, does he just hit a pad and the melody starts playing? How can you be sure the melody will be on tempo?
Comment: @MartinCopes Three ways (at least) a drummer might trigger something: 1) a pad, 2) a drum trigger attached to a real drum or cymbal, 3) a foot controller of some kind. Synchronization can be handled in different ways. Musicians can be given a click that matches the backing track, they can just play along with the backing track if they are good enough and the track is clear enough, the backing track can be made to speed up and slow down to follow the musicians, or the backing can just be sample that doesn't play at a certain tempo and is repeatedly triggered and plays once for a short time.
Answer: I believe Coldplay simply plays to pre-recorded tracks that just play all the way through their song. I haven't seen anything in their performances which indicate the musicians are triggering them live. A click track in the musician's in ear monitors would allow only the band to hear the click and keep in sync with the recorded tracks.
In regards to the video you posted, that is a music video for a studio recording which is typically not a good representation of how they actually perform it live. To get a better idea of how they perform the song it's best to look at live concert videos. From looking up a couple different live versions of the song, they have a sax player play that part live.

So that makes me think that the electronic melody was done via "studio magic". It is extremely common for bands to do things in the studio that they don't/cannot do live such as have the singer sing the harmonies along with their own lead vocal, have the guitarist record different guitar parts which play at the same time, or in the case of your example the keyboardist probably recorded multiple parts in the studio and then they hire an additional sax player when they perform live.


How to use data in a content type from another content?

Question: Is it possible to use data in a content type from another content?
I will create a website for a football club. I want to add a content type for clubmembers (approx. 250 members) with personal information.
The members could order clothes from the club through a board member, who will keep the orders per member through a page.
To not have to re-enter some data, is it possible to establish a link with the personal member page? For example, I want to use some fields that are contained in another content type.
If it's possible, how can I do that?
Answer: I will suggest to use Entity reference module.

Provides a field type that can reference arbitrary entities.

Also you can take a look References module.

This project provides 'node_reference' and 'user_reference' field
  types.


Fast intercontinental Remote Desktop Sessions

Question: I will be working from Thailand for the next months and I want to be able to RDP or Anydesk my office PC in Greece. Previous attempts have been proven unstable with varied results throughout the day - from flawless, to terrible connections. I am reading that ping time is the most crucial element in such connections. I have tried subscribing to a VPN service but the results are at best the same as not using VPN at all.
I am interested to find out if there is tried and tested way to approach this issue. I am not aware on how intercontinental routing is performed and if one can direct packets through an optimal route. I think this is outside the end-user's control but I would be interested to know if there are companies and subscription options that accomplish intercontinental routes with low latency.
Comment: Do you have different ISPs in local area? Sometime switching ISP get a new route that could help.
Comment: Have you tested the two location<>IXP connection pairs with whatever procedure the respective regulatory agency recommends? The way your question reads right now, the "intercontinental" part could well be irrelevant.
Comment: How are you reaching your computer with RDP? Does it have a public IP or is otherwise routable from the internet? Or are you already on some kind of VPN to begin with?
Comment: @MihailMalostanidis No, there is no public IP. I am connected through OpenVPN with our premises but I suppose this is the same as if I was connecting through a public IP.
Comment: @Saloom it's far from the same, packet loss and high latency are somewhat worked around with UDP mode, and you are probably not getting those benefits. Note that I am not suggesting you expose your computer to the open internet since you weren't doing this previously. Have you tried TeamViewer? Out of third party solutions it has always given me significantly better responsiveness. There's also https://github.com/rustdesk/rustdesk *if* you're prepared to trust it.
Comment: @MihailMalostanidis Yes I am using Anydesk quite a lot and I have noticed it is slightly faster than RDP under my setup, although if I have the option, I prefer RDP since the overall user experience is better IMHO.
Comment: I would look at `tracert` and/or `pathping` and check if I could do anything about the RTT or if it's "outside". If that's so, you can't do anything about it.
Answer:
Previous attempts have been proven unstable with varied results throughout the day - from flawless, to terrible connections.

You do need a reliable Internet connection, with no or very low packet loss. Less than 0.1% is OK, less than 1% should be still usable, more than 1% is terrible.

ping time is the most crucial element in such connections

No, a low packet loss ratio is the most crucial parameter. Round-trip time (RTT/latency) as measured by ping is the second most crucial parameter. [edit] As Austin has accurately pointed out, a low variance in latency is also crucial when working with interactive user interfaces (RDP or similar).

I have tried subscribing to a VPN service

A VPN service cannot improve the packet loss ratio and definitely increases RTT. That won't help.
[edit] As @Bob has correctly pointed out, there are fringe cases where VPN might help: when your access ISP connection is actually good, but packet loss and latency deteriorate between your ISP and the destination network. A VPN connection might allow you to get around that problem, when the tunnel takes another route between your access ISP and the VPN provider that doesn't hurt connectivity (as much).
However, I wouldn't put much effort into this approach as it's not very likely to find a suitable VPN provider without in-depth knowledge (or research) of the access ISP's and VPN provider's connectivities.

find out if there is tried and tested way to approach this issue

The only thing you can do is find a better Internet uplink, in respect of packet loss ratio and RTT. The latter is subject to physical limitations (speed of light mostly), so it'll increase with growing distance (10 ms per 1000 km can be considered very good).

I am not aware on how intercontinental routing is performed and if one can direct packets through an optimal route.

That is nothing you can control, aside from choosing your Internet provider.
If connection quality regularly changes over the course of a day, you might need to adjust your working hours to that, if possible.
Comment: Possibly of note, if the RTT is consistently less than about 500ms, then it's much more important that the _variance_ in RTT is low than that the _peak_ RTT is low. The human brain can compensate for a few hundred ms of latency just based on a bit of practice, but the latency needs to be consistent for that to be possible.
Comment: A VPN actually can improve both packet loss and RTT, in some situations. Some ISPs have poor international routing but can be good locally. This can be sidestepped by connecting via a local VPN endpoint to so international routing is via the VPN's gateway rather than the ISP. Of course, this won't help if you're suffering packet loss issues locally.
Comment: @Bob That's possible, agreed - but not very likely.
Comment: I'd contest that for RTT, the limitation is not the speed of light (Earth circumference at that speed is around 130ms), but rather the number of hops - each router, each switch, each media conversion, they all add their own latency.
Comment: @JanDorniak I was hinting at the *physical* lower limit of RTT over distance (depending on the speed of light in silica, appr. *distance / 200,000 km/s * 2*). Of course, additonal delays at intermediate hops come on top of that, so that effectively half that speed (or twice the latency) is actually realistic.
Answer: Are there other ISP's that you can use? Are they any better than your current ISP?
At the end of the day, no matter what you might try, your connection is dependent upon the network ISP/provider/carrier that you're using. VPN's and other mechanisms can't avoid traversing your ISP. You're just adding additional network overhead.
Answer: With that latency? No. It will be a miserable user experience with lags and disconnects.  I've supported remote desktop environments with similar latency and even with the better providers and clean links, it's miserable. There are some tweaks such as disabling audio but no magic bullet.
https://www.consoleconnect.com/locations/athens/
Athens <-> Bangkok 343 ms
Comment: @Saloom: that could mean that somewhere there are links that are oversubscribed/overcapacity. There's a huge difference in providers too. Verizon has excellent SLA's between the US and nearly the entire world. Between other countries not so much.
Comment: I get a constant 235ms from Athens, pinging DNS Servers in BKK right now. When I was in BKK last year, I had a quite decent experience in the early mornings. In the afternoon, it was becoming much worse. I am not sure what was causing this, but I would be happy if I could maintain this early morning experience.
Answer: For direct RDP, you may want to look at some sort of jump host in Azure or AWS. These companies have relatively reliable low-latency networks between datacenters. So, you RDP to a host in SE Asia region, which RDPs to a host in France, which RDPs to your host at home. While the RTT of such a connection is still big (about 300ms), it is probably better then going peer-to-peer. Limit the RDP "experience" to save bandwidth. You probably don't need transparency effects or desktop backgrounds.
A different option, which might work quite well, is to use a conferencing app, i.e. Zoom, Teams, Teamviewer etc. These apps generally employ different protocols, sacrificing image quality for lower latency.
You would need both though. The RDP to join the Teams meeting and to approve remote control.
Comment: @ Rainmaker Initially I thought of using AWS to somehow route traffic through their network but I never thought of doing it through daisy chaining RDPs. There is also the overhead produced by each session, transcribing packets to image to packets. A packet proxy might be more sufficient.  I think it is an overkill but I will try that just for the fun of it and see how it goes. Is there a way to assign EC2 instances from different regions to the same VPC and connect the RDPs without using their public IPs?
Comment: I once RDPed from singapore to an Azure VM to install a linux instance over a KVM over IP instance. This miiight work


How to change date format inside table in MySQL?

Question: I want my DateOfBirth inside a Table to be displayed in dd/mm/yy format. I know we can retrieve dates in different format. But how could I change the format in the table itself?
Comment: You don't.  You store dates and times using native SQL data types.  Then you fetch them and use `date_format()` to get whatever format you want for presentation.
Comment: Please, do not save dates as varchar.
Comment: Storing a date in a non-MySQL date compliant format cannot be done on a date field.
Answer: Why would you bother how it is stored? Just turn it to whatever format you need when retrieving it. If for some reasons you need a formatted version there just place it in a varchar column and apply custom format while inserting. Just mind that this way any date operations on it become harder and incredibly inefficient.
Answer: You can do it like this SQLFIDDLE
<code>SELECT DATE_FORMAT(dates, '%D of %M, %Y') FROM datetbl;
</code>
Reference https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format


RDS 2012 R2: Broker HA round-robin-name fails

Question: I have these servers...
<code>Name : DC1
Roles: PDC, File/Print, RD License, SQL 2012

Name : DC2
Roles: BDC, RD Webaccess

Name : SVRDS1
Roles: RD Broker (primary), RD Host session

Name : SVRDS2
Roles: RD Broker, RD Host session

Name : SVRDS3
Roles: RD Broker, RD Host session, RD Gateway
</code>
I've set up a round-robin dns (called rd.mycompany.local) for the SVRDS1, SVRDS2 and SVRDS3.
This round-robin name is set up in broker HA round-robin name.
If I log on externally via webaccess (I see that the round-robin name is used as address), I get an error ... "An authentication error has occurred (Code: 0x607)".
If I change the round-robin name in the broker HA to SVRDS1.mycompany.local, then I log on perfectly fine.
If I change the round-robin name in the broker HA to SVRDS2.mycompany.local or SVRDS3.mycompany.com, then I get the error again ... "An authentication error has occurred (Code: 0x607)".
I'm lost to where to start to look.
Why is it only one of my rd hosts that works with the round-robin dns name?
Why doesn't it work with the round-robin dns name rd.mycompany.com?
Thanks.
Comment: Just to verify then, you do have rd.mycompany.com pointed to all three servers in DNS?  Meaning there are three separate entries in DNS with the same name but pointing to the three IPs of the RDSH servers?  If not, then that is your first problem.
Comment: Yes all three RDSH servers IPs use the same dns (rd.mycompany.comn) in DNS.
Comment: Forgive these trivial questions I'll be asking you, but I think I know what's going on and I just need to confirm before I direct you on how to proceed.  1) Does using rd.mycompany.local in your Remote Desktop Connection log you on to the farm?  If yes, great, if not, then we'll address that.  2)  If you're trying to use rd.mycompany.com, do you have a zone for mycompany.com which is different than mycompany.local?  If you don't, resolution is your problem and we can address that too.  Please let me know the answers to these.  I work with RDS all the time so we should be able to fix it.
Comment: ... And the above two questions are asking from the standpoint of you being inside your network, on the LAN.  We'll deal with the WAN/external users after that.
Comment: Answers to these?
Comment: Hi Brad, sry I didn't see your answers till now. Yesterday I wrote in this thread http://tinyurl.com/kcnf34l and I was advised to only have one broker and remove my round-robin. Did that, but still have problems. I'm about to give up and call Microsoft. Here's my network: http://pho.to/5RWyQ. I only have one server in collection SVRDS1. If I use webaccess then I get this error trying to connect "An authentication error occurred (Code: 0×607). Remote computer SVRDS1.mycompany.com."....
Comment: ... If I remove SVRDS1 from collection and add SVRDS2, then I get this error "An authentication error occurred (Code: 0×607). Remote computer SVRDS2.mycompany.com." - so the error is on all servers. Any idea? Maybe it's time to call MS.
Comment: Don't call MS yet.  I was going to suggest to use one Broker, and make it separate from the RDSH servers.  Create a separate machine for the broker, then put your 3 RDSH servers back in Round Robin DNS.  Try logging in then let me know.  If I can't help you in the next few steps we'll call MS, but let's try my method first.
Comment: Ok - I've created the round robin called rd.company.com, but I'm unsure where in the RDS setup I tell them to use the round robin? When I had the broker HA, there was a round robin entry there, but I'm unsure where to put it now?
Comment: ... when I use the Webaccess it says "DC1" in the  "Remote Computer" - should this point to the round robin? - and how do I do that :)
Comment: It doesn't necessarily need to point to the Round Robin. You can change that server name too... follow this... http://technet.microsoft.com/en-us/library/dd759250.aspx also, if you're up to it I can do a remote session and take a look at your setup... let me know and I can call you or you call me... if you're not comfortable the next step would be MS but I'd like to save you that money and headache... LMK...
Comment: It's very kind of you and a great offer - but I'm sure I'm not allowed to do that for my company. I guess the company have to pay MS :) I will let you know the result. Thanks for all you help Brad! :)
Comment: I understand. One last thing... can you try this before you call MS: http://social.technet.microsoft.com/Forums/windowsserver/en-US/67dfab70-7e10-4e0b-a3c8-63ce776f2355/how-do-i-change-the-url-to-the-remote-web-access-server-in-windows-server-2012?forum=winserverTS                  try going through the 2nd post (1st answer)
Comment: Did you try that last link I sent?  At least try it and let me know, thanks.
Answer: Problem solved by calling MS.
They changed CAP and RAP to default values and lowered the security on collection to low.
Furthermore I found out it's only possible to use collection by using webaccess. I thought I could use Remote Desktop App and the broker address as "Computer Address", but that's not possible.


Changing background in banner

Question: This is the code I'm working on.
HTML

Etiam adipiscing

Magna feugiat lorem dolor egestas

Learn More

CSS
#banner {
    padding: 8em 0 6em 0;
    background-color: #662800;
    color: rgba(255, 255, 255, 0.75);
    background-attachment: fixed;
    background-image: url("../images/banner.jpg");
    background-size: cover;
    text-align: center;
}

#banner input, #banner select, #banner textarea {
    color: #fff;
}

#banner a {
    color: #FF6600;
}

Which is the easiest way to make background (images) of the slider to change without any action every 2-3 seconds? I did my research, tried to include this with some modifications, but it's not working. I'm not really sure how to modify existing CSS in the right way, and how my HTML should look in the end.
Any idea how to make that work? Is there any easier way?
Comment: Check this out and get the basic idea.! A simple CSS based [slider](http://codepen.io/dudleystorey/pen/ehKpi).
Answer: If you're looking to just have the background change, without any kind of interaction, here's an adaptation of the other fiddle you were trying to get working.
var images = [ "http://domain.com/imageoneurl.jpg", "http://domain.com/imagetwourl.jpg"];

Include all the images you want to cycle through in the above array, separated by commas, in quotation marks.
Below we're setting a variable for the banner element, as well as the interval time in milliseconds.
var bannerBackground = document.getElementById( 'banner' );
var interval = 2500; //in milliseconds

Below the actual magic is happening. We're popping off the last image and setting the background-image property to the first image in the array, and repeating every 2500 milliseconds. You can adjust that timer by changing the number in the var interval = declaration.
setInterval( function(){
  images.unshift( images.pop() );
  bannerBackground.style.backgroundImage = "url(" + "'" + images[0] + "'" + ")";
 }, interval );

No modifications need to be made to your HTML itself, you do need to include this JavaScript somehow though. Either paste it all into a .js file and include it that way at the bottom of your document, or paste it into the document itself, like so:

Paste this at the bottom, right above your closing  tag.
Comment: I have one more question, how to limit image size to 95% percent of the screen size? I tried to limit banner, but it's not working properly on smaller screen sizes.

Changing background in banner


Inverting a matrix with the same diagonal entries in a particular form

Question: Hi I'm struggling with this inversion and any help would be greatly appreciated.
I want to invert the following $\mathbb R^{m\times m}$ matrix
\begin{bmatrix}
    1 + m       & m & \dots & \dots & m \\
    m       & 1+m & m & \dots & m\\
    \dots & \dots &\dots & \dots & \dots\\
    m       & m & m & \dots & 1 +m
\end{bmatrix} such that it is of the following form: $I - \gamma \textbf{u}\textbf{u}^T$ for a constant $\gamma$ that I need to find, and $\textbf{u} = \begin{bmatrix}
           1 \\
           1 \\
           \vdots \\
           1
         \end{bmatrix} \in \mathbb R^m. $
So the matrix to invert is square and has $1+m$ in all its diagonal entries and $m$ everywhere else, not sure if there is a special way to invert such a matrix. Thanks.
Answer: The solution is $\gamma=\frac{m}{m^2+1}$.
When writing out the product of the matrix that needs to be inverted with the proposed form of the inverse:
\begin{equation}
\begin{bmatrix}
    1 + m       & m & \dots & m \\
    m       & 1+m & \ddots & \vdots\\
    \vdots & \ddots &\ddots & m\\
    m       & \dots & m & 1 +m
\end{bmatrix}
\begin{bmatrix}
    1-\gamma       & -\gamma & \dots & -\gamma \\
    -\gamma       & 1-\gamma & \ddots & \vdots\\
    \vdots & \ddots &\ddots & -\gamma\\
    -\gamma       & \dots & -\gamma & 1-\gamma
\end{bmatrix} =
\begin{bmatrix}
    1       & 0 & \dots & 0 \\
    0       & 1 & \ddots & \vdots\\
    \vdots & \ddots &\ddots & 0\\
    0       & \dots & 0 & 1
\end{bmatrix}
\end{equation}
you'll notice that for each diagonal element of the resulting identity matrix, you have
\begin{equation}
(1+m)(1-\gamma) + (m-1) m (-\gamma) = 1
\end{equation}
while on the off-diagonal, you have
\begin{equation}
m (1-\gamma) + (1+m)(-\gamma) + (m-2)m(-\gamma) = 0
\end{equation}
Both equations have the same solution for $\gamma$, namely $\gamma=\frac{m}{m^2+1}$.
Comment: Thank you! That makes a lot of sense i don't know why i never thought to do that myself, thanks again for your help.


Notating rhythms in 6/8

Question: I've been composing in 6/8, and come up with this, but the notation I've used looks a little messy and it's not something I've seen used anywhere else, is there a better, perhaps easier to read way of notating this (e.g. by converting the notes in the left hand into groups of 4 sextuplets and writing it in 4/4):
... Or is this acceptable as it is?
Comment: Well , In the first and second bar, every 6th note in the left hand is accented, but in the third, it's every 3, so that's what made me think it would look better in 4/4, especially since i know I've seen similar things in music like this: https://www.youtube.com/watch?v=yQw3DvqEbxI
Comment: Do you want a compound time march feel? 6/8 normally has a slightly different feel from 4/4 with triplets/sextuplets or 12/8. If you don't want the march/2-time feel, then you could try 12/8. You could instead double the values of every note and replace single measures with two measures (i.e., dotted eights would become dotted quarters, 32nd notes would become 16ths, etc, and you would have six measures instead of three).
Comment: How do you span the first l.h. notes? Play the top one r.h?
Comment: Yeah i use both hands through the whole first bar.
Comment: Again, at https://youtu.be/XEkDsUrmFC4?t=473 , there's another example of using sextuplets, I've yet to find anything notated anything like mine.
Answer: My recommendation is to quadruple your note values, and write it in 6/8.  That is, the first 6 32nd notes become one measure.  If the music is supposed to be fast (which is the impression I get), then let that be reflected by the tempo mark.
Comment: At 400 bpm using mattputnam's suggestion for notation,  you'd be playing 20 notes per second. Any faster, and you ought to get Guinness to watch you because you'll have a world record.
Comment: Seems a formally sound approach, but in practise would mean to have a tempo meter of > 400 bpm, which doesn't seem practical to me...
Comment: @joseem then it's already unplayable
Comment: I understand your approach would not change the actual tempo, I just wanted to note that the tempo marking in the normal bpm would not be of much use as no metronome (and even most software pieces, I think) can mark bpm that high.
Comment: And I'm saying that if the piece is that fast then there's no point in bothering because this piece is unplayable anyway.
Answer: Without any more context, the snippet in your OP "feels like" it is really four beats in a bar, with the left hand playing triplets. But almost everything in your notation contradicts that visually. The main purpose of music notation is communication, and this disconnect seems (to me at least) to be a major communication failure.
If you really intend this to be a complicated cross-rhythm, then your notation is fine  - though adding a few accents might make it clearer.
But if you actually mean "four beats in the bar", then write it that way.
I don't really see how splitting each bar into four and using longer note values would make it any clearer. 32nd-notes and/or triplets won't "frighten the horses," so long as they communicate what you really mean.
Comment: Thanks for the advice, I've written it in 4/4 now at 60-70 bpm and it does seem to fit the feel of the passage better, working on the fingering now :s http://music.stackexchange.com/questions/45388/determining-fingering-for-complex-arpeggiations

Notating rhythms in 6/8


Write mixed linear model as two level hierarchical model

Question: How do I show that this mixed linear model
$$\textbf{Y}=\textbf{X}\beta+\textbf{Zb+e},$$
where
${\textbf{b}\choose \textbf{e}} \sim N\left({\textbf{0} \choose \textbf{0}}, { \textbf{D} 0 \choose 0 \Sigma}\right)$
can be represented by a two-level hierarchical model
$$\textbf{Y|b} \sim N(\textbf{X}\beta+\textbf{Zb},\Sigma),$$
where $\textbf{b} \sim N(\textbf{0},\textbf{D}).$
Comment: Your second equation isn't a two-level hierarchical model, it's just an alternative representation of the first one.
Comment: You probably mean something more like $y_{ij} = \beta_0 + \beta_i x_{ij} + u_j + e_{ij}$
Answer: If you start with
$$
Y\mid b \sim\mathcal N(X\beta + Zb, \Sigma) \\
b \sim \mathcal N(0, D)
$$
then you can use the tower property and law of total variance, along with the fact that convolutions of Gaussians are Gaussian, to work out the marginal distribution of $Y$. Once you do this, you'll have a Gaussian RV with some mean and covariance. Then compare that to the marginal distribution of $X\beta + Zb + e$ and you should have your answer.


Will there be Volume 2 of Mathematical Statistics by Bickel and Doksum and Robust Asymptotic Statistics by Rieder?

Question:
It was mentioned that Volume 2 of Mathematical Statistics by Bickel
and Doksum was scheduled to be published in 2003.  I was wondering
if I miss something, but why it is not yet available? Is there some
change of plan?
Volume 1 of Robust Asymptotic Statistics by Helmut Rieder was
published in 90's.  But it seems no volume 2 yet. Am I correct?

Thanks?
Comment: Did you try to email the authors and ask?
Comment: Or the publishers. Or look on Amazon (they sometimes have details of things).  Or ask a librarian (if you are at a university).
Comment: @kjetilbhalvorsen: not yet. I don't think they will care to reply me.
Comment: @PeterFlom: Amazon doesn't have vol2's.
Comment: Well, the authors re the only one who will know!
Comment: If you don't mind me asking, what makes you like Bickel's books?
Answer: Volume 2 of Bickel and Doksum has finally been published: http://www.amazon.com/Mathematical-Statistics-Selected-Chapman-Statistical/dp/1498722687/ref=pd_cp_14_1?ie=UTF8&refRID=0BM864NEEG9F092Z2VYT


One parameter family of non-isomorphic indecomposable quiver representations

Question: Consider a quiver $Q$ that is not of finite type. Can you construct a free $k[t]$-representation $M$ of $Q$ such that the $k$-representations $M\otimes_{k[t]}k[t]/(t-\lambda)$ are indecomposable and belong to infinitely many isomorphism classes (you may assume $k$ algebraically closed, and you are free to choose a dimension vector)?
This should follow from the tame-wild dichotomy, but I would like to see a more direct proof.
Answer: You can do this more or less "by hand" if you're willing to use Gabriel's theorem which classifies quivers of finite type.  I will assume that $Q$ is connected (to simplify) and that $k$ is algebraically closed (it could just be infinite for this proof).
The first step is an application of Gabriel's theorem: if $Q$ is of finite type, then it is an orientation of a Dynkin diagram of type $A,D$ or $E$.
The second step is combinatorial: if $Q$ is not an orientation of a Dynkin diagram of type $A,D$ or $E$, then it contains as a subquiver an orientation of a diagram of type $\tilde{A}$, $\tilde{D}$ or $\tilde{E}$.  This is proved by a straightforward case by case analysis.
The third step is the observation that if $Q'$ is a subquiver of $Q$, then any indecomposable representation of $Q'$ induces an indecomposable representation of $Q$, and this induction procedure preserves isomorphism classes.  Therefore, to prove the statement of the question, it suffices to prove it for quivers which are orientations of diagrams of type $\tilde{A}$, $\tilde{D}$ or $\tilde{E}$.
The last step is then devoted to finding a representation $M$ as in the statement of the question for quivers of type $\tilde{A}$, $\tilde{D}$ or $\tilde{E}$.  It is not too hard (although it is tedious) to construct such representations whose dimension vector is the imaginary root of the underlying diagram, and prove that they are indecomposable.
For instance, in type $\tilde{A}$, one gets (for any orientation, not just the one pictured)
$$
\begin{array}{ccccccccccc}
k[t] & \xrightarrow{t} & k[t] & \xrightarrow{1} & k[t] & \xrightarrow{1} & \ldots & \xrightarrow{1} & k[t] \\
   & \searrow_1 &  &  &  &  &  & \nearrow^1 & \\
     &  & k[t] & \xrightarrow{1} & \ldots & \xrightarrow{1} & k[t] &  &
\end{array}
$$
and in type $\tilde{D}$ for a certain orientation, one gets
$$
\begin{array}{ccccccccccc}
k[t] & \xrightarrow{(1,0)^T} & k[t]^2 & \xrightarrow{id} & \ldots & \xrightarrow{id} & k[t]^2 & \xrightarrow{(1,1)} & k[t] \\
   & \nearrow_{(0,1)^T} &  &  &  &  &  & \searrow^{(1,t)} & \\
 k[t]    &  &  &  &  &  &  &  & k[t].
\end{array}
$$

I'll add two remarks:

If you don't want to use Gabriel's theorem, then the above still proves the existence of one-parameter families of indecomposable modules for quivers which are not orientations of Dynkin diagrams.
If the field is finite, then one-parameter families are finite as well.  To prove that the non-Dynkin quivers admit infinitely many isomorphism classes of indecomposable representations, one needs to consider integer multiples of the dimension vectors used in the last step.


Do chord voicings matter for the intervals

Question: If I'm playing in C Major the C Major open guitar chord and then I want to play the 5th to this chord, what chord should I play ?
I know there's a rule that says "to determine interval between 2 notes you count from the lowest note to the highest", and I assume that when someone says "give me the 5th of C Major open chord" it means a chord whose root note is a 5th interval apart from the root note C. So, following this logic I can tell that F Major bar chord on 1th fret fits perfectly:

since from F on 1st fret of 6th string to C on 3rd fret on 5th string the interval is P5.
But, at the same time I can build F Major chord differently, in other words use other voicing:

And in this voicing interval between C on 3rd fret of 5th string to the root F on 3rd fret of 4th string is P4.
So, in first voicing the interval is P5 and in second vocing the interval is P4.
And the question is: "Who is the real P5 to our C Major" ? Can voicings change the function of the chord (P5 to P4 etc.) ?
Comment: A 5th up from C is G, btw [guitar strings are mainly a 4th apart]. I don't actually understand the rest of what you're saying, sorry.
Comment: Ah, I see what you're doing - the F is a 5th *below* the C, which is going to confuse you to start with. For now, always count *up*, or if you count down, start from 8 & count backwards.
Comment: Several topics have gotten mixed up here. When we talk about "intervals," the context is usually talking about the distance between individual notes, not chords. We also use language like "the fifth of" when talking about the function of cords within a key, as in "the fifth of C major is G." And then we also use it when talking about the notes within the chord itself, in which one of the notes is the "root," and the other two notes in a simple cord are the "third" and the "5th."
Comment: @Tetsujin,

F on 1st fret of 6th string is also 5th from the C (on 3rd fret of 5th string). Which chord considered to be 5th then F or G ?
Comment: This can't be answered as it stands, as it's asked using skewed facts, and uses distorted information.
Answer: The advice you're working with -- "to determine interval between 2 notes you count from the lowest note to the highest" -- is incorrect.  In fact, you can count in either direction and get the same result, but the direction is of course the opposite.  If you count up from C to G, you get an ascending perfect fifth.  If you count down from G to C you get a descending perfect fifth.  In both cases the interval spans five letters (counting inclusively) and seven semitones (not counting inclusively).
On the other hand, if you count down from C to G (or up from G to C) you have changed the interval.  (This change is known as "inversion.")
English uses ordinal numbers for intervals and for scale degrees.  Because we identify the components of a chord by the interval between the root and the component in question, we also use ordinal numbers to identify them.
As mentioned above, intervals can be either ascending or descending.  A perfect fifth above C is G.  A perfect fifth below C is F.  But because scale degrees and chord components are always identified by the ascending interval, the fifth degree of a C scale is always G.  The fifth of a C chord (and of C7, Cm, Cm7, Cmaj7) is always G, regardless of the chord's voicing.
To identify the chord built on the fifth degree of the scale we use a roman numeral, and we speak it as a cardinal number.  Therefore, "the V chord" is pronounced "the five chord," and in C major (and C minor for that matter) it is always G, because as described above the fifth degree of the scale is always G.
Therefore, your question

If I'm playing in C Major the C Major open guitar chord and then I want to play the 5th to this chord, what chord should I play?"

... doesn't make a lot of sense, because the fifth of any chord isn't another chord; it's just a single pitch.  Since you're asking what chord to play, I suspect that the question is a mistranslation and that it ought to be "...and then I want to play the V chord...," but if it isn't a mistranslation then the second half of the question should be"...what note should I play?"

In the comments, it has been asserted that the major third is so called because it is the third degree of the major scale.  While this is not particularly relevant to this question about "fifth" and "five," it seems like a good opportunity to point out that the reverse is true: the major scale is so called because its third degree is a major third.  I recently addressed this with respect to major chords in my answer to Why is a minor chord or key considered to be "lesser?"
Comment: "you can count in either direction and get the same result" But if you count up three letters in the scale of C you get E, a major 3rd. If you count down three letters you get A. And A-C is a minor 3rd. Because we name intervals by counting up from the lower note, no matter what order the notes are played in. The 'perfect' intervals, 4ths, 5ths and octaves, remain perfect if you count down diatonically. Other intervals don't.   Main point - however you arrive it, from below or above - an interval is always NAMED by counting up from the lower note.
Comment: @phoog And it's called a major 3rd because E is the 3re note of a C major scale.  That's just how the system of interval naming works.  If the top note's in the major scale starting on the bottom note, it's a major interval.  One semitone smaller, it's minor. Another, diminished.  One semitone larger, augmented.  Special case for the 'perfect' intervals, they contract straight to diminished.  We all learnt this in Theory#101.  It's a conventional naming system, not deep harmonic analysis.
Comment: @oyevtushe a perfect fifth is always 7 half steps, but seven half steps isn't always a perfect fifth.  It could be a diminished sixth, for example.  F is always the 4th degree of the C major scale, but any given F could be a fifth below some given C, or a twelfth below, or an 11th above.  The functional role of F in the key of C is typically expressed by IV from its position in the ascending C scale, abstractly, which is why specific voicings don't affect this.
Comment: From what I've understood:

1. the definiton of V chord is bound by scale context, it's not just the 7 half-steps from root notes of chords.
Comment: 2. there's quite an important notion of octave ignorance where we always count from the scale tonic to the note in question, even if notes are in different octaves like F2 and C3, if C is a tonic, then we'll count from C to F and say that F is P4, and it stays P4 no matter the octave it's in (maybe compound intervals add something to this, I didn't think of it yet). So, when we're talking in context of chords and their progression/function in scale, we count intervals this way.
Comment: It's still super confusing, since there's a notion of interval in the context of scale, and the notion of interval like a distance in half-steps between notes in question.
Comment: @Laurence the given rule is "to determine interval between 2 notes...."  To determine the interval between C and and the E above it, you can start at C and count up or you can start at E and count down.  Why would anyone trying to identify the interval between C and the E above it "count down three letters" starting at C??  It makes no sense whatsoever.
Comment: @Laurence to say "we name intervals by counting up from the lower note, no matter what order the notes are played in" makes no sense.  Just as it's 60 miles from London to Cambridge as well as 60 miles from Cambridge to London, counting C-D-E gives the same result as counting E-D-C: it's a third.  E is a major third above C; C is a major third below E.  There is nothing about the name "major third" that implies direction _per se,_ so there is no reason to say that the interval is named with respect to a particular direction.
Comment: @Laurence no, that's backwards.  The major scale is called a major scale because its third degree is a major third.  It's called a major third because it spans three letters and is the larger of the two intervals that may be obtained by spanning three letters.  This concept arose centuries before the major scale even existed as a theoretical construct, and it does not depend on the major scale for its existence (nor does it depend 8n direction).
Comment: @phoog  There are a lot more than two intervals obtainable from a span of three letters!   And that's without getting into double-sharps or flats.  Counting up from the bottom note isn't deep-level analysis, it's just an easy way of working out an interval's name.  Otherwise you've got to memorise a whole LOT of semitone-counts!
Comment: @Laurence well yes, I forgot to mention the additional constraint _without accidentals,_ or, if you prefer, _within any diatonic scale,_ in which case there are only two.  Comparing interval size to the corresponding degree of a major scale is indeed an easy way of identifying interval quality, but it shouldn't be misunderstood as the reason behind interval quality names, nor does it imply that interval measurement somehow works only in one direction.  And memorizing the sizes of the intervals in the major scale _is_ memorizing a lot of semitone counts.
Comment: @Laurence you can also reduce the memorization burden by figuring the quality of sixths and sevenths by inverting them to thirds and seconds and taking the opposite of the quality of the corresponding interval.  Then, for the imperfect intervals, you only have to memorize seconds and thirds.  It sounds cumbersome described like this, but in fact I was thinking of major and minor sevenths as being one and two half steps shy of an octave for years before I could quickly pull 11 and 10 out of my head in association with those intervals.
Comment: @phoog "And memorizing the sizes of the intervals in the major scale is memorizing a lot of semitone counts."  I suppose it would be!  I've never bothered to.  I just know my scales and key signatures.


$\mathcal{C}^{\infty}$ which are not analytical

Question: During a course of functional analysis, we gave the following definition:
$$\mathcal{C}^{\infty}_{c}(\Omega)=\mathcal{C}^{\infty}(\Omega)\cap\mathcal{C}_{c}(\Omega)\qquad\Omega\subseteq\mathbb{R}^{d}\hspace{1.5mm}\text{open}$$
That is, the set of smooth function with compact support. We pointed out that such functions need not to be analytical. My question is, how do we know such functions are not also analytical? Given $f\in\mathcal{C}^{\infty}_{c}(\Omega)$, what is $f$ missing in order to be analytical?
Comment: Bump functions are not analytical.
Comment: More than you'd probably ever want to know --- [How many smooth functions are non-analytic?](https://math.stackexchange.com/q/94634/13130) and [this 9 May 2002 sci.math post](https://web.archive.org/web/20161009194815/mathforum.org/kb/message.jspa?messageID=387148) and [this 19 May 2002 sci.math post](https://web.archive.org/web/20161009194829/http://mathforum.org/kb/message.jspa?messageID=387149).
Answer: Analytic means that there is a power series that converges to that function (locally at every point).
The only power series that is identically zero in a region is the zero series.
That is, nonzero analytic functions cannot have compact support (ignoring arbitrary domain restrictions).
Comment: For reference: This is called the 'identity principle' - it holds both for holomorphic functions and for real analytic functions as here.
Comment: Not quite correct: analytic means analytic at all points, which means that for all $x\in\Omega$ there is an open set $U\ni x$ such that $f(y)$ coincides with the value of a power series centered at $x$ for all $y\in U$. Compare with $\frac1{1+x^2}$ on $\Bbb R$, which is analytic at all points but no single power series represents it everywhere. This is a relevant technical detail in the economy of a proof.
Comment: Thanks, corrected


Is Mark V. Shaney still the best way to generate text?

Question: I want to take large documents and generate text that resembles them. I know that Markov Chains were used to do this with Mark V Shaney. Is there a better way to do it now, or is this approach still basically the best one available?
Comment: I dont know about your answer but this mark v shaney thing is awesome. Found the python code and started jumbling up websites about wolves. http://www.strout.net/info/coding/python/shaney.py
Answer: I am not sure whether Markov Chains are the best way of generating text but that's surely an easy way.
There is an alternative way in deep linguistic processing using semantic to grammatical generators such as the ACE Parser/Generator. Maybe you can test the generation power of deep grammar through their demo site. After you parse a sentence on the demo site, there is an option to generate similar sentences.


Setting up Apache HttpComponents PoolingClientConnectionManager for Spring Web RestTemplate

Question: I am using RestClient to connect to a remote JSON API.
Previously, in Spring 3.0, I was using Commons HTTPClient.
I found that performance was low due to a lot of locking in the old multithreaded connection manager.
I now want to try Apache HttpComponents 4.2 since it appears they fixed up the locking.
I would like to use the PoolingClientConnectionManager as the constructor parameter for the DefaultHttpClient that will be autowired for the different classes.
The challenge is setting up the PoolingClientConnectionManager connection manager. I want a high number of concurrent connection to the JSON API provider. These use HttpRoute objects to represent the hostname. But, as described in http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/PoolingClientConnectionManager.html, PoolingClientConnectionManager uses a setMaxPerRoute(HttpRoute, int maxConnections) method.
How can I set up the connection manager a Spring context.xml file, since it doesn't use simple setters?
Answer: How about wrapping the PoolingClientConnectionManager by extending it, and then creating setters using a Bean representing a route/max value. Ie.
// Your bean
public class RouteMax() {
  private HttpRoute httpRoute;
  private int max;
  ... setters/getters
}

// Extending the PoolingClientConnectionManager
...
public class CustomPoolingClientConnectionManager extends PoolingClientConnectionManager {
...
public setRouteMax(RouteMax routeMax) {
  super.setMaxPerRoute(routeMax.getHttpRoute(), routeMax.getMax());
}

..then in your Spring config you can set the routeMax property using your RouteMax bean.
Answer: In your Spring context.xml file, a better way to configure your httpClient with the PoolingClientConnectionManager is:
<bean id="httpClient" class="org.apache.http.impl.client.DefaultHttpClient">
<constructor-arg>
<bean class="org.apache.http.impl.conn.PoolingClientConnectionManager">
<property name="maxTotal" value="100" />
<property name="defaultMaxPerRoute" value="50" />
</bean>
</constructor-arg>
</bean>

The maxTotal and defaultMaxPerRoute properties should be configured according to the manual:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e627


Como capturar StackOverFlowException

Question: Olá,
Estou passando alguns problemas no servidor e com a aplicação desenvolvida em MVC...
Verifiquei que o site estava reiniciando o pool da aplicação sozinho, então fui no Event Viweer e percebi que a aplicação está sofrendo StackOverFlowException em alguma rotina (que não consegui mapear ainda).
Certo, sabendo disso criei um log de requests para obter as urls que acessavam e assim tentar achar a causa do problema debugando, porém, não consegui achar a causa principal, porque mesmo debugando o sistema pelo localhost e apontando para o banco de produção não ocorre esse StackOverFlowException. Gravo o log em um arquivo .txt antes de entrar em cada action (é desta forma que estou tentando descobrir a rotina que está causando o problema).
Preciso saber de uma forma de capturar essa exceção e descobrir em qual trecho do sistema está ocorrendo este problema.
OBS:
• A aplicação é desenvolvida em MVC.
• Utiliza AutoMapper (acredito que tenha algo a ver, já que tenho que converter para uma ViewModel/DTO cada objeto e exibir na tela as informações).
• Está alocado em um servidor IIS
Atualização 01/06/2017
Utilizei o Elmah, porém não funcionou a maneira que criava o log, pois o pool caía e creio que a versão do Elmah armazenava em memória. Descobri o problema ao entrar em uma página do sistema de forma local e a aplicação cair.
A razão pelo StackoverflowException se dava pelo fato de utilizar dois atributos de roteamento na mesma Controller`:
<code>[RoutePrefix("exemplo")]
[Route("{action}"]
public class TesteController : Controller
{
    ....
}
</code>
Retirei o segundo atributo e o problema sumiu.
O mais engraçado é que está configuração já estava há um bom tempo antes mesmo de eu assumir o projeto. Percebi que também ocorria de forma randômica, pois entrava normalmente em todas as actions desta Controller.
Comment: "acredito que tenha algo a ver, já que tenho que converter para uma ViewModel/DTO cada objeto e exibir na tela as informações". Por que?
Comment: Boa noite, no caso o AutoMapper me deu alguns problemas de referência circular, assim, uma entidade acaba mapeando outra e gera o Overflow. É claro, não é o AutoMapper em si que é o problema, mas a forma que devo estar utilizando ele. Tenho muitas classes mapeadas e eu acho que vai ser um trabalho árduo descobrir qual desses mapeamentos está dando problema.
Comment: Não, não. Eu perguntei por que você precisa "converter para uma ViewModel/DTO cada objeto", porque não precisa não.
Comment: Utilizam um sistema interno para gerarem as tabelas do Banco de Dados, também tem uma nomenclatura na qual cada campo devem ter menos de letras e acaba gerando uma grande confusão. Além disto, a maioria dos campos de todas as tabelas são 'nullables'. A maioria das tabelas possuem campos inutilizados, então eu jogo somente os campos que preciso nas View Models (apesar de poder fazer isso diretamente nas entidades raízes). Preferi fazer desta forma, acredito que foi um erro. Estou esperando a oportunidade de reformular este sistema, mas este erro apareceu e é prioridade corrigi-lo.
Answer: Um método mais eficiente para capturar a exceção (e a Stack Trace toda) é usando o ELMAH.
Procure também publicar juntamente com o sistema o arquivo <code>.pdb</code>, para que você tenha nas mensagens capturadas do ELMAH as linhas em que os erros ocorrem dentro do código fonte.
Comment: Obrigado cara, vou verificar e dar uma estudada nele agora.

Como capturar StackOverFlowException


How can I copy block placements and settings between themes?

Question: How to copy blocks placement and settings between themes? suggests that, in Drupal 7, I could run the following two SQL queries to copy block placements and settings between themes.
DELETE FROM block WHERE theme = 'NEW-THEME'

INSERT INTO block (module, delta, theme, status, weight, region, custom, visibility, pages, title, cache, i18n_mode) (SELECT module, delta, 'NEW-THEME', status, weight, region, custom, visibility, pages, title, cache, i18n_mode FROM block WHERE theme = 'OLD-THEME')

What is the equivalent query/method I could use to achieve the same task in Drupal 8?
Answer: There is a module available for Block backup and restore.
https://www.drupal.org/project/block_backup_restore
Answer: Drupal 8 block settings are in configuration files.  It is possible to transfer them but takes a bit of editing / file renaming.
You first have to do a complete export of the configuration files.  In this, the ones you are looking for have names like block.block....yml, e.g.: block.block.old_theme_main_menu.yml
First step is to rename these to block.block.new_theme...yml, e.g : block.block.new_theme_main_menu.yml.  Generally a quick bit of editing to create a script to do the renaming is the easiest.
Next, you need to change the internal theme references to the old theme to the new theme.  E.g. the old theme yml file will look like:
langcode: en
status: true
dependencies:
  config:
    - system.menu.main
  module:
    - block_class
    - system
  theme:
    - old_theme
third_party_settings:
  block_class:
    classes: ''
id: old_theme_main_menu
theme: old_theme
region: navigation_collapsible
weight: -34
provider: null
plugin: 'system_menu_block:main'
settings:
  id: 'system_menu_block:main'
  label: 'Main navigation'
  provider: system
  label_display: '0'
  level: 1
  depth: 2
visibility: {  }

A good editor should be able to do a replace in files to change old_theme to new_theme.  Double check that your theme names are unique in these files.
If the new theme does not have the same regions, then you will need to figure out how to change the region: setting to match your new theme.
In your new theme, create a config directory in the root and then an install directory under it.
Put all the yml files in the install directory.
Uninstall / re-install the new theme to import the settings here.
This assumes the same site with the same code / custom blocks.
If you are going to use this theme in a new site, you will have to make sure the site will provide the blocks defined in the yml config.  Generally, the install directory is used to place system level blocks (e.g main menu) that core provides.  But if you set up a system with a distro or manually to provide other blocks, this works as well.
There may be some minor gotcha's like visibility settings using the wrong node id and the like.
Answer: I was mostly successful in migrating about 500 blocks from one theme to the next by doing the following:
1. copy all block configs for old theme (eg block.block.theme1.*) to tmp directory
2. Removed configs that were disabled 'status: false'
3. bulk rename 500+ config files from theme1 to theme2 (need a tool for regex or partial string renaming, I used Windows PowerRename)
4. Renamed same theme name strings within each file
5. Removed uuid from each file
6. Copied back into my sync directory and imported.


Setting reply-to address in Domino/Notes

Question: As background, I'm a very reluctant Domino "admin" and know very little about settings on the server.
I have a mail-in database which is using the ID of the admin who set it up as the from/reply address.  Obviously he'd prefer that replies go back to the mail-in database.  Where can I set the reply-to address or the from address to something else?
Clarification (probably the first of many):  The mailbox receives mail (it's the webmaster@ourcompany address).  A couple of people monitor the mailbox and send replies if any are warranted.  We don't want the replies coming from any individual's address - just have them come from webmaster.  Instead, they appear to come from firstname.lastname@example.com.
Answer: I highly recommend converting the design of the mail-in database from the standard mail template to the DominoTeamMailbox template available at OpenNTF:
http://www.openntf.org/Projects/pmt.nsf/ProjectLookup/DominoTeamMailbox
You can manually set the from/reply-to addresses in the database configuration. We use it for all of our mail-in databases (as well as our customers').
Comment: This is looking promising.  I can't find any information about whether it's been updated for Domino 8.  Have you tried it under 8 yet?
Comment: We use it under both 7 and 8 with no problems. It's documented as working for Domino 7 or later, FYI.
Comment: I use this on several client sites, some running 8.5.3 and it works no problem.  The look and feel is not the 8 template, but functionality wise, works perfectly.
Answer: If you make mail-in-database and give it hierrarcical name like info/mail and put it as owner of the mail box, the reply address will be always the internet address of the mail-in-database. (it will show sent by someone though).
Answer: I take it he's got an agent within that database that is sending out email when a new message comes into the database?  Otherwise, why would you be concerned with replies for a database that receives email?
If my assumptions are correct, the easiest solution is to sign that agent with another ID.  You might create a generic ID for this purpose and name it the same or similar to your Mail In Database name.
Depending on how the emails are being generated, you could edit the code in the agent to set the reply address.  For example, if the agent is using the @MailSend function, there's a parameter for reply-to name.  Otherwise, the ID that signed the agent will be used for the from and reply addresses.


Laravel organize helper functions

Question: Please, don't talk to technical in the answers:-D I am not a hardcore programmer.
What is a good way to store certain functions in Laravel? I have functions that apply on a "post" only or "media" only, like getAttributeList or getComponents. I say "Post" and "Media" because both have their own controller, model and views. It feels wrong to put it in the model because that should be database stuff right? And traits are more for recurring functions all over the place, right? So, right now I have one big file called Helpers.php. And uh, it is getting large... should I simply separate it in PostHelpers.php, MediaHelpers.php etc? Or is there a more elegant way in Laravel to do it?
Answer: It is quite simple : Just check your composer.json file at root directory of ur app. and under autoload section add :
 "autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": ["app/helper.php"],
    "classmap": [
        "database/seeds",
        "database/factories"
    ]

"files": ["app/helper.php"], This is the line you need to add in ur composer file and provide the path to file .
In my case i have created a file helper.php in App directory where i keep all my functions .
after this run this command :
    composer dump-autoload
Now u can access your functions anywhere.
Comment: Thanks Shivam, I have that right now at the moment. So I simply chop it into several files. But is it a good idea to turn the helper-files into a class, like a Facade? I thought it was a good idea so I don't overwrite functions, and I don't have to check if the function already excists elsewhere all the time.
Answer: In your composer json file check this snippet
"autoload": {
        "files": [
                "app/Helpers/global_helper.php"
            ],

As you see I have auto loaded 1 single file called global_helper.php in a folder called Helpers Now in this file I have a function called loadHelper(...$files)
What this function does is
if (!function_exists('loadHelper')) {
    function loadHelper(...$file_names)
    {
        foreach ($file_names as $file) {
            include_once __DIR__ . '/' . $file . '_helper.php';
        }
    }
}

You can pass your file name as array or string and it will include those files into your Controller constructor
So In my Controller whenever I want some helper function I create a saperate helper file for that controller then in constructor i ust include it.
I am not sure if there is any better solution but so far this is how I am making all my projects .
I hope this will help you ;)

Laravel organize helper functions


QT: setStyleSheet from a resource QSS file?

Question: In my widget, I can do something like that:
MyWindow::MyWindow(QWidget *parent) :
    QWidget(parent)
{
    ui.setupUi(this);
    setStyleSheet("QWidget { background-color: red }");  // <--- HERE
}

This will set the widget background red.
I have a QSS file in my resources. How do I instruct my widget to take its style sheet content from there, vs just taking the qss syntax as parameter?
Answer: As an alternative to setting a style sheet for each widget, you can just load and set a stylesheet for a whole application. Something like this:
QApplication app( argc, argv );

// Load an application style
QFile styleFile( ":/style.qss" );
styleFile.open( QFile::ReadOnly );

// Apply the loaded stylesheet
QString style( styleFile.readAll() );
app.setStyleSheet( style );

In this case all widgets will pick their styles from the given stylesheet automatically.
Answer: Got it: you actually have to "read the file" from the resources, convert it to a QString and feed it to the setStyleSheet. E.g.:

QFile file(":/qss/default.qss");
file.open(QFile::ReadOnly);
QString styleSheet = QLatin1String(file.readAll());
setStyleSheet(styleSheet);

Comment: what is ensurePolished for?
Comment: But don't forget to call ensurePolished() otherwise the new stylesheet may not be applied.
Comment: @ffttyy This ensures that the new style is actually applied to the widgets. I had cases where the new style wasn't applied otherwise.


Mathematical derivation from Deep learning book

Question: In https://www.deeplearningbook.org/contents/mlp.html p. 179 this derivation is made but lacks details that I need to understand it:
$P(y)= \frac{exp(yz)}{\sum_{y'=0}^{1}exp(y'z)} = \sigma((2y-1)z)$
Where $\sigma(x) =  \frac{1}{1+exp(-x)} =  \frac{exp(x)}{1+exp(x)}$
I just cannot see how they "magically" make this $(2y-1)z$ appear… please can someone kindly show me all the details of this derivation?
I tried things /tricks like multiplying by fractions equal to 1 such as $exp(…)/exp(…)$ etc. but cannot find…
P.s. I think this expression can be developed as:
$ \frac{exp(yz)}{\sum_{y'=0}^{1}exp(y'z)} =  \frac{exp(yz)}{exp(0*z)+exp(1*z)}=  \frac{exp(yz)}{1+exp(z)}$
However, I do not see how one can play with this last expression to make it equal to  $\sigma((2y-1)z)$ …
Comment: There are these tricks when a variable takes on one of two values (e.g. 0 or 1, -1 or 1, etc.). If y can only be 0 or 1, then 2y-1 can only be 1 or -1. It's a way of making the choice of {0,1} into a choice of {-1,1}. Sometimes we want to have the latter over the former. That's my guess over why it just pops up.
Comment: Hum but how do they get the general formula with 2y-1 …?
Comment: It does matter I would like to understand at least your substitution
Comment: $y$ can only ever be $0$ or $1$, so you only need to check the equation for those two values. Substitute each one in turn and you will see the equation is true. I don't think it's true for other values of $y$.
Comment: Divine inspiration? Who knows? Does it matter as long as it's true?
Comment: The sigmoid((2y-1)z) will either be sigmoid(z) or sigmoid(-z) but by substituting y=0 or y=1 in the other eq. I would get both times sigmoid(z) hence I can never get simoid(-z) what do you think?
Comment: $\sigma (-z) = \exp (-z) / (1 + \exp(-z)) = 1 / (1 + \exp z) = P(0)$. I don't see a probem.
Comment: Oh yes I see now. Sorry I got confused. Thanks. You are a genius.
Answer: You only need to write things...
$$
P(y=0) = \frac{1}{1+\exp(z)}= \sigma(-z)
$$
$$
P(y=1) = 1-\sigma(-z) = \sigma(z)
$$
So you can write 'magically' $P(y)=\sigma((2y-1)z)$ for $y=0$ or $1$.


Is there a way to subtract a column values according to other column?

Question: I have this dataframe:
<code>  name     color   number
0  john     red       4
1   ana     red       4
2   ana     red       5
3  paul     red       6
4  mark     red       3
5   ana  yellow      10
6  john  yellow      11
7  john  yellow      12
8  john     red      13
</code>
If the value in color column change (according to the name column), I want to create another column with the subtraction between the last value associated to the color and the first value from the new color. If the value in color column don't change, return -999.
Ex:
Looking to ana, the last value for red is 5 and the first value for yellow is 10. So, the new column will be 10 - 5 = 5 to ana.
Looking to john, the last value for red is 4 and the first value for yellow is 11. So, the new column will be 11 - 4 = 7 to john. Do that just one time. If the color change again, it doesn't mather.
I want this output:
<code>   name   color  number  difference
0  john     red       4           7
1   ana     red       4           5
2   ana     red       5           5
3  paul     red       6        -999
4  mark     red       3        -999
5   ana  yellow      10           5
6  john  yellow      11           7
7  john  yellow      12           7
8  john     red      13           7
</code>
please, somebody help me?
Comment: But isn't the John's last `red` equal to `13`?
Comment: John's last red, before switch to yellow, equal to 4
Answer: try in this way
<code>df = pd.DataFrame({'name':['john','ana','ana','paul','mark','ana','john','john','john'],
                   'color':['red','red','red','red','red','yellow','yellow','yellow','red'],
                   'number':[4,4,5,6,3,10,11,12,13]})

df['color_code'] = df['color'].factorize()[0]

partial_df = pd.DataFrame()
partial_df['difference'] = df.groupby('name')['number'].apply(lambda x: list(np.diff(x))).explode()
partial_df['change_status'] = df.groupby('name')['color_code'].apply(lambda x: list((np.diff(x)>0)+0)).explode()

map_difference = partial_df.loc[partial_df.change_status != 0].reset_index().drop_duplicates('name').set_index('name')['difference']
df['difference'] = df.name.copy().map(map_difference).fillna(-999)
df
</code>


Using fwrite with angle brackets and quotation marks

Question: I'm creating a form to append data into an XML database, which is being read by a widget on another page. The format that I need the data to be in is as follows:
<event start="1914" end="1918" isDuration="true" title="World War I" color="red">
Lots of guns and death.
</event>

However, I'm not sure how to do this with PHP's fwrite function because of the use of angle brackets and quotation marks. For example, I tried the following:
fwrite($database, <event start="$startdate" end="$enddate"
isDuration="$isDuration" title="$title" color="$color">
$description
</event>);

But this does not work, I get errors about unexpected angle brackets, etc. If anyone can help I would greatly appreciate it.
Answer: You're supposed to give it a string.

string
The string that is to be written.
Answer: fwrite($database, "<event start=\"{$startdate}\" end=\"{$enddate}\"  isDuration=\"{$isDuration}\" title=\"{$title}\" color=\"{$color}\"> {$description} </event>");


the set of matrices $A=\begin{bmatrix} a & b \\ c & d \end{bmatrix}$ satisfies following properties

Question: consider a matrix $A\in\mathbb{R^{2\times2}}$
$$A=\begin{bmatrix}
a & b \\
c & d
\end{bmatrix}$$
and let $A$ has the following properties
$\bullet$ $A$ is not invertible
$\bullet$ $A$ is symmetric
$\bullet$ all the entries of $A$ is positive
$\bullet$ $A$ has a positive eigenvalue $\lambda=p>0$
Find the set of all matrices $A$ as a function of $p$
My attempt
$\bullet$ $A$ is not invertible $\implies ad=bc$
$\bullet$ $A$ is symmetric $\implies b=c$
$$(A-\lambda I)v=0\\
\begin{bmatrix}
a-\lambda & b \\
c & d-\lambda
\end{bmatrix}v=0\\
(a-\lambda)(d-\lambda )-bc=0\\
\lambda^2-\lambda (a+d)+ad-cb=0\quad,\text{and}\quad ad=bc\\
\lambda^2-\lambda (a+d)=0$$
We know the determinant is the product of eigenvalue. Since it is singular, one of its eigenvalue must be zero, and the other is $p=a+d$
So the set of all matrices is as long as $p=a+d$
Second way
$$A=\begin{bmatrix}
a & b \\
c & d
\end{bmatrix}\sim \begin{bmatrix}
ac & bc \\
ca & da
\end{bmatrix}\sim \begin{bmatrix}
0 & ad-bc \\
c & d
\end{bmatrix}\sim\begin{bmatrix}
c & d \\
0 & ad-bc
\end{bmatrix}$$
Then $c$ will be that positive eigenvalue, and $ad=bc=p^2$ then proceeded to obtain
$$\begin{bmatrix}
a & p \\
p & \frac{p^2}{a}
\end{bmatrix}$$
What's wrong with this second way? I think it's row operation change the eigenvalue? I am not too sure.
Comment: What's your question? Or should it be a wiki?
Comment: Very good so far. What's your question?
Comment: Thank you for your reply. I am not sure if this is correct, is this looks right?
Comment: Just a note: rather than perform all of that algebra, you could use that the determinant is the product of the eigenvalues (as you noted) and the trace is the sum of the eigenvalues to know that $a+d=p$
Answer: You we have done is fine. It lacks the final answer to the question, which is:$$\left\{\begin{bmatrix}a&\sqrt{a(p-a)}\\\sqrt{a(p-a)}&p-a\end{bmatrix}\,\middle|\,a\in(0,p)\right\}.$$
Comment: There is nothing wrong with that approach. Without seeing the details, I can't say what went wrong. But note that what you got were the matrices $\left[\begin{smallmatrix}a&b\\c&d\end{smallmatrix}\right]$ which are symmetric, with $0$ determinant and such that $a+d=p(\iff d=p-a)$. That is precisely my answer.
Comment: In the first step of your sequence of matrices, you multiply the first line by $c$ and the second line by $a$. That changes the eigenvalues. If a matrix is, say, $\left[\begin{smallmatrix}2&0\\3&0\end{smallmatrix}\right]$, its eigenvalues are $2$ and $0$. Now, if you multiply the first line by $3$ and the second line by $2$, you get $\left[\begin{smallmatrix}6&0\\6&0\end{smallmatrix}\right]$, its eigenvalues are $6$ and $0$, not $2$ and $0$.
Comment: Thank you for your reply.  I then tried differently, going with reducing the matrix into a triangular form, then it seems to get a different answer. Is that never trying to find the eigenvalue by reducing the matrix into triangular form?
Comment: I think it should be $a\in [0,p]$
Comment: @JoséCarlosSantos Thank you for your reply. I've just edited another part.
Comment: @Joe If positive here means greater than or equal to $0$, yes. But I assumed that it meant greater than $0$.
Comment: ah, I completely missed that condition.
Comment: @JoséCarlosSantos would you please check out my **Second way**
Comment: Why would $c$ be the positive eigenvalue? Why not $ad-bc$? Besides, do you have something against my solution?
Comment: @JoséCarlosSantos I don't have any issue with your solution, but I cannot tell exactly where **method 2** went wrong. The $c$ be eigenvalues simply turns matrix into a triangular form, so that the diagonal is the eigenvalues, $ad-bc$ is another eigenvalue $0$


Getting a perfect output using .format()

Question: Write a function called print_grades that accepts the name of a file (string) as input argument. Your function should call the function to read a file and create the grades dictionary. Using the grades dictionary, your function should print the names, grades, and averages of students with the exact format shown below. Notice that you are asked to write a function (NOT a program) and that function prints the grades. Your function should return None after printing the grades.
Sample Input file:
1000123456,Rubble,Test_3,80,Test_4,80,quiz,90
1000123210,Bunny,Test_2,100,Test_1,100,Test_3,100,Test_4,100
1000123458,Duck,Test_1,86,Test_5,100,Test_2,93,Test_4,94

Your program's output should be:
    ID     |       Name       | Test_1 | Test_2 | Test_3 | Test_4 |  Avg.  |
1000123210 | Bunny            |    100 |    100 |    100 |    100 | 100.00 |
1000123456 | Rubble           |      0 |      0 |     80 |     80 |  40.00 |
1000123458 | Duck             |     86 |     93 |      0 |     94 |  68.25 |

Notes:

Column titles are all centered
The printed output is sorted in ascending order based on the student IDs
Each column is seperated from a neighboring column(s) by three characters ' | ' (space vertical_bar space).
IDs are always 10 characters and they are left justified (not counting the boundary characters)
Names are left justified (maximum of 16 characters, not counting the boundary characters).
Grades and averages are right justified. The width of the columns for the grades and averages is 6 characters (not counting the boundary characters).
Averages are right justified with two digits of accuracy after the decimal point.

Code developed so far. And please tell me what to do next.
CODE:
def create_grades_dict(file_name):
my_dict={}
file_pointer=open(file_name, "r")
data = file_pointer.readlines()
for line in data:
    datalist = line.strip().split(',')
    if len(datalist) < 2:
        continue
    stud_id, last_name = datalist[:2]
    namelist, gradelist = [], []
    for name in datalist[2::2]:
        namelist.append(name.strip())
    for grade in datalist[3::2]:
        gradelist.append(int(grade.strip()))
    namelist.append('avg')
    avg = sum(gradelist)/float(len(gradelist))
    gradelist.append(avg)

    newdict = dict(zip(namelist, gradelist))
    my_dict[stud_id]=[last_name, newdict]
    return my_dict

ERROR:
Error in evaluating function:
ValueError at line 7
too many values to unpack

Comment: You gave only six names to a line that has eight values.
Comment: your trying to split 8 values into 6 variables
Answer: A few things you should keep in mind:

Your input line may contain junk data - data you need to ignore.
Your input file may have blank lines, which you need to test for.

Unpacking a variable requires a balance between the left and the right hand side of the = sign; if you have too many things on the right, and too few variables on the left, you will get:
>>> a,b,c = 1,2,3,4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

Of course, if you have too many variables on the left, then you get a different error:
>>> a,b,c = 1,2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

Try reading the entire line, and split by , (as you are doing now). Then, step through the list returned, and then separate your values - rather than assuming all the lines will have the correct information in the right order.
Answer: As Burhan explained you the error. you can proceed like this:
a = "1000123456,Rubble,Test_3,80,Test_4,80,quiz,90"
>>> my_val = a.split(",")
>>> my_val
['1000123456', 'Rubble', 'Test_3', '80', 'Test_4', '80', 'quiz', '90']
>>> id,name = my_val[0], my_val[1]
>>> id
'1000123456'
>>> name
'Rubble'
my_dict = dict(zip(my_val[2::2],my_val[3::2]))
>>> my_dict
{'Test_4': '80', 'Test_3': '80', 'quiz': '90'}

NOW you can use dict.get(key[,default])
>>> my_dict.get('Test_4',0)
'80'

Answer: To get this as you expected you need two functions:
First function:
def create_grades_dict(file_name):
    my_dictionary = {}
    file_pointer = open(file_name, 'r')
    data = file_pointer.readlines()
    for line in data:
        student_row = map(str.strip, line.strip().split(','))
        student_id = student_row.pop(0)
        student_lastname = student_row.pop(0)
        student_data = [student_lastname]
        for valid_test in ['Test_1', 'Test_2', 'Test_3', 'Test_4']:
            if valid_test in student_row:
                student_data.append(int(student_row[student_row.index(valid_test) + 1]))
            else:
                student_data.append(0)
        student_data.append(sum(student_data[-4: ])/4)
        my_dictionary[student_id] = student_data
    return my_dictionary

2nd function:
def print_grades(file_name):
    # Call your create_grades_dict() function to create the dictionary
    grades_dict=create_grades_dict(file_name)
    print ("    ID     |       Name       | Test_1 | Test_2 | Test_3 | Test_4 |  Avg.  |")
    for key in sorted(grades_dict.keys()):
        print ("{0:<10} | {1:<16} | {2:>6} | {3:>6} | {4:>6} | {5:>6} | {6:>6.2f} |".format(key, grades_dict[key][0],  grades_dict[key][1],  grades_dict[key][2], grades_dict[key][3], grades_dict[key][4], grades_dict[key][5], ))

So you see second function call the first function and it gave the correct output:
 ID     |       Name       | Test_1 | Test_2 | Test_3 | Test_4 |  Avg.  |
1000123210 | Bunny            |    100 |    100 |    100 |    100 | 100.00 |
1000123456 | Rubble           |      0 |      0 |     80 |     80 |  40.00 |
1000123458 | Duck             |     86 |     93 |      0 |     94 |  68.25 |


Conditional probability to be calculated but I'm not able to solve the first part of the question

Question: Suppose that a box contains one blue card and four red cards. The red cards are labelled $X$, $Y$ , $Z$, and $W$. Suppose also that two of these five cards are selected at random, without replacement.

If it is known that card $X$ has been selected, what is the probability that both cards are red?

If it is known that at least one red card has been selected, what is the probability that both cards are red?

I'm not able to solve the first part $P(i) = 3/4$ but idk how like help.
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info). Then tell us what you understand thus far, what
you've tried & where you're stuck. We'll provide hints to
help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you
is grounds for closing.
Comment: You have five cards overall, and you label them with four letters? Is $X$ a red card? What in $i$ in $P(i)$?
Comment: Nikhil, I have edited the question to make "The red cards are labelled X, Y , Z, and W." more salient (initially I thought/interpreted that the blue one could just as well be labeled with X, Y, Z, or W). I guess that this was the intention of the question, or otherwise I do not see how we can get 3/4.
Comment: yeah my professor didn't write the question properly and initially I also assumed that it was likely that the blue card could be labelled. But now I've got it thanks!
Answer: Can you at least make a list of possible two-card sets from five cards labeled $B, W, X, Y, Z$?  Hint: There are only ten such sets; you find more than ten, check for duplicates in your list, and remember that $\{B,X\}$ is the same set as $\{X,B\}$. How many of these two-card sets on your list include $X$ as one of the cards? How many of these two-card sets that include $X$ on your (hopefully shorter) list consist of two red cards? Hint: one of the cards must be $X$; what is the other red card?
Comment: yay! got the answer thanks!!!!!
Answer: It depends on how we got to know that card X is among the two cards.
Like Dilip Sarwate's answer (+1) we can enumerate the different sets with an X in it (and make it a combinatorial problem), but we do not know how the sets arise and whether they have equal probabilities conditional on X being in the set.
For example, it could be that always a random labeled (red) card from the two selected cards is revealed (whether it is X or not). It just happens that it contains an X but it could have been another letter. If the X occurs among the two selected cards while one of them is a blue card, then it is more likely that it gets revealed (because it is the only labeled card). This makes the problem related to the Monty Hall problem.
This is an example that shows that we need to know the entire process that generates the data and information. Just a conditional statement, without context, is not enough.


How to show contact profile and membership details in one Civicrm report?

Question: I had a new profile called "Registration details" for contacts, and the profile fields can be edited in account page.
In my contribution page, membership form is enabled as a sign up form for my members, and the new profile  "Registration details" is included in the form.
I would like to have a report to show a summary of contact details, including  "Registration details" profile, and filter by membership status.
If I'm using Constituent Summary Report, I can get all the contact details summary, but I can't filter the report to show those with active membership only.
If I'm using Membership Details Report, I can filter the membership status accurately, but can't show the new profile fields of "Registration details".
Is there anyway I can configure it so that I can show both contact details and filter by membership status? Or should I make any changes to the profile?
PS: I'm using drupal 7, with CiviCRM 4.4.6.
Answer: Since you are using Drupal it can often be easier in my non-coding experience, to build a View to provide you with these kind of Reports - happy to provide more pointers if that is the direction you end up going
Comment: Thanks for taking the time to accept the answer. If you haven't committed yet to the area51 for CiviCRM please do so.
Comment: Yes, I had committed. Hope the beta site will be available soon!


Why is the pip installation of Cython taking so long?

Question: Few minutes ago I tried to install Cython on my computer (currently I'm working on Windows 10, Python 3.6), and I typed "pip install Cython" to command prompt, so it has downloaded it successfully, now installation still lasts, it has been working about 10 minutes, so something is wrong. The same story happened with NumPy, but I've given up with installation, because it isn't necessary for me now. Any ideas? Before I've updated Visual C++, because when I tried to install NumPy, error occurred and referred me to install last Visual C++ version so I did it with link attached with error message.
Comment: probably it is compiling, you should either wait, or give more details on what is happening in the console.
Comment: https://scr.hu/6AlB22
Comment: @dannyxn you should edit your question and directly embed it (don't link externally)
Comment: Both need to compile a lot of things. In case of you are having a slow computer it will take even longer. Check your task manager to see what its doing. But most likely you will see compiler process running and consuming a lot of resources.
Answer: It's taking a long time because it's compiling the library from it's C source. Depending on the speed of your computer and the size of the library, this can take a long time.
You say you're not seeing any output while the compilation takes place. Most likely the setup that starts the compiling isn't piping stdout and stderr lines. Have a look at your Task Manager and see if the compiler process is taking up a lot of CPU, if it is, then most likely it's working. Leave the machine alone while it compiles (don't watch videos in the background, etc.), plug it in if it's a laptop.
There may be pre-compiled binaries in the wild, but they'll need to be linked against the same version of Python you're using.
Comment: Installing cython on a raspberry pi 3 with python 3.6.3 took ~15 minutes just now, and appeared to hang at the same point as in @dannyxn's screenshot for most of that time, before completing successfully.  Just give it time.
Comment: Why doesn't the he see the output of the compilation then? At least on Linux, installing Cython produces loads of output.
Comment: You should mention in your question that you're not seeing any output.
Comment: But as I remember, when I was installing, for example NumPy, on my old computer, there wasn't the same problem, now I'm working on much faster.
Comment: I was asking about that
Comment: Becouse i felt that something is wrong, I am worrying about no output in console
Comment: I pasted screenshot


Solution to $xy\,dx-(x^2+y^2)\,dy=0$

Question: I need to find the general solution to this differential equation, can anyone help?
$$xy\,dx-(x^2+y^2)\,dy=0$$
Comment: Have you tried the exactness test ? What have you tried ??
Comment: It's a homogeneous differential equation.
Comment: Well if I hit this into Wolfram|Alpha I get$$y=\pm\frac x{\sqrt{W(Kx^2)}}$$where $K$ is an arbitrary constant and $W(x)$ is Lambert's W function.
Answer: $$(xy) dx-(x^2+y^2)dy = 0$$
Let $F(x,y) = xy$ and let $G(x,y) = x^2+y^2$
Now consider a function $u(x,y) = 0$
Then $$\frac{\partial u}{\partial x}dx + \frac{\partial u}{\partial y}dy = 0 $$
So $$\frac{dy}{dx} = -\frac{\frac{\partial u}{\partial x}}{\frac{\partial u}{\partial y}}$$
If $\frac{\partial F}{\partial y} = \frac{\partial G}{\partial x}$, then $u(x,y)$ is a solution
$\frac{\partial F}{\partial y} = x \neq \frac{\partial G}{\partial x} = -2x$
So consider an integrating factor $\lambda:$
$$(\lambda xy)dx -\lambda(x^2+y^2)dy = 0$$
We want to have $\lambda$ such that:
$$\frac{\partial \lambda F}{\partial y} = \frac{\partial \lambda G}{\partial x}$$
First let's try $\lambda$ as a function of $x$:
$$\implies \lambda\frac{\partial F}{\partial y} = \lambda\frac{\partial  G}{\partial x}+G\frac{\partial \lambda}{\partial x}$$
Substituting in we get:
$$\lambda x = -2\lambda x -(x^2+y^2)\frac{d \lambda}{dx}$$
$$3\lambda x +(x^2+y^2)\frac{d \lambda}{dx} = 0$$ - and stuck - try instead $\lambda(y)$
$$\implies \lambda \frac{\partial F}{\partial y} + F\frac{\partial \lambda}{\partial y} = \lambda \frac{\partial G}{\partial x}$$
Substituting in:
$$\lambda x +xy \frac{d \lambda}{dy} = -\lambda \cdot 2x$$
$$3\lambda x +xy \frac{d \lambda}{dy} = 0$$
$$x(3\lambda + y\frac{d \lambda}{dy}) = 0$$
$$\frac{d \lambda}{dy} = \frac{-3\lambda}{y}$$
$$\implies \ln \lambda = -3\ln y + c \implies \lambda = Ae^{\ln y^{-3}} = \frac{A}{y^3}$$
Letting $A = 1$
Then we have $\lambda (y) = \frac{1}{y^3}$
$$(\frac{x}{y^2})dx -(\frac{x^2}{y^3}+\frac{1}{y})dy = 0$$
Now this is in exact form.
So we have that $$\frac{\partial u}{\partial x} = \frac{x}{y^2}$$
$$\implies u = \frac{x^2}{2y^2} + f(y) + c_{1}$$
We also have that  $$\frac{\partial u}{\partial y} = -(\frac{x^2}{y^3}+\frac{1}{y})$$
Now taking the partial derivative of our expression of $u$ with respect to $y$:
$$\frac{\partial u}{\partial y} = -\frac{x^2}{y^3} + \frac{\partial f(y)}{\partial y}$$
Then comparing these two we can see that:
$$\frac{\partial f(y)}{\partial y} = -\frac{1}{y}$$
$$f(y) = -\ln|y|$$
Then our final solution is: $$u(x,y) = \frac{x^2}{2y^2}-\ln|y|+c_{1} = 0$$
$$\implies x^2 = 2y^2\ln |y| + 2c_{1}y^2$$
$$x^2 = y^2 \ln(y^2) + \ln (c_{2}) y^2$$, with $\ln c_{2} = 2c_{1}$
Then $$x^2= y^2(\ln(y^2) + \ln c_{2})$$
$$\implies x^2 = y^2\ln(c_{2}y^2)$$
Comment: @JakeF That answer follows from what I had, I edited my answer to get the answer in that form.

Solution to $xy\,dx-(x^2+y^2)\,dy=0$


delete/approve comment

Question: How can the administrator delete an "impolite" comment and approve comments before publishing?
Globally speaking, what is the best management of the comments?
Answer: You can set permissions for users - Skip comment approval in admin/people/permissions/list#module-comment(in drupal 7). After as admin you can manage your comments here - admin/content/comment you can approve comments, delete them or unpublish.

delete/approve comment


Azure.Data.Tables querying only next record (limit/take 1?)

Question: I am using the quite new NuGet package Azure.Data.Tables-package with .NET 6 with two Azure Functions. One function is writing some records to a table. The other function is timer triggered and should pick up only one record at a time. The next record is identified by a DateTime column called Next.
So I have some code like this:
var yesterday = DateTime.UtcNow.Add(TimeSpan.FromDays(-1));
Pageable<MyEntity> queriedEntities = TableClient.Query<MyEntity>(filter: TableClient.CreateQueryFilter($"Next gt {yesterday}"));

Now I don't want the Azure function to pull all records to the memory while I only want to work with one record. In MySQL for example I would do it with LIMIT 1. ORDER BY is not required. It should only be one record for each run.
How do I add this limitation to the code sample above? Is it even possible? I read about take option, but I don't get it...
Comment: I'm not well versed in this library, but I believe it should be `TableClient.Query(filter: TableClient.CreateQueryFilter($"Next gt {yesterday}")).Take(1);`, that it, just add the take method at the end of your call.
Comment: You made me facepalm myself. Thanks, bro. I confused myself by my IDE, because the return type changes to IEnumerable so .Take(1) did not compile...
Comment: However, this would still pull all records and only take one from the result..., so not comparable with a true limit, I guess. I don't think, that .Take(1) will ensure a better Query-performance.
Comment: Take(1) is supported by the library, and provided it is called on a queryable should only bring one result. If it is fetching a thousand results and filtering in memory, it is probably treating as an enumerable source.
Comment: Do I understand correctly that you always want the newest entry? Then you could for examle use the Unix timestamp - current datetime in ticks as your PartitionKey and just query 1 item without any filters.
Comment: Not the newest entry, but an entry that will be next according to a DateTime column.

Ortigas and your answer both work well. However, I would say the version with .Take(1) is more economical.
Answer: To get just one item you can query like this
var entity = await tableClient.QueryAsync<T>(filter: TableClient.CreateQueryFilter($"Next gt {yesterday}"), maxPerPage: 1).FirstOrDefaultAsync();

Note: I'm using the System.Linq.Async package here.


CMake Couldn't find OPENMP(Mingw,Win10,VSCODE)

Question: I'm struggling in compiling a project using OpenMP on Win10. My c++ project is on VSCODE, and I use MINGW32.
The error is :
<code>-- Could NOT find OpenMP_C (missing: OpenMP_C_FLAGS OpenMP_C_LIB_NAMES)
-- Could NOT find OpenMP_CXX (missing: OpenMP_CXX_FLAGS OpenMP_CXX_LIB_NAMES)
-- Could NOT find OpenMP (missing: OpenMP_C_FOUND OpenMP_CXX_FOUND)
-- Configuring done
-- Generating done
-- Build files have been written to:F:.../build
</code>
The CMakeLists file associated to the search of OpenMP in the project is the following:
<code>cmake_minimum_required(VERSION 3.10)
project(RayTracing)

set(CMAKE_CXX_STANDARD 17)
set (CMAKE_FIND_ROOT_PATH C:/MinGW)

message(STATUS "Checking OpenMP")
find_package(OpenMP)
IF(OPENMP_FOUND)
    message("Found OpenMP! ^_^")
    # add flags for OpenMP
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${OpenMP_SHARED_LINKER_FLAGS}")
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}  ${OpenMP_EXE_LINKER_FLAGS}")
    target_link_libraries(RayTracing PUBLIC OpenMP::OpenMP_CXX)
ELSE()
    message("Missed OpenMP! x_x")
ENDIF()

set(SOURCE_FILES main.cpp)

add_executable(RayTracing ${SOURCE_FILES})
</code>
Yes, I have searched almost all the posts on Internet. But they are all about MacOS and clang. I cannot find a solution for my case. Any ideas? Please, I really need help.
Answer: Are you still using the old MinGW? You should really use MinGW-w64 instead.
The MinGW-w64 build from http://winlibs.com/ comes with OpenMP.


Shell script within .app bundle errors out

Question: I use a shell script named myapp.command to open an app such as the Microsoft PowerShell app:
#!/bin/sh
exec /usr/local/microsoft/powershell/7/pwsh

The script works fine. However, when I put the same script inside a macOS bundle (called myapp.app), it does not work. The error message I get is, myapp.app quit unexpectedly.
Error report reveals that the error occurs in /Applications/myapp.app/Contents/MacOS/myapp.command.
Exception type: EXC_CRASH (SIGABRT)
Exception Note: EXC_CORPSE_NOTIFY
Application Specific Information: abort() called
The contents of Info.plist are as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>English</string>
    <key>CFBundleGetInfoString</key>
    <string>1.0, Copyright © 2019 MyCompany, All Rights Reserved</string>
    <key>CFBundleIdentifier</key>
    <string>com.mycompany.MyApp</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>mycompany.myapp</string>
    <key>CFBundlePackageType</key>
    <string>BNDL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>1.0</string>
    <key>NSHumanReadableCopyright</key>
    <string>Copyright © 2019 MyCompany, All Rights Reserved.</string>
    <key>NSPrincipalClass</key>
    <string>ShellScript</string>
    <key>CFBundleExecutable</key>
    <string>myapp.command</string>
    <key>CFBundleIconFile</key>
    <string>MyCompany</string>
    <key>NSMainNibFile</key>
    <string>main.nib</string>
</dict>
</plist>

How can I fix/troubleshoot this?
Comment: "It's criminal. There ought to be a law. Criminal."
Comment: Odds are it's a gatekeeper issue; I don't see any appropriate permissions in the info.plist. I assume this is an AppleScript app, so can you show the relevant code (the line(s) where you call the shell script)? You may have to give it permission to control other apps in System Preferences☞Security & Privacy☞Privacy☞Automation
Comment: It is a command line app made with .net core. **myapp.command** works when I double-click on it. I can also open the app by entering `./path/to/file` in Terminal.
Answer: pwsh crashes because it is not connected to any tty
A work-around is to tell the Terminal App to launch it:
#!/bin/sh
osascript -e '
    tell app "Terminal"
        do script "/usr/local/microsoft/powershell/7/pwsh; exit $?"
        activate
    end tell
'