How to create a video from frames named using timestamp with ffmpeg

Question: I have a folder filled with frames that have the timestamp in the name in the folowing format

im_%H_%M_%S_%MS.png

im_08_05_09_007324.png
im_08_05_09_532857.png
im_08_05_10_059340.png
im_08_05_10_575862.png
im_08_05_11_118361.png
im_08_05_11_596814.png
im_08_05_12_148340.png
im_08_05_12_665838.png

I try to use -pattern_type glob in windows but it does not work.
ffmpeg.exe -framerate 10 -pattern_type glob -i im_*.png -c:v libx264 -r 30 -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2"  -pix_fmt yuv420p $videoName

I get
 Pattern type 'glob' was selected but globbing is not supported by this libavformat build im_*.png: Function not implemented

later I found that this do not work on windows :( which is what I am using. ffmpeg Error: Pattern type 'glob' was selected but globbing is not support ed by this libavformat build
I also try
ffmpeg.exe -framerate 10 -pattern_type glob -i im_%02d_%02d_%02d_%06d.png -c:v libx264 -r 30 -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2"  -pix_fmt yuv420p $videoName

I got
im_%02d_%02d_%02d_%06d.png: No such file or directory

I am running out of ideas. I refuse to believe that there is no way to do this in ffmpeg and powershell.
I really appreciate any help!
Answer: You can use a workaround, via the concat demuxer
Create a text file with the list of filenames in order
file im_08_05_09_007324.png
file im_08_05_09_532857.png
file im_08_05_10_059340.png
file im_08_05_10_575862.png
file im_08_05_11_118361.png

and then run
ffmpeg -f concat -r 10 -i list.txt -c:v libx264 ...

(this will produce warnings about invalid DTS but you can ignore them)
Comment: Thank you very much!! Sorry for my late answer. I was in a hurry that day and decided to created the videos with Fiji imageJ. However, now that I need to create lot of videos, I found the necessity to create a script. Building on your answer I wrote my full solution.
Answer: Building on Mulvya solution I wrote a powershell script that will create the txt with filename in the suggested format.

Create a txt file with directory png content
$inFolder = "C:\my_folder_with_Png_frames\"
$inSearch = $inFolder+"*.png"
$outFile  = $inFolder + "framenames.txt"
Get-childitem -path $inSearch -recurse -name | Out-File $outFile -Encoding ASCII

I added the Encoding on the Out-File cmdlet, since the default is UTF-8-BOM and ffmpeg does not like it.

Pre-append the string "file " to each line of the txt file.
$prependVar = "file "
$lines      = get-content $outFile
$newlines   = $lines | ForEach-Object{ "$prependVar$_"}
$newlines | Out-File $outFile -Encoding ASCII

Call FFMPEG
 cd $inFolder
 C:/ffmpeg/bin.\ffmpeg.exe -f concat -r 10 -i $outFile -c:v libx264 -r 30  -pix_fmt yuv420p out.mp4

Steps 1. and 2. will not produce a txt file with fullpath names. Only the names. This is why we need to cd to the folder.
Comment: Hey, I am trying to do something similar to what you have here and it is reading my filename 'file myjpegfile.jpg'  wron somehow. I get an error "Impossible to open file 'Dmyjpegfile.jpg" For some reason it is appending on a 'D' that doesn't exist. I am guessing it is a format issue, but I am using the ASCII Encoding so I am not sure what is causing it.


product in cart but when clicking on cart it shows empty

Question: I really don't understand this one...
I have Drupal commerce on Drupal 7.
When I'm adding a product it shows in the cart summary just fine. but when I go on mysite/cart ...the cart is empty. It is not a browser issue I think. Any help on that odd problem would be more than just appreciate, please.
I tried clearing the cache on the server, browser ..none worked
Answer: If you do a quick search of the issue queue for "Views results empty", you should turn up the solution: you've probably customized your shopping cart View to include a product relationship, but your test user must not have access to view all products. When Views goes to render the results and performs the access check on the View results, it won't show anything as a result.
If this is the case, my recommended solution would be to edit the View, open the advanced settings fields, and edit your query settings to disable SQL rewriting for the View.
Answer: You may do the next variants to solve this problem:

check orders manage page on backend /admin/commerce/orders For all
users (for without registration mode disable "Commerce Checkout
Redirect") created new order with "Cart" status
Check View for Cart
page admin/structure/views/view/commerce_cart_form/edit Maybe
contains wrong settings


What exactly does it mean to "play over the changes"

Question: I've been watching a podcast lately which features a country guitarist and a blues guitarist discussing various aspects of guitar-craft. When comparing stylistic  differences, the blues guitarist often says to the country guitarist something akin to...

that's because you are playing over the changes

I've seen questions on here about playing over the changes but I'm a little unsure as to exactly what they mean.
So, specifically, what is 'playing over the changes'? What are the stylistic implications for country and blues, and more generally in other styles like jazz and rock?
Comment: I wonder if the use is derived from a style of English church bell ringing.
Comment: @hpaulj i think not. It's "playing over the [chord] changes" of the tune.
Comment: Can you direct us to this podcast?  Otherwise we're just guessing.  (Though I think we can be confident it has nothing to do with church bells.  Nice try, hpaulj :-)
Answer: Some players will tend to use, for example, the A pent min. scale notes all through a 12 bar in A. It sort of works, if they're careful (or lucky!) but when playing the changes, they will tend to use the Am pent notes while the tune is on A, change to using the Dm pent notes on D, and the Em pent notes on E. This then starts to sound like he knows where he is rather than just 'widdling'.
Obviously it works just as well, if in a more complex manner, with any song chord sequence, not just 12 bar blues.Certain notes work for certain chords - and sequences - and these are what help when 'playing the changes'.
However, it's not just guitar that this fits for - it's all solo instruments, from Listz playing a cadenza to Getz on sax.And it works for all genres. In fact, listen to a good player who plays over the changes, and you don't even need the changes. The solo notes make them pretty clear.
As Richard says, playing over the changes can also mean putting in 'wrong' notes on purpose, which the player know will work because he understands not just the chords themselves, but how they react in sequence.
Answer: I'm not sure of any stylistic implications, but my understanding has always been that "the changes" simply refer to the chords themselves---in other words, the chord "changes" that make up the progression. Thus "playing the changes" or "playing over the changes" simply means you're playing with an awareness of the harmonic environment.
This is especially vital, of course, for soloists. If they're playing without full knowledge of the changes, they're liable to emphasize so-called "avoid" notes over certain chords, creating unintentional dissonances that they probably wouldn't have made (at least, wouldn't have accidentally made) had they had a proper knowledge of the underlying chord structure. Since they don't know the chords, they don't know the dissonance they're playing, so they don't know how to resolve the dissonances, and soon the solo just spirals out of control and the audience is left twiddling their thumbs for the next person up.
Interestingly, when someone really knows the changes they can have a lot of fun intentionally hitting some of those dissonant pitches. Dexter Gordon (tenor sax) holds a great B♮ over a B♭ chord in "Watermelon Man" that's just terrific. (It's at 3:20, a few seconds into where I started the video. Yeah, it's a ♭9, I know, but in this piece it really sticks out.)
Comment: in the context of Watermelon Man, that B is also a standard note of the F blues scale. Actually, that 2nd chorus of Dexter Gordon has a lot of blues licks inside, not actually playing over the changes. Herbie's chorus, has much more a "playing over the changes" feeling, imo.
Comment: Really good point. But Gordon also has to have an understanding of the changes to know to resolve that Bn to Bf, no matter how briefly.
Comment: @richard watermelon man only has the 1, 4 and 5 chords in it though, it's essentially an elongated 12 bar blues.  So in that sense, any blues play "knows the changes": blues players aren't just knocking out pentatonics at random (despite what some jazzers might think ;) )  When I listen to the soloing on watermelon man, if anything I get the opposite impression: they're more or less playing "licks" with a less-than-average regard to the change between the I and IV chord (compared to a blues player).
Answer: Brian Wampler has actually explained what he means in this podcast, so I'll include it here for completeness.

In short, basing his solos around the chord shapes of the progression.
Comment: Very helpful to see and hear what "playing through the chords/changes" means to us non-musicians. Very informative and eye-opening when he finally got around to "playing through". A subtle but very impactful effect. +1
Answer: "Over the changes" (to me) is a relative perception and no one is necessarily going to see it in the same way. 'For me' it is about a few things ... my timing relative to the rhythm section, my choice of notes, phrasing, release times ...
"IF" I find a place in time that is slightly ahead (above / over) the groove, I sometimes seem to be released from the necessity of strictly staying in the same 'exact' key as the changes dictate.
I can play the odd notes that wouldn't quite work if I were more laid back, and in the right 'posture' (physical / perceptual posture) they do work, to my ears, as long as I don't get 'too far away' from the harmonic structure.
It's as if I'm sneakin' them by before the changes tell me I can't do that, and I get away with it.
Answer: In the strictest sense, 'Playing over the changes' means improvising over the chord changes to Gershwin's 'I got Rhythm'. There's a wiki page if you're interested.
Comment: I'm pretty sure that's absolutely not what a blues guitarist is talking to a country guitarist about...


Validar RadioButton com jQuery

Question: Gostaria de fazer uma validação via jQuery, para saber se o cliente selecionou algum RadioButton
JSFiddle Demo
Ele exibe um alert caso não tenha selecionado, mas ele ainda envia (submited), não deveria.
HTML

        <input id="RadioButtonList1_0" type="radio" name="RadioButtonList1" value="1" />opc 01

        <input id="RadioButtonList1_1" type="radio" name="RadioButtonList1" value="2" />opc 02

        <input id="RadioButtonList1_2" type="radio" name="RadioButtonList1" value="3" />opc 03

        <input id="RadioButtonList1_3" type="radio" name="RadioButtonList1" value="4" />opc 04

        <input id="RadioButtonList1_4" type="radio" name="RadioButtonList1" value="5" />opc 5

<input type="submit" name="Button1" value="Votar" id="Button1" class="btn btn-primary" />

JS
 jQuery(function(){
    jQuery('#Button1').bind('click',checkRadio);
 })

 function checkRadio() {
    var isChecked = jQuery("input[name=fileType]:checked").val();
    var booleanVlaueIsChecked = false;
    if (!isChecked) {
        booleanVlaueIsChecked = true;
        alert('Selecione algum logotipo');
    }
 }

Comment: Faltou dar `preventDefault` no evento gerado pelo click quando não quiser submeter o formulário. Além disso precisa declarar o evento como parâmetro da função.
Comment: Adicionei partes relevantes do código na pergunta, para facilitar o entendimento.
Answer: Você pode colocar um return false depois do alert:
jQuery(function(){
   jQuery('#Button1').bind('click',checkRadio);
});

function checkRadio() {
   var isChecked = jQuery("input[name=RadioButtonList1]:checked").val();
   var booleanVlaueIsChecked = false;
   if (!isChecked) {
       booleanVlaueIsChecked = true;
       alert('Selecione algum logotipo');
       return false;
   }
}

