select recursive and order by

Question: I use below query to select recursive top to bottom
e.g
If tagId is 1 will get rows 1 > 3,4, > 5 now works fine,
but I want to know how to get result order by "Name" at each level(same parent id) get rows 1 > 4,3 > 5 ?
I treid add ORDER BY "Name" after SELECT * FROM "Tag" WHERE "TagId" = $1 but not work .
and if add after SELECT * FROM tag_tree that will mess level become 1,4,5,3 not what I want .
CREATE TABLE IF NOT EXISTS "Tag"(
"TagId" SERIAL NOT NULL,
"ParentTagId" integer,
"Name" varchar,
PRIMARY KEY ("TagId")
);

TagId | ParentTagId | Name |
1     |             | a   |
2     |             | b   |
3     | 1           | b   |
4     | 1           | a   |
5     | 3           | a   |

var query = 'WITH RECURSIVE tag_tree AS (
  (
    SELECT * FROM "Tag" WHERE "TagId" = $1
  )
  UNION ALL
  SELECT child.* FROM "Tag" child
    JOIN tag_tree parent on parent."TagId" = child."ParentTagId"
)
SELECT * FROM tag_tree';

Answer: Add ORDER BY with coalesce():
WITH RECURSIVE tag_tree AS (
  (
    SELECT * FROM "Tag" WHERE "TagId" = 1
  )
  UNION ALL
  SELECT child.* FROM "Tag" child
    JOIN tag_tree parent on parent."TagId" = child."ParentTagId"
)
SELECT * FROM tag_tree
ORDER BY coalesce("ParentTagId", 0), "Name";

 TagId | ParentTagId | Name
-------+-------------+------
     1 |             | a
     4 |           1 | a
     3 |           1 | b
     5 |           3 | a
(4 rows)

For the documentation:

The COALESCE function returns the first of its arguments that is not
  null. Null is returned only if all arguments are null. It is often
  used to substitute a default value for null values when data is
  retrieved for display.

In this case the function changes null to 0.
Comment: what is the 0 means??

select recursive and order by


Understanding the statement $S = \{x : x \in S\}$

Question: In Introduction to analysis by Rosenlicht there is the following set definition:
$$S = \{x : x \in S\}$$
There is no specific context to this it's just that I find this a little recursive. I would read it "$S$ is a set of $x$ for which every $x$ is an element of $S$". Is that correct?
Comment: You're reading it wrong, by the way. It says "$S$ is **the** set of $x$ such that $x\in S$". "the" versus "a" is hugely important here...
Comment: Does the book actually give that as the _definition_ of $S$? I hope not - that would make no sense. More likely is the author just presents it as a true fact, _not_ a definition.
Answer: You are right! This definition is recursive and meaningless. You are also reading it correctly as something like "the set of everything that is an element of S"
The problem here is that there is no definition of set. It is a primary concept. The reason why we don't define "set" is because you would have defined it in terms of other things, which themselves are defined in terms of "lower-level things" and the chain would never end.
So, unless you really want to go deeper into the foundations of mathematics and set theory, for most practical purposes, you can just think of a set as an "arbitrary collection of elements" that is defined ONLY by its elements, and where order does not matter.
For example, if $S:=\{1,2,3\}, T:=\{2,3,1\}$ and $U:=\{x \in \mathbb{Z} : 0<x<4\}$, then $S, T$ and $U$ are the same set.
Comment: @MichaelMunta It's not a definition, it just says that "for any set, we have....", meaning that statement is true for any set (see Mauro Allegranza's final paragraph)
Comment: So what I have specified is the most general way we can define a set with mathematical notation? If we put any other condition after the colon it would already be something specific.
Comment: I wouldn't say so, because that's not a definition at all. It's like saying that "a continuous function is any function that is continuous". Note that not only you are defining $S$ in terms of $S$ itself, but also the notation sign "$\in$" only makes sense once the concept of set is already defined
Comment: Hmm, what is the point of that line in the book then? What does the author want to say with that?
Comment: I don't have the book within my hands, so who knows
Comment: https://www.amazon.com/Introduction-Analysis-Maxwell-Rosenlicht/dp/1388262800   You can look inside the book, it is on the 3rd page
Comment: So it can be thought of like every set $S$ has certain elements $x$ for which there is an implied condition of $x \in S$? It is just something that is universally true for a set that contains some elements.
Comment: @MichaelMunta Sure, if $x$ is an element of $S$, then $x \in S$ This holds for any conceivable $x$ and $S$
Comment: It's a definition. It's just not a predicative definition.
Answer: The so-called Set-builder notation is used to "specify" a set.
Its syntax is

$S = \{ x \mid \varphi(x) \}$

where formula $\varphi(x)$ expresses a property (a condition).
The meaning is :

"the set $S$ is made of all and only those object that satisfy condition $\varphi(x)$".

As a way to define a new set $S$, it makes little sense to use $x ∈ S$ as "specifying condition".
But obviously, if we are not defining $S$ but we already know it, then we have trivially that $S = \{ x \mid x∈S \}$.


How to install Pygame in PyCharm with error "no such option: --build-dir"

Question: I have created a PyCharm project, updated pip to 22.0.4 and updated setuptools to 62.0.0 (both the latest versions). When I go to the project settings>Project Interpreter>Install and attempt to install pygame, it throws the following error:
<code>Executed command: pip install pygame

Error occured: Non-zero exit code (2)

Proposed solution: Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at 'C:\Users\geema\PycharmProjects\smallgame\venv\Scripts\python.exe'.

Usage:
  C:\Users\geema\PycharmProjects\smallgame\venv\Scripts\python.exe -m pip install [options] <requirement specifier> [package-index-options] ...

  C:\Users\geema\PycharmProjects\smallgame\venv\Scripts\python.exe -m pip install [options] -r <requirements file> [package-index-options] ...

  C:\Users\geema\PycharmProjects\smallgame\venv\Scripts\python.exe -m pip install [options] [-e] <vcs project url> ...

  C:\Users\geema\PycharmProjects\smallgame\venv\Scripts\python.exe -m pip install [options] [-e] <local project path> ...

  C:\Users\geema\PycharmProjects\smallgame\venv\Scripts\python.exe -m pip install [options] <archive url/path> ...

no such option: --build-dir
</code>
How can I resolve this issue?
Comment: Did you try the proposed solution? What happened?
Comment: Yes, I have tried running 'pip install pygame', 'pip3 install pygame' in the terminal and it didn't work. I also have ensured that the latest version of pip is installed, and can see that pip is up to date in the project interpreter settings.
Comment: "I have tried running 'pip install pygame', 'pip3 install pygame' in the terminal and it didn't work" - Did it give the same error, another one or none at all? Does the terminal says that pygame is installed, but can't you use it in pycharm? Can you import pygame in the python console?
Comment: @The_spider After running 'install pygame' it throws the error:
Command "python setup.py egg_info" failed with error code 1 in C:\Users\geema\AppData\Local\Temp\pip-install-6vyhw2v9\pygame\
Python is not installed, it is clear as I can go to the project settings and see that pygame isn't there. I do not understand what you mean by 'importing pygame in the python console.'
Comment: "Python is not installed" - Do you mean pygame instead of python?
Comment: To go to the python console, search for a progrom named python and open it. Then type "import pygame" and press enter. It should look like this: https://www.tutorialsteacher.com/Content/images/python/python-shell.png
Answer: I have managed to simply use the interpreter from another project on my current one, and the interpreter has Pygame on it. I am still not sure as to why the error occurred.


Length of parametric curve in polar coordinates

Question: I have to find the length of this parametric curve: $R(\theta)= \theta^4 $  with $0 < \theta < 1$
So, We have the formula: $ ds = \sqrt{r^2 + (\frac{dr}{d\theta})^2} d\theta $.
My question: As I have understood. I have to convert the $\theta$  into trig functions. How do I do that and proceed with my calculations?
Answer: We have
\begin{align}
ds &= \sqrt{r^2 + \left(\frac{dr}{d\theta}\right)^2} d\theta \\
&= \sqrt{\theta^8 + 16\theta^6} \ d\theta \\
&= \theta^3 \sqrt{\theta^2 + 16} \ d\theta
\end{align}
Now, take $\theta = 4\tan\alpha$, and integrate.
Comment: Oh sorry, yes. There should be a factor of $4$.
Comment: Using $x=\sqrt{\theta^2+16}\implies xdx=\theta d\theta\implies\theta^3\sqrt{\theta^2+16}d\theta=(x^2-16)xdx$ is a bit easier.
Comment: @Ishan Deo Thank you. How did you get the $\theta = 4 \tan α $?
Comment: That was a substitution I was assuming in order to integrate.
Comment: Ok. So go integrate: $(4 tan α)^3 \sqrt{(4 tan α)^2 +16 }dα$?
Comment: You'll have an additional $\sec^2\alpha$ term as $d\theta = \sec^2\alpha \ d\alpha$
Comment: Shouldn't that be $4 \sec^2 α$? Since derivative of $4 \tan α$ is that? $(4\tan α)^3 \sqrt{(4\tan)^2 + 16 }(4 \sec^2 α) $ Is that correct?


Guitar exercises for simultaneous fingers movement

Question: I'm newbie in the guitar world and I have some problems.
One of them is the simultaneous movement of my fingers, for example I'm trying to play a simple sequence of chords: G - D - E - C.
Well, when I have to change from G to D or from C to G I have to slow down, move one finger at time and then I can continue.
In particular way I can't move ring when I'm moving the other two fingers.
Are there any exercises to learn how to move all fingers together?
Thanks!
PS: I'm learning guitar by myself, at the moment I have no teacher.
Answer: One "offline" (without guitar) exercise I got from my teacher is like this:

Put your hand on the table. Lift fingers two or three at a time; if you are like me, combinations 1+3, 2+4, 1+2+4 and 1+3+4 will feel weird; you should try to make them comfortable.

