Tips on playing arpeggios fast ([eg. c arpeggio] c, e, g, (now octave higher) c, e, g)

Question: I have trouble making the c major arpeggio sound smooth. Whenever I attempt to play it smooth, it sounds like groups of 3, perhaps because I press each note too hard.
What are some tips on playing the c major arpeggio?
Comment: By 'C chord run' do you mean 'arpeggio'? And do you mean the 4th note played (C) is too emphasised?
Comment: Yes, "apreggio" that is what it is called! Now, when I seach for it on google I actually get some desired results, as opposed to when I searched for chord runs.

Yeah, my issue is that the 4th note is too emphasised, how do I practice "smoothening the notes out"
Answer: You found a solution, not, maybe, the solution.Can't really see what his elbow is doing, but it could be nudging to the right on the way up, in order to get that thumb underneath the palm ready for the next C.
I prefer students to move the whole hand during and after playing the G with middle finger,, so the thumb is ready to play the next note, C. His method is more like leave the hand where it is on C E and G until it has to move, and then put the thumb under, so it reaches the next C. Mine is keep the hand (and arm) moving all the time, so it sort of slides over the keys, dropping on notes as the fingers are over them. Elbow doesn't have to move at all, except in line with the wrist, instead of out in a nudging action. Much easier to explain in a video - which I don't have - but somewhat different from your guy's approach. Give it a few tries and let me know!
Answer: Maybe you are crossing your thumb under the palm and uncurling it is hindering timing?  Maybe you are twisting your wrist in ulnar deviation which will create an uneven sound.
Try this: Don't abduct (stretch out) your fingers but instead, as you ascend move your arm up the keyboard so that the arm places the hand and next finger. Also, since your fingers are all different lengths when executing a 123 1235 fingering play on the outer edge of the key where they are lightest, then come out for the index, out further for the middle, all while raising the forearm a bit, then repeat with an in motion for the thumb.  Of course, in for the pinky at the end.
There are other movements such as rotation (using the pronator and supinator around the elbow) and forward shifting into the keys but start with the aforementioned.
Here is a $175 lesson:
Answer:
Relax your wrist and arm and relieve all tension.
Make sure everything you're doing feels natural. If it's uncomfortable, don't do it or try to do it as little as possible.
Remember to go across the keys with minimal effort as if you're laying a blanket rather than trying to dig into every note.
If you relax into the keys, your arm weight will automatically do the hard work for you.
Having correct playing posture helps - keep your wrists elevated, playing with your fingertips, etc.
This might seem obvious but check your fingering.
Answer: I completely agree with all of the above comments, but there's another simple way to figure out what's going wrong (and also to improve the speed and fluidity) - slow down! I've found that the best way to figure out what's going wrong is to slow down the arpeggio (or scale, or whatever) until I can get it perfectly smooth... and then speed it up slowly  (time after time after time) until it's second nature to play it smoothly and quickly. Another great tip? Changing up the rhythm - pick a noticeable rhythm (a bell, cartoon sound, or whatever) - and then play the arpeggio to the rhythm of that. It forces you to think and feel more carefully whatever's coming next, rather than "next note/next note/next note".
Answer: Act naturally.
There are always rigid teacher with rigid methods and teaching the only single way, as "don't turn your wrist, don't move your elbow, don't stretch your fingers, don't tap your feet."
Why not combining all natural movements: a little help by  the  under going thumb, a slight turn of the wrist, a quick move of the hand, a slight support by the elbow all in a coordinated natural movement.


C# - When to use standard threads, ThreadPool, and TPL in a high-activity server

Question: I've been reading a lot about threading lately as I am looking to develop a high-performance, scalable TCP server capable of handling up to 10,000-20,000 clients, each client of which is consistently communicating bidirectionally to the server with a command-based system.  The server will receive a command, and execute either a single (or many) tasks as per the command.  My question is how to appropriately make use of the .NET threading constructs for a variety of situations, executing tasks that could take between one minute to several hours, depending on the work being performed.
What's confusing me the most is the fact that everywhere I read, I see something like "use a manually created Thread (or custom thread pool) to handle 'long-running' tasks, and use TPL for short-lived tasks, or tasks that require parallel processing."  What exactly is a long-running task?  Is that 5 seconds, 60 seconds, an hour?
With what time frame should I be using each of these three methods of creating threads:

Manually created Threads
The .NET ThreadPool class
TPL

Another issue I've contemplated is as follows--say my server does in fact have 20,000 clients connected, each of which sends 1 command (which could translate to one or many tasks) per second.  Even with powerful hardware, isn't there a chance that I could be pushing too high of a workload into whatever thread pool / work item queue I have, thereby eventually generating an OutOfMemoryException after the queue slowly fills to the maximum?
Any insight would be greatly appreciated.
Comment: @slashp Long running means "more than a couple hundred milliseconds", ie. something that disrupts your other work (and introduces significant latency to processing). If you aim for 5 ms latency for example, even 1ms can be considered "long running" :D Also, I'd like to point out that 20k TCP clients is getting close to the practical limit - each TCP connection needs a separate port, and you only have 65535 of those *maximum* - and they live for about 4 minutes after being closed. You might have to think about scaling out (more servers) rather than scaling up (more connections per server).
Comment: And on average how long will each command take to be procesed?
Comment: That's the thing--there's really not telling how long the command will take to complete.  I feel that I've received enough information to plan accordingly.  Of course 20,000 clients is a long shot (5,000 is more like it), but I want to be ready to scale in the future if necessary.  Thank you everyone for your responses.
Answer: Actually, for that scenario all of those are secondary; the first thing you should look at is asyc-IO, aka <code>.BeginRead(...)</code> etc; this allows you to minimise the number of threads by waiting on IO completion ports - much more efficient.
Once you have a complete message, at that scale I would throw the message into a custom thread-pool/synchronized-queue. I would have a controlled number of regular threads (not pool threads or IOCP) servicing that queue to process each item.
As it happens I'm doing something similar (lower scale) at the moment; to prevent memory exploding, I have capped the work queue; if it gets full (i.e. the workers can't keep up) then you might block IOCP for a small while, perhaps with a timeout eventually that tells the client "too busy" at the IOCP layer.
Comment: Sorry, I forgot to mention I understand IOCP will be used for the networking portion, I just wanted to give some background on what I want to accomplish.  I also understand I need to be careful about heap fragmentation when using IOCP which can cause OutOfMemoryException as well.  I really just need clarification on when to use which of the three constructs, as well as the definition of a "long-running" task.
Comment: +1 for "queue + servicing threads" - very likely to be the best approach
Comment: @slashp I edited to add some thoughts on the memory issue; since you are likely to be running constantly, you may as well own the threads yourself - avoids messing with ThreadPool, plus you can name them
Answer:
What's confusing me the most is the
  fact that everywhere I read, I see
  something like "use a manually created
  Thread (or custom thread pool) to
  handle 'long-running' tasks, and use
  TPL for short-lived tasks, or tasks
  that require parallel processing."

Strange advice, or maybe you mis-quoted a little. A thread is also capable of parallel processing, and with the TPL you can create a Task with the LongRunning option. What remains is that you should not launch long tasks on the ThreadPool.

What exactly is a long-running task?
  Is that 5 seconds, 60 seconds, an
  hour?

The TPL runs on top of the ThreadPool and the TP will create new Threads at a max of 2 per second. So long-running is >= 500 ms

Even with powerful hardware, isn't
  there a chance that I could be pushing
  too high of a workload into whatever
  thread pool / work item queue I have,

Yes, no Threading tool can extend your actual capacity...
With 20k clients you will probably need a Server Farm, an option to include in your design early...
So you should probably give WCF a good look before getting to deep into sockets.
Comment: Even though LongRunning is defined as a hint the actual implementation in the default TaskScheduler will always create a new thread - see http://coderkarl.wordpress.com/2012/12/13/long-running-tasks-and-threads/
Comment: Now I thought the thread scheduler wouldn't always respect the "LongRunning" option?  Thanks for the info on "long-running."
Comment: @slas LongRunning is a hint for the scheduler so I suppose it's free to ignore  it, the whole "no LongRunning" thing is about (not) upsetting the scheduler / load-balancing.
Comment: @HenkHolterman How do you know that ThreadPool creates new Thread at a max 2 per second? Where it can be configured?
Answer: Marcs suggestion is the way I would do it. But if you tasks take longer than one second and the clients sends a request per second the queue would steadily increase.
In that case I would use one server as facade which gets all requests from the clients and send responses back to them in an asynchronous manner.
The server would put all requests in a message queue which is read by several other servers. Those servers handle the requests and put the response in another message queue which is read by the first server.
Another solution would be to use a load balancing server.
Answer: You appear to be building a server which will service thousands of concurrent requests, each long-running in terms of minutes to hours.
Typically, make thread workloads short enough to complete at most within a few seconds.  Anything longer, you'll start hogging server resources and seriously affect your server's scalability.  Having tens of thousands of threads block on long-running operations, or doing those long-running operations simultaneously, will definitely kill your scalability.
Not sure how much CPU time you're consuming in each long-running.  This will affect your design, e.g.:
If each long-running is primarily blocking on I/O, you may use one thread to wait on overlapped I/O or I/O completion port, then wake up new threads to process completed I/O (up to a throttled limit).  You'll need to have a limit number of threads to service the waiting connections.
If each long-running operation waits for other operations to complete, consider Windows Workflow Foundation.
If each long-running operation consumes CPU, you don't want too many of them to be running at any one time or it will thrash your server.  In this case, use MSMQ and/or TPL to queue tasks and make sure only a few are running at the same time.
In all of these, it seems that you are keeping the client connection open.  The worst thing to do is to keep one thread blocking for each connection.  You'll need to implement thread-pooling strategies in order to use only a limited number of threads to service all outstanding connections.


How to export field collection with Drupal 7 views data export plugin?

Question: The Views Data Export plugin appears to work perfectly with the data that I have, though I have a field called "Items Bought" consisting of fields ("Item Bought" and "Cost"). For each content type of type "ShoppingRecord" a user could have one or more "Items Bought" field collections (i.e. Bannana $2, Apple $5).
When I add the field to my "page". I noticed that when I create a view with the "Data Export" and use CSV as the option, I am getting blanks for all the rows in the "Items Bought" column. Is there some way to get the plugin to recognize field collections and maybe export them all into the same field in the CSV? All the other fields that are not field collections appear to export properly.
Answer: If you only need the first result you can add a relationship in the view. Search for the name of the field collection. Once you add this relationship you should be able to access the field collection items and add them to your output.
If you want all the values you need to search add the field collection to your view rather than the fields directly. You then have the options of how to display the results but these options are limited.


Como pintar um gráfico no r a partir de um valor específico?

Question: x <- seq(0, 15, length.out=10000)

dat <- data.frame(x=x, px=dexp(x, rate = 1/5 ))

library(ggplot2)

ggplot(dat, aes(x=x, y=px)) + geom_line()

eu gostaria de pintar esse gráfico a partir do valor 10, algo como isso:
Answer: Para pintar a área debaixo da curva, pode-se usar o geom_ribbon.
A base tem de ser reduzida aos valores de x a partir do ponto mínimo, neste caso 10.
E deve ser usado antes de geom_line para não se sobrepor à linha.
library(ggplot2)

ggplot(dat, aes(x = x, y = px)) +
  geom_ribbon(
    data = subset(dat, x > 10),
    aes(ymin = 0, ymax = px),
    fill = "blue") +
  geom_line()