Tem mais um erro no script, o nome do campo
var isChecked = jQuery("input[name=fileType]:checked").val();

Altere para
var isChecked = jQuery("input[name=RadioButtonList1]:checked").val();

JSFiddle
Comment: Esta solução funcionou para o meu caso também estava com a mesma dificuldade em validar os RadioButton no meu caso também faltou dar um Return false na função.
Answer: Teste assim:
 jQuery(function () {
     jQuery('#form1').on('submit', checkRadio);
 })

 function checkRadio() {
     var isChecked = jQuery("input[name=fileType]:checked").val();

     var booleanVlaueIsChecked = false;
     if (!isChecked) {
         booleanVlaueIsChecked = true;
         alert('Selecione algum logotipo');
         return false;
     }
 }

http://jsfiddle.net/6xs5x/1/
A diferença é que agora eu escuto o submit da form e no caso de dar erro faço return false;
Comment: +1 - minha resposta estava pronta, por isso publiquei :)
Comment: @abfurlan, obrigado. A sua resposta é boa também, porem eu prefiro ter certeza que é no `form submit`, não vá o botão ser carregado com teclado.

Validar RadioButton com jQuery


Prove that every permutation matrix satisfies its characteristic polynomial.

Question:
Let $P$ is a permutation matrix which represents the permutation $\sigma\in S_{n}$. Let $\sigma_{1}$,$\sigma_{2}$,...$\sigma_{k}$ denote the disjoint permutations in the cycle form of $\sigma$.
Let $P_{i}$ and $c_{i}$ represents the permutation matrix corresponding to the permutations $\sigma_{i}$ and the cycle lengths of $\sigma_{i}$ respectively. Prove that P satisfies the equation (its characteristic polynomial)
$$\prod_{i=1}^{k}(P^{c_{i}}-I) =0$$

I know the following facts:

For disjoint permutation matrices $P_{i},P_{j}$ we have $(P_{j}-I)(P_{i}-I) = 0$.

For disjoint permutation matrices $P_{1},P_{2},\cdots,P_{k}$ we have $$\prod_{i=1}^{k}P_{i} = \sum_{i=1}^{k}P_{i}-(k-1)I.$$

If P and Q are disjoint permutation matrices so are $P^{m}$ and $Q^{n}$  , $\forall m,n\in \Bbb N$.

If P and Q are disjoint permutation matrices they commute.

If P is a single-cycled permutation matrix with cycle length $k$ then $P^{k}=I$.

Combining the fact $2$ and $3$ for disjoint permutation matrices $P_{1},P_{2},\cdots,P_{k}$ we also have $$\prod_{i=1}^{k}P_{i}^{m} = \sum_{i=1}^{k}P_{i}^{m}-(k-1)I, \forall m\in \Bbb N.$$

Combining the fact $1$ and $3$ we have $(P_{j}^{n}-I)(P_{i}^{m}-I) = 0$ for any $n,m \in \Bbb N.$

MY TRY: I tried with an case  where $P$ breaks in two single-cycled disjoint permutations $Q$ and $R$ with cycle lengths $m,n$ respectively. We need to prove that $$(P^{n}-I)(P^{m}-I) = \Bigr((QR)^{n}-I\Bigl)\Bigr((QR)^{m}-I\Bigl) = 0$$
Using fact $4$ and $5$
$$\Bigr((QR)^{n}-I\Bigl)\Bigr((QR)^{m}-I\Bigl)=\Bigr(Q^{n}R^{n}-I\Bigl)\Bigr(Q^{m}R^{m}-I\Bigl) =  \Bigr(R^{n}-I\Bigl)\Bigr(Q^{m}-I\Bigl)$$ The fact $7$ as stated above states that it vanishes.
But it gets more calculative when P breaks in $3$ disjoint single cycled permutations. Also, generalisation would need more calculations.
I do not know Cayley hamilton theorem. I am new to group theory. Please ask for clarifications if something is not clear. Any hint would be a great help.
Answer: I think this is much easier than you are making it out to be. By relabelling, you may assume that the permutation is $$(1,\dots,c_1)(c_1+1,\dots,c_1+c_2)...$$
The permutation matrix of this product of disjoint cycles is a block-diagonal matrix, with the blocks being the permutation matrices of each cycle.
Products and sums of block-diagonal matrices are block-diagonal, obtained by taking the products and sums of each block. Thus a block-diagonal matrix satisfies a polynomial if and only if each block of it does.
Block $i$ certainly satisfies the polynomial $P^{c_i}-I$, your fact 5. Thus this is the zero matrix, and the product of this with anything else is zero, in particular your polynomial is the zero matrix on the $i$th block. Thus your matrix is zero.
Answer: This is just an even more elementary version of David Craven's answer.
For each cycle $(i_1, \ldots, i_c)$ of $\sigma$, note that $P^c e_{i_j} = e_{i_j}$, so $P^c - I$ vanishes on $\mathrm{Span}(e_{i_1}, \ldots, e_{i_c})$. Thus $\prod_{i=1}^k (P^{c_i} - I)$ vanishes on this span as well, hence also on the span of these spans, which is the whole space.
The only fact of note we've used is, for every j,
$$ \prod_{i=1}^k (P^{c_i} - I) = \left(\prod_{\substack{i=1 \\ i \neq j}}^k (P^{c_i} - I)\right) (P^{c_j} - I), $$
which is of course immediate, e.g.
$$(P^a - I)(P^b - I) = P^{a+b} - P^a - P^b + I = (P^b - I)(P^a - I).$$
Answer: As, Disjoint permutations are commutative
$$\prod_{i=1}^{k}(P^{c_{i}}-I) =\prod_{i=1}^{k}\Biggl(\biggl(\prod_{j=1}^{k}P_{j}\biggr)^{c_{i}}-I\Biggl) = \prod_{i=1}^{k}\Biggl(\prod_{j=1}^{k}P_{j}^{c_{i}}-I\Biggl)$$
We call the above equation as $[1]$. Your fact $6$ tells us that

The product of $k$ disjoint permutation matrices equals Identity matrix subtracted $k-1$ times from the sum of those permutation matrices

Also, as $P_{i}^{c_{i}}=I$. Using these both, the product term in the rightmost expression in [$1$] $$\prod_{j=1}^{k}P_{j}^{c_{i}}=\sum_{j=1}^{k}P_{j}^{c_{i}}-(k-1)I=\sum_{j\neq i}^{k}P_{j}^{c_{i}}-kI$$ Plugging it back in the rightmost term in the equation [$1$], equation [$1$] becomes
$$\prod_{i=1}^{k}(P^{c_{i}}-I) =\prod_{i=1}^{k}\Biggl(\biggr(\sum_{j\neq i}^{k}P_{j}^{c_{i}}-kI\biggl)-I\Biggl)=\prod_{i=1}^{k}\Biggl(\sum_{j\neq i}^{k}(P_{j}^{c_{i}}-I)\Biggl)$$
Let's now handle the product on the right. Before that, let $A_j$ denote the matrices of the kind $P_{j}^{a}-I$ for any $a$ . First, we should understand the following two properties for $i,j\in \Bbb N$
$1$. $A_jA_i = 0$ for $j\neq i$ (immediate from the fact $7$)
$2$.  $A_jA_i=A_iA_j$
Proof of 2: As $P_{j}^a$ and $P_{i}^b$ are disjoint they are commutative so, $(P_{j}^a-I)(P_{i}^b-I)=P_{j}^aP_{i}^b-P_{i}^b-P_{j}^a+I=P_{i}^aP_{j}^b-P_{j}^a-P_{i}^b+I=(P_{i}^b-I)(P_{j}^a-I)$
Coming back to product, we are left with the product of $k$ terms $$(A_2+A_3...+A_k)(A_1+A_3...+A_k)...(A_1+A_2...+A_{k-1})$$
The resulting expression will be a "polynomial of degree $k$ in $A$". But, We can't have a term like $A_i^k$ in the "polynomial" for any $i$, as the $i_{th}$ bracket in this product does not have  $A_i$.
Hence, we must have terms in the polynomial involving product of at least two different $A_i's$. But by commutativity of $A_i$'s we can take any such pair of cross terms together. So, the polynomial is just the sum of terms of the form $MA_iA_j$ for some $i\neq j$ and $M$ is a matrix of "degree" $(k-2)$ in $A$. But the property $1$ says that every such term is a zero matrix. Hence, we conclude that the product which resulted in such a polynomial is zero matrix. Leaving us with,
$$\prod_{i=1}^{k}(P^{c_{i}}-I)=0.$$


What are some good drafting strategies for a recreation basketball league?