This is for both hands (you only need your left hand improved, but it cannot hurt if you train your right hand too).
Other than that, practice. Try a progression with one or only a few hard changes (I played some variation of G-C-Am-C-D with simplified "power" versions of C and Am) so your brain has time to rest between the hard changes. If a progression with lots of easy changes becomes too boring, cut easy stuff from the middle (I always end up playing G-D-G-D like crazy).
Comment: Thank you for the advice; the combinations you gave are really weird! The 2+4 is breaking my brain :)
Comment: Yes, I really like this approach too, and get pupils to do similar exercises away from the instrument. (For younger pupils I suggest they do them in boring school lessons! I jest of course...) Even simply trying to make the shape of a chord "in-the-air" can help you to move all fingers to a chord shape simultaneously, rather than one at a time. Also, I suggest pupils practise moving their hand to a chord from some distance away, their knee if sitting down, for instance. This encourages them to "get-to-the-shape" rather than thinking about what each finger is doing in each chord change.
Answer: Hammering-on incorporates quickly stabbing a finger onto the fretboard. Hold it down once a note sounds.Do it not too gently - it is called hammer.When you're happy making one note with this technique, try two and three fingers, in the shape of the chord you're weak on. It will help all the fingers for that chord arrive on the fretboard together, which is what you need to train them to do. Open E and A are the easiest, but then move to G, C and D. Don't worry about the open strings - you didn't need to finger those anyway.On electric, maybe you can turn the volume up initially, but when you get good, try with little or no volume. Bass guitarists have been known to play whole gigs in this way, using the other hand for their pint.
Comment: I am too newbie for hammer on, pull off, bending etc. :)
Comment: I teach those techniques within a couple of months. They are all part and parcel of being a guitarist, so get cracking !
Comment: So, in your opinion, I should try these techniques even if I can't play some simple chords; right?
Comment: Absolutely ! Start as you mean to go on. It's all new stuff, and hammers and pulls can be sorted quite soon. Good luck !
Answer: I had a similar problem and I tried to solve it by just playing some basic chord progressions and paying attention to switching between chords. It helped for particular chord progressions, but it didn't improve my finger coordination in general. By doing that I simply developed muscle memory for particular movements that didn't work for new chords and new positions on the fretboard.
A thing that works for me is the warm up exercise from John Petrucci`s Rock Discipline DVD.
It was designed for stretching, but it helped me a lot to solve the problem of coordination of simultaneous finger movements.
I guess it helps because it involves all fingers in all positions. But more important, it involves pairs of fingers (not all combinations of them, but you can get the idea and improve the exercise). Try to warm up every day with it and you should notice some improvement after a couple of weeks; but remember to do it slowly and concentrate on finger coordination and muscle relaxation instead of stretching.
Answer: I think this is one of the hurdles we all have to jump when learning guitar - or even when you can already play some but are just learning a new chord shape.
The G chord was a tricky one for me so I cheated.
I play G with 1st finger on the high E or sometimes both E and B, at the 3rd fret.
Then use thumb to fret the E string at 3rd fret, and damp the A with it too.
When I was starting out (yeeeears ago) this got me though that "having to slop down" thing. It also allows me to move gtom G to D quite quickly because the relevant fingers are in the right area aldreay. I've later found that it also leaves a couple of finger free for playing riffs etc.
I can play a "normal" G (a string at 2nd fret) now because I've practiced but frankly I hardly ever do. Purists will probably throw their hands up in horror at this but I say : If we all obeyed the (precieved) rules, we wouldn't have Hendrix.
There are other ways to play chords - eg C : traditionally with open G string (ooer missus) or you can barre it by moving the A shape up 3 frets.
I'd suggest experimenting with chord shapes and find the best that suit you to gain the quickest change- but view it as a way to get things changing quickly, not necessarily as the "Final" way you're going to do things. It;ll enable you to get a flow going and that's where things get really fun :-D


When do you switch ends of the court in tennis?

Question: Including with respect to a tiebreak game.
Answer: This question covers everything but the tiebreak: players switch sides after every odd game in the set and after every set.
Within a tiebreak, players switch sides after every 6 points played. At least, that's the case in major tournaments; local rules may differ:

Tiebreaker Changeovers
Two different types of tiebreakers -- one used in major tournaments and another sometimes used in United States Tennis Association play -- both require frequent changeovers. The first is the classic 12-point tiebreaker when the set score is tied at six games. The first player to win seven points and be two points ahead wins the set. Players switch sides after every six points. The Coman tiebreaker works the same way except players change sides after the first point and every subsequent four points.

(source)


playing radio in background

Question: I just need to confirm if an iPhone app can play or stream radio in the background.
I created a radio app which is working fine.
I want to add a feature by which the user can play radio in a background process, i.e. they don't have to keep the application open to play the radio.
They can close the app, and the radio is still playing.
I read a long time back that Apple has a private API by which an app can run radio in the background, but since it is private, I can't use it.
Any suggestions?
Comment: I don't know about how to implement it, but yes you can play music while you app is in the background. It is one of the background processes that iOS supports.
Answer: iOS SDK should be above 4.0;
first in your delegate codes:
- (void)applicationDidEnterBackground:(UIApplication *)application {

    if (isAbove4_0)

 {

        CTCallCenter *_center = [[CTCallCenter alloc] init];

        _center.callEventHandler = ^(CTCall *call)
       {

            //NSLog(@"call:%@", call.callState);
            if ([call.callState isEqualToString:CTCallStateIncoming])

                {

                [RadioPlayer pausePlayer];

        }
    };
    }

}

then,
I used MPMoviePlayerController, and AVPlayer is OK;
if (isAbove4_0) {
    if (_mpmovieplayer == nil) {
        _mpmovieplayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
        [_mpmovieplayer setMovieControlMode:MPMovieControlModeHidden];
    }

    [_mpmovieplayer setContentURL:url];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    // This is necessary if you want to play a sequence of songs, otherwise your app will be
    // killed after the first one finishes.
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;

    [_mpmovieplayer play];

    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
    if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
        [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
    bgTaskId = newTaskId;

}

PS:my english is poor, I hope this could be helpful to you :)
Answer: You can use one of these audio streamer for play in background
https://github.com/mattgallagher/AudioStreamer
https://github.com/DigitalDJ/AudioStreamer
it might help you.
Answer: This is how it works for me.
Add following to you app-info.plist file
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>

Then in application:didFinishLaunchingWithOptions add following
UIBackgroundTaskIdentifier backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
     /* just fail if this happens. */
     NSLog(@"BackgroundTask Expiration Handler is called");
     [application endBackgroundTask:backgroundTask];
}];

playing radio in background


The subscription does not have QuotaId/Feature required by SKU 'S0' from kind 'QnAMaker'

Question: The subscription does not have QuotaId/Feature required by SKU 'S0' from kind 'QnAMaker' .
i am using Bot Framework Composer and i want to add QNA MAKER knowledge base
but it require set up qna maker and i am getting this error now
"The subscription does not have QuotaId/Feature required by SKU 'S0' from kind 'QnAMaker' ."
i am using Bot Framework Composer and i want to add QNA MAKER knowledge base and for this i create resourse in the azure
but it require set up qna maker and i am getting this error now
"The subscription does not have QuotaId/Feature required by SKU 'S0' from kind 'QnAMaker' ."
Answer:
The subscription does not have QuotaId/Feature required by SKU 'S0' from kind 'QnAMaker

As per this Jon Gallant blog article, it is said that this error occurs because of retirement of S0 SKU's, changing to S will fix the issue.
But there is a REST API that gets the Resource SKU's List for the Azure Cognitive Services that are available in your Azure Subscription:
<code>GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/skus?api-version=2021-10-01
</code>

AFAIK, if the specific resource SKU's is not registered/subscribed in our Azure Subscription, then it will throw this exception.
Answer: From now onwards you can't create new QnA Maker. If you have an old QnA Maker in your Azure resources, you use it in Composer.


How to get the number of commits on a file from all authors cumulatively

Question: In other words, what git log --follow <file> does, but for all authors together.
For example, if "contributor1" commits to a file 5 times, and I do it 3, the result should be 8 for that file.
Comment: what do you want for your answer?  a list of authors?  a list of authors with counts per author?  or just a single number total: number of authors who committed to this file?
Comment: Just the total number of commits. I'm trying to track activity on a file, and it seems like files with an excessive number of commits could be candidates for refactoring.
Comment: I just realized my question was incorrect. I updated it so it has the correct git command.
Comment: So you want to count the number of commits in the output of the command you gave?  In this case, go with Wolf's answer – add the `--oneline` output format for `git log` and count the number of lines in the output.
Answer: You can find the total number of commits to a given file, even through renames, by combining git log with wc:
git log --follow --oneline -- filename | wc -l

Answer: One option to get the number of commits for each file would be
git log --format=format: --name-only | sort | uniq -c

This lists the files that were changed in each commit, then groups by file name and counts the occurrences.
If you just want to know the number of commits for a single file, you can use
git rev-list --count HEAD -- <filename>


Alternatives to percentage change?

Question: You can have the same mean but different standard deviation. Or the same standard deviation but a different coefficient of variation or 1 over signal-to-noise ratio or whatever. (I think  that's the same as different mean.)
Question: Is there a similar 'alternative' to percentage change?
Context: This is based on my previous question:
Can you do hypothesis testing when instead of a 'sample' size you have 'actual' size? Alternatively, how would you use statistics to compare means?
(The context of the ff is chess / 9LX engine evaluations.)
I thought the 7% difference between the numbers 0.1913 and 0.179 might be 'significant' (whether 'practically' or 'statistically'; see the answer in the question) :
$(0.1913-0.1790)/0.1790 = 0.06871508379 \approx 6.87 \% $, almost $7\% $
But it was pointed out to me that:

This percentage doesn't tell the whole picture or even close: there's a 200% difference between +0.01 and +0.03 but they're hardly distinguishable

I think I need some way to kinda 'boost' the 7%, as in make the 7% a bigger number to show its importance and a way to 'nerf' the 200%, as in make the 200% a small number to show its non-importance.
Well simply multiplying the percentage change with the original value gives me the absolute change. Maybe multiplying percentage change with new value?
7% x 0.1913 = 0.013391
200% x 0.03 = 0.06
Eh doesn't quite work... but at least we did bring down 2.00 to 0.06. That's a start maybe?
Comment: I haven't intended to suggest anything. You are the one that knows this data and what measures are meaningful. I'm just pressing you to justify your choice to use percentage at all.
Comment: You've asked many questions related to the same problem. As far as I can tell, there is not a statistical question here. You are simply comparing the engine evaluation between two sets of chess starting positions. What you seem to be stuck on is appropriately conveying the *meaning* of that engine score difference. In a standard game of chess, with certain engines, a +1 evaluation difference is the equivalent of a pawn. That's usually how you assign meaning to chess evaluations, by mapping to a difference in material.
Comment: Gasai, nerf? Some readers will know this subculture jargon, bur others won't. I fear you're losing many readers there.
Comment: You've said that percentages are not meaningful; okay, I believe you. But you have not explained why absolute differences are not meaningful. You also haven't said why it would be inadequate to just write to your intended audience the explanation you've tried to give to us about how they should compare the 0.01->0.03 change with the 0.1913->0.179 change. You're stuck on this idea of "boosting" and "nerfing" but why are you even starting from percentage change to begin with?
Comment: If you don't care about relative change why do you use %? Say, \$0.01 to \$0.03 is 200% but it's \$0.02, so why not just use \$?
Comment: @Jen well...i guess absolute differences are meaningful...hmmm...idk it's like this. i just wanted to say that in chess90 white has on average a 7% higher advantage compared to chess870. i'm trying to use this 7% as an argument to say chess90 bad chess870 good. The other guy told me 0.03 vs 0.01 has a 200% higher advantage. soooo your suggestion is to just skip percentage difference and go with just absolute difference?
Comment: @Jen that's fair...idk...i just learned about percentage changes in 2ndary school and then i figured to use it now...?
Comment: @Tim oh absolute difference instead of percentage difference? but 0.1913-0.179 = 0.0123 < 0.03-0.01=0.02 ?
Comment: @statsplease i know ok. i'm not n00b. i used to be 1900 on chesscube. and how can i possibly ask all these questions about 9LX if I'm a n00b? (well i'm certainly chess openings but i'm not a n00b otherwise.) ughh...anyway...
Comment: @statsplease my goal is making meaning out of the 7%. Clearly 200% is way bigger than 7% but 0.03 and 0.01 and too small individually for anyone to really care. mean while 0.1790 and 0.1913 are huge. the biggest sesse eval is 0.57, a little over half a pawn. 0.1913 is really close to half way 0..57/2=0.285. so anyhoo i need to boost this 7% by showing that it's from big numbers and nerf the 200% by showing it's from small numbers. Hence, I'm asking for some equivalent of coefficient of variation or signal-to-noise for percentage change.
Answer: If the actual numbers are important rather than the percentage difference, then report the actual numbers. And if it's helpful to report the differences, report those too.
Like:

before
after
change

0.1913
0.179
-0.0123

0.01
0.03
0.02

And if it's important for the reader to understand that a difference of 0.02 has no practical significance, write that out for them, like, "In the context of ___, a difference of 0.02 or smaller is of no practical significance."
Comment: thanks but i mean ...you know Gasai how like you can have the same mean but different standard deviation? or the same standard deviation but a different coefficient of variation (or that's the same as different mean?) ? i'm thinking something like that. i need to like...use the smallness of the numbers 0.01 and 0.03 to nerf this 200% thing and then use the largeness of the numbers 0.1913 and 0.179 to boost this 7% thing.
Comment: No, sorry, I don't know what you're talking about. But it sounds like you know what you want to do.
Comment: I really don't. :| it's like 5 and 10 have the same average as 3 and 12 but different standard deviation right? here's the absolute difference is about the same 0.0123 vs 0.02 but the percentage differences are 7% vs 200%. percentage difference provides 1 way to differentiate the 0.0123 and the 0.02, but this 'favours' the 0.02. is there another way to differentiate the 0.0123 and the 0.02 in a way that 'favours' the 0.0123?
Comment: Jen edited post to hopefully be clearer

Alternatives to percentage change?


How do I add to my URL from .htaccess based on cookie

Question: I have a site that is creating a cookie based on a users geoIP, so that the location is always part of the URL, like example.com/dc-metro/fly-a-kite. I am having an issue when a user comes to example.com/fly-a-kite and inserting the correct location to the URL. Here is what I have in my .htaccess file:
RewriteCond %{HTTP_COOKIE} market=([dc-metro]) [NC]
RewriteRule ^fly-a-kite(.*)$ /dc-metro/fly-a-kite$1 [L,R=301]

RewriteCond %{HTTP_COOKIE} market=([chicago]) [NC]
RewriteRule ^fly-a-kite(.*)$ /chicago/fly-a-kite$1 [L,R=301]

I am using MODX, which I don't think should make a difference, the problem I am having is that when I try going directly to example.com/fly-a-kite it is inserting different locations other than what should be my saved cookie.
Thank you for any help you can provide.
Answer: I found a solution last night that is working, not sure if it is the best answer, but it is working for me. Instead of using ([name]) for the cookie value I got rid of the ([ ]) so my htaccess looks like:
RewriteCond %{HTTP_COOKIE} market=dc-metro [NC]
RewriteRule ^fly-a-kite(.*)$ /dc-metro/fly-a-kite$1 [L,R=301]

RewriteCond %{HTTP_COOKIE} market=chicago [NC]
RewriteRule ^fly-a-kite(.*)$ /chicago/fly-a-kite$1 [L,R=301]


how do I put code of files into separate memory regions with the GNU Linker

Question: I am trying to use the linker script (LD) in order to split my code into 2 different MEMORY regions.
i.e. - all code should go to MEM1 region. and only file2.o should go to MEM2 region.
<code>MEMORY
{
    MEM1           : ORIGIN = 0x00000000,          LENGTH = 100K
    MEM2           : ORIGIN = 0x00800000,          LENGTH = 100K
}

SECTIONS
{
    .text    : { *(.text .text.*) } >MEM1
}
</code>
how do I exclude file2.o from going to MEM1 and direct it to MEM2?
I have tried using EXCLUDE_FILE (for file2.o and MEM1 region) without success.
any help/directions will be helpful
thanks
Answer: From the LD manual, 18.104.22.168 Input Section Wildcard Patterns:

If a file name matches more than one wildcard pattern, or if a file name appears explicitly and is also matched by a wildcard pattern, the linker will use the first match in the linker script.

Have you tried something like this?
<code>.text2 : { file2.o(.text .text.*) } >MEM2
.text  : {       *(.text .text.*) } >MEM1
</code>
However, this should work too:
<code>.text  : { *(EXCLUDE_FILE(*file2.o) .text .text.*) } >MEM1
.text2 : { file2.o(.text .text.*) } >MEM2
</code>


Writing to a custom field in PHP

Question: In Drupal 7, using the Field module, Field SQL Storage and Field UI I've created several custom user fields.  I can display them in PHP like this:
global $user;
$account = user_load($GLOBALS['user']->uid);
if ($items = field_get_items('user', $account, 'field_keys_available')) {
   $keys_remaining = $items[0]['value'];

The above example displays the custom keys_available field, a field we use to determine if the user is entitled to software license keys.  I need to decrement field_keys_available in the PHP that issues a license key to a user.  Can someone help with the syntax on this?  I've discovered fifty ways to generate white screens, but haven't landed on the right syntax.
Answer: It should be something as simple as
$account = user_load($GLOBALS['user']->uid);
$edit['field_keys_available'][LANGUAGE_NONE][0]['value'] = 'new value';
user_save($account, $edit);

The comments in the user_save() docs have some more details and examples.

Writing to a custom field in PHP


asp.net mvc error not showing ysod

Question: Im running an asp.net mvc site on iis7, using iis express in dev and when an exception occurs in one of my views, the browser returns something that looks like binary in a text editor.
Its not generating the normal ysod.
Has anyone seen this before?
Cheers,
Byron
EDIT
Its related to my compression action filter. It looks like the response isnt 'decompressing' if an exception occurs in the view.
<code>public class EnableCompression : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext) {

        HttpRequestBase request = filterContext.HttpContext.Request;

        string acceptEncoding = request.Headers["Accept-Encoding"];

        if (string.IsNullOrEmpty(acceptEncoding)) return;

        acceptEncoding = acceptEncoding.ToUpperInvariant();

        HttpResponseBase response = filterContext.HttpContext.Response;

        if (acceptEncoding.Contains("GZIP")) {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        } else if (acceptEncoding.Contains("DEFLATE")) {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
    }
}
</code>
Comment: Have you tried debugging?  Stepping through your code, or at least setting a break point at the beginning of the code where you think is causing this?
Comment: Hey, im not after the actual exception, im wondering why when an exception is throw when rendering a view template its not showing me the traditional yellow screen
Answer: it is because you aren't handling all/default cases for request.Headers["Accept-Encoding"].  You have an "if/else if"  with no other handling for other cases.  See all possible values in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.  Then add a default handler for requests not caught by your if/else if.  Also, you may want to use .ToLower and test agains only lowercase values.

asp.net mvc error not showing ysod


What is a null conjunction analysis in an fMRI study?

Question: I'm reading an article, The commonality of neural networks for verbal and visual short-term memory (Majerus et al., J Cogn Neurosci 2010 22(11): 2570), about brain imaging in which the results are analysed with multiple analyses.
One of them is a null conjunction analysis.
I've tried googling a bit but I didn't come up with something useful.
I did find some results on 'conjunction analysis', but I'm not sure if that's the exact same thing.
Can anyone explain to me what this analysis is (Goals, method...)?
Answer: The original paradigm originates from the work of Price and Friston (1997, 1999), and it has been criticized in a more recent paper by Tom Nichols et al. (2005), but see Friston et al. (2005) for a reply.
The idea behind conjunction analysis is to determine whether two tasks activate the same region(s) of the brain. Quoting Towards Evidence of Absence: Conjunction Analyses in fMRI, contrary to the subtraction approach ((a) sum all of the activation maps (AM) from the baseline condition, (b) sum all of the AMs from the stimulation condition, (c) rescale them by converting these summated AMs to average images, (d) subtract the baseline AM from the stimulation AM in order to reveal the activation locations (voxels)), the idea is that

each voxel should be significantly activated by the two tasks;
each voxel should not be significantly modulated by an interaction effect between tasks;
the estimated relationships between each voxel and each task are not significantly different.

The rest of the blog post is worth reading, IMO.
References

Price, C.J. and Friston, K.J. (1997). Cognitive conjunction: a new approach to brain activation experiments. Neuroimage, 5, 261-70.
Friston, K.J., Holmes, A.P., Price, C.J., Büchel, C., and Worsley, K.J. (1999). Multisubject fMRI Studies and Conjunction Analyses. NeuroImage, 10(4), 385-396.
Nichols, T., Brett, M., Andersson, J., Wager, T., Poline, J.-B. (2005). Valid conjunction inference with the minimum statistic. Neuroimage, 15;25(3): 653-60.
Friston, K.J., Penny, W.D., and Glaser, D.E. (2005). Conjunction revisited. NeuroImage, 25, 661-667.
Comment: Yes, that's the analysis that's used. I saw 'Friston, 2005' on one of the slides accompanying the article.
Thanks @chl.


how to add links or update existing links property to a JUNG graph

Question: I have a result set coming from a mysql database and I am trying to build a JUNG graph using these values. I already have instantiated my empty graph as:
Graph<Node, Edge> g = new SparseMultigraph<>();

then I have added nodes (586). I am now in the process of adding links and now things get more complicated. The structure of my custom Edge is very simple, it just has a "time" property like:
Multiset<Timestamp> time;

The result set for links contains 3273684 entries in the form:
id  time                    sender  receiver
12  2014-03-20 09:26:04.000 2       99

Now, what I want to do is to create a link from node with id 2 and node with id 99 if the link does not exist, or to just add the timestamp to the already existing link. What I do is:
while (resultSet.next()) {
    // retrieve sender
    Node sender = findNode(resultSet.getInt("sender"), g);
    // retrieve receiver
    Node receiver = findNode(resultSet.getInt("receiver"), g);
    // if they are already linked
    if(g.isPredecessor(sender, receiver)){
        // just add the new timestamp to the existing link
        Collection<Edge> outEdges = g.getOutEdges(sender);
        // find the right edge
        for(Edge e:outEdges){
            // if this edge is connected to receiver
            if(g.getDest(e).equals(receiver)){
                // add the new timestamp to this edge
                e.setTime(resultSet.getTimestamp("time"));
            }
        }
    } else { // else a new link is added
        Information e = new Information();
        e.setId(resultSet.getInt("id"));
        e.setTime(resultSet.getTimestamp("time"));
        g.addEdge(e, sender, receiver, EdgeType.DIRECTED);
    }
}

My problem is that this is really slow, and I do not understand if it is normal, since the result set is quite big, or if I am missing a clearer/faster way to implement what I need.
For the sake of clarity, my findNode() method is like this:
private static Node findNode(int aInt, Graph<Node, Edge>g) {
    for(Node n:g.getVertices()){
        if(n.getId()== aInt){
            return n;
        }
    }
    return null;
}

Answer: This is slow for two reasons:
(1) You don't have an efficient way to look up a node given an ID.  For a graph of this size I'd recommend building a Map as you populate the graph, and using that map to implement findNode().
(2) Once you have your two nodes and you want to get the edge that connects them (if any), just use Graph.findEdge().
(1) is by far the biggest reason that your code is slow.  (2) will not help as much, but it will also make your code easier to read and more elegant.
Comment: An example, no.  In essence when you're constructing your graph, at some point you will have just constructed your node object, and so you'll have at hand the node and its ID; put them in a map at that point.  Offhand the easiest way to do this would probably be to have your node class have a static Map instance inside it.  This would also imply that findNode() itself should be a static method of your node class.
Comment: Thanks Joshua, I opted for a hashmap where I put the ID and the node just before adding the node to the Graph... at this point I don't ever need a findNode() method anymore, it's just a get() from the hash map when I need to find the right node... Is this somewhat close to what you meant in your answer?
Comment: and btw, I have problems with Graph.findEdge()... you see I test for g.isPredecessor(sender, receiver) but if this is true and I ask for g.findEdge(sender, receiver) I get a null pointer exception...
Comment: Simone@ the findEdge() issue sounds like a different problem.  :)  Please post it as a separate question with a stack trace and a small self-contained example that demonstrates it.
Comment: Simone@, I can't tell for sure from your description, but it sounds like your solution for the Map<> is essentially what I described.


Erro em código para detecção de letra

Question: Estou trabalhando em um código para detecção de letra com a utilização de uma função, para um exercício de aula. A ideia é que quando eu digita uma letra a função detecte se ela for:

maiscula = 1
minuscula = 0
outra coisa = -1.

Este retornos de 1, 0 e -1 retorna para a main().
O meu retorno esta sempre -1.
    int main()
    {
    char le;
    int x; x=0;

    printf ( " \n Programa que detecta se a letra e maiuscula e ou
    minuscula");

    printf (" \nDigite uma letra : ");
    scanf ("%s", &le);

    detletra (l);

    if  ( x = 0)
    {
         printf (" \n A letra digitada e minuscula! "  );
    }
    else if  ( x = 1)
    {
         printf (" \n A letra digitada e maiscula! "  );
    }
    else if  ( x = -1)
    {
         printf (" \n A letra digitada não pertence ao alfabeto "  );
    }

    printf ( " \n %d", x);
    }

    void detletra ( char letra ) // função  processamento dos dados
    {
    if (letra >= 'a' &&  letra <= 'z') // Verifica se a letra é minuscula
    {
    int x;
    x = 0;
    return x; // retorna o valor para main
    }
    else if (letra >= 'A' && letra <= 'Z' ) // Verifica se a letra é maiscula
    {
    int x;
    x = 1;
    return x; // retorna o valor para main
    }
    else // Verifica se a letra não é do alfabeto
    {
    int x;
    x = -1;
    return x; // retorna o valor para main
    }

    }

Comment: o tipo de retorno do metodo esta como void
Comment: alem de nao passar o retorno da funcao para a variavel x
Comment: Obrigado pelo retorno, no caso se eu mudar para int, o compilador reclama a mensagem |D:\UNISSINOS\linguagem c\Trabalho 1 _v2\main.c|32|error: conflicting types for 'detletra'| D:\UNISSINOS\linguagem c\Trabalho 1 _v2\main.c|33|note: an argument type that has a default promotion can't match an empty parameter name list declaration|
Answer: Tem vários erros, alguns mais críticos que outros. Vamos lá.
A função deve retornar um tipo de dado inteiro, conforme a definição do problema e não um tipo que não retorna valor.
A variável x não está recebendo o valor retorna pela função, mudei isso pegando esse retorno. Talvez achou que o x de uma função é a mesma coisa do x da outra função, mas não é, por isso que retorna algo.
A comparação se faz com o operador == e não o = que é o operador de atribuição, então você está mudando o valor de x de forma inadequada no lugar que acha que está comparando algo.
Para pedir uma letra deve usar a formatação %c e não %s.
Melhorei os nomes dos identificadores (deixei o x que poderia ter melhor nome), eles são importante para dar legibilidade no código. E tirei comentários que não ajudavam em nada entender oque está acontecendo ali, só dizia obviedades, comentário não é para isto. E claro, organizei muito o código, tirei um monte de coisa que não era necessária e mantive um padrão.
Uma mudança mais radical que fiz foi simplificar a comparação das letras. O valor de uma comparação já é um número 0 ou 1, então pode usar o resultado para evitar parte do código. E mesmo que usasse o if como uso no primeiro caso, não precisa declarara a variável, atribuir um valor para ela e depois usar esse valor, não tem porque usar variável ali, use o valor direto.
Como retorna 1 para verdadeiro e 0 para falso e eu quero que retorno 0 ou -1 então subtraio 1 do resultado. Mas esse conta só ocorre que já não ficou no if anterior que retorna o 1.
Acertar a ordem das comparações é algo que um programador tem que pensar, pode simplificar muito o código. E conhecer todos os mecanismos da linguagem para usar de forma adequada e simples.
Olha como o código pode ficar muito menor:
#include <stdio.h>
int detecta(char letra) {
    if (letra >= 'A' && letra <= 'Z') return 1;
    else return (letra >= 'a' && letra <= 'z') - 1;
}

int main() {
    char letra;
    printf("Programa que detecta se a letra e maiuscula e ou minuscula");
    printf("\nDigite uma letra: ");
    scanf("%c", &letra);
    int x = detecta(letra);
    if (x == 0) printf("\nA letra digitada e minuscula!");
    else if (x == 1) printf("\nA letra digitada e maiscula!");
    else if (x == -1) printf("\nA letra digitada não pertence ao alfabeto");
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Entenda o que cada parte, o que cada caractere do código faz, assim organiza melhor, deixa mais legível, e passa saber oque está acontecendo ali, sem parecer uma magia.
Comment: Obrigado Maneiro, vou tomar mais cuidado nos identificadores e retomar alguns conceitos que eu estou confundindo.

Erro em código para detecção de letra


Using a Random Forest for Time Series Data

Question: This is a simple question, is it okay to use a Random Forest model on Time Series Data? I ask this because, in a random forest model, we perform bootstrapping of observations where we randomly sample from the training set with replacement. Doesn't this ruin the "ordering of observations" in the model, since it being time series data.
I'm asking this with context to financial data, say I'm doing a classification type problem to buy/not buy an asset, and I collect daily data for some features to predict this variable.
Answer: It works well but only if the features are properly prepared so that the order of the lines is not important anymore.
E.g. for a univariate time series $y_i$, you would use $y_i$ as response and e.g. the following features:

Lagged versions $y_{i-1}$, $y_{i-2}$, $y_{i-3}$ etc.
Differences of appropriate order, e.g.  $y_{i-1} - y_{i-2}$, $y_{i-1} - y_{i-8}$ (if there is weekly seasonality expected and the observations occur daily) etc.
Integer or dummy coded periodic time info such as month in year, week day, hour of day, minute in hour etc.

The same approach works for different modelling techniques, including linear regression, neural nets, boosted trees etc.
An example is the following (using a binary target "temperature increase" (y/n)):
<code>library(tidyverse)
library(lubridate)
library(ranger)
library(MetricsWeighted) # AUC

# Import
raw <- read.csv("https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv")

# Explore
str(raw)
head(raw)
summary(raw)
hist(raw$Temp, breaks = "FD")

# Prepare and add binary response
prep <- raw %>%
  mutate(Date = ymd(Date),
         y = year(Date),
         m = month(Date),
         d = day(Date),
         increase = 0 + (Temp > lag(Temp)))

with(prep, table(y))
summary(prep)

# Plot full data -> year as seasonality
ggplot(data = prep, aes(x = Date, y = Temp))+
  geom_line(color = "#00AFBB", size = 2) +
  scale_x_date()

# No visible within year seasonality
prep %>%
  filter(y == 1987) %>%
ggplot(aes(x = Date, y = Temp))+
  geom_line(color = "#00AFBB", size = 2) +
  scale_x_date()

# Add some lags and diffs & remove incomplete rows
prep <- prep %>%
  mutate(lag1 = lag(Temp),
         lag2 = lag(Temp, 2L),
         lag3 = lag(Temp, 3L),
         dif1 = lag1 - lag2,
         dif2 = lag2 - lag3) %>%
  filter(complete.cases(.))

# Train/valid split in blocks
valid <- prep %>%
  filter(y == 1990)
train <- prep %>%
  filter(y < 1990)

# Models
y <- "increase" # response
x <- c("lag1", "lag2", "lag3", "dif1", "dif2", "y", "m", "d") # covariables
form <- reformulate(x, y)

# Logistic model: Linear dependence between difs and lags
fit_glm <- glm(form,
               data = train,
               family = binomial())
summary(fit_glm)

# Random forest
fit_rf <- ranger(form,
                 data = train,
                 seed = 345345,
                 importance = "impurity",
                 probability = TRUE)
fit_rf
barplot(-sort(-importance(fit_rf))) # Variable importance

# Evaluate on 1990 for glm by looking at ROC AUC
pred_glm <- predict(fit_glm, valid, type = "response")
AUC(valid[[y]], pred_glm) # 0.684 ROC AUC

# Then for rf
pred_rf <- predict(fit_rf, valid)$predictions[, 2]
AUC(valid[[y]], pred_rf)    # 0.702 ROC AUC

# view OOB residuals of rf within one month to see if structure is left over
random_month <- train %>%
  mutate(residuals = increase - fit_rf$predictions[, 2]) %>%
  filter(y == 1987, m == 3)

ggplot(random_month, aes(x = Date, y = residuals))+
  geom_line(color = "#00AFBB", size = 2) +
  scale_x_date()
</code>
Replacing variables "y" and "m" by factors would probably improve the logistic regression. But since the question was about random forests, I leave this to the reader.
Comment: Yes exactly: Lags, differences etc.
Comment: "but only if the features are properly prepared so that the order of the lines is not important anymore." If I understand you correctly, you basically need to calculate all the lagged versions to be features, so the order of the lines is no longer important?
Comment: I have tried to add this example with binary response.
Comment: @MichaelM - I have two quick questions; when entering data for lagged versions, what do you do when there is not a value (for example, y_i-2 for y_i)? Would it be a NaN, 0...? Also, is there any place where I could find an example of how to handle the differences? I am not sure I understand what I am trying to do there.
Comment: I'd probably remove the few lines without lag. By differences I mean those between different lagged versions of the time series. So e.g. if you have hourly values $y_{i}$ of river temperatures, you can use $y_{i-1}$, $y_{i-2}$, $y_{i-24}$, $y_{i-1} - y_{i-24}$ and $y_{i-1} - y_{i-2}$ as predictors. This example is for a univariate series.
Comment: @MichaelM - I am also working with univariate series, adding lagged versions (columns $y_i-1$ to $y_i-n$) for all rows. (Sorry, still figuring out how to do subscripts correctly as i-1 and i-n are supposed to be subscripts). For the differences, I have data that is taken once a day, but there is no cyclic periodicity. How would these needs to be handled? Is there a concrete example online that I could maybe follow? Thanks!
Comment: You need to put curly brackets like x_{t-1} (tex style). Is there a publicly available data set (e.g. in R) you want me to create a realistic example for?
Comment: @MichaelM - Thank you, I will take as little of your time as possible! If you had [this day/temperature data set](https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv), for example, how would you remove time dependencies? Giving me just a few rows would be enough. Thanks again!
Comment: Also - Just to give you more details, in my particular case I am dealing with a classification problem, which would be the equivalent of trying to predict whether the temperature will increase or decrease. Since, of course, I have the temperature column for training, I have created an extra column for the label, which is True if the temperature for $y_{i}$ >= $y_{i-1}$ and False otherwise. I imagine this means that the temperature column itself would not be used as a feature for training after the label is created.
Comment: Thank you so much! I will translate it to Python and will let you know if I have any more questions. You've been so helpful!
Answer: A random forest would not be expected to perform well on time series data for a variety of reasons. In my view the greatest pitfalls are unrelated to the bootstrapping, however, and are not unique to random forests:

Time series have an interdependence between observations, which the model will ignore.
The underlying learner is typically a tree based algorithm, which does not extrapolate trends. If there are genuine time trends in the data these will not be projected forward.
Comment: Random Forest can be, and is used for time-series predictions. Look at a few examples: Dudek, G. (2015). Short-term load forecasting using random forests. In Intelligent Systems' 2014 (pp. 821-828). Springer, Cham./// Mei, J., He, D., Harley, R., Habetler, T., & Qu, G. (2014, July). A random forest method for real-time price forecasting in New York electricity market. In 2014 IEEE PES General Meeting| Conference & Exposition (pp. 1-5). IEEE.
Comment: @MichaelM how  does RF deal with features like multiple level shifts and/or multiple deterministic time trends. Does one have to specify them. How about the window of response around holidays with each holiday having its own pattern ?


Probability of two aces when we get at least one ace

Question: "In drawing two cards from a deck (without returning the first card) what is the probability of two aces when you get at least one ace?"
I am aware there is exact same question answered here.
Probability of two aces when you get at least one ace
I know and understand then answers mentioned.
I would like to approach the problem in a different way.
Let us denote A = event that we get ace from first suite in case of success, i.e. when two aces are drawn., or alternately speaking, atleast one ace is from first suite
similarly B,C,D.
What we want to know is $P(A\cup B \cup C\cup D) $
$=\sum_A ^D{P(X)} - {4 \choose 2 }P(A \cap B)$(due to symmetry) + {ignoring the other intersections since we can't have more than two cards}
$= 4*\frac {3}{51} - {4 \choose 2 } *\frac{1}{{52 \choose 2 }}$
$= 3/13$
which is not right answer, obviously I did some mistake, but where?
Comment: Where does $3/51$ come from. Surely the probability of drawing the ace of spades is $1/26$?
Comment: @LordSharktheUnknown Given we have ace of spades, we have 3/51 probability that we will have two aces.
Comment: @Peter I know the answer comes out to be 1/33 using bayes' theorem. I want to find gaps in my understanding by approaching it differently
Comment: @Peter I know that. I have mentioned that answers to the question are available here https://math.stackexchange.com/questions/1390830/probability-of-two-aces-when-you-get-at-least-one-ace

 I want to get more grip on my understanding by approaching it in this manner. What am I doing wrong with this approach? How should I correct it? Is formulation of the problem wrong, or something else. Thanks

Edit: or why this approach doesn't work.
Comment: OK, so you only want to analyze your concrete approach - You used the conditional probability within the formula for the probability of $P(A\cup B\cup C\cup D)$. This might be the issue.
Comment: @Peter  I have defined and A as event that we get two ace give we have ace of first suite, doesn't this imply  p( A) as conditional probability that we get two ace when we have ace of first suite?
Answer: Your "$P(A)=\frac{3}{51}$" is a conditional probability; the probability that we have a second ace, given that we have the ace of spades. Now you want to add that to $P(B)$, the probability that we have a second ace given that we have the ace of clubs. This sum ... doesn't represent anything meaningful. Those events don't live in the same space, because they don't have the same condition. Then, of course, $P(A\cap B)$ is nonsense, because $A$ and $B$ aren't in the same space. Conditional probabilities create a new probability space by taking a slice of the old one and scaling up the measure - but of course, that means it's a different space for every condition.
Then again, when you wrote

Let us denote A = event that we get ace from first suite in case of success, i.e. when two aces are drawn.

That suggests that $A$ is the event that one of or two cards is the ace of spades given that both are aces. Now we're basically in a deck of four cards - we pick two, so the probability of getting a particular card is $\frac12$. That doesn't seem like a particularly fruitful approach.
I've answered based on my best understanding of the post, but there's enough self-contradiction in there to muddy everything severely. You definitely need to work on writing clearly and saying what you mean.
Comment: Thanks sir. English is my second language.

What i meant was the problem says "given atleast one ace", then  event A= the given ace = ace of first suite.

"Now you want to add that to P(B), the probability that we have a second ace given that we have the ace of clubs. This sum ... doesn't represent anything meaningful."

I wanted to take 4 cases, for the "given ace", as the "given ace" can be of any one of 4 suits, and wanted to union all 4 cases.

How should we approach the problem one suite at a time for the "given ace"(which I tried)?
Comment: Honestly, all I can see is the conventional method. We find the probability that two random cards have at least one ace (possibly with an inclusion-exclusion sum based on which aces appear), the probability that the two cards are both aces, and then we divide to get the conditional probability asked for. It's hard to get anywhere by conditioning on something we haven't measured yet, and conditioning on other things is just asking for confusion.
Comment: Yes straightforward is the right way to go. I as a beginner try to see why other approaches fail, that provides valuable insights that are not presented in ready made form in the texts. Thank you.


Integer Solutions to the equation $x^6+5y^2=z^2$

Question: This problem is on Page 194 of "Number Theory and Its History", by Oystein Ore. I can find infinitely many solutions by letting $x=1$ so that $z^2-5y^2=1$ which has infinitely many solutions. So my question is, are there solutions with x not equal to one, and how can they be found?
Comment: Note for each $(y_1,z_1)$ integer solutions to $z^2 - 5(y^2) = 1$, then $x^6(z^2) - 5(x^6)(y^2) = x^6 \; \to \; (x^{3}z)^2 - 5(x^{3}y)^2 = x^6$, so $(x_1,x_1^3(y_1),x_1^3(z_1))$ is a solution to $z^2 - 5y^2 = x^6$ for all integers $x_1$.
Answer: The equation is not difficult to solve. It's just that the formula will be cumbersome. Before us is the Pythagorean triple.
$$(x^3)^2+5y^2=z^2$$
We will write the parametrization as.
$$x^3=X^2-5Y^2$$
$$y=2XY$$
$$z=X^2+5Y^2$$
It remains to find the parametrization of this equation. It must be solved.  $x^3=X^2-5Y^2$
The solution to this equation is there. Given prime $p$, find solutions to $x^2 + p y^2 = z^3$
The formula turns out to be cumbersome. After substituting one formula into another, you will get parameterization. You'll have to do it yourself.
Answer: If $x_0,y_0$ and $z_0$ is a solution to the equation then we see that $$x=x_0t,\;\;y=y_0t^3,\;\;z=z_0t^3$$ is also a solution for arbitrary integer $t$.
So all you need is to find one specific solution $x_0,y_0,z_0$ which is not hard to find.

 $x_0= 1$, $y_0=4$ and $z_0= 9$ and thus $x=t$, $y=4t^3$ and $z=9t^3$ which means that there is a solution to the equation for an arbitrary $x$.


Undefined property: DatePeriod::$format

Question: Estou fazendo um sistema que cadastre um conjunto de datas via $_POST. Quero inserir no banco de dados o intervalo criado abaixo via datetime. Porém quando executo aparece a mensagem acima. Como proceder? O erro aparece na instrução $sql.
    $start = new DateTime($_POST["data1"]); //nova data começo
    $end = new DateTime($_POST["data2"]); // final da data

    $interval = new DateInterval("P1D"); //intervalo de datas no periodo de um dia

    $period = new DatePeriod($start, $interval, $end); //periodo no começo da data, intervalo e final da data

    try
    {
        $connection = new PDO("mysql:host=localhost;dbname=php","root","");
        $connection->exec("set_names_utf8");
    }
    catch(PDOExeption $e)
    {
        echo "Erro" . $e->getMessage();
    }

    $sql = "INSERT INTO datas(datas) VALUES('$period->format('d-m-Y')')";
    $x = $connection->prepare($sql);
    $x->execute();

Answer: O erro diz que não é possível utilizar o método format. Você está utilizando o objeto da forma errada. Verifique na documentação do DatePeriod os métodos disponíveis:
DatePeriod implements Traversable {

    /* Constants */
    const integer EXCLUDE_START_DATE = 1 ;

    /* Properties */
    public integer $recurrences ;
    public boolean $include_start_date ;
    public DateTimeInterface $start ;
    public DateTimeInterface $current ;
    public DateTimeInterface $end ;
    public DateInterval $interval ;

    /* Methods */
    public __construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
    public __construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
    public __construct ( string $isostr [, int $options ] )
    public getDateInterval ( void ) : DateInterval
    public getEndDate ( void ) : DateTimeInterface
    public getRecurrences ( void ) : int
    public getStartDate ( void ) : DateTimeInterface
}

O que você pode estar tentando fazer é inserir ambas as datas no banco. Se for isso, você pode utilizar $period->getStartDate()->format('...') e $period->getEndDate()->format('...').
Existem outros problemas com seu código. Ele está sujeito a SQL injection e é importante você tratar as entradas de dados do seu sistema, e melhorar como você constroi suas queries. As perguntas abaixo vão te ajudar:

Como prevenir injeção de código SQL no meu código PHP?
Como filtrar a entrada de dados de um formulário para o Banco de Dados?

Undefined property: DatePeriod::$format


Locating segmentation fault for multithread program running on cluster

Question: It's quite straightforward to use gdb in order to locate a segmentation fault while running a simple program in interactive mode. But consider we have a multithread program - written by pthread - submitted to a cluster node (by qsub command). So we don't have an interactive operation.
How we can locate the segmentation fault? I am looking for a general approach, a program or test tool. I can not provide a reproducible example as the program is really big and crashes on the cluster in some unknown situations.
I need to find a problem in such hard situation because the program runs correctly on the local machine with any number of threads.
Comment: Do you have a core file?
Comment: How large is your cluster? How many nodes does your program require?
Comment: @SamMiller Working on one node of up to 32 cores (threads)
Comment: @SamMiller The core file is created, but empty!
Comment: what operating system? What cluster management software?
Comment: @SamMiller It's Scientific Linux release 6.1 (Carbon). I access cluster using commands like qsub, qhost, qdel, etc. Is there specific way to find cluster management software?
Comment: It is either Sun Grid Engine (now Oracle Grid Engine or may be Open Grid Scheduler) or PBS (OpenPBS or may be Torque). If you specify the run-time as `-l h_rt=hh:mm:ss` then it's definitely SGE.
Comment: @SamMiller According to the man page of qsub, it is Open Grid Scheduler v6.2u5
Answer: The "normal" approach is to have the environment produce a core file and get hold of those. If this isn't an option, you might want to try installing a signal handler for SIGSEGV which obtains, at least, a stack trace dumped somewhere. Of course, this immediately leads to the question "how to get a stack trace" but this is answered elsewhere.
The easiest approach is probably to get hold of a core file. Assuming you have a similar machine where the core file can be read, you can use gdb program corefile to debug the program program which produced the core file corefile: You should be able to look at the different threads, their data (to some extend), etc. If you don't have a suitable machine it may be necessary to cross-compile gdb matching the hardware of the machine where it was run.
I'm a bit confused about the statement that the core files are empty: You can set the limits for core files using ulimit on the shell. If the size for cores is set to zero it shouldn't produce any core file. Producing an empty one seems odd. However, if you cannot change the limits on your program you are probably down to installing a signal handler and dumping out a stack trace from the offending thread.
Thinking of it, you may be able to put the program to sleep in the signal handler and attach to it using a debugger, assuming you can run a debugger on the corresponding machine. You would determine the process ID (using, e.g., ps -elf | grep program) and then attach to it using
gdb program pid

I'm not sure how to put a program to sleep from within the program, though (possibly installing the handler for SIGSTOP for SIGSEGV...).
That said, I assume you tried running your program on your local machine...? Some problems are more fundamental than needing a distributed system of many threads running on each node. This is, obviously, not a replacement for the approach above.
Comment: Thanks, I updated the question.I think the core files are generated.
Comment: @Ali: If a core file is generated, get hold of it and see what the situation is! That sounds simple enough.
Comment: Thanks, but reading your proposed page I could find no idea about how to use the core files. It's not so simple for me, the same as you!
Comment: If you use `gdb program corefile` you should be able to have a look at where the program occurs and, to some extend, inspect the content of variables. It assumes that you have a `gdb` capable of reading programs and core files of the architecture the programs run on. Even if you don't have a similar computer, you can build a suitable cross version of gdb (if I recall correctly; it is a while since I cross-compiled code and needed to debug it).
Comment: The other "normal" approach is to request an interactive session, that would give you access to the same type of node, and then run the program with the same memory and stack size limits as the batch job under the control of a debugger.
Comment: @HristoIliev Thanks for your suggestion. I have already done exactly the same, but unfortunately the program works perfectly in the interactive way!
Comment: Were the (virtual) memory/stack/locked memory size limits the same as for your batch jobs? Stack space exhaustion is the number one trivial reason for misterious segmentation faults in threaded applications.
Comment: @HristoIliev This was the first thing I checked!
Comment: @DietmarKühl I tried to check the core files, they are created but empty!


Specify outgoing address for cron messages with postfix

Question: I have a server with Gentoo and Postfix. Postfix is configured so that all e-mail messages are routed through an external relay which requires a particular address in 'From'.
From /etc/postfix/main.cf:
relayhost = relay.example.com

I also have a cron task, which I'd like to send e-mail from. But the 'From' address is 'user@hostname', which is not allowed on a relay. Is it possible to substitute the correct address to cron for sending messages or fix the Postfix configuration in some way?
Comment: What is the command that you are using to send the emails?
Comment: There is no command, just MAILTO='' in a crontab file...
Answer: I use vixie-cron and ssmtp for a similar situation. What I do, especially for root jobs, is pipe the output of the command through | mail -r "firstname.lastname@example.com" firstname.lastname@example.com; it's tedious but it works.
Comment: Yes, I also have vixie-cron. Unfortunatelly this is a custom built VDS even without 'mail' command. Finally I wrap the call to my task in php which captures output and emails it. You solution should work too, so I mark it as an answer.


Timeout on geolocation get user permission

Question: I am getting user geolocation with js and want to solve the following scenario:
I have managed to done 1 ~ 4, but having a problem on 5.
The main problem is I can't tell when is the browser starting to get the location.
Thanks
ps: I am using the api at Geolocation.getCurrentPosition() https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
--- Scenarios ---

If user previously chose permission on geo location, give it a 5 seconds timeout on acquiring the location.
If user clicks 'deny', return null immediately.
If user click 'allow', let browser get geo location with 5 seconds timeout
If user ignores the 'allow/deny' prompt, give it a 5 seconds timeout (thinking time) and return null when user still ignore the prompt.
If user ignores the 'allow/deny' prompt for within 5 seconds, and clicks 'allow', give the user/browser another 5 seconds for getting the geo location.

--- some code ----
api.getGeoLocation = function() {

    var getGeoPromise = $q(function(resolve, reject){

        //give the timeout for user to decided
        var geoPromptTimout = $timeout(function(){
            reject();
        }, GEO_LOCATION_USER_PROMPT_TIMEOUT);

        $window.navigator.geolocation.getCurrentPosition(function(pos){
            $timeout.cancel(geoPromptTimout);
            resolve(pos);
        }, function(positionError) {
            $timeout.cancel(geoPromptTimout);
            reject();
        }, {
            timeout: GEO_LOCATION_ACQUIRE_TIMEOUT,
            maximumAge: GEO_LOCATION_CACHED_AGE
        });
    });

    return getGeoPromise;
};

Answer: I ends up using $q.defer.notify method.
First notify the consume code when it is timeout for user ignoring the prompt.
Then when user click allow just before the timeout, still load geo location in the background, and use notify to tell consume code again geo location successfully acquired.


Maven - creating and sharing packages between projects

Question: If I am working for a large organization, when is a situation where I would want to create my own Maven packages and share them with other projects inside my organization?
As I understand it a maven Package is just a maven project that you mvn deploy, then you can add the JAR to other projects. Is that it, or is there more to it?
Answer: You'll need an artifact repository such as Artifactory or Nexus. Once you setup artifact repo, you'll have to configure your projects to deploy artifacts there. This is done through your pom.xml file. Then when you run mvn deploy the artifacts will be published to your repo.
Other projects can declare your artifacts as dependencies the same way you do with any other dependencies, but to resolve them they need to know about your artifact repo. This is done in settings.xml
Comment: Great thanks! You should check out Visual Studio Team Services Package Manager (mouthfull), it does kinda the same, but keeps it all connected to VS :)
Comment: Just to be clear, an artifact is an entire package? So 1 dependency = 1 artifact?


Winding number of composition of maps

Question: If $f,g:S^{1}\rightarrow S^{1}$ maps, show that $N(f\circ g)=N(f)N(g)$, where $N(f)$ is the winding number of $f$.
We defined the winding number of $f$ to be $N(f)=\frac{1}{2\pi}(\tilde{f}(1)- \tilde{f}(0) )$ where $\tilde{f}$ is a lift of $f$.
I tried to look for a lift of $f \circ g$ but couldn't manage to find anything that makes sense for this problem.
Can anybody help me, please?
Thank you in advance!
Comment: What exactly do you mean by a lift of $f$? I would have thought $\tilde{f}$ is a map $S^1 \to \mathbb{R}$ such that $f = \pi\circ\tilde{f}$ where $\pi : \mathbb{R} \to S^1$ is covering projection, but in that case $\tilde{f}$ is not defined at $0$.
Comment: They mean to think of $f, g$ as loops in $S^1$ (i.e. precompose your $\widetilde{f}$ with $\pi$).
Answer: This may be a bit "cheating", but anyway... If $n = N(f)$ and $m = N(g)$, we know from the calculation of $\pi_1(S^1)$ that $f$ is homotopic to $z \mapsto z^n$ and $g$ is homotopic to $z \mapsto z^m$ (two maps with the same winding number are homotopic). But then $f \circ g$ is homotopic to $z \mapsto (z^m)^n = z^{mn}$, which has winding number $mn = N(f)N(g)$.
Answer: Here's a sketch of the idea.
Let $p : \mathbb{R} \to S^1$ be the standard covering map with period $2\pi$. Let $f' = f \circ p : \mathbb{R} \to S^1$, and let $\widetilde{g}$ be a lift of $g$. Then because $\mathbb{R}$ is convex, $\widetilde{g}$ is homotopic rel endpoints to a constant-velocity path $\gamma : I \to \mathbb{R}$. Now let $l : I \to \mathbb{R}$ be a lift of $f' \circ \gamma$. It's easy to show that $l$ is homotopic rel endpoints to a lift of $f \circ g$. The important thing is that we have the formula that $\gamma(t) = \gamma(0) + 2\pi N(g) t$.
For each $j \in \{1,\dotsc,N(g) - 1\}$, observe that for $rj \le t \le (j+1)/N(g)$, we have $l((j+t)/N(g)) = \widetilde{f}(t) + 2\pi j$. You can use this to argue by induction that for each $j \in \{1,\dotsc,N(g)\}$, we must have $l(j/N(g)) = l(0) + 2\pi jN(f)$. In particular, setting $j = N(g)$ will give you $l(1) = l(0) + 2\pi N(g)N(f)$, and you're done.
Alternatively, if you have the machinery of $\pi_1$ at your disposal and know that $\pi_1(S^1) \cong \mathbb{Z}$, you can use the fact that a homomorphism $\phi : \mathbb{Z} \to \mathbb{Z}$ can be computed via multiplication by $\phi(1)$, and that $N(f) = f^*(1)$. Then, you have $N(f \circ g) = (f \circ g)^*(1) = f^*(g^*(1)) = N(f)N(g)$.
Comment: Thank you very much! Great ideas!

Winding number of composition of maps


JSON payload error when receiving data from backend

Question: I have set up an API that uses OAUth Mediator for generating an access token in an external backend. I'm testing the endpoint using cURL.
From enabling wire logs I see the message from cURL is received correctly, then APIM consumes external backend, which replies with the desired information.
However, I'm getting two errors:
org.apache.axis2.AxisFault: Payload could not be written as JSON.
.
.
.
org.apache.axis2.AxisFault: Failed to submit the response

cURL never gets a reponse and times out (Empty reply from server).
Please see attached image of the Carbon log.
Things to note:

External API replies with content-type "application/hal-json". This is configured in my API by setting the Consumes field accordingly
Axis2.xml has been edited to include the following lines, in their respective sections:
<messageBuilder contentType="application/hal+json" class="org.apache.axis2.json.JSONStreamBuilder"/>
.
.
.
<messageFormatter contentType="application/hal+json" class="org.apache.synapse.commons.json.JsonStreamFormatter"/>

I have two mediation policies
In:

        <?xml version="1.0" encoding="UTF-8"?>
        <sequence name="secuenciaPrueba" statistics="enable" trace="enable" xmlns="http://ws.apache.org/ns/synapse">
            <log description="" level="full"/>
            <property name="DISABLE_CHUNKING" scope="axis2" type="STRING" value="true"/>
            <class name="org.wso2.apim.mediators.oauth.OAuthMediator">
                <property name="endpointId" value="EP1"/>
            </class>
        </sequence>

Out:
        <?xml version="1.0" encoding="UTF-8"?>
        <sequence name="secuenciaPruebaOut" statistics="enable" trace="enable" xmlns="http://ws.apache.org/ns/synapse">
            <log level="full">
                <property name="OUT_MESSAGE" value="OUT_MESSAGE"/>
            </log>
            <log level="custom">
                <property expression="get-property('ENDPOINT_PREFIX')" name="Endpoint"/>
                <property expression="get-property('transport', 'Content-Type')" name="Content-Type"/>
                <property expression="get-property('msgID')" name="Correlation_Id"/>
            </log>
            <property name="DISABLE_CHUNKING" scope="axis2" type="STRING" value="true"/>
        </sequence>

I need to return the JSON data to cURL, what is missing here?
Answer: Problem was the messageFormatter and messageBuilder classes were wrong. The correct settings are:
<messageFormatter contentType="application/hal+json"
class="org.apache.synapse.commons.json.JsonStreamFormatter"/>
.
.
.
<messageBuilder contentType="application/hal+json"
class="org.apache.synapse.commons.json.JsonStreamBuilder"/>


Os dados não estão salvando

Question: Criei um projeto que contém a parte de admin que seleciona as horas para ficar disponível para o cliente e tem a página de contato, quando eu vou primeiro no admin e seleciono as horas e clico em atualizar (botão que eu criei) ele vai para página de contato e aparece as horas que eu selecionei... agora quando eu clico primeiro na home e depois volto para página de contato as horas que eu selecionei não estão mais lá... a minha dúvida é, deve ser por que eu estou localmente e por isso acontece?
Tenho medo de eu hospedar o site e o problema ainda continar, pelo fato de não esta aparecendo as horas que eu selecionei logo depois de ter dado uma "navegada" no meu site....
Código do PHP e da página que recebe os dados:

Marca uma visita agora!

                    <form>

                                <input class="detalhe-campo-velho" type="text" placeholder="Nome">

                                <input class="detalhe-campo-velho" type="number" placeholder="Codigo de segurança">

                        <form>

Agenda disponível

                                <?php

                                        if(isset($_POST["hora"])) {

                                            for($i = 0; $i < count($_POST["hora"]); $i++) {

                                    echo " ".$_POST["hora"] [$i]." <input type='radio'/>
";

                                    }
                                        }
                                ?>

                        </form>

                            <button class="botao-confir margin-top20">Confirmar</button>

                    </form>

Página admin :
<form method="post" action="agendamento.php">

            10:00
            <input type="checkbox"  id="blankRadio1" value="10:00" name="hora[]" aria-label="..." ng-model="um">

            10:30
            <input type="checkbox"  id="blankRadio1" value="10:30"  name="hora[]" aria-label="..." ng-model="dois">

            11:00
            <input type="checkbox"  id="blankRadio1" value="11:00" name="hora[]" aria-label="..." ng-model="tres">

            11:30
            <input type="checkbox"  id="blankRadio1" value="11:30" name="hora[]" aria-label="..." ng-model="quatro">

            13:00
            <input type="checkbox" name="hora[]" id="blankRadio1" value="13:00" aria-label="..." ng-model="cinco">

            13:30
            <input type="checkbox" name="hora[]" id="blankRadio1" value="13:30" aria-label="..." ng-model="seis">

            14:00
            <input type="checkbox" name="hora[]" id="blankRadio1" value="14:00" aria-label="..." ng-model="sete">

            14:30
            <input type="checkbox" name="hora[]" id="blankRadio1" value="14:30" aria-label="..." ng-model="oito">

            15:00
            <input type="checkbox" name="hora[]" id="blankRadio1" value="15:00" aria-label="..." ng-model="dez">

            15:30
            <input type="checkbox" name="hora[]" id="blankRadio1" value="15:30" aria-label="..." ng-model="onze">

            16:00
            <input type="checkbox" name="hora[]" id="blankRadio1" value="16:00" aria-label="..." ng-model="doze">

            16:30
            <input type="checkbox" name="hora[]" id="blankRadio1" value="16:30" aria-label="..." ng-model="treze">

            17:00
            <input type="checkbox" name="hora[]" id="blankRadio1" value="17:00" aria-label="..." ng-model="quatorze">

        <button ng-click="atualizar()" value="descobrir">Atualizar</button>

</form>

Alguém poderia me explicar como funciona... eu sei que para fazer o envio de email através do php ele exige que o site esteja hospedado, ja esse método que fiz não sei se o site precisa de estar hospedado.
Answer: A sua página que recebe dados está usando a $_POST para exibir as horas selecionadas. A variável $_POST só existe quando você as envia de um formulário (são os valores inseridos nos campos input). Se você vai da Home->Página que recebe dados, a variável $_POST não estará setada, logo, não terá o que exibir.
Comment: No caso o mais recomendável é que você salve OS VALORES DAS VARIÁVEIS em um banco de dados. Daí, quando você for exibí-los, basta buscar no banco.
Para saber como fazer isso, basta procurar sobre CRUD (Create, Read, Update, Delete - ações a se fazer em um banco de dados).
Comment: Qualquer dado salvo no banco pode ser manipulado. Por isso recomendei que você lesse sobre CRUD.
Comment: Ah tendi... e como poderia solucionar esse problema... eu precisava salvar essas variaveis pois vai que o usuário queira navegar no site e depois voltar para marcar a hora...
Comment: Mas quando eu salvar os dados da variaveis no banco eu poderei manipular quais dados quero mostrar na outra tela?
Comment: Entendi... obrigado

Os dados não estão salvando


Changing the basis in codomain and domain of a linear transform and its effect on some result

Question: Question:
Let $V$ be a finite-dimensional vector space and $T:V\rightarrow V$ a linear transformation. Let $B$ be a basis for $V$, and let $A$ be the matrix of $T$ with respect to $B$ (in both domain and codomain). Show that for any $v\in V$ and any scalar $\lambda$, the following are equivalent:
 - $v$ is an eigenvector of $T$ corresponding to $\lambda$;
 - $[v]_B$ is an eigenvector of $A$ corresponding to eigenvalue $\lambda$.
I have already proved these two equivalences (mathematically, I don't understand them intuitively).
The next question says:
Does the same result still hold if we use different bases for $V$ in the domain and codomain? Explain.
I'm not sure how to mathematically prove if it does/doesn't hold. I would also like some intuition (or how you would intuitively describe this relation).
Answer: No, it doesn't hold if the bases are different. Take any basis $B_1=\{{b_1,...,b_2}\}$ for your domain, and take $B_2=\{\frac{1}{2}b_1,...,\frac{1}{2}b_2\}$ for your codomain.
The matrix of $T=Id$ for this choice of basis is the matrix $A=2.Id$. Then $2$ is an eigenvalue of $A$, but not an eigenvalue of $T$.


EF6 - Carga apressada trazendo menos dados agregados que os dados do banco

Question: Estou tendo o seguinte problema com meus relacionamentos no Entity.
Quando eu busco por exemplo um Cliente do banco pelo Id :
return _databaseContext.Clientes
                               .Include(x => x.Enderecos)
                               .Include(x => x.Documentos)
                               .Include(x => x.Telefones)
                               .SingleOrDefault(x => x.Id == id);

Ele possui 2 Enderecos, 2 Documentos e 3 Telefones.
Mas o Entity só traz 1 documento, 1 endereco e 2 telefones. :

Não consigo entender o motivo. Até usando o LazyLoad ele não carrega, fora que ele está gerando uma query extremamente enorme e mal feita com vários Unions e SubSelects. Alguém tem alguma idéia?
Vou colocar apenas algumas props pois a classe é enorme:
public class ClienteEntity : Entity<int>
{
    private IList<EnderecoClienteEntity> _enderecos;

    public ClienteEntity(string nome,
        IList<EnderecoClienteEntity> enderecos)
    {
        Nome = nome;

        _enderecos = new List<EnderecoClienteEntity>();
        enderecos.ToList().ForEach(endereco => AddEndereco(endereco));
    }

    public string Nome { get; private set; }

    public virtual ICollection<EnderecoClienteEntity> Enderecos
    {
        get { return _enderecos; }
        private set { _enderecos = new List<EnderecoClienteEntity>(value); }
    }

    public void AddEndereco(EnderecoClienteEntity endereco)
    {
        if(endereco.CriarEndereco())
            _enderecos.Add(endereco);
    }
}

Descobri aqui onde está o erro, ele está na lista:
public virtual ICollection<EnderecoClienteEntity> Enderecos { get; set; }
  //  {
  //      get { return _enderecos; }
  //      private set { _enderecos = new List<EnderecoClienteEntity>(value);    }
  //   }

Se eu deixar a lista assim, ele traz tudo que tem no relacionamento. Mas qual seria o motivo?
Comment: Opa, blz Cigano? Está normal fazendo o relacionamento one-to-many e mapeando a ClienteId nas tabelas Endereco, Telefone e Documento.
Os dados já estão no banco e inclusive se eu rodar o select que aparece no output quando uso lazyload está certinha. Porém ela não traz todos os objetos relacionados, apenas alguns.
Comment: Como estão os dados no banco?
Comment: Tem como colocar as suas classes ?
Comment: Atualizado, coloquei as query gerada também.
Comment: Sim, mas eu preciso de um exemplo. Por exemplo, ClienteId 1, Endereços 2 e 3, Documentos 4 e 5, Telefones 6, 7 e 8.
Comment: Você quer ver os dados que estão no banco?
Comment: Isso. Aparentemente, não há nada de errado com a consulta. Está otimizada, inclusive.
Comment: O que é `endereco.CriarEndereco()`? Qual a necessidade disso?
Comment: Descobri o motivo do erro, se eu tirar o meu get e private set e colocar apenas {get; set;} ele traz tudo do relacionamento. Teria como arrumar sem usar tudo publico?
Answer: Todo este código é inútil:
public ClienteEntity(string nome,
    IList<EnderecoClienteEntity> enderecos)
{
    Nome = nome;

    _enderecos = new List<EnderecoClienteEntity>();
    enderecos.ToList().ForEach(endereco => AddEndereco(endereco));
}

public virtual ICollection<EnderecoClienteEntity> Enderecos
{
    get { return _enderecos; }
    private set { _enderecos = new List<EnderecoClienteEntity>(value); }
}

public void AddEndereco(EnderecoClienteEntity endereco)
{
    if(endereco.CriarEndereco())
        _enderecos.Add(endereco);
}

Simplifique este para:
public virtual ICollection<EnderecoClienteEntity> Enderecos { get; set; }

Não é você que tem manipular as entidades agregadas e os níveis de proteção. É o Entity Framework que faz isso. Apenas deixe o framework trabalhar por você e não se preocupe tanto com segurança de código.
Comment: Assim você está "impedindo do lado de fora" também o *Controller* de manipular a propriedade, o que é absolutamente normal no MVC. Não vale a pena manter.
Comment: Você precisa fazer **urgentemente** meu curso. Não use DDD. Só vai te atrapalhar.
Comment: Vou te chamar lá no face pra gente conversa sobre o curso que agora fiquei curioso rsrs. Enfim mto obrigado pela sua ajuda aqui mano. Um abraço!
Comment: Eu utilizo assim porcausa da classe scope que válida as informações do campo da entidade endereço por exemplo. Se estiver tudo certo eu adiciono na lista na entidade. Outro motivo de eu usar assim é pra impedir do lado de fora da classe cliente.Enderecos.Add(endereco). Vc acha que msm assim não vale a pena manter?
Comment: Estou usando DDD e tentei aplicar o conceito de modelo rico que vi em um curso. Vi que na prop da lista vc tirou o private do set. Isso só se aplica as listas ou nas outras props tbem?  Esse controller que vc falou que manipula a propriedade e do mvc ou do entity framework?


Hey! Why my Javascript code is not working

Question: I tried to create a function in Javascript that will give a random integer between two integers (including both).
But, unfortunately this is not including the first integer.
The code is as follows:
const randomEjector = (num1,num2) => {return Math.ceil(Math.random() * (num2 - num1)) + num1}

I am considering the analogy of inequality.++
Let's consider,
(Math.random() will output a no. between 0(including) and 1(excluding)).
Let's say x = Math.random(), then x∈[0,1)
So, 0 ≤ x < 1
0 * (num2-num1) ≤ x * (num2-num1) < 1 * (num2-num1)
Again, x*(num2-num1)∈[0,1*(num2-num1))
Now opening Math.ceil() part:

But, Math.ceil() is like greatest integer function:
So, for (0,1] it will return 1.
for 0 => 0
and for interval ((num2-num1)-1,(num2-num1)),it will return (num2-num1).
So, After Math.ceil() is executed, we should be left with an interval [0,(num2-num1)].
Now, x*num2-num1∈ [0,(num2-num1)]
Finally, let y = x*(num2-num1)
So,0 ≤ y ≤ (num2-num1)
So,0 + num1 ≤  y + num1 ≤ (num2-num1) + num1
Which will give num1 ≤ y + num1 ≤  num2
Let, z = y + num1
So, z ∈ [num1,num2]
Then, why my function is excluding 1st term and making it like (num1,num2]?
Where's the problem?
For instance for console.log(randomEjector(3,4)), it will always give 4 and never 3.
Comment: [What are the chances of Math.random returning 0?](https://stackoverflow.com/questions/52089553/what-are-the-chances-of-math-random-returning-0)
Answer: It's unspeakably unlikely that Math.random() will ever return exactly 0, so Math.ceil(Math.random()) will unspeakably likely always return 1.
In other words, randomEjector(3,4) will, once in a very, very blue moon, give you 3.
Comment: Ok, that means Math.random() can never generate 0. Thank you.
Comment: @Xeroid No, it _can_ generate 0. The odds are just ridiculously slim. ([Around one in 2^1075](https://stackoverflow.com/a/52095861/479156).)
Comment: I got another query too.
`let myNumbers = [100,998,997];`
`const nestedArray = [];`
`const newNumber = myNumbers.map((value)=>{`
    `if(value>400){`
        `nestedArray.push(value);`
    `}`
    `return nestedArray;`
`})`
`console.log(newNumber);`

I am expecting the output to be **[[ 998, 997 ]]** but getting **[[ 998, 997 ],[ 998, 997 ],[ 998, 997 ]]**
Comment: @Xeroid New questions go [here](https://stackoverflow.com/questions/ask). (That is, after you have done enough research yourself first to find the answer.)
Comment: So, if i will run my code for 2^1075 times making my browser lag and then, I will get 3. Of all, it might take more than a year too.
Comment: @Xeroid I'm no mathematician, but I think you'll need more time than the universe exists. And even then, it is random. So there is a decent chance you don't even guess it after that time.
Answer: It returns 4 because you are always ceiling the result, if you want it to return 4 then you need to floor the result.
Comment: But, Math.ceil() is like greatest integer function. When, 3 is integer, Math.ceil(3) will return 3.Ok,,since, Math.random() will never return 0 and hence, my output will never be 3 and always be 4. I got it now. Thank You.


Apache as a reverse proxy with restricting allowed hosts

Question: I've come up with apache configuration that does reverse-proxy for an internal owncloud installation. It works very well and now I'd like to restrict hosts by IP, that would have access to this reverse-proxied host, but I noticed 2 things (example config of the host doing the proxying):
<VirtualHost *:443>
  # I put below line here but it seems it isn't used when reverse-proxying
  DocumentRoot "c:/apache/owncloud"
  # this host is going to answer to The World to requests to owncloud
  ServerName cloud.example.com:443
  ServerAdmin email@example.com
  ErrorLog "c:/apache/logs/ssl-owncloud-error.log"
  TransferLog "c:/apache/logs/ssl-owncloud-access.log"
  # the actual host with owncloud is reachable from intranet by this name
  ProxyPass "/" "https://cloud.example.com/"
  ProxyPassReverse "/" "https://cloud.example.com/"
  # This is important, the Directory section, I imagined this would work...
  <Directory "c:/apache/owncloud">
    Options FollowSymLinks
    AllowOverride FileInfo
    Require IP xxx.xxx.xxx.xxx
    Require IP yyy.yyy.yyy.yyy
    Require all denied
  </Directory>
  SSLEngine on
  SSLCertificateFile "c:/apache/ssl/server.pem"
  SSLCertificateKeyFile "c:/apache/ssl/privkey.decr.key"
  SSLProxyEngine On
</VirtualHost>

1) I've put the Directory section and thought it would be respected, but it isn't.
2) Naturally the proxied machine (owncloud host) has no idea that in reality host external to our LAN pulled the page, in access logs it's only showing IP of the proxy, so I can't do the restricting there.
Please share your knowledge as to where do I setup IP based restrictions because these above don't work and effectively whole world can see owncloud as it is.
Comment: I'm not quite sure what you're asking but if you want to apply restrictions to a reverse proxy you should probably set both the ProxyPass and ACL's  in a `Location` container.
Comment: Right, I've significantly shortended the question to focus on relevant info only. Yes, I'd like to apply restrictions and I will try with `Location` later today
Answer: Since a ProxyPass does not map requests to the local file system setting access controls in a Directory block does not work. You'll need to set them in a Location container, i.e. use something like this:
<Location />
    ProxyPass  "https://cloud.example.com/"
    ProxyPassReverse "https://cloud.example.com/"
    <RequireAll>
       Require IP xxx.xxx.xxx.xxx
       Require IP yyy.yyy.yyy.yyy
       Require all denied
    </RequireAll>
</Location>

Comment: afaik that set of Require directives would need to be enclosed in a  tag.


What's the ammount of solutions to the Equation $A+B+C+D=24$ with restrictions on $A$ and $B$

Question: As the title says, I have the the following equation:
$A+B+C+D=24$
$2\leq A\leq 5$ and $4\leq B\leq 7$
And i need to find the number of possible solutions. $A,B,C,D\geq 0$, They are integers.
I'm not sure if my solution is right, What i did is:
I've made a new equation stating $A_1=A-2$ and $B_1=B-4,$ So i get:
$A_1+B_1+C+D=30.$
So my restrictions now are $0\leq B \leq 3$, Marking $A_1+B_1=S, S=[0,6],$ Means:
$C+D=30-S $ And the number of possibilities for that one is $31-S$.
So now i need to do the sum: $\sum (31-S)$ from $S=0$ to  $ S=6$ and multiply it by $3^2 \;$ [Which represents the different combinations of $A$ and $B$] so that equals to: $1774.$
Did I do something wrong or it seems fine?
Comment: Actually, you did something wrong : you believed for a given $S$ there are $3^2$ pairs $(A_1,B_1)$ such that $A_1+B_1=S$. The exact number is less in general (try to compute it).
Comment: As a general hint, you had better have a look at this: http://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29
Comment: Thanks but i already read that one [and used that in my solution], I just want to understand i did something wrong.
Comment: Acually, I made a mistake, But I think there are -more- numbers.
Cause if 0<=A,B<=3
Means A,B can be [0,3], And we actually get 16 options.
Answer: By using ordinary generating function:
let $A=g_1(x)=(x^2+x^3+x^4+x^5)=x^2(1+x+x^2+x^3)$
let $B=g_2(x)=(x^4+x^5+x^6+x^7)=x^4(1+x+x^2+x^3)$
let $C=g_3(x)=(1+x+x^2+\dots\dots)$
let $D=g_4(x)=(1+x+x^2+\dots\dots)$
Then $G(x)=g_1(x)g_2(x)g_3(x)g_4(x)=x^6\frac{(1-x^4)^2}{(1-x)^2}\frac{1}{(1-x)^2}=x^6\frac{1-2x^4+x^8}{(1-x)^4}$, now you need to find $[x^{18}]$ in $\frac{1-2x^4+x^8}{(1-x)^4}$, then you get
$$\binom{18+4-1}{4-1}-2\binom{14+4-1}{4-1}+\binom{10+4-1}{4-1}=256$$
Answer: I think you're trying to simplify things, but you're making some arithmetic errors in the process.  Firstly, you should subtract 6 both sides, rather than subtracting 6 on the left, and adding it on the right.  Then there's some other bugs noted in the comments.  But you needn't do any of this anyway.
As you point out, the number of non-negative integer solutions to $C+D=24-A-B$ (once the values of $A$ and $B$ are decided) is indeed $24-A-B+1$: the solutions are $$(C,D) \in \big\{(i,24-A-B-i):i \in \{0,1,\ldots,24-A-B\}\big\}.$$
Now we can just do the bookkeeping.  The following lists the possible values of $(A,B)$, denoted <code>[ A, B ]</code> along with the value of $24-A-B+1$.
<code>[ 2, 4 ] 19
[ 2, 5 ] 18
[ 2, 6 ] 17
[ 2, 7 ] 16
[ 3, 4 ] 18
[ 3, 5 ] 17
[ 3, 6 ] 16
[ 3, 7 ] 15
[ 4, 4 ] 17
[ 4, 5 ] 16
[ 4, 6 ] 15
[ 4, 7 ] 14
[ 5, 4 ] 16
[ 5, 5 ] 15
[ 5, 6 ] 14
[ 5, 7 ] 13
</code>
We add this up to give 256.
Comment: Nice one, Thanks.
Answer: You've had a good idea to set $A_1=A-2$ and $B_1=B-4$, but from there, you start having issues. We can rewrite $A=A_1+2$ and $B=B_1+4$ to give us $$A_1+B_1+C+D+6=24,$$ or $$A_1+B_1+C+D=18,\tag{1}$$ with our new constraints that $A_1,B_1,C,D$ are all nonnegative integers with $A_1\le3$ and $B_1\le 3$.
As you note in the comments, there are $16$ pairs $A_1,B_1$ that meet our constraints. However, there are not $16$ different ways to make $A_1+B_1=S$ for each integer $0\leq S\leq 6$. Consider the following table of sums: $$\begin{array}{c|cccc}& 0 & 1 & 2 & 3\\\hline\\0 & 0 & 1 & 2 & 3\\1 & 1 & 2 & 3 & 4\\2 & 2 & 3 & 4 & 5\\3 & 3 & 4 & 5 & 6\end{array}$$ In general, then, given an integer $0\le S\le 6$, there are $$\min\{S,6-S\}+1=4-|3-S|$$ ways to choose $A_1,B_1$ meeting our constraints such that $A_1+B_1=S$.
Now, given any integer $0\le S\le 6,$ there are indeed $19-S$ ways to choose nonnegative integers $C,D$ such that $S+C+D=18$. Hence, the sum you're looking for is $$\begin{align}\sum_{S=0}^6\bigl(4-|3-S|\bigr)(19-S) &= 1\cdot 19+2\cdot 18+3\cdot 17+4\cdot 16+3\cdot 15+2\cdot 14+1\cdot 13\\ &= 19+36+51+64+45+28+13\\ &= 256.\end{align}$$
Comment: Great comment, Really helped me understand things.


Is there a way to communicate between server and client in Python without opening up ports?

Question: I was working on a decentralized python chat room. I was just wondering, if you don't open up a port, you can't receive messages. But, if you open up a port, you are vulnerable to getting hacked or something. So, is there a way to communicate with Python between a server and a client without opening up ports?
Comment: **"But, if you open up a port, you are vulnerable to getting hacked or something"**, well, I think that would be the least of your problems. Just use secure connections and that's all.
Comment: The vulnerability of open ports is not that they are ports, but that they are open. If you are open for any kind of communication, that leaves you vulnerable. You should focus on communicating securely, not on communicating without... erm... communicating.
Answer: At least one of the client or the server should have an open port (typically, the server). As soon as a TCP connection is established (typically, by the client), a random (= chosen by the operating system) port will be used by the client to be reachable by the server.
Comment: By definition, an application listening for a connection is a server.


Confusion about computation of average precision

Question: I am trying to learn what AP (average precision) means and I came across this page: https://towardsdatascience.com/breaking-down-mean-average-precision-map-ae462f623a52
Here is the given formula:

And here is the given example:

This is a little intuitive to be to set the numerator at all red crossed images (false positives) to 0, because at these points, TP seen in the formula is bigger than 0 -- in the 2nd and 3rd predicted positives (which are false) TP seen so far is 1, and in the 6th predicted positive (which is also false), TP is 3. Then why the author used 0 as "TP seen" for them?
Comment: If we use "TP seen so far" rather than 0 for the numerators of the false positives as well, what we get for the above example would be: (1/3) * (1/1 + 1/2 + 1/3 + 2/4 + 3/5 + 3/6 + 3/7 + 3/8 + ..... + 3/n), which will be bigger than 1. Using 0 provides the formula to result in a maximum average precision of 1.
Answer: I read the article diagonally, so maybe I understood it wrong. But, I think the reason for not adding 1/2, 1/3, is just for penalizing even more those delayed true positives.
Because this Average Precision measures "how soon you get your True Positives", or in the words of creator of the post, "quantify the goodness of the sort based on the score function d( , )". So, if you get all your TPs at the beginning, everything is perfect, and your score is 1. But if the TPs do not arrive at the beginning, the score starts to decrease, and returns a number which assess precisely how "late" the TPs come.
So, that said, it could be used in a cumulative way as you say: (1+1/2+1/3+2/4+3/5+4/5)... but it would penalize less the delayed TPs than using it as the author explains
Comment: Thanks, I get that, but then the formula and example are inconsistent, aren't they? Also, you said "but it would penalize less the delayed TPs than using it as the author explains" -- does the author consider the version I suggest? Or do you refer by "author explains" to the the part that he talks about the fact that we want to penalize false positives?
Comment: yes, also for me it is incosistent. I think it would be better explained if the formula was written in other way, for example, just adding the condition inside  (instead of TP seen  --> if TP = TPseen, else: zero)

And refering to your second quest...  I think the author doesn't consider your version, or at least, I didn't see it. I just wanted to underline that forcing non-TP's 0  would penalize even more the delay. But, depending on what you need, maybe is better to do it as you suggest.