Comment: Pode usar `geom_area` no lugar de `geom_ribbon`, assim não precisa especificar outra estética.


What is the best way to add a list of 'skills' to a user model in rails?

Question: On my User's edit page I want users to be able to select from checkboxes what programming languages they know. I will give them about 15 to choose from. I then want to store these results in the User model to be accessed/searched for later.
What is the best way to go about this?
Comment: http://guides.rubyonrails.org/association_basics.html
Answer: You can apply a many to many associations for achieving so. If you Google or even search SO, you will get lots of examples.
However, you can simply achieve same thing using the following gem
https://github.com/mbleigh/acts-as-taggable-on
It appears it's example matches your requirements. In the examples, they described same (skills) thing. So, you will get it done easily.


Hypotheses of Nakayama's lemma are necessary

Question: Nakayama's lemma. Let $M$ be a finitely generated $A$-module, $I\subseteq A$ an ideal such that $I\subseteq \mathfrak{R}(A)$ Jacobson's radical of $A$. If $IM=M$, then $M=0$.
I'd like to show that both the finitely generated hypothesis on $M$ and the inclusion hypothesis in the Jacobson's radical $\mathfrak{R}(A)$ are necessary. Explicitly, I'm looking for:

A non finitely generated $A$-module $M\neq 0$ with an ideal $I\subseteq \mathfrak{R}(A)$ such that $IM=M$.
A finitely generated $A$-module $M\neq 0$ with an ideal $I\nsubseteq \mathfrak{R}(A)$ such that $IM=M$.

I found that $\mathbb{Q}$ as $\mathbb{Z}_{(2)}$-module with the maximal ideal $I=(2)\cdot\mathbb{Z}_{(2)}$ works for the first request.
I couldn't find any example for the second request, apart from the trivial $\mathbb{Z}$ as $\mathbb{Z}$-module with $I=\mathbb{Z}$. Is there any example with an ideal $I\nsubseteq \mathfrak{R}(A)$ but still a proper ideal of $A$?
Comment: Please use markdown to format non-mathematical text: for instance, `**bold**` produces **bold**. I've made the upgrade for you this time.
Answer: For the second request, you could take $A = \mathbb Z$, $M = \mathbb Z / 2\mathbb Z$ and $I = 3\mathbb Z$. Clearly, $IM = M$, but $M \neq 0$. The reason why Nakayama's lemma is not applicable here is that $I \nsubseteq \mathfrak{R}(A)$, since $I$ is not contained in the maximal ideal $2\mathbb Z$, for example.
Answer: Take your favourite non-zero field $K$ and consider the product ring $R=K\times K$. Then we have two idempotents $(1,0)$ and $(0,1)$ which generate maximal ideals $I_1$ and $I_2$. $I_1 \cap I_2=0$ so the Jacobson radical is also 0. Consider the $R-$submodule $M=K\times 0 \subset R$, and you have $I_1M=M$.


NBA mandatory timeout rules

Question: From the NBA rule book, on pg. 22, there are the rules for mandatory timeouts, which state:

If neither team has taken a timeout prior to 6:59 of the  period, it shall be mandatory for the Official Scorer to take it at the first dead ball and charge it to the home team. If no subsequent timeouts are taken prior to 2:59, it shall be mandatory for the Official Scorer to take it and charge it to the team not previously charged.

Now, the question I have is what happens if both the home and road teams have taken a timeout in the first 5 minutes of a quarter, and there are no other taken timeouts? Certainly, in this case, there is no timeout charged at the first dead ball after the 7:00 mark. Because there are no subsequent timeouts, one of the teams must be charged with a timeout on a dead ball at the 3:00 mark, but which one will be charged with this timeout. Or, would this be scored as an officials's timeout?
Answer: Here's my interpretation of the rules:

There must be at least two timeouts taken in each period.  These timeouts will be longer than any later timeouts in the period (by an amount that depends on television coverage).
One of these two timeouts must be prior to 6:59 or one will be forced.
Both of these timeouts must be prior to 2:59 or one will be forced.