Question: Age: 16 - 18
I analyzed the past two championship teams who won it all in the last two years, and here is what I discovered about the types of players they drafted:
1. Last year's team:
First Round pick: Quick explosive ball handler
Second Round pick: Big man
Third Round pick: Big man
Fourth Round pick: Big man
From there on out, the team drafted mostly all-around role players and ball handlers.
2. Champions from two years ago:
First Round pick: Strong big man
Second Round pick: Strong big man
Third Round pick: Ball handler / Three point shooter
Fourth Round pick: Big man / Ball handler
From there on out, the team drafted all-around role players.
The obvious pattern here is that in order to build a good team, you should draft big men early. But Team 1 drafted the best player available (which wasn't a big man) and then proceeded to use the next three picks to draft big men. Team 2 made sure it drafted big men early and then went on to draft ball handlers, role players etc.
Looking at this, what would be a good strategy to build a strong team that doesn't solely rely on perimeter (jump shooting team) but also isn't a slow big team that has good big men but very average ball-handlers?
Comment: I'd think the best draft strategy matches the one we see in fantasy sports, since it's a similar situation of information lack (we don't get the opportunity to personall know the guys being drafted, we just may know a few things about them).  So I'd say your job is to focus on the rarest skills first, particularly if they are the skills you desire most.  And attempt to take players who should have already been drafted rather than reach for people who the other teams won't take.  Honestly, it's probably 75% luck in such a information-lacking situation.
Comment: I think this is a very tricky question to answer; IMHO it all depends on how much better the best PG is compared to the next best PG, and so on. Bottom line is that you need to find a compromise you are comfortable with
Answer: Recreational basketball is an extremely tricky field. After playing on multiple teams over the years, here are some lessons that I've learned which affect drafting strategies:

You win games when you hustle.

Invariably, the most successful teams I've played on were comprised of a bunch of guys who were willing to hustle. Loose balls, boxing out, tenacious defense... the hustle factor is an often-overlooked element during draft day

Big guys are important

When you have a big guy, you immediately have presence in the lane. This pays off on offense and defense, and IMHO is the biggest factor for rec ball

Build a team of shooters - don't single out one guy to take most of the shots

You can ride along with one good shooter, but even the best guys have bad games. I've lost to worse teams because we depended too much on one guy to shoot.
This doesn't really affect the draft (pick a great shooter if you can)... but if your great shooter isn't willing to give the ball up - watch out

You need a designated PG

Don't draft two guys who both think they can play PG. Your PG is your offensive leader and he needs to know that from the start

With that in mind, here's my draft strategy:
1. Big man who plays solid defense
2. PG
3. Best defender/hustle player out there, not a PG
4. Fill your positions with the best players left.
Answer: At that age group you pick the best players available.  Being the best is not only ability but willingness to play hard all the time (and do some dirty work).  Also defense should count for more than offense at that level.  Even good rec league players aren't GREAT scorers, so defense is more important.  You can get lucky and make shots, you can't get lucky (consistently) and make jump shots with a guy in your face.
Also for that age range I would think big men would be less coveted (most tall young rec league players can't finish).  I played in a league a few years ago with a lot of college teams (out of season).  What is funny is that most of the teams were just the bigs.  So we are facing a team whose PG is 6'5".  Well the first game we lost by 40.  The second game we pressed the entire time... didn't lose another game.
Just by putting guys into buckets you are disabling your team.  You can start 3 "PG"s and 2 "SF"s in a rec league and be dominant.  If the two best players are both centers then get those two guys first.  I would do the exact opposite of what Matt said.  I would go best players for first 3 rounds for sure.  After that I might bump a guy up or down a little based on need.  And when I say need it would have to be a really drastic need.
Example of the need flaw:  So you are in round 3 and have no PG.  The 4 best available players are bigs.  You take the next best PG.  Well now you have your team ran by a middling PG who will look to dominate ball since he has best ball skills, but he really isn't a good player.  You would be better off getting the big and creating a mismatch.  Understanding that you might have a few more turnovers but easier scoring once you get the ball up.
Answer: I believe there is no perfect strategy. Every coach is different and will implement their own gameplan for their strengths and weaknesses.
That being said, overall talent is king butttt you do need a ball handler of some sort or you could be in for a long season.
Defense can be taught easily.  Well at least for me. ha
But ball handling takes time (as well as confidence) to develop.
A key strategy to not KEEP IN MIND is not so much in your first couple picks as it is in your last couple that will change your season.
If you end up coasting in your draft and picking 2 or three of the bottom 10 players it can negate your early round picks almost completely.
Let me explain...
If you have horrible talent, the last thing you want is them with the ball in their hand in key situations.
That equals turnovers for days. Which brings the entire team morale down severely and team morale is huge.
I can easily double team a stud player and drive him crazy all game. Easy pickens...
I always have my do not picks and my lower steals that give me an advantage.


In basketball, what would be the result of a foul on the shooter and then a foul on the player attempting to block the shot?

Question: Inspired a bit by this question...
The scenario:

A player is fouled by a defender while in the act of shooting, and puts up a shot.
Another defender sees the shot being taken, and has a path to block the shot on its upward trajectory.
As he goes to block it, another offensive player steps late into the path of the defender, illegally impeding him.

What would the result be?
I'm assuming a player is legally allowed to block a shot after a whistle (when continuation is given... or also after the horn to end a quarter) since the shot is still live.
I'm also under the belief that typically an offensive player illegally impeding a defender's block would be a loose ball foul if the shot has already been released (an offensive foul before the ball is shot)?
Would the result be akin to a typical double foul?
Answer: If the foul was called after the shooter was fouled, then this should lead to free throws for the shooter. This part is a given.
Getting to defensive player being impeded by another offensive player - Keep in mind that after the shooter is fouled, and the whistle is blown for that foul, there can be no "block" because the ball is dead (even if it's in the air). From this point on there can only be a goal tend (if the foul happened during continuation).
So basically your question is, "If an offensive player is fouled after his teammate earns a shooting foul, can that foul be called?". Short answer. Absolutely. In basketball, a foul is a foul, whether it occurs during a dead ball or not.
Comment: In the NBA I am almost positive you can block a shot after the whistle so the fouled player does not get an easy and 1 on a layup
Comment: @Daffy yes but that is not recorded as a "block" on the stat sheet, else, w/ all the continuation in the NBA, we'd have a ton of players getting tons of blocked shots recorded.
Comment: that makes sense. I misread and thought you meant that the action of a block would automatically be considered a goaltend after a foul


Is there a better way to create an alternative URL Alias Pattern?

Question: Say for example my alias pattern for one node is set up as:
style-[node:field_style]/[node:title]

There may be a case that node:field_style is blank so I would like to use another field and a slightly different url alias pattern:
type-[node:field_type]/[node:title]

I am thinking about just using hook_pathauto_pattern_alter() but wondering if there is a better way?
Answer: I'd create a token for that specific data; I'm not sure it's necessarily better (or worse) than using the alter hook, but it has the advantage of being reusable elsewhere in the site.
A simple (untested) example:
function MYMODULE_token_info_alter(&$data) {
  $data['tokens']['node']['field_type_or_title'] = array(
    'name' => t('Field type or title'),
    'description' => t('Value from field_type if available, node title otherwise.'),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    if (isset($tokens['field_type_or_title'])) {
      if ($items = field_get_items('node', $node, 'field_type')) {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($items[0]['value']) : $items[0]['value'];
      }
      else {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($node->title) : $node->title;
      }

    }
  }
  return $replacements;
}

Comment: This answers this question and I'm sure other similar questions related to this topic. Amazing! Now, do you guys have an idea if we can return our token's value to be a combination of other previously defined tokens? This should make this answer even more useful. Thanks :-)


Interpretation of scaled error measures

Question: can someone give me an explanation on how one would interpret the result of a scaled error measure.
For example the Mean Absolute Scaled Measure (MASE). The numerator is the mean absolute error and the denominator the mean absolute error of a benchmarking method.
While I know that a MASE < 1 means that the forecasting method is better than the naive one, and MASE > 1 that it is worse, I still have a difficult time trying to interpret the results.
Does the result say nothing about how the forecast performed in regards to the actual result? Does it only compare the result to a benchmarking method?
Let's say you are working for a company that makes sales predictions, now you want to present your performance to a customer. What would a e.g. 0,8 MASE say about your overall performance? Does it just say you're better than the naive method because it is < 1?
The MAPE for example would say that you are off by 80% if the MAPE were 0,8, but then again the mape is heavily unreliable, this is why I opted for scaled measures. I just find it so difficult to interpret the result in a 'customer friendly' way.
Thanks for your help!
Answer: Your interpretation is exactly correct: a MASE <1 simply says that our method performs better than the benchmark method, in terms of the MAE. (One could also look at scaled squared errors, in which case we would compare MSEs between the focal and the benchmark method.) As such, the MASE does not tell you anything about "absolute" forecast accuracy, just about whether we improved on the benchmark.
In addition, note that how exactly we calculate the benchmark MAE matters. For instance, in the original MASE formulation by Hyndman & Koehler (2006), the benchmark error, i.e., the denominator, was the MAE of the random walk forecast in-sample. So for the MASE, we compare the out-of-sample performance of our focal forecasting method to the benchmark in-sample. See Interpretation of mean absolute scaled error (MASE) on what kind of confusion may result.
You are right to be worried about interpretation. Clients often don't care that much about whether we have improved on a benchmark. (Even if such an improvement over a simple benchmark is by no means a foregone conclusion.) Then again, "absolute" accuracy measures may not be all that informative, either.
I personally like "forecast implication metrics": what are the implications of different forecasts? Forecast A may be more accurate than forecast B, but if subsequent processes mean that they have the same implications (e.g., because we are using forecasts as an input to a production planning process, but logistical constraints mean that both forecasts will lead to the same production plan), then in terms of actual outcomes, both forecasts are equally good.
Better forecasts won't earn you money. Better production plans, capacity utilization, or stock control will. Forecast accuracy is only a means to an end. And yes, this implies that interpreting forecast accuracy without looking at the larger picture is short-sighted.

Interpretation of scaled error measures


What does it mean if the residuals for a log-linear model are all zero?

Question: Probably a very basic question, but I have a contingency table formed of 3 categorical variables (one with 3 levels, the rest with 2) and have been asked to try to test the association between them using log-linear modelling. However, the output I get states that residuals are all zero, and remain so regardless of what I specify as the model (e.g. saturated, or just the one variable, or an interaction etc.). I know from other analyses that there is not a perfect relationship between these variables.
What does this mean in terms of the model? Is it an indication that it violates assumptions?

Edited to add the output table:

This is for a model containing the interaction term (which is what we're interested in).
Comment: Without knowing more detail it is hard to tell. I suspect you may be taking the log of 0 counts, which results in NA's, which are dropped from the analysis by the software you are using, leaving only a few cases.
Comment: Hi @VictorZurkowski - we don't have any 0 counts in the data (the lowest is >130). We have 12 sets of counts in total, in case that helps at all.
Comment: I think it is an indication that you are fitting the wrong model, indeed the saturated one. Could you provide us with output of the software?
Comment: @Knarpie - I've added an image of the output. Thanks!
Answer: This is indeed a perfect fit. The command "Constant + Time * Condition*OutcomeType" must mean that a saturated model is fitted, i.e. with all possible two-way and three-way interactions. Check the help-files of your software to fit the model you want to.
Comment: It's this interaction that we're wanting to test though (the individual variables on their own don't really mean much outside of this interaction). Is there another way we should be testing this?
Comment: Also I should add that even if an individual variable is added to the model without this interaction, it's the same result
Comment: @DrJay This is simply not possible, you can never get a perfect fit with only one variable if you know there is no perfect relationship. Please check and double check that your model is doing what you think it does. If you show us output from the more limited model we can perhaps help you further.
To test the significance of interaction terms you need to fit the simpler model, or use a Wald-type test.
Comment: Yes, sorry, you're quite right - I was taking the variables out of the analysis (so that only one remained) but keeping the 'saturated model' option checked in error.
Comment: @DrJay You're welcome, we are all here to learn. Kindly accept my answer if you think my help was useful :-)


how could I modify/recompile an already defined function during runtime

Question: Firstly, yes I know this is not good practice. It's just an experiment, not actual planned code.
The problem:
I have a function
def foo:
    print("hi there")

def foo2:
    #Any stack/recompiling manipulation goes here

def main:
    foo2()
    foo()

Is there any way to manipulate the definition of foo() from foo2() during runtime?
I have been fiddling with trying to change variables in the frames, but most are read only (save f_local).
Comment: @JonathanBurk please tell us what you are actually trying to do.  The more specific you can be the more likely we can give you what you need.  just saying you want to "modify it at runtime" is far to vague to get decent answers.
Comment: Responding with "I just want to learn about the stack" is valid, I can point you to non-manipulative resources in that case, but I really think that anything else has a better solution than low level monkey patching.
Comment: completely depends on what you are trying to modify, if it fits any use case that might come up in the real world there may be things you can do with decorators/factory functions but we need to know what you want to do with it.
Comment: What are "variables in the frames"?
Comment: The variable I most wanted to change is f_code. From there I would hope to change main to do things such as skip over foo() entirely.
Comment: @TadhgMcDonald-Jensen you have answered my original question. I was wondering as an extra step, can you do something like the above code, but let's say there is now foo3() after foo() in main. Could you modify execution to entirely skip foo3() using only foo2()

Thank you all for the help, sorry for the confusion on my part.
Comment: @TheYargonaut when you are learning it's good to see examples of good code and mess around with internals to learn how things work. You have gotten an answer for both of these and you are now asking for an example of how to mess around with internals.  This worries me because it suggests you are not just doing this for educational purposes but trying to accomplish something which **python is designed to not let you mess with**.  An example that modifies the stack directly mid-execution puts your computer at risk to even play with.  I will ask one more time: **What do you actually want to do?**
Comment: I agree with you, I'm just trying to figure out for intrigue how far it can go
Answer: If you are interested in byte code level stuff in python let me introduce dis, compile and CodeType
don't do any of this in production code
You can compile python code (as a string) into a Code object which can then override a functions __code__ property
def foo():
    print('hi there')
code_stuff = compile("print('this is hacked in')", "dummy file", "exec")
foo.__code__ = code_stuff
foo() #prints "this is hacked in"

if you want to modify more than a no inputs no outputs function take a look at the types.CodeType constructor:
>>> import types
>>> help(types.CodeType)
Help on class code in module builtins:

class code(object)
 |  code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,
 |        constants, names, varnames, filename, name, firstlineno,
 |        lnotab[, freevars[, cellvars]])
 |
 |  Create a code object.  Not for the faint of heart.
 |  ...

Which - much like writing assembly code - involves risking seg-faults, crashing the python interpreter or worse.  You know when the only documentation is Not for the faint of heart. the developer was not intending for it to be directly used.
if you want to see what byte code actually executes as you can use dis. which is short for "disassemble"
def foo():
    print('hi there')

import dis
dis.dis(foo)

This is interesting to see how python code actually executes.
I'm not sure exactly what you are trying to do with the stack but I'm fairly certain what ever it is, the developers of python have made sure it's not easy since that is not something you should be touching in python. These types only exist in python for introspection reasons (like seeing what the arguments of a function are at runtime by inspecting it's call signature)
Comment: @JonathanBurk: Nope. Replacing a function's code object won't change the code object for calls already on the stack.
Comment: Also, seconding the point about telling us exactly what you want to do. This question is too vague and broad as it stands.
Comment: Thank you! This is very helpful. Is there any way to modify the execution flow with this method? For example, if we now wish to overwrite main() from foo()
Comment: If you want to screw with a function's internals, this is only the tip of the iceberg, though. There are a lot more fiddly bits, version-specific details, and other things to get right, and especially if you try to construct code objects directly, it's easy to segfault your interpreter.
Comment: Good to know. Is there any way to jump to lines/skip lines by manipulating the stack?
Comment: @TheYargonaut see [my other comment](https://stackoverflow.com/questions/52884144/how-could-i-modify-recompile-an-already-defined-function-during-runtime/52884319#comment92681881_52884144) tell us exactly what you want to do and we can help. Less technical like "manipulate the stack" and more detailed like "I want to abort a function mid execution and fake it to return a specific value"
Comment: @TheYargonaut: Sort of, but with a lot of restrictions on where you can jump, and CPython pretty much only lets debuggers do it. Writing a trace function to gain access to the functionality is yet another can of worms, as is figuring out what the right line numbers are and/or making sure your code object actually has meaningful line numbers.
Answer: If you want to manipulate the definition of foo, it's straightforward to redefine foo much the same way you would assign any other global variable, with a global statement and =:
def foo():
    print('hi there')

def foo2():
    global foo
    def replacement_foo():
        print('hi from over here')
    foo = replacement_foo

def main():
    foo2()
    foo()

main()

It's probably also safe to just def foo(): ... inside foo2 instead of defining replacement_foo and then assigning, but that's officially not permitted, even though the implementation doesn't enforce it.

In the comments, you seem to be very interested in manipulating foo through the stack somehow. The definition of foo doesn't live on the stack, and no call to foo is on the stack during the execution of foo, so the stack is the wrong place to look.
Also, most of Python's stack inspection is read-only. Even if you were to reassign a function's code object, it wouldn't change the code of calls already on the stack. You can't change main's code object to make it not call foo (though you can change foo's code object, and that'll take effect when main calls foo).
Comment: This doesn't modify the original function `foo`, though, it replaces it with a completely unrelated function by reassigning to the global name `foo`. (Which might or might not be what the OP is looking for.)
Comment: @JonathanBurk: Yes. `foo` still isn't on the stack when `foo2` runs, though. You asked about manipulating the definition of `foo`, so I wrote an answer that redefines `foo`.
Comment: That's true, although that does help, I'm wondering if it's possible to replace things in the stack. For example, modifying the current line/place in the execution flow, changing the underlying bytecode of main etc.
Comment: @JonathanBurk: `foo` isn't *on* the stack when `foo2` runs, so I'm not sure why you're talking about the stack. Is your goal to fiddle with the stack? It didn't sound like it from your question.
Comment: Wouldn't main have the execution flow with something like foo2() then foo() then end?
Comment: Yes, I don't think I properly asked the question. Sorry. I am trying to redefine foo by manipulating the stack/frames (I am new to Python, so forgive me if my description is poor)


Using calc() for positioning

Question: I have a relative-positioned div, and want to align it using CSS3's lovely calc(). It's not working.
Fiddle.
Apologies for messy code, just mocking up a comparable design to avoid shoving the more complex code surrounding my actual project in your faces.
For some reason, this is throwing an invalid property value error, and I can't work out why. Is there any workaround?
Answer: It's working on my browser, but anyways try using the prefixed versions just to make sure, -webkit-calc() and -moz-calc()
Comment: *sigh* Thank you so much. Due to computer issues, I'm presently operating off of a Lucid Lynx LiveCD, and apparently only an outdated version of Chromium is supported by it. Vendor prefixing: it's what's for dinner.
Answer: A simple test you can do is:
left: calc(100% + 1px);

if you see it left 100% and just a tiny 1px space.... :D
https://developer.mozilla.org/en-US/docs/Web/CSS/calc (12/2013) says it all:

This is an experimental technology
  Because this technology's specification has not stabilized, check the compatibility table for the proper prefixes to use in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the spec changes.
Comment: BTW for simple positioning use cases it's also possible to combine positioning with margin to avoid `calc()`, e.g.: `left: 100%; margin-left: 1px` will have the same effect as `left: calc(100% + 1px)` ([fiddle](http://jsfiddle.net/XYrK4/2/)), good to keep in mind when old browsers are concerned.

Using calc() for positioning


'Change email' form on custom page

Question: I would basically like to display the form/field that is used for changing the user's email address on a custom page with my own layout and things.
Ideally, I would like to make it so that if Javascript is enabled, the email address would appear as text with a 'Change' link next to it. The link would make a text box appear in place of text so that the user can change the address. Obviously, all this would happen without refreshing the page, and if Javascript is not enabled the email address should appear in the text box immediately like normal. If anybody can provide me with at least some, or all of the code that I need, that'd be so awesome.
Thanks in advance
Answer: If you've enabled the PHP Input Filter, you could add the following into your node/page. The javascipt won't execute if disabled, leaving only the input field :)
<?php
    drupal_add_js('misc/jquery.js', 'core', 'header');
?>

<?php
function userEmail_form() {
    global $user;

    $form['email'] = array(
        '#type' => 'textfield',
        '#default_value' => $user->mail
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit'
    );

    return $form;
}

function userEmail_form_validate(&$form, $form_state) {
    if (!valid_email_address($form_state['values']['email'])) form_set_error('email', 'Invalid Email Address');
}

function userEmail_form_submit(&$form, $form_state) {
    global $user;
    db_query('UPDATE {users} SET `mail` = "%s" WHERE `uid` = %d', $form_state['values']['email'], $user->uid);
    drupal_set_message('Email updated');
}

echo drupal_get_form('userEmail_form');
?>

Comment: Just thinking actually, is it possible to make it so that if the user press enter the form is submitted, and also make it so that there is a 'confirm' link to submit the form, rather than a button that is always there. If possible, I would like the email to changed without the page being refreshed.

'Change email' form on custom page


Can I destructure an event handler object? React

Question: I have an object, called value from Firebase Realtime db in my component. With an onClick button, I want to push the values of the object plus an extra ID (tuid) back to the database. How can I fix it so that I can send 'suid' and 'content' back to the db?
  function sendMessage(event) {
    // console.log("sendMessage -> event", event.target.value); // <--- is an object
    setWriteError(null);
    try {
      db.ref("messages/toDisplay").push({
        suid: event.target.value.uid,         //<---- .uid fails
        content: event.target.value.content,  //<---- .content fails
        timestamp: Date.now(),
        tuid: user.email, // use email as user uid
      });
    } catch (error) {
      setWriteError(error.message);
    }
  }

with this code:
    return (

      {readError ? readError : ""}

      {dashboard.map((value, index) => (

          {value.content}{" "}
          <button))}
            onClick={sendMessage}
            value={value}>     {/* {value.content} with event.target.value works */}
            Accepted
          </button>
          ...
 ))}

where tuid is the currently logged in user; suid is the user IN the object received from FB db.
This is what works
  function sendMessage(event) {
    setWriteError(null);
    try {
      db.ref("messages/toDisplay").push({
        //suid: event.target.value.uid,  <--- problem commented out
        content: event.target.value,   // so no problem
        timestamp: Date.now(),
        tuid: user.email,
      });
    } catch (error) {
      setWriteError(error.message);
    }
  }

with this button

      {readError ? readError : ""}

      {dashboard.map((value, index) => (

          {value.content}{" "}
          <button))}
            onClick={sendMessage}
            value={value.content}>   {/*no problem here*/}
            Accepted
          </button>
          ...
 ))}

Comment: I'm not sure I understand how your title relates to your post?
Comment: I also don't know what this question means: "How can I fix it so that I can send suid and content back to the db?"
Comment: Oops! I tried to be as clear as I could given my limited coding experience;  however, thankfully @DrewReece got what I meant so I was able to try his solutions.
Answer: React uses Synthetic events that are (usually very quickly) nullified and returned back to the event pool. As such, when you enqueue these event properties into a structure that is likely later processed, those values have been nullified by then.
Event Pooling

The SyntheticEvent is pooled. This means that the SyntheticEvent
object will be reused and all properties will be nullified after the
event callback has been invoked. This is for performance reasons. As
such, you cannot access the event in an asynchronous way.

You can either save a local copy of the event properties you need, or try to persist the event object.
Solution 1 - Destructure the Event Properties (Recommended)
function sendMessage(event) {
  const { value: { content, uid: suid } } = event.target;

  setWriteError(null);
  try {
    db.ref("messages/toDisplay").push({
      suid,
      content,
      timestamp: Date.now(),
      tuid: user.email,
    });
  } catch (error) {
    setWriteError(error.message);
  }
}

Solution 2 - Persist the event object

Note:
If you want to access the event properties in an asynchronous way, you
should call event.persist() on the event, which will remove the
synthetic event from the pool and allow references to the event to be
retained by user code.