In the question's scenario, if both teams have taken a timeout in the first 5 minutes of the quarter, they will together complete the mandatory timeouts.  Television has been able to run the long ad packages and no further must be taken in that period.  So no timeout is forced and no team is charged.
If there is only one timeout prior to 2:59 (whether forced by the official or otherwise), then the team that has not taken one yet in the period will be charged with a timeout.
As an example, lets take a look at the Oct 31, 2017 Pistons - Lakers game.  In the second quarter, three timeouts were taken in the first four minutes of the quarter.  No other timeouts are shown for the rest of the quarter.
(stats.nba.com is not perfect, and I've found some data errors there before, so it would be nice if someone knows of another site where I could confirm the timeout information).
Answer: The way I'm reading this rule based on its text is as follows:

If no subsequent timeouts are taken prior to 2:59, it shall be
  mandatory for the Official Scorer to take it and charge it to the team
  not previously charged.

So if Team A takes a timeout at 9:45 and Team B takes a timeout at 7:20, then team A should be charged for the timeout at next deadball of 2:59. Because Team B was the team that was "previously charged" with a timeout. And Team A was the team that was "not previously charged" with a timeout.
I'm answering this question based solely off of how the text is written in this quotation.

NBA mandatory timeout rules


Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in you

Question:   $wordsAry = explode(" ", $search);
$wordsCount = count($wordsAry);
$queryCondition = " WHERE ";
for($i=0;$i<$wordsCount;$i++) {
    $queryCondition .= "`location` LIKE '%$wordsAry[$i]%'";
    if($i!=$wordsCount-1) {
        $queryCondition .= " OR ";
    }
}
echo $queryCondition;

$sql1 = "SELECT * FROM `shelves_instruments`
:szukaj
ORDER BY location ASC";
$licz_ilosc = $connect_db -> prepare($sql1);
$licz_ilosc -> bindValue(':szukaj', $queryCondition, PDO::PARAM_STR);
$licz_ilosc -> execute();
$ilosc_stron = $licz_ilosc->rowCount();

WHERE location LIKE '%walida%'

Fatal error: Uncaught PDOException:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near '' WHERE
location LIKE '%walida%'' ORDER BY location ASC' at line 2 in

What could be wrong?
Answer: Prepared statements aren't a fancy way of substituting text. You can't send an entire WHERE clause as a single parameter.
You need to create a WHERE clause like this:
$where = "WHERE `location` like :term1 OR `location` like :term2";

Then create your terms such that
     $param1 = '%'.$firstTerm.'%'  ;
     $param2 = '%'.$secondTerm.'%'  ;

Then bind your terms to your prepared statement
$query = "SELECT * FROM `shelves_instruments` ".$where." ORDER BY location ASC"
$licz_ilosc = $connect_db -> prepare($query);
$licz_ilosc->execute([
    "term1"=>$param1,
    "term2"=>$param2
]);

Comment: Outstanding answer! You figured out what the questioner was trying to do, and gave him (and us all) the conceptual framework to get it right.


When, if ever, does $(I + H)/H \not\cong I/H$? (Equivalently, when $I/(H\cap I) \not\cong I/H$?)

Question:
The quotient $G /H$ of two abelian groups, $H \subseteq G$, is defined as the set of all cosets of $H$: $$G/H := \{ g+H: g \in G \} \,. $$
Question: How does this definition depend on the fact that $H \subseteq G$? It seems like it only depends on addition of elements of $G$ and elements of $H$ being defined.
More specifically, let's say we have another subgroup of $G$, call it $I$, and possibly $H \not\subseteq I$.
1. Nevertheless, addition of elements of $H$ and $I$ is well-defined, so why is the set $$"I/H" := \{ g+H: g \in I \} $$ not well-defined as a group?
2. If it is well-defined as a group, why is not equal (isomorphic) to $(I+H)/H$ in general?

Attempt: The fact that all groups are abelian simplifies things inasmuch as we are guaranteed that all subgroups are normal subgroups. But we still need to check in this case whether addition in $"I/H"$ is well-defined, since possibly $H \not\subseteq I$.
So let's say that $x_1, x_2 \in I$ are such that $x_1 + H = x_2 +H$, and $y_1, y_2 \in I$ are such that $y_1 +H = y_2 + H$. Then $(x_1 +H) + (y_1 +H) = (x_2 +H) + (y_2 +H)$ if and only if $$(x_1 + y_1) + H = (x_2 +y _2) + H \iff (x_1 + y_1) - (x_2 + y_2) \in H \,.$$ But $(x_1 + y_1) - (x_2 + y_2) = (x_1 - x_2) + (y_1 - y_2)$. And $(x_1 - x_2) \in H$ since $x_1 + H = x_2 + H$, and also $(y_1 - y_2) \in H$ since $y_1 +H = y_2 +H$, and since $H$ is a group, $(x_1 - x_2), (y_1 - y_2) \in H \implies (x_1 +y_1) - (x_2 + y_2) = (x_1 - x_2) + (y_1 - y_2) \in H$.
In other words, addition in $"I /H"$ does seem well-defined. Also, $"I/H"$ is closed under inverses, because $I$ is. And since $"I/H"$ is a subset of $G/H$ closed under addition and forming inverses, it should be a subgroup of $G/H$. Therefore, at no point does the assumption $H \subseteq I$ seem necessary.
Motivation: I started thinking about this when trying to show that the quotient $R/I$ of a graded ring $R$ by a homogeneous ideal $I$ is again a graded ring, because the first thing I wrote down for the possible grading of $R/I$ was $\oplus_{d \ge 0} R_d/I$, before realizing that, in general, $I \not\subseteq R_d$. This led me to try $\oplus_{d \ge 0} (R_d +I)/I$, which worked.
But now I think I may have been led to the right answer for the wrong reason, since I can't justify my original claim that $I \not\subseteq R_d$ implies that $R_d /I$ is not well-defined.
Note: This question is related, but is even more general, since it does not restrict to abelian groups. However, neither of the two answers to that question (one deleted) explain why the subset condition is necessary.
Comment: Given $G$ and $H$ you have a surjective map from $G$ to $G/H$ and what you define is simply the image of $I$ under this map, which is a subgroup of $G/H$ and indeed isomorphic to $(I+H)/H$.
Comment: They are not only isomorphic they are equal.
Comment: In short, whenever $H \subseteq I$, since $H+I = I$, then $(I+H)/H = I/H$, and whenever $H \not\subseteq I$, the conventional definition of $I/H$ is not well-defined/does not exist, and then the definition of $I/H$ I give above (the image of the surjection you mention) is equal to $(I +H)/H$ (which always makes sense in the conventional sense, since clearly $H \subseteq I+H$), so we _always_ have that $(I+H)/H = I/H$. I was incorrectly confusing this with the question of when $(I + H)/H \cong I$, which occurs when $I+H = I \oplus H$.
Comment: @TobiasKildetoft How do I show that $I/H$ and $(I+H)/H$ are isomorphic? I wrote out the definitions of both once and got that they were the same, but I thought I was making a mistake -- was I not?
Comment: @DerekHolt Is that still true even when $H \not\subseteq I$? I know this is a really dumb/stupid/basic question, but that's why it's all the more important to me that I am sure I have the right understanding (because if I'm wrong about this, then I'll be wrong about everything that depends on it, which is a lot, because it is so basic)
Answer: I've addressed the more general noncommutative version of your question in this answer, so here I'll address your motivation question directly:
The issue with "$R_d/I$", given that $I$ is not a subgroup of $R_d$, isn't one of well-definedness. It's just nonstandard terminology. The set of cosets of $I$ by elements of $R_d$ is, in fact, equal, both as a set and as a group, to $(R_d+I)/I$.
Moreover, $(R_d+I)/I$ is isomorphic to $R_d/(I \cap R_d)$, so that gives two ways to describe the group using standard notation. The fact that "$R_d/I$" is nonstandard is simply an emphasis of the fact that every "quotient" of $R_d$ can come from a normal subgroup of $R_d$.
Comment: Oh... yes I think I get it now -- since $"R_d/I"$ can be expressed by $R_d/(I \cap R_d)$, there is no need to confuse things by introducing a new concept of quotient groups for groups which are not subgroups. Thank you for explaining and confirming this for me.


Is there a particular word, name, classification or designation that differentiates "Slavic Sung" Vibrato?

Question: I introduce this question with something I'll amateurishly call "Slavic sung vibrato", because I don't know of a better term. It's a sort of recognizable extendeded and pronounced vibrato that proliferates in traditional and popular sung music of the region.
Although more-typical vibrato also occurs often in the music of that region, this sounds different to me, and it also seems different from vibratos and glissandi in traditional Perso-Arabic and Carnatic music.
(If you want more clarification, youtube: 1
2)
It is stylistic, but like other 'styles' it often seems to work in step with harmonic and melodic considerations. After listening to much music from the area over the past year and a half, it seems more subtle now but still powerful and affecting. I am guessing something of this spirit is in the 'terrible Soviet singing' Xenakis critiques at the end of this [informal interview]
(http://ada.evergreen.edu/~arunc/texts/music/xenakisFeldman.pdf) (I like Xenakis's music very much, by the way). I began to wonder, though, how this style fit within traditional Western music instrumentation and notation. In the same way the Georgian neutral third may have a harmonic function within 31-EDO or 11-limit (or maybe even 7-limit) JI - I wondered if extended vibratos might actually have some functional place in modern Western art music as more than just a simple ornamentation one day.
Sorry for the ramblings; my question is actually whether there was ever much of a known codification or notation of Slavic styles, beyond just the recording and arranging of individual folk tunes, or the writing and reviewing of new works in a 'nationalistic' style.
Answer: You need to back up a bit, to see the wood and not the trees, you can't break it down like that, you can't do one without the other nor t'other without the one, so because it's not logical to talk of it distinctly, there's no term for it. It all comes from beat, where interference patterns make new tones in the harmonics.
Xenakis is talking about one of the oldest known musical practices: the caves where cave paintings are found also usually have excellent acoustics for overtone enharmonic singing. Most caves either echo wildly or not at all: it's therefore thought this is not coincidental.
The way to access this in voice is to listen carefully for the harmonics of a group of singers supposedly aiming for the same note: normally someone'll be out and you'll hear the beat come in at about 10 cents off pitch. Repeat on your own in the bathroom using the echo of your own voice to work with.
The physics of it is wave interference, where two waves of slightly different wavelength meet, the wave heights add, crests and dips becoming bigger where they meet their same, and zeroing out where they meet the opposite. The result is another hypertone forming, a harmonic. And that can sound like a vibrato, but a vibrato it isn't.
Answer: I have never heard of special notation for styles of Slavic music. I do not believe a notation specific to it in regards to stylistic differences exist.


How to find sum for each category in an array?

Question: I have an array that contains multiple items. This is a Realm array. It contains data in the following structure:
Results<Entry> <0x7ff04840e1a0> (
    [0] Entry {
        name = Salary;
        amount = 40000;
        date = 2020-03-18 16:00:00 +0000;
        category = Main Incomes;
        entryType = Income;
    },
    [1] Entry {
        name = Diff;
        amount = -500;
        date = 2020-04-18 16:00:00 +0000;
        category = Misc;
        entryType = Expense;
    },
    [2] Entry {
        name = Cat Food;
        amount = -399;
        date = 2020-04-18 16:00:00 +0000;
        category = Animals;
        entryType = Expense;
    },
    [3] Entry {
        name = Fish Food;
        amount = -599;
        date = 2020-04-18 16:00:00 +0000;
        category = Animals;
        entryType = Expense;
    }
)

What I am trying to achieve is to make another array that will 'pivot' totals for each category. So it can work as a pivot table in Excel.
The desired output is an array that will contain totals for each category:
[0] X-Array {
        category = Main Incomes;
        amount = XXXX;
    },
    [1] X-Array {
        category = Animals;
        amount = XXXX;

And so on...

I'm fairly new to this fancy one-liners like .map and .reduce and other Swift's array management sugar, so would very much appreciate the advice!
Thank you!
P.S. I plan to do the same thing with total expenses and incomes in order to calculate closing balance.
Comment: A quick look at the documentation shows that `Results` has some aggregation functions, why not use them? [Realm Aggregate Operations](https://realm.io/docs/swift/latest/api/Classes/Results.html#/Aggregate%20Operations)
Comment: That's not an array, it's a Realm results object and while they are similar there are some distinct differences. Also, the question is a but unclear - Do you want the total of each entry type? e.g. Income = 4000, Expense = 500+399+599? Or are you looking for something else? Lastly, this isn't a code writing service - please show the code you've attempted and indicate what your stuck on. Please review [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Answer: I think use Dictionary is easier to do categorize and later you can convert it to array or anything you want
var dict:[String:Double] = [:]

list.forEach {
    if let current = dict[$0.category]{
        dict[$0.category] = current + $0.amount
    }else{
        dict[$0.category] = $0.amount
    }
}

print(dict)

Answer: I think the question is asking how to get the sum for each category, Income, Expense etc. If so, here's how it's done using the .sum function on the results.
let totalIncome = realm.objects(AccountClass.self)
                       .filter("entryType == 'Income'")
                       .sum(ofProperty: "amount") as Int
let totalExpense = realm.objects(AccountClass.self)
                        .filter("entryType == 'Expense'")
                        .sum(ofProperty: "amount") as Int

print("Total Income: \(totalIncome)")
print("Total Expense: \(totalExpense)")

and the output for your example data is
Total Income: 40000
Total Expense: 1498

If you want a pivot table, you could just add the amounts to an array - if you need the labels, use a tuple to store them in an array like this
let i = ("Income", totalIncome)
let e = ("Expense", totalExpense)

let tupleArray = [i, e]

for account in tupleArray {
   print(account.0, account.1)
}

Keep in mind that a Results object is not an array but has some array-like functions. Results are live updating so as the underlying data in Realm changes, the Results change along with it.


Probability of getting at least 2 numbers smaller of the average of n numbers if you pick 3 of them

Question: I have got the numbers "   13,  15,  12,  9,  6,  3,  5,  12,  17,  10,  12,  9,  6,  8,  10,  8,  10" and I have to find ,if I randomly pick three of these
numbers, what is the probability that at least two of them are smaller than the
average of all seventeen?
The average is 9.7 = 10. I have 8 numbers smaller than 10 . The probability of getting at least 2 smaller than the average is P(of getting 2 smaller and 1 greater) + P(of getting 3 smaller and no greater) so is (8/17 * 7/16 *9/15 )+
(8/17 * 7/17 * 6/17 ) .
I am not sure if that is the correct way . Can anyone tell me if am right?
Comment: Note that $9.7=10$ is false.  It does not change the result as there are no numbers smaller than $10$ that are not also smaller than $9.7$, but it would if you were considering smaller than or equal to.
Answer: Pretty much!  It's just that you can pick those 2 smaller + 1 not smaller in 3 different ways, because you can pick that not smaller one as your first, second, or third. So, you get:
3* (8/17 * 7/16 *9/15 )+ (8/17 * 7/16 * 6/15 )
(also note you had 17 in the denominator for each of the terms in the second expression, which wasn't right, but that was just a typo on your part since you had it right in the first term)
Comment: @PinelopiConstantinou  Please check my answer again ... you need to add the factor of 3 for the first term!
Comment: yeap i checked it , thank you again!!
Comment: @PinelopiConstantinou You're welcome! ... how'd you make out on that matches puzzle?
Comment: nothing yet ..I decided to leave it at the end because its the difficult one. I can not deal with such kind of problems :p
Comment: done! :) if you have any other hints or why not the solution of the problem with the matches let me know! :)
Comment: @PinelopiConstantinou I just posted a start ...


$i\sin(x)$ phase shift

Question: By Euler's formula, I can express $i$ in the following way:
$$ i  = \cos(\pi/2) + i \sin(\pi/2) = \exp(i \pi/2) $$
I wonder if it is legitimate to write
$$\begin{align}i \sin x &= \exp(i\pi/2) \cdot \frac{\exp(ix)-\exp(-ix)}{2i} \\
 &= \frac{\exp(ix)\exp(i\pi/2)-\exp(-ix)\exp(i\pi/2)}{2i} \\
 &= \frac{\exp(i(x+\pi/2))-\exp(-i(x+\pi/2))}{2i} \\
 &= \sin(x+\pi/2) \end{align}$$
I don't feel like this is right, because it would imply a lot of weird things. So where is my mistake? note: I'm really missing sleep, so please be kind with me.
Answer: In your sleep-deprived delirium, you have said $$ e^{-ix}e^{i\pi/2} = e^{-i(x+\pi/2)}$$ where it is actually $$ e^{-ix}e^{i\pi/2} = e^{-i(x-\pi/2)}.$$
It would certainly be strange if $i\sin(x) = \sin(x+\pi/2)$ since one is pure imaginary and the other real for real $x.$
Comment: Thank you, I shouldn't even be trying. I will drown in self-pity till I fall asleep.

$i\sin(x)$ phase shift


How can I show that $\frac{\exp\left({-\frac{tx}{1-t}}\right)}{1-t}$ is the generating function for the Laguerre polynomials

Question: How do I show that
$$\frac{\exp\left({-\frac{tx}{1-t}}\right)}{1-t}  = \sum_{n=0}^\infty \left( \sum_{k=0}^n \frac{(-1)^k n! x^k }{(k!)^2 (n-k)!} \right ) \cdot  \frac{t^n}{n!} $$
So far, I tried (assuming $|t|<1$)
$$\frac{\exp\left({-\frac{tx}{1-t}}\right)}{1-t}  = \exp \left( - x \sum_{n=0}^\infty t^{n+1} \right )\cdot \sum_{n=0}^\infty t^n  = \prod_{m=0}^\infty  \exp\left( -xt^{m+1} \right )\cdot \sum_{n=0}^\infty t^n$$
How to collect $t^n$ from here on??
ADDED:: How to show that the above expression is the generating function for Laguerre polynomial?
Comment: `Laguerre`. $ $
Comment: yes ... sorry for misnomer :(
Answer: Your formula has an erroneous $n!$ in the denominator.
Using the identity
$$\frac{1}{(1-t)^{n+1}} = \frac{1}{n!}\left(\frac{d}{dt}\right)^{n} \frac{1}{1-t}$$
for $n \geqslant 0$, we compute
$$\begin{align}
\frac{\exp \left(\frac{-tx}{1-t}\right)}{1-t} &= \sum_{k=0}^\infty \frac{(-tx)^k}{k!}\frac{1}{(1-t)^{k+1}}\\
&= \sum_{k=0}^\infty \frac{(-tx)^k}{(k!)^2} \left(\frac{d}{dt}\right)^k\sum_{n=0}^\infty t^n\\
&= \sum_{k=0}^\infty \frac{(-tx)^k}{(k!)^2} \sum_{n=k}^\infty \frac{n!}{(n-k)!}t^{n-k}\\
&= \sum_{k=0}^\infty \sum_{n=k}^\infty \frac{(-1)^k n! x^k}{(k!)^2(n-k)!}t^n\\
&= \sum_{n=0}^\infty \left(\sum_{k=0}^n \frac{(-1)^k n! x^k}{(k!)^2(n-k)!}\right)t^n
\end{align}$$
changing the order of summation, which is legitimate since the double series converges absolutely (for $\lvert t\rvert < 1$).
Comment: I guess the third identity in the second formula needs more details? It is a infinite sum, the differentiation may not be computed term by term.


Como consigo adicionar um filtro para listar apenas as países acima de x casos?

Question: confirmed <- read.csv('time_series_covid_19_confirmed.csv',
                      stringsAsFactors = FALSE)

library(dplyr)

covid <- confirmed %>% select(Country.Region, X3.29.20) %>%
  group_by(Country.Region) %>%
  summarise(sum_X3.29.20 = sum(X3.29.20))

Answer: Só adicionar um filter ao final da função:
library(dplyr)

covid <- confirmed %>% select(Country.Region, X3.29.20) %>%
  group_by(Country.Region) %>%
  summarise(sum_X3.29.20 = sum(X3.29.20)) %>%
  filter(sum_X3.29.20 > 500)

Assim, todos os países com mas de 500 casos de covid-19 serão considerados.


JavaScript - What is the better way to skip an input when necessary for a code editor?

Question: I am programming a web app like an online code editor. One of the basic functions is that when users input, say, a left parenthesis symbol "(", the editor will automatically add the right one ")" for you.
So an immediate idea is that I create an object for that, defined as follows:
var pairCharData = {
    "{": "}",
    "(": ")",
    "\"":"\"",
    "'":"'"
};

That's not the end. I want the editor to be smarter so it should skip the input when necessary. For example, when I input in the editor a right parenthesis symbol immediately after I just added a left one (at that time, the right parenthesis already existed!), the editor is expected to only move the cursor but without showing one more duplicated one.
So I want to check if a next user-input character is one expected.
I created another map as follows:
var pairCharDataReverse = {
    "}": "{",
    ")": "(",
    "\"":"\"",
    "'":"'"
};

This is, you know, just the reverse version of the first map. My idea is to keep track of the input key from users. Here is my implementation
if(key in pairCharDataReverse) {
var leftPair = pairCharDataReverse[key];
if(this.lastKey === leftPair) {
    this.selectionStart = this.selectionEnd = start +1;
    e.preventDefault();
}

As I add more pairs of characters, I have to modify both maps, which is not I want.
I guess there must be another better way to store the data with less pain. Maybe with another data structure or there is just a trick that I really wonder.
Comment: Do you just want to be able to do a reverse lookup on your first map? Something [like this](http://stackoverflow.com/questions/10974493/javascript-quickly-lookup-value-in-object-like-we-can-with-properties)?
Comment: @LarryTurtis It worked. Thank you, although I wondered if there is a better way.
Answer: You can use a <select> element with <option> elements corresponding the characters the user selects to wrap text within. User selects text, user selects <option>, javascript performs action which wraps selected text in selected <option> .value.

var textarea = document.querySelector("textarea");
var select = document.querySelector("select");
var text;
select.onchange = function(e) {
  if (text) {
    var option = this.value.split("");
    textarea.value = textarea.value.slice(0, text[0])
                     + option[0]
                     + textarea.value.slice(text[0], text[1])
                     + option[1]
                     + textarea.value.slice(text[1]);
  }
  this.value = text = null;
}
textarea.onselect = function(e) {
  text = [this.selectionStart, this.selectionEnd]
}
<select>
  <option></option>
  <option value="()">()</option>
  <option value="[]">[]</option>
  </select>

<textarea></textarea>
Comment: Instead of attempting to programmatically insert characters as user types, allow user to select the characters they choose to wrap selected text within.
Comment: I didn't get your point. Can you add more details and why I need a selection elem?


asp.net client side validator on div with pop up

Question: I have the following snippet from a project I recently hopped on to.

The above snippet is a popup form with a rich text editor on it. Once the save button is pressed on the popup form, the text is then placed on the form in the RTE "placeholder"
I am trying to include the div as part of my validation summary with other controls on the form that use asp.net Validators.
Any tips on how to accomplish this?
Thanks
TR
Answer: DIV's don't naturally support validation.  What you could do to work around that is use a CustomValidator, set the ClientValidationFunction to a function that checks the inner contents for any text.  On the server, using ServerValidate, you can check that the DIV has some inner content that isn't blank, as long as the contents are posted back successfully.
Comment: Thanks @Brian-Mains

`function custdivDescEnClientValidate(sender, args) {
var text = document.getElementById("divDescEn").innerHTML;
if (text== '')
{
args.IsValid = false;
   }`
This then plugged in nicely to the rest of the client side validation I had in place.


Creating a new column equals the logarithm of another column in R

Question: As titled.I tried to create a new column called level_log by taking the logarithm of an existing column named "level"
I tried:
chol$level_log <-chol$log(level)

But it shows:
Warning: Unknown or uninitialised column: `log`.
Error: attempt to apply non-function

What's the problem here?
Thanks in advance
Comment: chol$level_log <- log(chol$level)
Answer: I believe you need to wrap your entire chol$level in a log rather than only the column, i.e. change
chol$level_log <-chol$log(level)
to
chol$level_log <-log(chol$level)
This is happening because R doesn't know what level is on its own. What if you had multiple data loaded and several of them had a column called level? In order to avoid this confusion it requires that you specify the exact column you mean, including where that column comes from.


Obter lista de arquivos alterados no diretório de trabalho (working directory)

Question: Quando se executa o comando git diff no terminal é aberta uma janela que apresenta o conteúdo dos arquivos com suas alterações. A partir daí posso saber quais arquivos foram alterados. O problema desse método é que para saber quais ou quantos arquivos foram alterados preciso ir até o fim do último arquivo apresentado.
Preciso de um recurso mais simples. Um recurso que mostre somente o nome dos arquivos alterados.
Qual o comando usado para listar os arquivos que foram alterados, mas não foram comitados?
Answer: Eu tenho a impressão que você quer apenas os arquivos modificados. Sem os arquivos "untracked" ou "staged". Nesse caso utilize
git ls-files --modified

ou
git ls-files -m

obs: os arquivos no índice não foram comitados ainda. Mas não ficou claro se você quer listar esses arquivos. Como o seu exemplo é a saída do git diff estou supondo que não.
Answer: O comando para ver os arquivos alterados que não foram comitados é o git status, conforme exemplo abaixo:

No link abaixo, você encontra maiores informações sobre gravar alterações no repositório e verificar status dos seus arquivos:
Git Essencial - Gravando Alterações no Repositório
Answer: O comando para mostrar os estado do repositório listando todos os arquivos alterados e novos arquivos (untracked files) é:
git status
Answer: Para saber os arquivos da branch que ainda não estão na master, você pode utilizar este comando:
git diff --name-only master

Isto é útil para saber quais arquivos devem ir para a produção, por exemplo.


Degrees of freedom for Kuiper's Test of uniformity

Question: How do you determine the degrees of freedom for Kuiper's Test of Uniformity for circular data?
I have been using various R packages for circular data (circular, CircStats) and I can't seem to find out how to get the degrees of freedom for the Kuiper's test.
Answer: As you can check from Wikipedia and from the help pages of the packages that you mention, Kuiper's test does not have a degree of freedom. It proceeds like the Kolmogorov-Smirnov test, which also does not have a degree of freedom.


Convert text values to int type values in google sheets from another sheet and sum it up in a sequence

Question: Need some help on converting string text to int values.
Here is what I tried:
<code>=IF(Survey!J2,"Myself",1,"My team",5,"Stakeholders",10,"Project",15,"")+Survey!T2,"Myself",1,"My team",5,"Stakeholders",10,"Project",15)</code>
Need it to look for string value in sheet2 named Survey! and add this value in sheet 1 name calculator in row K2.
Expected output would be 2, if user selected myself both times. The lookup value is called Impact in sheet two row 1, is there a way I could get the code to look for "Impact" in Sheet 2 and convert the string text to numbers, depending on what the user selected and then perform a sum for all of the impact columns.
Answer: try:
<code>=IFNA(VLOOKUP(Survey!J2, {"Myself",1;"My team",5;"Stakeholders",10;"Project",15}, 2, 0))+
 IFNA(VLOOKUP(Survey!T2, {"Myself",1;"My team",5;"Stakeholders",10;"Project",15}, 2, 0))
</code>


Is there an explicit construction of an embedding of Severi Brauer varieties $B(A)\times_k B(A')\hookrightarrow B(A\otimes_k A')$?

Question: This question arose from a note on Galois descent. If $A$ is a central simple algebra over a field $k$, let $B(A)$ be its Severi Brauer variety. There is always at least a morphism $$B(A)\times_k B(A')\to B(A\otimes_k A').$$
I am wondering, is there an explicit description/construction of a closed embedding $B(A)\times_k B(A')\hookrightarrow B(A\otimes_k A')$?
Answer: Sure. If I'm understanding the question correctly, this is just a twisted form of the standard Segre embedding, defined by taking a pair of right ideals $I$, $J$, to their tensor product $I \otimes J$.


How to check if a user is logged in inside a view

Question: I can easily check if a user is logged in in most templates by simply using a twig variable, or making a custom one myself. My issue is that I would like to be able to check if a user is logged in inside a custom text field in a view.
I used
{% if logged_in %}
     Test
{% endif %}

But it didn't seem to work. Also
{{ dump(logged_in) }}

came up null. Also I looked in the available options for context filters and relationships but nothing seemed to have anything to do with the current user. Only authors of the content.
Is there a way to know if the user is logged in from a view?
I suspect that it might be possible with some preprocess hook for views but if that can be avoided by using an option in views that would be preferable.
For clarification this is a view that displays a list of articles. Each with an image, title, and a snippet of body text. The article node has a field deciding whether a user login is required. If the user login is required then the body text is replaced for anyone that isn't logged in.
UPDATE: I attempted adding the variable in a preprocess hook but that didn't seem to do anything either.
function mymodule_preprocess_views_view_field(&$variables){
    $variables['logged_in'] = (\Drupal::currentUser()->isAnonymous())?false:true;
}

But {{ dump(logged_in) }} still came up null.
Comment: What about adding your custom text field to a views attachment and limiting the permissions on the attachment instead of mixing permissions on your main view?
Comment: My view is a list of articles that show an image and part of the body. Each article may or may not require a user to be logged in. If the individual article requires a login the body text is replaced. It's not an all or nothing thing. Unless a views attachment can handle that situation.
Comment: Views attachment won't handle that. I'd go back and debug the logged_in check in your twig file or put it in a preprocess. Twig would be my vote.
Comment: lynbermt do you know of a good preprocess function to put that in? I made an attempt above but still had no luck
Answer: I managed to accomplish this task by creating my own custom view field plugin
in mymodule.views.inc I used
function mymodule_views_data() {

  $data['views']['table']['group'] = t('Current User');
  $data['views']['table']['join'] = [
    // #global is a special flag which allows a table to appear all the time.
    '#global' => [],
  ];

  $data['views']['logged_in'] = [
    'title' => t('Logged In'),
    'help' => t('Check if user is logged in'),
    'field' => [
      'id' => 'logged_in',
    ],
  ];

  return $data;
}

and then in /mymodule/src/Plugins/views/field/LoggedIn.php I had
<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("logged_in")
 */
class LoggedIn extends FieldPluginBase {

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);
        $this->field_alias = 'logged_in';
    }

    /**
     * {@inheritdoc}
     */
    public function usesGroupBy() {
        return FALSE;
    }

    /**
     * {@inheritdoc}
     */
    public function query() {
        // Do nothing -- to override the parent query.
    }

    /**
     * {@inheritdoc}
     */
    protected function defineOptions() {
        $options = parent::defineOptions();

        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {

        $logged_in = \Drupal\mymodule\Modules\CurrentUser::isLoggedIn();
        return $logged_in;
    }

}

Some of the contents of LoggedIn.php might not be necessary (not 100% sure) I was using another module as an example.
Answer: In D7 views supported distinctions between 2 views based on the Permissions/Roles settings per View.
I'm not sure this functionality exists in D8 of using 1 display over another depending on Permission settings of the View.
In D7 and using Display Suite you can set a view_mode different for the 1st or Nth view row returned by Views. It was a submodule of Display Suite. Using something like DS in D8 should to allow you to modify the View Mode of rows in the view result set depending on the rows' special flag value.
Comment: I'm researching Display Suite but I'm not seeing how DS in D8 could be used to accomplish this task.
Answer: I see you've already achieved what you needed but I think the easiest way is to copy over the field's tpl template from the views folder, rename it to the name provided under "Information" in the view's settings put it in your theme's folder, and add
global $user; if($user->uid) {
The other option is a bit of views trickery using the "No results behaviour" option in a field's settings. You would have two views with their visibility controlled by blocks / panels / context etc., one for logged in users with no changes, and one for anonymous users where you exclude the body field from display, add the Boolean field for being logged in, click "Treat 0 as empty", and use the replacement pattern to display the body field if empty.
Comment: This is Drupal 8 not 7. I only have twig templates not tpl's
Answer: I posted a module for this (link below) based on Matt's answer, but with a change in the way the render function is done:
https://github.com/andileco/logged_in


Como acessar variáveis de outra classe de objetos por array?

Question: Tenho 2 Classes,sendo elas : Percurso e Custos.
Percurso :
public double getKmPercorrida() {
    return kmPercorrida;
}
public void setKmPercorrida(double kmPercorrida) {
    this.kmPercorrida = kmPercorrida;
}
public double getValorCombustivel() {
    return valorCombustivel;
}
public void setValorCombustivel(double valorCombustivel) {
    this.valorCombustivel = valorCombustivel;
}
public double getValorPedagio() {
    return valorPedagio;
}
public void setValorPedagio(double valorPedagio) {
    this.valorPedagio = valorPedagio;
}

public void cadastrarPercurso() {
    setKmPercorrida(Double.parseDouble(JOptionPane.showInputDialog(null,"Digite os km percorridos : ","Km percorridos",JOptionPane.QUESTION_MESSAGE)));
    setValorCombustivel(Double.parseDouble(JOptionPane.showInputDialog(null,"Digite o valor do combustivel : ","Combustivel",JOptionPane.QUESTION_MESSAGE)));
    setValorPedagio(Double.parseDouble(JOptionPane.showInputDialog(null,"Digite o valor do pedágio : ","Pedágio",JOptionPane.QUESTION_MESSAGE)));
}

public void listarPercurso() {
    JOptionPane.showMessageDialog(null,"Km percorridos : " + getKmPercorrida() +
            "Valor do combustivel : "  + getValorCombustivel() +
            "Valor do pedágio : " + getValorPedagio());
}

Custos :
private double totalPercurso;

public double getTotalPercurso() {
    return totalPercurso;
}

public void setTotalPercurso(double totalPercurso) {
    this.totalPercurso = totalPercurso;
}

public String calcularViagem(Percurso [] p) {

    return "";

}

Na classe Custos no método calcularViagem eu tenho que receber um array de objetos do tipo Percurso,e calcular o valor da viagem,sendo então :
totalPercurso = (kmPercorrida * valorCombustivel) + valorPedagio

A variável totalPercurso vai receber as variáveis do objeto Percurso e calcular todas elas através do método em que ele está.
Mas como posso fazer isto ?
Comment: Não ficou claro. Quando se trata de programação orientada a objetos, não se fala em "variáveis da classe" e sim "variáveis do objeto". Mas não estou vendo nenhum objeto do tipo Percurso sendo usado na sua classe "Custos".
Comment: Novamente, não faz sentido falar em "total da classe". A classe é só um molde pra criar objetos. Além disso, o que quer dizer com "total"? Total de quê?
Comment: Estou recebendo ele como um array de objetos ali no método calcularViagem,e com isto,tenho que calcular o total do percurso da classe Percurso.
Comment: Total do valor junto com as outras variáveis.Eu tenho que somar todas elas pela variável totalPercurso,e isto através pelo parâmetro que estou passando que é o objeto Percurso.
Answer: Considerando que este total que você deseja calcular é o total de todos os atributos, o cálculo (já que não está claro na pergunta) ficaria assim:
public String calcularViagem(Percurso[] p) {
  totalPercurso = 0;

  for (int indice = 0; indice < p.length; indice++) {
    Percurso percurso = p[indice];

    totalPercurso = totalPercurso + (percurso.getKmPercorrida() * percurso.getValorCombustivel()) + percurso.getValorPedagio();
  }

  return String.valueOf(totalPercurso);
}

E o método para testar a solução:
public static void main(String[] args) {
  Percurso percurso1 = new Percurso();
  percurso1.cadastrarPercurso();
  percurso1.listarPercurso();

  Percurso percurso2 = new Percurso();
  percurso2.cadastrarPercurso();
  percurso2.listarPercurso();

  Percurso[] percursos = new Percurso[]{percurso1, percurso2};
  Custos custos = new Custos();

  System.out.println(custos.calcularViagem(percursos));
}

Agora algumas observações:

O retorno do seu método está como String quando na realidade é um cálculo. Ele deveria ser igual ao tipo das suas variáveis quantitativas, que no caso é double;
Você está misturando elementos de apresentação com elementos de negócio, no caso utilizando JOptionPane dentro da suas classes de negócio/modelo. Veja mais como poderia organizar melhor o seu projeto na resposta da pergunta Como funciona a estrutura MVC para aplicações Desktop? que apesar de ser em C++ pode ser aplicada a praticamente qualquer tipo de projeto.
Comment: @Mondial Edite sua pergunta descrevendo melhor o que é esse cálculo. Com exemplos, por favor, porque não estamos entendendo.
Comment: O total seria a soma de todas as variáveis do objeto Percurso,e isto eu teria que fazer pelo parâmetro que estou recebendo.O seu exemplo me ajudou,mas eu preciso é calcular todas as variáveis do objeto e não só uma.E o modelo MVC eu já entendo sim,mas como é uma aplicação que estou fazendo simplesmente em casa e não no trabalho,eu não uso ele então.
Comment: @PabloAlmeida Tudo bem,me desculpe se não deixei muito claro a pergunta,sou novo aqui e ainda não sei muito bem como postar corretamente.
Comment: @Mondial alterado para corresponder com seu enunciado
Comment: @Sorack Obrigado,testei sua resposta e deu certo.
Comment: @Mondial acho que a melhor abordagem é usar um `List` e não um `array`.
Comment: Consegui fazer funcionar certinho com a sua abordagem,muito obrigado.Mas por que seria então melhor usar List e não array ?


is using empty list expensive than doing a null check om a list in java?

Question: I have below code. I am setting list to null at line 2 and further i am checking if list is null.I would like to know if creating an empty list is expensive than checking if list is null or not?
private void check(Product p){
 List<ProductAction> list=null; // line 2
 if(p.hasSubProducts){
     list = // list  of
      ProductAction for sub products
 }
  if(list == null){
     //some logic
  }
}

Comment: Same cost O(1), no difference
Comment: The cost is in the readability of the code. If you would do the same thing for a null list as you would with an empty list, why bother having to handle those cases separately?
Answer: I'm just repeating the concept in the comments.
If you declare the list as null it is a declaration cost which is O(1) because you're just under the table declaring a pointer to NULL address, which is the base memory value.
Otherwise if you make a comparison if(list == null) you're just saying is the address value of list equal to NULL address. Obviously this operation costs O(1), therefore the cost is the same.
Probably in your situation the best way to code in order of readability is:
private void check(Product p){
 List<ProductAction> list; // this is already equal to null
 if(p.hasSubProducts()){
     list = // list  of
      ProductAction for sub products
    // i assume you declare and update the list here
 }
  if(list == null){
     //some logic
  }
}

This because of comments inside the code.


About root distribution of complex polynomial

Question: We have some Laurent polynomial $f(z)$ with powers of $z$ from $a$ to $-b$, $a,b$ be positive integers.
Consider the equation $f(z)-E=0$.
Let $P$ be the set defined by:  $z'\in P$ $\iff$ $\exists E\in \mathbf{C}$ , $z'$ is one of the $b$ smallest roots ordered by magnitude of $f(z)-E=0$.
Prove or disprove: $P$ has a finite diameter.
Notes for clarification:
1.For some fixed $E'$, let the roots of $f(z)-E'=0$ be $|z_1|\leq |z_2|\leq ...$, then $z_1,z_2 ...,z_b$ are in the set P.(Counting or not counting terms with same magnitude as $z_b$ does not affect the result) The full set $P$ would be the union of all these $z$ over all $E'$.
2.e.g. If $f(z)=z+\frac{1}{z}$, P would be the unit circle and its interior.
My numerical checks show that it is always finite, but I haven't figured out a proof.
Answer: Let $f(z)=R(z)+Q(z)/z^b, \deg Q \le b-1, Q(0) \ne 0, \deg R =a$. For $E \ne 0$ the equation $f(z)=E$ is equivalent to $z^b-\frac{z^bR(z)+Q(z)}{E}=0$ since $Q(0)\ne 0$ so $z=0$ is not a root of the latter.
Let $M=\max_{|z|=1}|z^bR(z)+Q(z)|$ then by Rouche for $E>M$ we have that the equation has precisely as many roots as $z^b=0$ inside the unit circle so  $b$ roots have modulus bounded by $1$.
Since for $E \le M$ we can write the equation as $z^bR(z)+Q(z)-Ez^b=\sum a_mz^m=0, m=a+b, a_m \ne 0$ fixed, we see that the highest root is bounded by the positive root of the associated Cauchy polynomial $|a_m|z^m-\sum_{k \le m-1}|a_k|z^k$ which have uniformly bounded roots since the coefficients are uniformly bounded and $a_m$ is fixed, so we are done and the set $P$ is indeed bounded


Views: Show current user-entered filter

Question: I have a view with an exposed form for searching titles/bodies of content. Is there a way I can display "Showing results for: $keywords" with the values that the user enters?
Answer: You can use the PHP text filter in core. It is quick and dirty.
Add a Header of global text area to the view. Then add this PHP code using the PHP code text format:
<code><?php
$query_params = drupal_get_query_parameters();
if (isset($query_params['title'])) {
  print t("Results for @query", array('@query' => $query_params['title']));
}
?>
</code>
Exposed filter and sort queries in views are passed as query parameters in the form of:
<code>?title=test
</code>
In the above code I am just looking at the parameter 'title', but you can adapt that code snippet to suit your needs. Just look at your url to see what query parameters are passed along.

Views: Show current user-entered filter


Integral with the delta function: How to get this limit?

Question: Consider $\Psi_{xx}+(\lambda-u(x))\Psi=0$ and $u(x)=-U_0\delta(x)$, where $U_0$ is a constant and $\delta(x)$ is Dirac's delta function.
Integrating the equation from $-\varepsilon$ to $+\varepsilon$, one gets
$$
[\Psi_x]_{-\varepsilon}^\varepsilon=\int_{-\varepsilon}^\varepsilon (\lambda+U_0\delta(x))\Psi\, dx.
$$
Now it is said that, if $\varepsilon\to 0$, one gets
$$
[\Psi_x]=-U_0\Psi(0),\tag{*}
$$
where $[\cdot]$ denotes the change in $\Psi_x$, provided $\Psi$ is continuous at $x=0$.
Can someone explain to me how we get $(*)$? I do not see it.
In particular, where does the (assumed) continuity of $\Psi$ at $x=0$ come into play?
Comment: Do you know how to evaluate an integral with a dirac delta function in the integrand?
Comment: Two things: (1) if $\Psi$ is continuous on $[-\epsilon, \epsilon]$, then it attains a maximum $M$ on that interval, and the integral on that interval is $\le 2M\epsilon$, but if it isn't continuous, then it's possible $\lim_{x\to 0}\Psi(x)=\infty$ and the integral isn't even defined (2) $\int_{-\epsilon}^{\epsilon}f(x)\delta(x)=f(0)$ if $f$ is continuous at 0; otherwise evaluating that, if possible, requires more advanced analysis.
Comment: Do you suggest $$\int_{-\varepsilon}^{\varepsilon}(\lambda + U_0\delta(x))\Psi\, dx=\int_{-\varepsilon}^{\varepsilon}\lambda\Psi\, dx+\underbrace{\int_{-\varepsilon}^{\varepsilon}U_0\delta(x)\Psi\, dx}_{=U_0\Psi(0)}$$ and the first integral on the right-hand side tends to $0$ as $\varepsilon\to 0$ only if $\Psi$ is continuous in $x=0$?
Comment: Yes, that is correct.
Comment: Suppose $\Psi$ is **not** continuous at $x=0$. Why does the integral then not vanish as $\varepsilon\to 0$?
Comment: Thanks a lot, I got it!
Comment: You're welcome.
Answer: If you take the fourier transform wrt $x$:
$$\mathcal{F}[\varphi(x,t)]\{\omega\}=\int_{-\infty}^\infty \varphi e^{-j\omega x}\,dx=\hat{\varphi}(\omega,t)$$
and assume that:
$$\lim_{x\to\pm\infty}\varphi=\lim_{x\to\pm\infty}\varphi_x=0$$
you arrive at the equation:
$$(\lambda-\omega^2)\hat{\varphi}+U_0\varphi(0,t)=0$$
then you can use the inverse fourier transform and boundary conditions for $\varphi$.


A Function to select a forecast method

Question: I often have more than one time series to fit a model. Thanks to forecast and forecastHybrid packages they make easy to fit a model to a time series. But often I have more than one ts. When the number of ts are sufficiently high it is a lot of work to do it one by one because the method I choose could do good job for some but it may do bad job for the others ts. To choose a model and to avoid  the work I wrote the following code.
It works but I would like to know :
Would I face any problem?
Are there issues that I cannot see? (sure it is slow but except that)
Best
A
    choose_model <-  function(x,end_train,start_test){
  library(forecast)
  library(forecastHybrid)
  library(tidyverse)

  #train data

  x_train <- window(x, end = end_train )

  x_test <- window(x, start = start_test)

  h1=length(x_test)
  #model1

  stlf(x_train,method="arima",s.window= 12, h=h1)-> fc_stlf

  #model2
  auto.arima(x_train, stepwise = FALSE, approximation = FALSE)%>%forecast(h=h1) -> fc_arima

  #model3
  set.seed(12345)#for nnetar model
  nnetar(x_train)%>%forecast(h=h1) -> fc_nnetar

  #model4
  snaive(x_train,h=h1)->fc_snaive

  #model5
  hybridModel(x_train,models = "anst",weights = c("equal"),errorMethod = c("RMSE", "MAE", "MASE"),verbose=FALSE)%>%forecast(h=h1) -> fc_hy

  #model6
  hybridModel(x_train,models = "an",weights = c("equal"),errorMethod = c("RMSE", "MAE", "MASE"),verbose=FALSE)%>%forecast(h=h1) -> fc_hy_2

  #model7

  ets(x_train)%>%forecast(h=h1)->fc_ets

  #model8

  holt(x_train, h=h1)->fc_holt

  #model9

  hw(x_train,seasonal = "additive",  h=h1)->fc_hw_ad

  #model10

  hw(x_train,seasonal = "multiplicative", h=h1)->fc_hw_mul

  #model11

  hw(x_train,seasonal = "additive",damped = TRUE,  h=h1)->fc_hw_ad_dam

  #model12
  hw(x_train,seasonal = "multiplicative",damped = TRUE, h=h1)->fc_hw_mul_dam

  #accuracy

  model1 <- accuracy(fc_stlf$mean,x_test)[2]

  model2 <- accuracy(fc_arima$mean,x_test)[2]

  model3 <- accuracy(fc_nnetar$mean,x_test)[2]

  model4 <- accuracy(fc_snaive$mean,x_test)[2]

  model5 <- accuracy(fc_hy$mean,x_test)[2]

  model6 <- accuracy(fc_hy_2$mean,x_test)[2]

  model7 <- accuracy(fc_ets$mean,x_test)[2]

  model8 <- accuracy(fc_holt$mean,x_test)[2]

  model9 <- accuracy(fc_hw_ad$mean,x_test)[2]

  model10 <- accuracy(fc_hw_mul$mean,x_test)[2]

  model11 <- accuracy(fc_hw_ad_dam$mean,x_test)[2]

  model12 <- accuracy(fc_hw_mul_dam$mean,x_test)[2]

  best_model <- min(c(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12))

  if(best_model==model1){
    print(fc_stlf$model)
  }
  if(best_model==model2){

    print(fc_arima$model)
  }
  if(best_model==model3){

    print(fc_nnetar$model)
  }
  if(best_model==model4){

    print(fc_snaive$model)
  }
  if(best_model==model5){

    print(fc_hy$model)
  }
  if(best_model==model6){

    print(fc_hy_2$model)
  }

  if(best_model==model7){

    print(fc_ets$model)
  }

  if(best_model==model8){

    print(fc_holt$model)
  }

  if(best_model==model9){

    print(fc_hw_ad$model)
  }

  if(best_model==model10){

    print(fc_hw_mul$model)
  }

  if(best_model==model11){

    print(fc_hw_ad_dam$model)
  }

  if(best_model==model12){

    print(fc_hw_mul_dam$model)
  }

}
choose_model_monthly(my_data,7,c(2018,01),c(2018,02))

Edit
Thank you for your answer @Tim and for your comment forecaster, here is my new code. I will be happy if you give me some feedback. Thank you all.
choose_model <- function(x,h,reg,new_reg,end_train,start_test){
  library(forecast)
  library(forecastHybrid)
  library(tidyverse)

  #train data

  x_train <- window(x, end = end_train )

  x_test <- window(x, start = start_test)

  #train and test for regressors

  reg_train <- window(reg, end = end_train )

  reg_test <- window(reg, start = start_test)

  h1=length(x_test)

  #model1

  stlf(x_train , method="arima",s.window= nrow(x_train),xreg = reg_train, newxreg = reg_test, h=h1)-> fc_stlf_xreg

  #model2
  auto.arima(x_train, stepwise = FALSE, approximation = FALSE,xreg=reg_train)%>%forecast(h=h1,xreg=reg_test) -> fc_arima_xreg

  #model3
  set.seed(12345)#for nnetar model
  nnetar(x_train, MaxNWts=nrow(x), xreg=reg_train)%>%forecast(h=h1, xreg=reg_test) -> fc_nnetar_xreg

  #model4
  stlf(x_train , method= "ets",s.window= 12, h=h1)-> fc_stlf_ets

  #Combination

  mod1 <- lm(x_test ~ 0 + fc_stlf_xreg$mean + fc_arima_xreg$mean + fc_nnetar_xreg$mean + fc_stlf_ets$mean)
  mod2 <- lm(x_test/I(sum(coef(mod1))) ~ 0 + fc_stlf_xreg$mean + fc_arima_xreg$mean + fc_nnetar_xreg$mean + fc_stlf_ets$mean)

  #model1

  stlf(x, method="arima",s.window= 12,xreg=reg, newxreg=new_reg, h=h)-> fc_stlf

  #model2
  auto.arima(x, stepwise = FALSE, approximation = FALSE,xreg=reg)%>%forecast(h=h,xreg=new_reg) -> fc_arima

  #model3
  set.seed(12345)#for nnetar model
  nnetar(x, MaxNWts=nrow(x), xreg=reg)%>%forecast(h=h, xreg=new_reg) -> fc_nnetar

  #model4
  stlf(x , method= "ets",s.window= 12, h=h)-> fc_stlf_e

  #Combination

  Combi <- (mod2$coefficients[[1]]*fc_stlf$mean + mod2$coefficients[[2]]*fc_arima$mean +
              mod2$coefficients[[3]]*fc_nnetar$mean + mod2$coefficients[[4]]*fc_stlf_e$mean)

  return(Combi)
}

Comment: Doesn't `auto.arima()` from the `forecast` package already choose the best model automatically for you based on AIC?
Comment: Ok, so long as you are aware that a flat forecast is not a problem in itself, as there is a reason for it - which you have stated yourself - when there is no trend or seasonality, a flat forecast is perfectly adequate.
Answer: Don't choose, aggregate. If you can afford to fit multiple forecasts, then you also can aggregate them. You can take simple arithmetic average, or do something more clever, but on both cases should work well.
The M4 forecasting competition has just ended (see Makridakis, Spiliotis and Assimakopoulos, 2018) and the results show that combinations of forecasts were most common among the best performing solutions. While the winning solution by Slawek Smyl was a hybrid approach that combined exponential smoothing and recurrent neural networks in a single model, the second best solution was by the Montero-Manso, Talagala, Hyndman, and Athanasopoulos that used a weighted combination of standard forecasting methods, where the weights were learned by XGBoost algorithm. Many of other top scoring solutions used some kind of combined forecasts. There was also another solution by the team that included Rob Hyndman that used FFORMS algorithm implemented in their seer package, which was choosing among multiple forecast by using Random Forest (you can here more about both solutions in here), but it was further away in the ranking.
Results of M4 fit many other similar competitions and surveys that show that combinations of forecasts usually perform better then any single forecasting method alone. Same is true about most of the winning Kaggle solutions.
On another hand, if you have multiple series that come from same hierarchy (departments of store etc.), then it could be reasonable to use hierarchical forecast (see slides, book chapter, paper, and corresponding hts package by Rob Hyndman et al), since it should work better then making only the individual forecasts alone.

Makridakis, S., Spiliotis, E., & Assimakopoulos, V. (2018). The M4 Competition: Results, findings, conclusion and way forward. International Journal of Forecasting.
Comment: +1 use simple median or mean to aggregate instead of machine learning, they work very well or at least consider them as benchmark.
Comment: Thank you for your answer Tim  and for your comment @forecaster ,  my new code below as an answer. Thank you, and I would be happy if you could give me a feedback.

A Function to select a forecast method


What does it mean if the cumulative normal = 1?

Question: What is the significance of cumulative normal = 1?
I am trying to program a game, however I have inherited code from another programmer. He
is using the cumulative norm. his code is outputting a value of one for a certain value
x, mean and standard deviation.
I have a product value which lets say is = 2.5.
The standard deviation is 0.625.
The x value was generated iteratively and eventually comes to 10.931456.
So are you saying that X or the mean is the 2.5,
x is the 10.93,
and the sd = 0.625?
Also that the probability of 2.5 being at the point x = 10.93 is 1?
Answer: If I understand your question correctly, you have a normally distributed random variable $X$, and the program says that the probability that $X\le x$ is $1$. Now for a normally distributed random variable $X$, the probability that $X\le x$ can never be exactly equal to $1$, it must always be less than $1$.
However, the tails decay very rapidly, so we may have $P(X\le x)$ for all practical purposes. So for example we could easily have $P(X\le x)=1-10^{-12}$. For instance, the probability that a standard normal $Z$ is $\le 6$ is about $1-2\times 10^{-9}$.
The programmer may have decided to round such a number to $1$. Or else, because of precision limitations, there is automatic rounding.
Deciding to round is very sensible. When you are modelling a real phenomenon using the normal distribution, that distribution will never model the phenomenon exactly.  Sort of close is the best one can hope for.
Added: For your edited question, I do not know what the $2.5$ means. But the range from $2.5$ to $10.93$ is $8.43$, which is $8.43/0.625$ standard deviation units, about $13.5$ standard deviation units. That is an astoundingly large range, really quite inconsistent with a normal distribution. For most practical (or even impractical) purposes, in a normal there is virtually nothing $4$ standard deviation units or more away from the mean.
Comment: Yes it is assumed one since the value gets closer and closer to 1. And  yes because of precision limits. Can you see my edit above?
Comment: So is my edit above (in the original question) correct?
Comment: @user1064028: I added some stuff to the answer. I cannot know what the numbers stand for, except for the standard deviation. It makes sense that the $x$ is $10.93$. The number $2.5$ cannot be "at" $10.93$, that doesn't make sense. The random variable $X$ (the numerical result of the experiment) can in principle be $\ge 10.93$, though with a normal with SD $0.625$, and mean $2.5$, or even a mean as large as $8$, this can basically never happen.  That is consistent with the computed cumulative distribution function being virtually $1$ at $10.93$.
Comment: Ok thank you it is making sense now


Kotlin - how to make a map serializable

Question: I am programming in android (but for this question it might not matter). i have a kotlin map defined as follows:
var filters: MutableMap<String, Any?>

i need to pass it to another screen (Activity in android) and for this i ususally make it serializable in java. but in kotlin this data structure is not serializable.  Lets see what i am trying to do:
var b = Bundle()
b.putSerializable("myFilter",filters) //- this gives a compile error that filters is not serializable.

I tried calling filters.toMap() but that does not work either.  How is this done in kotlin ? how can i send a map to another screen in android ?
Answer: Use HashMap in place of MutableMap.
The bundle requires a Serialiable object. MutableMap is an interface and hence is not serialiable. HashMap is a concrete class which implements serializable. You can use any concrete sub class of Map which implements serializable
Create a hashmap :
val filters: HashMap<String, Any?> = HashMap()
filters.put("a", 2)

Or
val filters: HashMap<String, Any?> = hashMapOf("a" to 2)

Put into bundle:
val b = Bundle()
b.putSerializable("myFilter", filters)

Comment: You can simply use,  val map : HashMap = mutableMapOf() as HashMap
Comment: Don't cast your map just to a `HashMap`. Better call the constructor of the `HashMap` with your MutableMap: `HashMap(mutableMapOf(...))`. Otherwise you may get a `ClassCastException`, if the Kotlin developers decide to not use a HashMap anymore for their MutableMaps (or you decide to refactor your code to for ex. use the immutable `mapOf`).

Kotlin - how to make a map serializable


Adjoint of Equivalence Functors

Question: Suppose that $A$ and $B$ are equivalent categories. Then there exist functors $F: A \rightarrow B$ and $G: B \rightarrow A$ such that $F \circ G \cong 1$ and $G \circ F \cong 1$.
I am trying to show that $G$ is a left and right adjoint of $F$ (Actually, the problem states that these functors have left and right adjoints, but I think that these are the correct adjoints).
I have been trying to work with the definition of adjunction that two functors are adjoint when $B(F(A), B) \cong A(A, G(B))$. I haven't been able to work out isomorphism is that would show that these two fuctors are adjoint. How should I proceed?
Comment: I just want to emphasize a subtlety here : even if indeed $F$ and $G$ are adjoint, the natural isos $FG\simeq 1$ and $GF\simeq 1$ that show that there are equivalences need not be the unit and counit of the adjunction. The [nlab](https://ncatlab.org/nlab/show/adjoint+equivalence) explains that you can keep one of them, but the other one might need to be adjusted.
Comment: Does this affect the answer given by @Long? His answer seems to avoid considerations of the unit and couunit.
Comment: No it does not, the answer seems good to me. In fact, Long's answer inscribes in this remark as follow: it shows that $F$ is left adjoint to $G$ and keep the natural iso $1 \overset \simeq \to GF$ to be the unit; so it will be the counit that might not be exactly the isos $FG\overset \simeq \to 1$ that we have.  (This is very understandable as this natural iso does not play any role in Long's proof.)
Answer: $(Fa,b) \simeq (GFa,Gb) \simeq (a,Gb)$
The first bijection is due to $G$ being a category equivalence and the second is via composing with the natural transformation $Id \to GF $.
Comment: @Topos $G$ being a functor only gives you a function $(Fa,b)\to (GFa,Gb)$. This will be a bijection if and only if $G$ is full and faithful.
Comment: Does the first bijection follow from the fact that $G$ is full?
Comment: @Long How would I show that this isomorphism is natural in $A$ and $B$ though? Don't I also need to show that these functors are adjoint?
Comment: @Topos by definition of naturality; it is quite straight forward. First show the left bijection is natural, then show it for the right. Adjointness is the consequence of the naturality of the bijection - by definition...
Comment: @Long I'm really new to category theory, so it's not as simple as you'd think for me. Could you show me how to start it off?
Comment: How are you learning category theory? Do you have some math background?
Comment: Yes, I have a standard undergrad background (analysis, algebra, etc.), but I am finding category theory to be very abstract, and have very little intuition about all of the new concepts I am encountering (e.g. functors, natural transformations). I am trying to work through it, but keep getting stuck. I can't find many examples of how to work through a problem
Comment: join me in chat.stackexchange.com/

Adjoint of Equivalence Functors


rdlc report grouping data sort by numeric column

Question: I'm using rdlc report in C#. Inside rdlc report I had added one parent group and report shows data as I expected, Only problem is that I want to sort data by RowId Column This RowId is an int type(DataSet Column). Sort Order shows option A to Z and  Z to A. Reference image is attached here.
Suppose I have Row Id 1, 2,3,4 ....40. This report will sort data like 1,11, 12,13...., 2, 21,.......
How to sort this data in order of 1,2,3,4.....40

I'm using visual studio 2015.
Is there any other way to sort data?
Answer: Finally I got solution to this problem, I use expression for converting existing value to int. Expression used is as below,
 =CInt(Fields!RowId.Value)


p-subgroup of $\mathrm{GL}_{n}(\mathbb{F }_{p})$ and Sylow's Theorem

Question: Consider the Sylow p-subgroup of $\mathrm{GL}_{n}(\mathbb{F%
}_{p})$ by taking the group of upper triangular matrices with ones along the
diagonal, namely $UT(n,\mathbb{F}_{p})$.  $\mathrm{GL}_{n}(\mathbb{F}_{p})$ has $n_{p}=\prod_{k=2}^{n}\frac{p^{k}-1%
}{p-1}$ Sylow $p$-subgroups, of which $UT(n,\mathbb{F}_{p})$ is only one. Suppose we have $e_{p^{m}}$ elementary abelian p-subgroups of rank $m$ in $UT(n,\mathbb{F}_{p})$. By Sylow's Theorem, every elementary abelian p-subgroup of $\mathrm{GL}_{n}(\mathbb{F}_{p})$ is conjugate to an elementary abelian p-subgroup  of $UT(n,\mathbb{F}_{p})$. So, what reason that prevents the number of elementary abelian p-subgroups of rank $m$ in $\mathrm{GL}_{n}(\mathbb{F%
}_{p})$ to be $n_{p}\times e_{p^{m}}$?.
Thank you in advance!
Comment: An elementary abelian subgroup can lie in more than one Sylow. So you're probably over-counting.
Answer: As Brauer Suzuki suggested, you are overcounting. To see this consider the following example with $n=4$. The set of matrices matching the pattern
$$
\left(\begin{array}{cccc}1&0&*&*\\0&1&*&*\\0&0&1&0\\0&0&0&1\end{array}\right)
$$
form an elementary abelian $p$-subgroup $E$ of rank four. You see that $E$ is normalized by e.g. the permutation matrices $\rho(\alpha)$ and $\rho(\beta)$ representing the 2-cycles $\alpha=(12)$ and $\beta=(34)$.
As neither $\rho(\alpha)$ nor $\rho(\beta)$ normalizes $UT(4)$ this means that in addition to $UT(4)$, the group $E$ appears as a subgroup of the Sylow $p$-subgroup
$UT(4)^{\rho(\alpha)}$ of matrices of the shape
$$
\left(\begin{array}{cccc}1&0&*&*\\*&1&*&*\\0&0&1&*\\0&0&0&1\end{array}\right)
$$
as well as a subroup of $UT(4)^{\rho(\beta)}$ of matrices of the shape
$$
\left(\begin{array}{cccc}1&*&*&*\\0&1&*&*\\0&0&1&0\\0&0&*&1\end{array}\right).
$$


"Rate Module" How to put the number inside the button?

Question: http://drupal.org/project/rate
As you can see, the "yes/no" widget on the bottom of the screenshot is:
[button] [number]
The number is not part of the button.  How to make it like this instead:
[button number]
edit: a perfect example, the thumbs-up/thumbs-down rating widget on Yahoo Answers: http://answers.yahoo.com/question/index;_ylt=Ao37OQz9iO3ZJvacOl9pH8_j1KIX;_ylv=3?qid=20121104010935AAs5NQk
The number is in the button.  Clicking anywhere on that button registers a vote.
Answer: This is done by using some CSS.
look at the HTML structure there. 'LI' tag is used there. Just use the anchor style to LI tag.
background: #EEE;
border: 1px solid #CCC;
margin-right: 3px;
Use this style to li and remove anchor border. Also change the hover style of anchor tag.
Use firebug to find the structure.
Comment: ok, the number is visually inside the button, but how to make the number clickable as part of that button?
Comment: Add hover effect to li. then add cursor:pointer to li.
Comment: I mean, css makes it visually look like it's part of the button, but functionally that number still doesn't behave any differently, it still does nothing (a user clicking on it won't make it register a vote for that button).
Comment: You mean the functionality is not working?
Comment: the yes/no widget "looks" like this:

[ yes 0 ]  [ no 0 ]

but the structure is still

[ yes ] [ 0 ]   [ no ] [ 0 ]

the number isn't an anchor and clicking the number doesn't register a vote.
Comment: I'm not asking how to use css to make the number "look" like it's inside a button.  I want to know how to change the markup so the number is integrated into the button.


Calling Async WCF service at Application_Exit

Question: I have the following code..
<code> Private Sub Application_Exit(ByVal o As Object, ByVal e As EventArgs) Handles Me.Exit
        If MainPage.ModeOfOperation = "PROPOSALMODIFICATION" Then

            MainPage.InitializeServiceEndPoint(client.Endpoint)
            MessageBox.Show("This is a test")
            client.FlagQuotationWithUserAsync(MainPage.FetchQuotationNo, MainPage.FetchReferenceNo, "F", "", "", "")

        End If

    End Sub
</code>
But it doesnot work as I think Async calls are not allowed at the time of the application exit.
I have also done the following

Converting the Async method to sync by the following code in the WCF service :

OperationContract(AsyncPattern:=False)
and then calling it from the xaml like
<code>client.SR_IService1_BeginFlagQuotationWithUser(FetchQuotationNo, ID, "T", UserRole, ProdCode, UserID, Nothing, Nothing)
</code>
But still the function is not being called at the time of the Application exit.
PLEASE NOTE : The main problem is that I want to do something at the time of the application close/exit and I have to call a WCF webservice. Please help I have no clue now..
Answer: I'd consider to change your method call to sync but "one way".
Afterthis, i'd call it from aplication_exit code behind method.
I think in this case your app still "exists" (until method execution not done).
Take a look on this simple post for short example: Need sample fire and forget async call to WCF service
This solution may also help: http://www.codeproject.com/Articles/564450/CallingplusintoplusyourplusdatabaseplusonplusSilve
Comment: can you help me with the code for the one way ? Something like this OperationContract(AsyncPattern:=False Oneway:=true). Please let me know.
Comment: No it is not working. As I have mentioned in the question that it is working when I am calling it in the page load or in other place but When I am using it in the application_exit or UserControl_lostfocus then it is not working. do you have a work around ?
Comment: updated - see also http://www.codeproject.com/Articles/564450/CallingplusintoplusyourplusdatabaseplusonplusSilve
Answer: I see what you are trying to accomplish. Unfortunately, while the application is exiting, you may run into issues trying to do it the way you are doing. This is because you have a proxy to the service reference and there is a whole bunch of things that go on behind the scenes you need to understand. Also, if the reason the application is shutting down is because of a System.ServiceModel exception, it's almost guaranteed you will not be able to make this type of call. It's also not best practice. Instead, just use REST. This will work 100%


TomatoUSB multiple IPs not forwarding

Question: I am trying to use this Guide to enable multiple IPs on TomatoUSB. Our Firewall rules need to NAT and allow a 1to1 to two servers.
<code>/usr/sbin/ip addr add 208.x.x.133/30 dev vlan1
/usr/sbin/ip addr add 208.x.x.132/30 dev vlan1

/usr/sbin/iptables -t nat -I PREROUTING -d 208.x.x.133 -j DNAT --to-destination 192.168.7.100
/usr/sbin/iptables -t nat -I PREROUTING -d 208.x.x.132 -j DNAT --to-destination 192.168.7.130

/usr/sbin/iptables -I FORWARD -p tcp -d 192.168.7.130 --dport 25 -j ACCEPT
/usr/sbin/iptables -I FORWARD -p tcp -d 192.168.7.101 --dport 80 -j ACCEPT

/usr/sbin/iptables -t nat -I POSTROUTING 1 -p all -s 192.168.7.130 -j SNAT --to 208.x.x.132
/usr/sbin/iptables -t nat -I POSTROUTING 1 -p all -s 192.168.7.101 -j SNAT --to 208.x.x.133
</code>

I used the guide to write these but the router only forwards 1 IP , is what I did wrong or s the guide wrong? Can you point out what is wrong by chance?
Comment: Add: '#ip ad' and '#ip ro' and '#iptables -nv -L' and '#iptables -t nat -nv -L'
Comment: Assuming that you did a typo on '-I FORWARD -p tcp -d 192.168.7.101' instead of '192.168.7.100', provide what @alvosu asked you: 'iptables -vnL'.
Comment: Verify that you have not mistyped the IP addresses, in your post an in your firewall rules. Then again, please provide the updates requested so we can be able to try and give you an answer.
Answer: <code>#For each IP you need this command and this rule:
/sbin/ifconfig vlan1:0 208.x.x.130 netmask 255.255.255.224
/usr/sbin/iptables -t nat -I PREROUTING 2 -d 208.x.x.130 -j WANPREROUTING

#For each open port you need rules like these two:
/usr/sbin/iptables -t nat -A WANPREROUTING -p tcp -d 208.x.x.130 --dport 80 -j DNAT --to-destination 192.168.1.130:80
/usr/sbin/iptables -I wanin -p tcp -m tcp -d 192.168.1.130 --dport 80 -j ACCEPT
</code>
Enter these rules in the "Firewall" tab under "Administration".  Works for me.
Answer: It's been a few years since I have done something with two IPs on the same subnet, on the same interface, but it was not easy. I can't remember the exact commands, but just adding another IP address will not work.
That said, why are you trying to make this extra complex? Plug a switch into the Modem/DSL box and give both your servers an external IP address. Then install a good firewall on each server.
Comment: I fully agree, but the client feels thats too risky, and he doesn't want to upgrade the Firewall. I think I'll just swap to a Pfsense install
Comment: What's the goal? If you are doing 1to1 nat, aka with port forwarding every port to said box, then the firewall is doing nothing anyway.
Comment: Shorewall will do 1to1 nat. http://www.shorewall.net/NAT.htm

TomatoUSB multiple IPs not forwarding


Get certificate fingerprint from android app

Question: How to get app certificate's fingerprint from inside of this app?
I want to check if application is singed with my own certificate or if it was repacked / hacked.
I found part of solution here: Get Certificate from Android Application. So question now is: how to check certificate's fingerprint.
Comment: [`android.content.pm.Signature#getPublicKey()`](https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-11.0.0_r1/core/java/android/content/pm/Signature.java#220)
Answer: I put it here - the function gives the same result as keytool does it.
private String getCertificateSHA1Fingerprint() {
    PackageManager pm = mContext.getPackageManager();
    String packageName = mContext.getPackageName();
    int flags = PackageManager.GET_SIGNATURES;
    PackageInfo packageInfo = null;
    try {
        packageInfo = pm.getPackageInfo(packageName, flags);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    Signature[] signatures = packageInfo.signatures;
    byte[] cert = signatures[0].toByteArray();
    InputStream input = new ByteArrayInputStream(cert);
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance("X509");
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    X509Certificate c = null;
    try {
        c = (X509Certificate) cf.generateCertificate(input);
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    String hexString = null;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] publicKey = md.digest(c.getEncoded());
        hexString = byte2HexFormatted(publicKey);
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    }
    return hexString;
}

public static String byte2HexFormatted(byte[] arr) {
    StringBuilder str = new StringBuilder(arr.length * 2);
    for (int i = 0; i < arr.length; i++) {
        String h = Integer.toHexString(arr[i]);
        int l = h.length();
        if (l == 1) h = "0" + h;
        if (l > 2) h = h.substring(l - 2, l);
        str.append(h.toUpperCase());
        if (i < (arr.length - 1)) str.append(':');
    }
    return str.toString();
}

Comment: I don't think this error is related to a keystore. Probably another piece of code in your app causes this Exception. Check the function in an empty project  with your keystore  - this should work.
Comment: Hi, its working with debug kestore. But getting this error when used with signed apk

    java.lang.NoSuchMethodError: No static method setTimeout(Le/a/b/c/d;J)V in class Lorg/apache/http/conn/params/ConnManagerParams; or its super classes (declaration of 'org.apache.http.conn.params.ConnManagerParams' appears in /system/framework/ext.jar)
Comment: The resulting `byte[]` value of `signatures[0].toByteArray()` is the same as the value of `c.getEncoded()`. It seems it is possible to skip the part of certificate creation and make the SHA hash directly from `signatures[0].toByteArray()`.
Comment: Is it still relevant above VERSION_CODES.P? you need to get the GET_SIGNING_CERTIFICATES
Answer: Sorry, I was faster below my solution, thanks for your time;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            PackageManager pm = this.getPackageManager();
            String packageName = this.getPackageName();
            int flags = PackageManager.GET_SIGNATURES;

            PackageInfo packageInfo = null;

            try {
                    packageInfo = pm.getPackageInfo(packageName, flags);
            } catch (NameNotFoundException e) {
                    e.printStackTrace();
            }
            Signature[] signatures = packageInfo.signatures;

            byte[] cert = signatures[0].toByteArray();

            InputStream input = new ByteArrayInputStream(cert);

            CertificateFactory cf = null;
            try {
                    cf = CertificateFactory.getInstance("X509");

            } catch (CertificateException e) {
                    e.printStackTrace();
            }
            X509Certificate c = null;
            try {
                    c = (X509Certificate) cf.generateCertificate(input);
            } catch (CertificateException e) {
                    e.printStackTrace();
            }

            try {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                byte[] publicKey = md.digest(c.getPublicKey().getEncoded());

                StringBuffer hexString = new StringBuffer();
                for (int i=0;i<publicKey.length;i++) {
                    String appendString = Integer.toHexString(0xFF & publicKey[i]);
                    if(appendString.length()==1)hexString.append("0");
                    hexString.append(appendString);
                    }

                Log.d("Example", "Cer: "+ hexString.toString());

            } catch (NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            }

    }
}

Comment: You might want to look into [application licensing](http://developer.android.com/guide/publishing/licensing.html). Note, it only works if your app is paid.
Comment: My apps are not paid. I've heard about adware apps repacked, modified (changed ad publisher id) and send to market.
Comment: is it the signature fingerprint or just the signature? it is different from the one generated by `keytool -printcert -file sign.rsa`
Comment: getInstance("SHA1") - fingerprint


There is no inner product that induces the infinity norm in the space of continuous complex functions in [a,b]

Question: There is no inner product that induces the infinity norm $\|f\|_{\infty}:=\sup\{|f(x)|: x \in [a,b] \}$ in the space of continuous COMPLEX functions of domain $[a,b]$, where $[a,b]$ is a closed interval of the real numbers.
I couldn't prove this and I couldn't find counterexamples for the parallelogram rule. Can you provide a proof of this statement?
Answer: You can take$$f_1(x)=\begin{cases}\frac{\frac{a+b}2-x}{b-a}&\text{ if }x\leqslant \frac{a+b}2\\0&\text{ if }x>\frac{a+b}2\end{cases}\quad\text{and}\quad f_2(x)=\begin{cases}0&\text{ if }x\leqslant \frac{a+b}2\\\frac{x-\frac{a+b}2}{b-a}&\text{ if }x>\frac{a+b}2.\end{cases}$$Then all of the functions $f_1$, $f_2$, $f_1+f_2$, and $f_1-f_2$ have norm $\frac12$. Therefore, the parallelogram law doesn't hold.
Comment: Thank you very much.


How to add a book page: material types empty

Question: I run a Drupal 7 website since a year and have been always upgrading it - up to the version 7.10.
I have 2 Books and users' Blog at my web site. One of the Books is holding "Site Help" and "Imprint" stuff.
Now there have been a need to add to add 2 new pages "Terms of Service" and "Privacy Policy" to that book.
I go to /node/add but there is a message that no "material types" have been defined.
But I don't remember deleting them. And when I go to /admin/structure/types I see both "Machine name: blog" and "book" defined there:

Thank you
Comment: And you are not able to add this kind of content since your update to 7.10?
Comment: I'm not sure since when. But I have 2 Drupal 7.10 installs: preferans.de and simplex.ru and both have this problem.
Answer: Node/add works for me, but try admin/content/add.  Also check that you are logged on as the administrator.
Comment: /admin/content/add displays a link to /node/add. And /node/add says there are no content types defined and displays link to /admin/structure/types/add. And when I go there I see the picture shown above (blog and book). But nowhere can I add a new book page. Yes, I'm admin.