function sendMessage(event) {
  event.persist();

  setWriteError(null);
  try {
    db.ref("messages/toDisplay").push({
      suid: event.target.value.uid,
      content: event.target.value.content,
      timestamp: Date.now(),
      tuid: user.email,
    });
  } catch (error) {
    setWriteError(error.message);
  }
}

Comment: Thank you very much for your reply @drew! I tried both and sadly they did not work. I wanted the destructuring to work.
Comment: @AngelD Can you be more specific about what isn't working? Can you validate the destructured values from the event object exist? I see no reason for the destructuring to fail other than if you are running an older transpiler. Are there any errors?
Comment: I got this output in the console      "__reactEventHandlers$...": Object { error: "Reference.push failed: first argument contains undefined in property 'messages.toDisplay.suid'", children: "test message" }  "
Comment: When move suid to last place in the order of things, I got `previousElementSibling: span
"__reactEventHandlers$.....": {…}

children: "test message "

error: "Reference.push failed: first argument contains undefined in property 'messages.toDisplay.content'"

: Object { … }`
Comment: What is `db.ref("messages/toDisplay")` in the `sendMessage` handler?
Comment: I appreciate the help that you've given me @drew. It might be a Firebase Realtime database quirk and that's it. I might have to go with the basic version that works. Thank you for the explanation.
Comment: It adds the attributes of the message on a new node in Firebase. ie. root > messages > toDisplay. Under normal circumstances, I would get a new node with message UID, and under that appears content, timestamp and the uid of the current user (that I've called tuid).


is the case of scala function parameters relevant?

Question: regarding the following scala code, functions m2a and m2b apparently differ only by the case of the parameter, ie abc vs Abc. This seems to make some difference in the result as per example below. When running it with a recent 2.8 compiler, it results in the following (I would have expected all true). Any insights would be appreciated.
m1=true
m2a=true
m2b=false
m3=true

code
package sample

import scala.xml._

object ParamTest extends Application {

  def m1(n:Node, abc:String):Boolean = {
    n == <id>{Text(abc)}</id>
  }

  def m2a(n:Node, Abc:String):Boolean = n match {
    case <id>{Text(Abc)}</id> => true
    case _ => false;
  }

  // why does this one not work?
  def m2b(n:Node, abc:String):Boolean = n match {
    case <id>{Text(abc)}</id> => true
    case _ => false;
  }

  def m3(n:Node, abc:String):Boolean = n match {
    case Elem(_,"id",_,_, c @_ *) => {
      c contains Text(abc)
    }
  }

  def runner(n:Node, f:(Node, String)=>Boolean):Boolean = {
    f(n, "x") && !f(n, "y") && !f(n, "");
  }

  val x = <id>x</id>

  println("m1="+runner(x, m1));
  println("m2a="+runner(x, m2a));
  println("m2b="+runner(x, m2b));
  println("m3="+runner(x, m3));
}

Answer: The trick here is in how Scala handles variables in case expressions.  Lowercase variables in case expressions are taken by the compiler to introduce new variables, which are then pattern matched against.  Thus in method m2b, the method parameter "abc" is actually unused.  The case expression variable "abc" will match any string, since it is not otherwise constrained.  Thus "y" is successfully matched in the first case of m2b.  Uppercase variables in case expressions do not introduce new variables, so in m2a the match behaves as you expected.
The easiest way to match against the value of a lowercase variable is to wrap it in backquotes.  Thus
def m2b(n:Node, abc:String):Boolean = n match {
    case <id>{Text(`abc`)}</id> => true
    case _ => false;
  }

will give you the results you expected.
Answer: In pattern matching, identifiers in the pattern that start with a lower-case letter are taken to be free pattern variables that can be bound to values in the target of the match. Those that start with upper-case letters are so-called stable identifiers and must already be bound in the match expression's context and the value of that binding must equal the subexpression of the match target at the point in that value corresponding to that stable identifier's placement within the pattern expression.
Additionally, and relevant in this particular example, pattern variables (the lower-case names) will shadow any existing binding of the same name that is in effect in the context of the match expression (including the expression supplying the match target value).


design a user command and multiple inputs

Question: I am a JAVA beginner, and I've done some research. It turned out there is no such a way to deal with this problem. I'm assigned to design a prompt command with multiple data inputs, with only one scanner object.
Now, I've already achieved the following:

Set an array for saving the NimPlayer object.
Set the NimPlayer class for creating a unique NimPlayer object.
Set the counter, used as an index.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);

System.out.print('$');
String input = in.next();

// initialize an array
NimPlayer [] playerList = new NimPlayer[10];

// create a position in the array
int addUserCount = 0;
if (input.equals("addplayer")) {
    String userName = in.next();
    String familyName = in.next();
    String givenName = in.next();

    addUserCount +=1;
    playerList[addUserCount] = new NimPlayer(userName, familyName, givenName);

}

public class NimPlayer {
String userName;
String familyName;
String givenName;

public NimPlayer(String userName,String surName, String givenName) {
    this.userName = userName;
    this.familyName = surName;
    this.givenName = givenName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public void setFamilyName(String familyName) {
    this.familyName = familyName;
}
public void setGivenName(String givenName) {
    this.givenName = givenName;
}
public String getUserName() {
    return userName;
}
public String getfamilyName() {
    return familyName;
}
public String getGivenName() {
    return givenName;
}
}

the goal is to design like this:
addplayer userName,familyName,givenName

So, that's why I use next() to identify the first word, and space is the default delimiter.
I am not sure how to do next. What should I do to add a feature that separates the inputs using ",".
Any help is appreciated.
Comment: Have a look at the [javadoc for `Scanner`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html).  The [`useDelimiter`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useDelimiter-java.lang.String-) method might be what you're looking for.  Or it might be easier to read the rest of the line with `nextLine()` and then break the data apart using `String` method [`split`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-)
Answer: You can read lines with Scanner.nextLine(). Here is an example how you can type "username, surname, givenname" in one line and get splitted by String.split(",").
public static void main(String[] args) {
    Scanner s = new Scanner(System.in);

    String line = s.nextLine();
    String[] splittedLine = line.split(",");

    for(int i = 0; i < splittedLine.length; i++) {
        System.out.printf("splitted line: %d. %s \n", i, splittedLine[i].trim());
    }
}

Input:
name, surename, username

Output:
splitted line: 1. name
splitted line: 2. surename
splitted line: 3. username

Comment: Thanks for pointing out and your kind patience. I missed the split function. Now I successfully save the name in the array.


Por que o Entity Framework está gerando um novo registro no banco de dados?

Question: Seguinte, estou trabalhando em um novo projeto asp.net-mvc, e tenho 3 classes.
public class Anuncio
{
    public int AnuncioID { get; set; }

    public string UsuarioID { get; set; }

    [Required]
    [MaxLength(255)]
    [Display(Name="Título")]
    public string Titulo { get; set; }

    [Required]
    [MaxLength(2000)]
    [Display(Name="Descrição")]
    public string Descricao { get; set; }

    [Display(Name="Data do anúncio")]
    public DateTime DataAnunciado { get; set; }

    public Contato Contato { get; set; }

    [Display(Name="Endereço")]
    public Endereco Endereco { get; set; }

    public TipoCategoria Categoria { get; set; }

    public ICollection<Imagem> Imagens { get; set; }

}

public class Endereco
{
    [Key]
    public int EnderecoID { get; set; }

    [Required]
    public Estado Estado { get; set; }

    [Required,Display(Name="Município")]
    public Municipio Municipio { get; set; }

    public string Bairro { get; set; }

    public string Rua { get; set; }

    [Display(Name="Número")]
    public string Numero { get; set; }

    public string Cep { get; set; }
    public string Complemento { get; set; }
}

public class Estado
{
    [Key]
    public int EstadoID { get; set; }
    public string Nome { get; set; }
    public string Sigla { get; set; }
}

Então, como podem notar, um Anuncio possui 1 Endereco, que por sua vez possui 1 Estado.
Depois de executar a aplicação, incluo os estados, então por exemplo, tenho um Estado com EstadoID = 1, Nome = Paraná, Sigla = PR.
Quando vou cadastrar um novo Anuncio, mesmo definindo a instância do Estado que está no banco no Anuncio, por exemplo:
public ActionResult NovoAnuncio(Anuncio anuncio)
{
    if (ModelState.IsValid)
    {
        Estado estado = db.Estado.Find(1);
        anuncio.Endereco.Estado = estado;

        db.Anuncio.Add(anuncio);
        db.SaveChanges();

        return RedirectToAction("Index", "Home");
    }

    return View(anuncio);
}

Ele CRIA outro registro no BD.

Por que ele não referencia o Estado já registrado no BD?
Comment: O Objeto "Endereco" esta sendo populado da onde? pelo que eu estou vendo o método só recebe "Anuncio", você precisa de uma instancia de "Endereco" pra poder popular o atributo "Estado".
Comment: Verifique como está a instância de Endereço no Anúncio, se também não está inserindo um novo.
Comment: Entao senhores, esse Endereco, é sempre um novo, o usuario cadastra o endereco na View, entao vem um objeto Anuncio, ja com Endereco instanciado e populado, eu só seto o estado pra entro dele.
Answer: Conforme respondi nesta outra questão você está carregando o registro duas vezes no contexto e o Entity Framework entende que são dois registros diferentes. No seu caso, isso se aplica ao Endereco que não possui uma referência correta a Estado.
Modifique o seguinte para evitar isso:
var estado = db.Estado.Find(1);
anuncio.Endereco.EstadoId = estado.EstadoId;

EDIT
Conforme comentários, faltam duas propriedades para que o Entity Framework trabalhe corretamente:
Models\Endereco.cs
public class Endereco
{
    ...
    public int EstadoID { get; set; }
    ...
}

Models\Anuncio.cs
public class Anuncio
{
    ...
    public int EnderecoID { get; set; }
    ...
}

Comment: De forma alguma. É assim que o Entity Framework trabalha, inclusive todos os exemplos dos tutoriais de ASP.NET MVC trabalham desta forma. Fique à vontade para buscar uma solução alternativa.
Comment: @Ukyron se você não está incluindo uma propriedade que acessa a foreign key na sua classe você apenas está perdendo a oportunidade de acessá-la diretamente, pois internamente o EF cria a FK. Inclusive se tivesse a propriedade você não precisaria nem buscar o `Estado` como o @CiganoMorrisonMendez demonstrou, em vez de dar `Find(1)`, já que possui a PK poderia simplesmente setar `anuncio.Endereco.EstadoId = 1;` economizando uma query no DB.
Comment: Você precisa inserir a `property` referente ao Id do `Estado` no `Endereco` para que o Entity Framework não se perca ao manejar seu objeto. Possivelmente tendo esta coluna seu código da pergunta funcione normalmente.
Comment: opa, mas meu Endereco nao possui um atributo "EstadoId", quem tem esse atributo é meu objeto Estado, meu Endereco só tem atributo Estado, como fica entao?
Comment: mas aí acaba com varios principios da programação orientada a objetos, vou continuar procurando uma solução, caso nao encontre serei obrigado a fazer isso =/
Comment: bom, pelo jeito não tem como ser purista, pelo o que pesquisei tem q ser assim pra estes casos, vou ter que colocar o atributo no objeto, vou dar como resposta correta, só edite a resposta, solicitando que eu coloque o atributo EstadoID no Endereco, e EnderecoID no Anuncio.
Comment: @Ukyron Ok, editado. Obrigado!
Comment: @Ukyron, assim como você, também discordei da solução fraca que o EF usa para vincular corretamente suas FK no EF. Esse comportamento que voce e eu esperava de associar a classe existente na base ocorre naturalmente no NHibernate. A principio o ORM deveria fazer toda essa parte, mas alguns falham em fazer **todo** o trabalho...


jUnit loads another Class compared to WebApp runtime

Question: I'm working on a feature, where a Cron Job will trigger a connection through javax.mail, and scan all the incoming mails of a certain IMAP account.
It's a part of a Liferay Portlet, built with JSF-2 and Maven, and deployed on a Tomcat server.
I've built a jUnit Test that executes this scenario successfully, running the exact same function that would be called from the the Cron Job. I did this test by executing the maven build package target, and my Maven is using the same JVM with my Tomcat.
But after deploying the WebApp in the server and the Cron Trigger kicks in, I'm getting this error:
    org.quartz.SchedulerException: Job threw an unhandled exception. [See nested exception: java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger]
    at org.quartz.core.JobRunShell.run(JobRunShell.java:224)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)
Caused by: java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
    at javax.mail.Session.initLogger(Session.java:226)
    at javax.mail.Session.<init>(Session.java:210)
    at javax.mail.Session.getDefaultInstance(Session.java:321)
    at javax.mail.Session.getDefaultInstance(Session.java:361)

So I guess that under the Tomcat Runtime or Servlet Context or the quartz flow or whatever, there is a different resolution of com/sun/mail/util/MailLogger, compared to the resolution of jUnit.
Why is this happening, and how can I make sure I'm loading the correct Class  in all scenarios?
Comment: Looks like you have multiple versions of JavaMail in you classpath.  One that is Javamail 1.4.5 or older and one that is JavaMail 1.4.6 or newer.
Comment: @jmehrens You're right, my tomcat was using an older version. However I tried using the exact same version, and there was still a problem. Check my answer for more.
Comment: Is there a new error message?
Comment: not sure, If this is important for you I can try reproducing this in the next days.
Answer: By tracing the error, I found out that a different version of javax.mail was loaded from tomcat/ext/lib, and overriding mine, when the server was running and the flow was initiated in Server Context.
Finally, I managed to deal with this problem, by changing my javax.mail-api dependency from
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.5.4</version>
        </dependency>

to
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.4.4</version>
        <scope>provided</scope>
    </dependency>

I switched to an older javax.mail-api version, compatible with the server's one, and I'm also using the library that is provided in the runtime


Samantha age 40, buys a 20-year certain-and-life annuity due with a single premium. Find the reserve 5 years after issue.

Question:
Samantha age 40, buys a 20-year certain-and-life annuity due with a
  single premium. The annuity makes annual payments of $2,000$. If $i = 6\%$
  and you are given the following table, find the reserve 5 years after
  issue. (hint: the benefit is an annuity)
$l_{40} = 39,143.64$
$l_{45} = 23,582.45$
$l_{60} = 400.49$
$\ddot{a}_{40} = 5.90503$
$\ddot{a}_{45} = 4.69803$
$\ddot{a}_{60} = 2.12522$

So far I have: (sorry, some of the notation is difficult to create)
Premium (per 1 dollar) = $\dfrac{A_{40}}{\ddot{a}_{40:\overline{10}|}} = \dfrac{1 - d\ddot{a}_{40}}{\ddot{a}_{40:\overline{10}|}} = \dfrac{1 - (0.06/1.06)(5.90503)}{ ? }$
** I can't seem to figure out what $\ddot{a}_{40:\overline{10}|}$ is?
Furthermore, I know how to finally finish off the question as:
$2000 {}_5 ^{20}$$V_{40}= (2000)(1 - d\ddot{a}_{45}) - (2000)(\text{Premium})(\ddot{a}_{45:\overline{5}|})$
Any help would be greatly appreciated!!
Answer: The actuarial present value of the benefits is
$$2000\ddot{a}_{\overline{40:\overline{20}|}} = 2000(\ddot{a}_{\overline{20}|}+{}_{20|}\ddot{a}_{40}) = 2000(\ddot{a}_{\overline{20}|}+\ddot{a}_{60}\cdot {}_{20}E_{40})$$
(do you see why?) and assuming the equivalence principle, note that you have a single premium, so letting $P$ be the single premium,
$$P = 2000(\ddot{a}_{\overline{20}|}+\ddot{a}_{60}\cdot {}_{20}E_{40})\text{.}$$
I'm assuming you know how to compute these. You should know $\ddot{a}_{\overline{20}|}$ from FM.
The formula you have for the premium is false, since 1) we're not working with a whole-life insurance as the benefit, but rather, an annuity; 2) we only have ONE premium (so $\ddot{a}_{40:\overline{10}|}$ is unnecessary).
The reserve (I like using the simple notation ${}_{5}V$ for this) is
$${}_{5}V = 2000\ddot{a}_{\overline{15}|}+{}_{15|}\ddot{a}_{45}=2000\ddot{a}_{\overline{15}|}+\ddot{a}_{60}\cdot {}_{15}E_{45}\text{.}$$
Note here that NO PREMIUM is included. (Why?)
Comment: is it because there is only one single premium? Also, I don't have what a¨15  is in the last equation
Comment: @queence There is no premium after time 5. Note that under the prospective method for reserves, we're looking at FUTURE premiums which will be subtracted. The $\ddot{a}_{15}$ is a typo. (See edit.)
Comment: yes right, that makes sense. alright thanks a lot!


Polynomial whose roots are not integers but almost so

Question: Let $\varepsilon \in (0,\frac{1}{2})$. Say that a real number $x$ is an
$\varepsilon$-pseudointeger if it is not an integer but at distance at
most $\varepsilon$ from some integer (thus $|x-i|\leq \varepsilon, x\neq i$
for some integer $i$).
Is it true that for any $d\geq 2$ and $\varepsilon$, there is a monic polynomial
of degree $d$ with integer coefficients, all of whose roots
are simple, real and $\varepsilon$-pseudointegers ?
When $d=2$, for example, $X^2-(n^2+1)$ where
$n=\lceil \frac{1}{2\varepsilon} \rceil$ is an answer.
I'm looking for an explicit solution rather than a non-constructive proof.
Answer: Yes, it seems to be true.
If $d = 2k$, then example can be constructed using idea, similar to one, used in your example, meaning that polynomial will look like $\prod_{i = 1}^{k}(X^2 - i^2(n^2 + 1))$. It's clearly monic, has $d$ distinct real roots and by choosing $n = \lceil\frac{d}{2ε}\rceil$ we can account for increase in initial difference $(\sqrt{n^2 + 1} - n)$ by a factor of $d$.
If $d$ is odd (particularly $3 + 2k$), example will be a little harder to find. Still, let our needed polynomial be $(P(X) + 1)*\prod_{i = 1}^{k}(X^2 - i^2(n^2 + 1))$ where $P(X)$ is of the form $X(X^2 - p^2)$. $P(.)$ has 3 integer roots $\{-p, 0, p\}$ but what is interesting is values of $P'(.)$ corresponding to those roots: $2p^2, -p^2$ and $2p^2$ respectively. This observation gives an idea that by choosing appropriate large enough $p$ we will not change roots much when taking $P(.) + 1$ instead of $P(.)$.
Now to a question of actually finding $p$ needed depending on $ε$: it seems obvious that it exists and I might try to present particulars, but for now it seems that they would be relatively lengthy and not very exciting per se.
Answer: I interpret "all roots are simple, real and $\epsilon$-pseudointegers" as "all roots are simple, real but not integer, and $\epsilon$-pseudointegers"; otherwise $ (X-1)(X-2) \cdots (X-d) $ is a trivial solution.
The answer is yes if $d$ is even.
Your idea of obtaining solutions of the form $ \sqrt{n^2 +1} $ is very good and can be extended quite easily. Indeed, all the numbers of the form  $ \sqrt{N^2 +1} $ are closer to their respective integer $N$ than $ \sqrt{n^2 +1} $ is to $n$, if $N > n$.
Rigorously,
$$ N>n \implies \sqrt{N^2 +1} - N < \sqrt{n^2 + 1} - n $$
a fact that is not hard to prove.
Therefore
$$ (X^2 - (N_1^2 + 1)) \cdot (X^2 - (N_2^2 + 1)) \cdots (X^2 - (N_d^2 + 1)) $$
is a polynomial of degree $2d$, with $N_1, N_2, \dots, N_d$ distinct integers, and $N_i \geq \lceil {\frac{1}{2 \epsilon}} \rceil, \forall i \in \{ 1,2, \dots, k \} $, whose solutions are distinct, real but not integers, and $\epsilon$-pseudointegers.
Comment: A good way to extend the original solution.


SQL Server scrtipting loses original format of a compiled script

Question: Has anyone experienced this and come up with a solution?
SQL Server 2016 Enterprise on Windows Server 2012R2
Using the scripting tool from SSMS and it seems something has changed recently. The output from the SQL Server scripting engine does not resemble the way I have scripted stored procedures, for example, any longer; not even close.
I have used these tools for a long time and while there are some nuances this has an effect on my coding conventions and source code control.
Output from SQL server scripting - parameters are put on one line, indenting is lost, joins are split on multiple lines, case is changed. :
<code>CREATE PROCEDURE [dbo].[GetAdverseReaction]
@ID INT
AS
SELECT arc.CategoryName,
       ar.*
FROM   AdverseReaction AS ar
       INNER JOIN
       AdverseReactionCategory AS arc
       ON arc.ID = ar.CategoryID
WHERE  ar.ID = @ID;

-- input --
CREATE PROCEDURE GetAdverseReaction
(
    @ID int
)
AS
    SELECT arc.CategoryName, ar.*
        FROM AdverseReaction ar
            INNER JOIN AdverseReactionCategory arc ON arc.ID = ar.CategoryID
        WHERE ar.ID = @ID

GO
</code>
See answer below and read more here: Parameterization for Always Encrypted
Comment: Could you try to elaborate here please? I don't understand what you're trying to ask. Try to give examples of the behaviour you're seeing, when it's happening, and explain why it isn't desired.
Comment: Neither SSMS or SQL Server is doing that. SQL Server stores the DDL **exactly** as you wrote it. If it's changing after you've deployed it, then that is being caused by a different tool, or someone else. Take a look at this [DB<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=31e961fb1f579af0e75bacd63fef7794), for example, which shows exactly how the DDL is stored.
Comment: No it is definitely changed when compiled; this is not happening on SQL Server Standard 2016
Comment: I've used SQL Server 2008-SQL Server 2019 CTP. I have never seen this behaviour whatever tool I use to deploy to SQL Server; `sqlcmd`, SSMS, Azure Data Studio, Agent, Dynamic SQL, you name it. Unles you can provide a way for us to replicate this, I very much will still say that this an environment issue. *Maybe* someone's got a DDL trigger on the database that changes the formatted (and would be an insane trigger)... Don't know, but SSMS, nor SQL Server, will change the format a of query parsed.
Comment: Not happening on SQL Server developer either so that's a clue. Thanks for your help. I have to leave this alone until later. I will look into that DDL trigger thing.
Comment: Please see my answer: it's related to the query options and came about because we are using the new "always encrypted" scenario and thus checked this box ... read more at link provided
Comment: Please see that "First thing to note is that SSMS has rewritten the query  ..." and apparently does other things too based on my experience. You can reproduce this problem by checking that box in the "Query Options" advanced tab
Answer: I found in SSMS "Query Options" when the checkbox "Enable Parameterization for Always Encrypted" the script is reformatted as described, before it is executed. I unchecked that and things returned to normal. I am guessing this is specific to this version of SSMS. i.e. >= 17


NIC light is turned off after boot on Redhat 4.6 server

Question: I have a 2950 blade server setup with Red Hat 4.6 installed. I cannot get the NIC to work properly after reinstalling Linux. I activated the NIC, but the NIC light will not turn on when I plug the network cable into the hub. The status light on the hub will not turn on either. If I run ifconfig, the NIC status is UP. Also I can ping the IP address that I assign to the Linux machine, but I can't ping anything else that is plugged into the hub. When I reboot the system, the NIC light will stay on until the system fully boots and then it will turn off again. Is there something else that I need to do to get the NIC working? It appears to be disabled even though ifconfig says that it is UP. Maybe I need to configure something within the blade server (iDRAC)?
Comment: are you connected to a cisco switch?
Comment: The server is connected to a Hawking Technology 10/100 16-Port Switch (HFS16T).
Comment: I installed Red Hat Enterprise 5.3 and I do not experience the NIC problem that I get with 4.6.
Answer: Have you tried plugging the cable into the other NIC on the 2950? The order in which the kernel discovers the NICs on most Dell servers changed at some point - can't remember exactly which version of the kernel.
Comment: Between 4 and 5 on redhat systems the detect order seems to have changed.


What distribution is this? (time until task completion and submission)

Question: I am looking at submission data—the length of time it takes for someone to complete a flow which involves submitting an item of content. I am getting the following distributions. I have two quick questions:

What best describes the frequency distribution? I am thinking lognormal but am not sure.
Is the mean the best statistic to use, e.g., 'mean submission time is hh:mm'? Is there a better, e.g., median or % of submissions below hh:mm?
Comment: If you want to be able to see the ways in which a density function deviates from lognormal, you might plot log(f) vs log(x) (which should be quadratic if the original density were lognormal). On the other hand, if you have *data*, a normal QQ plot of log(X) would be a good approach.
Answer:
In the real world, there is no distribution that's going to define this perfectly; parametric distributions are, at best, idealized descriptions of how the data is really distributed. That being said, it appears that something like a lognormal or wiebull distribution may be a reasonable description of the process you're observing. However, if dynamics change in the next data collection, this may no longer be the case. Summary: log normal or weibull is probably appropriate for this dataset.
I would be a little hesitant to use the mean, as it is heavily influenced by extreme values, for which this dataset has more than a few. The median might be a more important measure. But much more importantly, you want the measure that really answers your question of interest!
Comment: Two reasonable approaches: take a log transformation of the data and then perform a t-test. If the data is approximately log-normal, this will have the most power. Alternatively, you could use the Wilcoxon Rank Sum test and have pretty good power, regardless of whether it's approximately log-normal or not.
Comment: Agree on choosing a statistic that is aligned to what is needed - what I would like is to make improvements in the process and use the statistic as a basis of (a) comparison in time to track improvement (b) compare processes between different flows (which have same distro). Any ideas on pros cons (you mentioned median vs mean above)?


"99 bottle of beer on the wall" code not working pure js. if statement and while loop

Question: Hi I have made a 99 bottles of beer song but my code does not seem to be working im not to sure and I cannot figure it out. I really need some help to see where I am going wrong or some one to show my where I am going wrong. I want to if statements or if there is a different way to do it but I need the set-up of how it is im not to sure how to fix it please help.
Thanks in advance.
This is my JavaScript.
var bottles = 99
bottle = "bottles";
text = "";

var output = document.getElementById('output');
while (bottles > 0) {

    if (bottles == 1) {
    bottle = "bottle";
    text = "
" + bottles + " " + bottle + " of beer on the wall, " + bottles + " " + bottle + " of beer.
";
    bottles--;

        output.innerHTML += text;
    }

    if (bottles == 0) {
    bottles = "no more";
    text += "Take one down and pass it around, " + bottles + " bottles of beer on the wall.
"

    output.innerHTML += text;
}

output.innerHTML += "
 No more bottles of beer on the wall, no more bottles of beer.
 Go to the store and buy some more, 99 bottles of beer on the wall.
"

This is my HTML.
<title>My Title</title>

99 Bottles of Beer Song

I also have a fiddle.
http://jsfiddle.net/Matt1990/1wg16qr5/46/
Comment: Can you provide a jsfiddle?
Comment: Where to start?..... There is no event starting your app. Syntax errors in your variable declaration ...
Answer: Your code is full of errors.
To debug client-side code like JavaScript you may use the developer tools in Chrome/Firefox by pressing CTRL + SHIFT + i. It shows syntax errors like the one in the variable declaration part.
For further reading see the Chrome DevTools Overview. Chrome Dev tools are by far better than Firefox/IE/whatever (IMHO)

Here is the working code. Please compare by yourself.

var bottles = 99,
    bottle = "bottles",
    text = "",
    output = document.getElementById('output');
while (bottles > 0) {
    if (bottles == 1) {
        bottle = "bottle";
    }

    text += bottles + " ";
    text += bottle + " of beer on the wall, ";
    text += bottles + " " + bottle + " of beer.
";

    bottles--;
    text += "Take one down and pass it around, ";
    text += + bottles + " bottles of beer on the wall.
"

    if (bottles == 0) {
        bottles = "no more";
    }
    output.innerHTML += text;
  text = '';
}

output.innerHTML += " No more bottles of beer on the wall, no more bottles of beer.  Go to the store and buy some more, 99 bottles of beer on the wall.";

99 Bottles of Beer Song

Answer: Starting Condition

We start with 99 bottles
Since both 99 and 98 are plural, both this round and next round are set to plural

Iteration
Everytime we start a new round, we need to check if the current (and next) num is plural or singular
Stop Cases
The while loop will run until num = 0. We have two special cases:

num === 1: this round is singular, next round should be no bottles of juice
num === 0: this round is no bottles of juice, next round should finish the song with Go to the store and buy some more, 99 bottles of juice on the wall. like the original song.

singBottles(15, 'juice');

function singBottles(givenNum, drinkType) {
  let num = givenNum;

  while (num >= 0) {
    const bottlesFirstLine = num === 0 ?
      `no more bottles` :
      `${ num } ${ getPluralState(num) }`;

    const bottlesSecondLine = num - 1 > 0 ?
      `${ num - 1 } ${ getPluralState(num - 1) }` :
      `no more bottles`;

    const firstLine = `${ bottlesFirstLine } of ${ drinkType } on the wall! ${ bottlesFirstLine } of ${ drinkType }!`;

    const secondLine = num - 1 >= 0 ? `Take one down, pass it around... ${ bottlesSecondLine } of ${ drinkType } on the wall!` :
      `Go to the store and buy some more, ${ givenNum } ${ getPluralState(givenNum) } of ${ drinkType } on the wall.`;

    console.log(`${ firstLine }\n${ secondLine }\n`);

    num--;
  }
}

function getPluralState(num) {
  return num === 1 ? 'bottle' : 'bottles';
}
Answer: There are syntax errors - and logical errors:
var bottles = 99
bottle = "bottles";
text = "";

var output = document.getElementById('output');
while (bottles >= 0) {

    if (bottles == 1) {
         bottle = "bottle";
    }

    // for all > 0
    text = "
" + bottles + " " + bottle + " of beer on the wall, " + bottles +
                           " " + bottle + " of beer.
";

    bottles--;

    if (bottles == 0) {
        bottles = "no more";
        text += "Take one down and pass it around, " +
                    bottles + " bottles of beer on the wall.
"; // ; missing
    } // } missing

    output.innerHTML += text; // needs to be done always!

}

output.innerHTML += "
 No more bottles of beer on the wall, no more bottles of beer.
 Go to the store and buy some more, 99 bottles of beer on the wall.
"

Fiddle here
Comment: `bottles--;` needs to be moved out of the `if` block
Comment: `bottle` is being defined after it's used. Move `if (bottles == 1){...}` before `text = ...`
Comment: @wumm No. Its define before the loop.
Comment: @AxelAmthor Yes, that's correct. But what's the purpose of that if this way? The variable will never be used again after it's set in this if. The if executes when `bottles` is 1. After the if `bottles` is decremented to 0. The while loop is no longer executed the variable isn't getting used.
Comment: what do i need to move and fix
Answer: You missed some parenthesis
var bottles = 99; //You need to declare each var like this var x = "x"; var y = "y"
var bottle = "bottles"; // or you can declare it like this var x = "x", y ="y"
var text = "";

var output = document.getElementById('output');
while (bottles > 0) {

    if (bottles == 1) {
    bottle = "bottle";
    }//Missed Parenthesis
    text = "
" + bottles + " " + bottle + " of beer on the wall, " + bottles + " " + bottle + " of beer.
";

    if (bottles == 0) {
    bottles = "no more";
    text += "Take one down and pass it around, " + bottles + " bottles of beer on the wall.
"
    }
    bottles--;//The decreasment is always at the end
    output.innerHTML += text;
}//Missed parenthesis

output.innerHTML += "
 No more bottles of beer on the wall, no more bottles of beer.
 Go to the store and buy some more, 99 bottles of beer on the wall.
"

http://jsfiddle.net/1wg16qr5/49/
Answer: var num = 99;
var bottles = " bottles";
var bottlesWillChange = " bottles"

while (num > 0) {

    if (num === 2) { bottlesWillChange = " bottle"; }
    if (num === 1) { bottles = " bottle"; bottlesWillChange = " bottles"; }

    console.log(num + bottles + " of juice on the wall! " + num + bottles + " of juice! Take one down, pass it around... " + (num - 1) + bottlesWillChange +" of juice on the wall!")

    num--
}

Explanation: First we create 3 variables: num, bottles, bottlesWillChange. In the second step we use a while loop with condition num > 0. Main part: if num === 2, we change value bottlesWillChange to "bottle", because in a part of our song when bottles equal 2, in last part of this string we should use "bottle". Next if statement work only if, our num === 1, we change first and second values of bottles variable to "bottle", because it's single and bottlesWillChange variable value to "bottles".
Comment: @Xcoder, look, first we create 3 variables:`num`, `bottles`, `bottlesWillChange`. In the second step we declarate while loop with condition `num > 0`.

Main part, `if num === 2`, we change value `bottlesWillChange` to "bottle", because in a part of our song when bottles equal 2, in last part of this string we should use "bottle". Next if statement work only if, our num `=== 1`, we change first and second values of `bottles` variable to "bottle", because it's single and `bottlesWiillchange` variable value to "bottles". I hope it's clear.
[when whe need change var](http://prntscr.com/ln5mru)


Unable to get devices using AVCaptureDevice

Question: I've managed to find some code that would give me access to the devices of a phone (such as the camera). The issue is that when I compile the code (and I'm printing the different devices) using Xcode, I get an empty array.
Here is what I wrote:
import UIKit
import AVFoundation

class ViewController: UIViewController {

  let captureSession = AVCaptureSession()
  var previewLayer : AVCaptureVideoPreviewLayer?

  // If we find a device we'll store it here for later us
  var captureDevice : AVCaptureDevice?

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    captureSession.sessionPreset = AVCaptureSessionPresetHigh

    let devices = AVCaptureDevice.devices()
    println(devices)
    // Loop through all the capture devices on this phone
    for (device in devices) {
        // Make sure this particular device supports video
        if (device.hasMediaType(AVMediaTypeVideo)) {
         // Finally check the position and confirm we've got the back camera
            if(device.position == AVCaptureDevicePosition.Back) {
                captureDevice = device as? AVCaptureDevice
                if captureDevice != nil {
                    println("Capture device found")
                    beginSession()
                }
            }
        }
      }

    }

    func beginSession() {

      var err : NSError? = nil
      captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))

      if err != nil {
          println("error: \(err?.localizedDescription)")
      }

      previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
      self.view.layer.addSublayer(previewLayer)
      previewLayer?.frame = self.view.layer.frame

      captureSession.startRunning()

    }

  }

Do you have any ideas as to why I am getting an empty array?
Comment: Are you trying it on a device?
Answer: If you're only running it in the simulator, the array will always be empty because it has no physical hardware to choose from. In fact, if you try to access physical hardware inside the Simulator, it will crash. If you plug a device in and still get an empty array, let me know.
Comment: This is absolutely the correct answer.. Who in the world downvoted this??
Comment: Yes I am because the code that was posted is very similar to what is in Apple's docs, and a common reason to not find abolutely _zero_ `AVCaptureDevices` is because it's being run in the simulator. Here are the docs with code like OP's: https://developer.apple.com/library/prerelease/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html
Answer: first check the current status of the authorization
AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)

more detail you can read this article
Answer: Check the current Status of Authorization for Swift 4
 AVCaptureDevice.authorizationStatus(for: AVMediaType.video)

Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. [How do I write a good answer? ](https://stackoverflow.com/help/how-to-answer)


Regression Gaussian Estimates instead of points

Question: I am using a support vector regression is order to get estimates of a variable y.
I want to receive a probability distribution of my estimates and not just point estimates.
I want to predict Gaussian Distributions for every point where the mean should be my point and I will also give a variance.
What I am thinking in order to avoid to use methods like Gaussian Processes or Probabilistic SVM is to use a history of N windows and to use the error as variance for my new estimates.
For example the std of the error of the last N windows is 0.5.
Then the estimate if my prediction is 5 is N(5,0.5).
Is this approach right?
Answer: Support vector regression maximizes the margin containing the points, up to slack. The objective function is thus not a probabilistic one, and anything tailored on top will not give you optimal results.
SVMs are not meant to provide this. The already mentioned Gaussian processes excel at this. Neural networks can be used if a special loss function is chosen.


How do you resolve HTTP Error 503. The service is unavailable on IIS7?

Question: I'm getting a 503 error when trying to access the localhost web site on my Windows 7 machine. When I look in the event log I'm getting a load of errors along the lies of:
<code>Windows cannot copy file \\?\C:\Users\Default\{979ea7af-5041-4710-838e-f2a62d4ddad2}\symimv.cat to location \\?\C:\Users\TEMP.IIS APPPOOL.001\{979ea7af-5041-4710-838e-f2a62d4ddad2}\symimv.cat. This error may be caused by network problems or insufficient security rights.

 DETAIL - Access is denied.
</code>
I have not touched the security permission on this DIR, has anyone any idea what might have caused this & how to resolve it? It seems to have started after doing a large number of windows updates last night.
Answer: It looks like the temp IIS profile that is used (normal for IIS) can't be created.  I bet you will have the same issue if you create a new user and try to use it.  In other words, the root issue is not related to IIS.  I don't know what symimv.cat is, but nothing turns up on a google search.  Is that something custom that you or your corporate team have installed?
In other words, it sounds like something amiss with your default user profile.
Comment: Any idea how I would track down what that is?
Comment: Try first to just create a new windows user on that server and see if you can log into the server as that user.  The best debugging tool to use is process monitor from www.sysinternals.com.  That will let you know what permissions it needs and why it's failing.  You may just need to tweak the permissions on your symimv.cat file to give it read permissions for the Users group, or something along those lines.
Comment: So i tried creating a brand new user and loggin in and I get "The user Profile Service failed the logon. User Profile cannot be loaded." Looks like I might have more troubles than just running IIS.
Comment: Sounds like good confirmation.  Check Event Viewer and try Process Monitor and see what you get from those two clues.  They should help.  The symimv.cat file is suspect.  That's possibly a custom component added by someone, but hopefully not a virus.
Comment: Try copying the C:\Users\Default profile folder from another machine over this one (copy to desktop, zip, move, unzip to desktop, copy over c:\Users) and see if that helps. Came across this today on a dev vm :-\
Answer: I have managed to fix this. It was caused by the permissions being incorrect on the C:\Users\Default folder and as such the system could not read any of the files in the profile when trying to make a copy. The symimv.cat file was just the first file in the profile and was not significant, when I deleted it the next one in the list started comming up. symimv.cat is part of Norton 360 by the way.
Does anyone know what the correct default permissions are for C:\Users and C:\Users\Default? I have largly given rights to everyone, which is perhaps not very secure.


Using regex to split special char

Question: string MyName = " 'hi, load1', 'hi, load2', varthatnotstring ";

I want to use regex to split the above string at every ,, while preserving strings that are inside quotation.
As such, splitting MyName should yield:
1: 'hi, load1'
2: 'hi, load2'
3: varthatnotstring

I currently use regex MyR("(.),(.),(.*)");, but that gives me:
1: 'hi
2: load1'
3: 'hi
4: load2'

What regular-expression should I use?
Comment: Why is it important that it be regex? You should strive to use the right tool for every task, so why force yourself to use one tool when another is a better fit?
Comment: You should not use a regular expression. This does not seem to be a good task for regular expressions. It'd be trivial to write a simple parser by hand that searches for quoted and unquoted strings.
Comment: yes but i need to be regex .... it is very important for me to be regex ...
Comment: ok please write for me a program with other way to do this ...
Comment: Something like `" *(('([^\']*(\\|\')*)*')|[^',]*), *"` (untested) ? (only handle `\'` and `\\` in quote).
Comment: not worked ... please check it again
Answer: Depending on how you want to handle certain corner cases, you can use the following:
std::regex reg(R"--((('.*?')|[^,])+)--");

Step, by step:

R"--(...)--" Is syntax for raw string literals, so we don't have to worry about escaping. We don't need it here, but I'm using them by default for regex strings.
('.*?') all characters between (and including) two apostrophes (non greedy)
[^,] anything that is not a comma
(('.*?')|[^,])+ arbitrary sequence of non-,-characters or '...'-sequences.
(Note: the ('.*?') part has to come first)

So this will also match e.g. tkasd 'rtzrze,123' as a single match. It will also NOT remove any whitespaces.
Usage:
std::regex reg(R"--((('.*?')|[^,])+)--");
std::string s = ",,t   '123,4565',k ,'rt',t,z";

for (std::sregex_iterator rit(s.begin(), s.end(), reg), end{}; rit != end; ++rit) {
    std::cout << rit->str() << std::endl;
}

Output:
t   '123,4565'
k
'rt'
t
z

Edit:
I rarely use regular expressions, so any comments about possible improvements or gotchas are welcome. Maybe there is also an even better solution using regex_token_iterator.
Comment: Note that you cannot use `\\` or `\'` to escape `\` or `'` with your regex.
Comment: @Jarod42: Do you mean, this would e.g. be a problem if the string contains something like `don't`? You are right, I didn't think of that. Thank you!. I don't see, why `\`` would be a problem though. In any event - depending on whether the OP has control over the formatting of the string, or not - I'd rather not require them to be escaped, but would only treat `'`s special, that come directly before or after a `,` (probably allow whitespaces in between).
Comment: Yes I mean something like `don\'t`.
Comment: Ok, I'll think about it. I guess the second symbol to escape wasn't `\`` as I initially though, but the backslash itself right?
Comment: I meant: `'` (quote) , and ```\```(backslash). (I (mis-)used backquote to render those char as code...)

Using regex to split special char


salt-ssh : Disable SSH Host Key Checking with python api

Question: I'm working with salt-ssh and with the command line I can use option -i to use 'StrictHostKeyChecking'
(agent) [root@NODE ~]# salt-ssh  'af0abc4b-6980d-4fdd-ba63-192cb3d116be' test.ping
af0abc4b-6980d-4fdd-ba63-192cb3d116be:
    ----------
    retcode:
        254
    stderr:
    stdout:
        The host key needs to be accepted, to auto accept run salt-ssh with the -i flag:
        The authenticity of host '10.10.10.10 (10.10.10.10)' can't be established.
        ECDSA key fingerprint is af:00:b8:ab:7a:3e:cd:06:9a:6c:36:e9:32:f0:a3:a4.
        Are you sure you want to continue connecting (yes/no)?

(agent) [root@NODE ~]# salt-ssh -i --no-host-keys 'af0abc4b-6980d-4fdd-ba63-192cb3d116be' test.ping
af0abc4b-6980d-4fdd-ba63-192cb3d116be:
    True

but when I want to do the same thing with the python api I didn't find a way to specify the -i option so can it be done.
this is the python code I'm using
from salt.client.ssh.client import SSHClient
salt = SSHClient()
salt.cmd('af0abc4b-6980d-4fdd-ba63-192cb3d116be', 'test.ping')
Out:
{'af0abc4b-6980d-4fdd-ba63-192cb3d116be': {'retcode': 254,
  'stderr': '',
  'stdout': "The host key needs to be accepted, to auto accept run salt-ssh with the -i flag:\nThe authenticity of host '10.10.10.10 (10.10.10.10)' can't be established.\nECDSA key fingerprint is af:00:b8:ab:7a:3e:cd:06:9a:6c:36:e9:32:f0:a3:a4.\nAre you sure you want to continue connecting (yes/no)? "}}

how can I do the same with the python code??
Answer: The only solution I found is to configure StrictHostKeyChecking in $HOME/.ssh/config`.
example of $HOME/.ssh/config
Host *
    StrictHostKeyChecking no

or
Host 10.10.10.15
   StrictHostKeyChecking no