removendo parte de uma string com php

Question: Galera tenho uma variável com o seguinte link:
https://www.youtube.com/embed/z1n34sRv1-A

Preciso remover tudo que vem antes do embed, ou seja preciso do seguinte id:
z1n34sRv1-A

Como posso fazer isso com php?
Comment: http://pt.stackoverflow.com/q/43810/91
Comment: nesse caso não vai dar certo porque não é um parametro GET ele faz parte da url.
Answer: Voce pode fazer desse jeito:
$url = "https://www.youtube.com/embed/z1n34sRv1-A";
$url = explode("embed/", $url);
$embed = $url[1];

Answer: Você pode usar o explode para dividir a String pelas barras e pegar a última posição que é o count do array:
$url_parts = explode("/", "https://www.youtube.com/embed/z1n34sRv1-A");
echo $url_parts[count($url_parts)-1];

Comment: perfeito, funcionou 100%
Answer: Você pode utilizar:
 substr($string,$start,$length);

$string = variável,
$start = começo da variável onde irá começar o corte da string em inteiro,
$length= fim da variável em inteiro,
Digamos que o padrão da URL tenha 25 caracteres, então ficaria desta forma:
substr($url,25,strlen($url));

Answer: Utilize o strrpos para detectar a última / da url e, com substr, extraia a parte desejada:
$url = 'https://www.youtube.com/embed/z1n34sRv1-A';

substr($url, strrpos($url, '/') + 1)

A função strrpos encontra a última ocorrência de / e retorna a posição. Como precisamos pegar o que vem depois disso, é necessário adicionar um +1.
Ainda utilizando uma linha, você pode facilitar usando array_reverse, para pegar apenas o último elemento do array gerado pelo explode.
 current(array_reverse(explode('/', $url)))

Answer: $url_parts = explode("/", "https://www.youtube.com/embed/z1n34sRv1-A");

echo end($url_parts);

removendo parte de uma string com php


adding three submit buttons inside a modal dialg box?

Question: And my second question ,,
I have a simple modal box opening when I click on 'add users' . The modal box contains 3 submit buttons ( add, delete, and submit) . I have done this with the help of a javascript.
 The html code is

X
<form action="" method="POST">

        user<input style="width:100px;" name="u" type="text"/>

        <input type ="submit" value = "add"> <input type="submit" value="delete">

        <select style="width:150px;">
            <option value="abc">abc</option>
        </select>

</form>
<input type="submit" value="Submit"/>

Click here to add user

and my javascript is
function overlay() {
    el = document.getElementById("overlay");
    el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";}

now my task is to to add a user when user types a name in the text field and press a add button, the same user name should come in the drop down list   and similarly if user selects one name from the dropdown list and press the delete button , it should delete that name .
And finally if he press the submit button then only the modal box should close and the datas will be shown on my main page..
I have just started doing my task and am planning to implement these functionality using php and some file operations .
My first question is as user first press the add button  ,, it will close the modal window and that is not what i am required ( I guess you understand my requirement )  Is there any way to solve this?   Please help this newbie    Thank you.
Comment: You want to save action in database? Can you create a jsFiddle?
Comment: @DonovanCharpin Sir ,, actually i am planning to use a file for saving and deleting datas. I will take the input save it in a file , and using php variable i wanna show this in drop down  ,, I donno how much efficient is this
Answer: You have to add eventsListeners to the button and prevent their default behave.
(function(){
    var addButton = document.getElementById("add_btn");
    var deleteButton = document.getElementById("delete_btn");
    addButton.addEventListener("click", addUser, false);
    deleteButton.addEventListener("click", deleteUser, false);
})();

function addUser(event) {
    event.preventDefault();
    var element = event.target;
    var userNameInput = document.getElementById("user_text");
    var userName = userNameInput.value;

    var usersList = document.getElementById("users_list");
    var user = document.createElement('option');
    user.value = userName;
    user.innerHTML = userName;
    usersList.appendChild(user);
    usersList.selectedIndex = usersList.length - 1;

    userNameInput.value = "";
}

function deleteUser(event) {
    event.preventDefault();
    var usersList = document.getElementById("users_list");
    usersList[usersList.selectedIndex].remove();
}

Here an example I wrote on jsFiddle of your code:
jsFiddle
Comment: This is Superb Mr. Expert!!   one more question is that ,, can i open a file and save/write these user information there?
Comment: When you click on the submit button, by the form `action` attribute, the browser create a Request to the the action with `post` type.
Then you have to use server-side code( In your case is php I'm suggesting)
Try to google about php post
here is a http://php.net/manual/en/reserved.variables.post.php
Comment: so may be I could write php in which it will take all the values which are there during submit, into an array and i can save it in a file in a format say csv (putcsv),   So is the var usersList contains the data? if no , where can i get it ,, ?
Comment: If you want to submit all the selected list you have to add an hidden field for holding the all users any time.
see my update http://jsfiddle.net/h7ttG/2/
then on server read the post I attached last comment for how get the information from the request on the server.
For working with files on php read this
http://php.net/manual/en/function.file-put-contents.php
Comment: is there anyway to keep the data in the dropdown box even if the page is refreshed? because even if the page is refreshed , the added users should be there ? am i right?
Comment: Yes, but you have to do it with php.
after you get the list of names from the server with `$_POST` you need to fill the selectlist with the values.
can you show what did you try to do so far (php)?
Comment: hi i think am confused.. this is my small php test

                      I added this under the delete button to see whether it is taking and i didnt change anything on the javascript,, thats why the value is coming on the dropdown still.. how can i get the variable value from js in php??  pls help
Comment: Shoul i remove user.innerHTML = userName; in js and try?  but i dont think i am right..
Comment: Yes you doing right except this you should write inside the select 'for loop' and the somthing like 'echo $add ' but you have first split the 'add' to array. Search for split function in php and after you split to array by delimiter like ',' you can iterate over any value and echo it into the select list
Comment: I am planning to do this,, am taking the js variable in a hidden input field ,, from there am reading into a php variable array and put into the dropdown list.. but am checking each value(   '.$add[0]. '} if($add[1])........ etc.. but this is not efficient as the contents may be in any no (as you mentioned). how to do that easily   ?.  also can we avoid adding of blank content?
Comment: foreach will do it,,,     anyway thanx for the help,,  a +1 is definitely there for u on the day when i reach 15 reputation !!!
Comment: I'm not php programmer but you can check for blank values on the client-side(javscript) and the server. you can find anything you need on google.
the main concept is to split the value that comes from the browser of the username beacuse it's sepereate by comma.
So php has build in function to split string by char or string.
Then you have an array of the values and you just iterate it with foreach exactly like you did.
If you will upload your code it will be more easier to help you considering the fact that i'm not php expert but it's very basic so I think i can help.
Comment: upvoted as I promised ( got 15+ reputation)   thnk u
Answer: Make your form submits using AJAX...default submit btn will refresh the page.
I assuming when you add/delete a user...you are actually saving them in the db.
1.When you press 'Add' btn...make an ajax call to the backend with the user details and save it and send a callback whether the user has been added successfully or not.
2. On the add user callback...you can call a function to update the drop-down list.
Comment: Hi ,, truely saying , I donno what this Ajax is, ? may be because i am doing my first website  .. could you pls give me some gem suggestions??
Comment: Ajax is asynchronous javascript used to communicate with the server. First of all are you using a db to store the usernames or your website is just a static website?
Comment: Actually I am using a file to save datas
Comment: As you are using php as your backend...you can write this data to a file.


Postfix (Maia Mailguard) relayhost update ignored

Question: I have a postfix mail server used in conjunction with Maia Mailguard, Amavis, and clamav for spam. I've upgraded the primary mail server and it has a new IP address. I change main.cf and transport to point to the new server 172.17.2.9 in /etc/postfix, then reload postfix. When I look in /var/log/mail.log, "postfix/smtp * relay=172.17.2.15[172.17.2.15]:25 is still the old mail server (172.17.2.15).
postconf -n with our actual domain changed to mydomain.com
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
content_filter = smtp-amavis:[127.0.0.1]:10024
delay_warning_time = 4h
inet_interfaces = all
local_recipient_maps =
mailbox_size_limit = 0
message_size_limit = 20480000
mydestination = mydomain.com
myhostname = spam.mydomain.com
mynetworks = 172.17.0.0/21 192.168.10.0/24, 192.168.16.0/24, 127.0.0.0/8
myorigin = mydomain.com
recipient_delimiter = ;
relay_domains = mydomain, mydomain.net, mydomain.int, 172.17.0.0/21 192.168.10.0/24, 192.168.16.0/24
relay_recipient_maps = hash:/etc/postfix/relay_recipients
relayhost = 172.17.2.9:25
smtpd_banner = $myhostname ESMTP $mail_name
transport_maps = hash:/etc/postfix/transport

Transport file
mydoamin.com smtp:[172.17.2.9]:25

I've checked resolve.conf and the hosts file to make sure there's nothing funny going on in there, all looks fine.
I've reviewed the maia config.php file and the maia.conf file, nothing there.
Where else could the old server IP be set for mail flow?
Answer: So it turns out I had everything changed that need to be changed:

/etc/postfix/main.cf
/etc/postfix/transport
/var/www/maia/config.php

You then need to run these commands to tell postfix to recreate the transport database and load the new config settings.
sudo postmap /etc/postfix/transport
sudo service postfix restart


How to make this data stationary

Question: What is the correct way to make this data stationary (without cutting it in half)?
Quarterly Data:
17996666000
17395339056
17338377000
17311651000
18043497534
18716063000
19335859000
19300627000
19602120000
19537854000
19888609000
19760257000
19339309125
18885771000
20311922000
19708371000
19326807000
18733706000
21059811000
20523668000
21906648000
24469040000
29176362000
28455903000
30348154000
31588708000
33588602000
32669267000
34233556000
35470378000
36709046000
35698357000
36881680000
37560603000
38169265000
37147402000
38707144000
39120015000
40466332000
41033858000
43142309000

Plot of data :

Differences won't make it stationary
adf.test(data)

    Augmented Dickey-Fuller Test

data:  data
Dickey-Fuller = -1.602, Lag order = 3, p-value = 0.7301
alternative hypothesis: stationary

> adf.test(diff(data))

    Augmented Dickey-Fuller Test

data:  diff(data)
Dickey-Fuller = -1.4163, Lag order = 3, p-value = 0.8026
alternative hypothesis: stationary

> adf.test(diff(diff(data)))

    Augmented Dickey-Fuller Test

data:  diff(diff(data))
Dickey-Fuller = -2.6651, Lag order = 3, p-value = 0.3129
alternative hypothesis: stationary

adf.test(diff(diff(diff(data)), lag=4))

    Augmented Dickey-Fuller Test

data:  diff(diff(diff(data)), lag = 4)
Dickey-Fuller = -2.9252, Lag order = 3, p-value = 0.2138
alternative hypothesis: stationary

plot of differenced data:

detrend with a line:

Residuals definitely not stationary:

2 diffs and seasonal difference, still not unit-root stationary per ADF
adf.test(diff(diff(diff(lm(y~t, g)$residuals)), lag=4, differences = 1))

    Augmented Dickey-Fuller Test

data:  diff(diff(diff(lm(y ~ t, g)$residuals)), lag = 4, differences = 1)
Dickey-Fuller = -2.9252, Lag order = 3, p-value = 0.2138
alternative hypothesis: stationary

This data gets stationary if I cut it in half, which eliminates the beginning flat part of the curve. For learning I am interested in seeing how to make it stationary with this part included though, but just for reference:

adf.test(diff(data[17:length(data)]))

    Augmented Dickey-Fuller Test

data:  diff(data[17:length(data)])
Dickey-Fuller = -3.8132, Lag order = 2, p-value = 0.03477
alternative hypothesis: stationary

I also tried tsoutliers package to look for interventions, but it gives me errors :
tsoutliers::tso(data,types = c("AO", "TC","LS", "IO"),maxit.iloop=10, maxit.oloop=10)

Error in arima(y, order = fit$arma[c(1, 6, 2)], seasonal = list(order = fit$arma[c(3,  :
  non-stationary seasonal AR part from CSS

tsoutliers::tso(diff(data),types = c("AO", "TC","LS", "IO"),maxit.iloop=10, maxit.oloop=10)

Error in auto.arima(x = c(-601326943.954987, -56962056.0450134, -26726000,  :
  No suitable ARIMA model found
In addition: Warning message:
In sqrt(diag(fit$var.coef)[id]) : NaNs produced

How can I make this stationary without cutting the data in half?
UPDATE:
I performed an intervention analysis following steps from the paper by Tsay, using the model ARIMA(0, 1, 0)(1, 0, 0)4 as an estimate, and following the iterative procedure in the paper, I found the following :
           w            v     hyp   types  t
11 102080630 9.828064e+14 3.256187    IO 22
4   69408316 5.806115e+14 2.880505    TC 22
2   39451617 3.232890e+14 2.194165    AO 22
3   70523673 6.465779e+14 2.773476    LC 22

The only hypothesis that passed the minimum criteria mentioned by Tsay is the innovative outlier at t=23 (23 because the data is differenced, so I add 1)
This is what the transformed data looks like:

The transformed data is mostly stationary after 2 differences:

Also, auto.arima believes this to be the model of the transformed data: ARIMA(0,2,2)(1,0,0)[4]
Answer: Differences do make it stationary when a level/step shift indicator is introduced to reflect a deterministic effect at period 23 . No need to segment the data ...just use a comprehensive hybrid model found via http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html .
Here is a useful model using AUTOBOX (a time series forecasting package that I have helped to develop)   (0,1,0)(1,0,0)4 with a level shift ( i.e. intercept change at period 23 and a pulse at period 22  .The Actual/Fit and Forecast is here   . The Residuals are here  with acf here suggesting model sufficiency .
The model includes simple differencing and an intercept adjustment at period 23 along with a simple pulse and a seasonal ar component. Quite simple but powerful and elegant.
Your comment "I also tried tsoutliers package to look for interventions, but it gives me errors " suggests to me possible serious software limitations or a possible "user error" which I can't immediately detect .
The Actual/Cleansed graph is illuminating.  while the forecast graph illustrates the 95% prediction limits using monte-carlo resampling.
EDITED TO SHOW EXPLICITELY HOW A FORECAST IS MADE:
The model can be expanded via algebra to present how a prediction can be seen as a "regression type model" . Here is a one-period out forecast computation where differences and autoregressive lag structure is incorporated..
Comment: Yes ! BUT the phrase "detrending with " should be "incorporating" as the term detrending is appropriate when a predictor series is a trending series. In this case the predictor series is simply a pattern of 22 consecutive 0's and 19 consecutive  1's  which does not have a trend.
Comment: I should add ... a pulse is a difference of a step ... a step is a difference of a time trend . When one has a hybrid model that includes a differencing operator ( as in this case) the de facto effect of a level shift is a time trend thus the upwards trending expectation.
Comment: I added a visual of how a forecast can be generated using expanded polynomial structure for this case. It like all forecasts is the weighted sum of both history and any needed deterministic structure.
Comment: You are very welcome .
Comment: When I regress with a level change (0, 0, .., 0, 1, 1, ..., 1), and then difference, the data looks much more stationary except for 1 outlier.
When I regress with the LC and a "pulse" of (0, 0, 0, 1, 0, 0, ..., 0), where the 1 is at position 22 or 23, and than difference, the outlier just moves over each time!
What am I doing wrong there? I hope I explained the question well.

Also, I'm working through that Tsay paper you linked, it is really helping.
Comment: Let me verbally help you ... you can call me . .the pulse indicator is not simply added as an after thought ..it has to be integrated into the model
Comment: Added an update. I followed the steps from the Tsay paper you posted, but the statistical tests in that paper only pass for an innovative outlier at t=23. Furthermore, after subtracting the innovative outlier, the data is still not failing ADF with 2 differences. It's much closer to failing ADF though, much better overall. Do you have any more good research papers lying around?
Comment: there is a pulse at 22 and a level shift at period 23 GIVEN that the arima model is a first difference and an ar(1) coefficient with lag 4 . Your software doesn't allow an ar(1) with lag 4 as it forces in LAGS 1,2,3 AND 4 . The ADF should suggest a first difference IF you incorporate the two deterministic series ( pulse and level shift) and adjust for a pulse at 22
Comment: I had an error in my code. I'm getting TC at 22 and IO at 23 now. (also using delta .8). Got to keep debugging maybe Monday (worked on this maybe 10 hours today). Thanks again!
Comment: Thanks again! This is great! So, am I correct that the clean data was produced by detrending with a level change and pulse as regressors?
Comment: Thank you so much
Answer: Well, when you're detrending the data, obviously the linear trend is not sufficient. The trend basically looks like a flat line followed by linear increase starting around $t=20$; that is not well approximately by a linear trend because it overestimates near the break point. You might want to use a more general parameterization for the trend- loess could go the job. Something to think about.
Comment: I tried loess and it had the same issue. The loess residuals looked quadratic. I didn't include because post was long enough already.

How to make this data stationary


How can I integrate this function? $\frac{\sqrt{e^{2x+2y+z}}}{(1+e^x+e^y+e^{x+y+z})^2}$

Question: I want to evaluate the following integration
$$
\int_{-\infty}^{\infty} dx \int_{-\infty}^{\infty} dy \int_{-\infty}^{\infty} dz \frac{\sqrt{e^{2x+2y+z}}}{(1+e^x+e^y+e^{x+y+z})^2}.
$$
According to Mathematica12, the answer is $\pi^2$.
How can I get the answer?
Answer: Let $x= \ln X$, $y=\ln Y$ and $z=2\ln Z$. Then
$$ I = \int_0^\infty\int_0^\infty\int_0^\infty\frac{XYZ}{(1+X+Y+XYZ^2)^2} \frac{dX}{X}\frac{dY}{Y}\frac{2\cdot dZ}{Z}.$$
This is a rational function, and thus can be easily integrated. For instance integrate first against X:
$$ I = 2\int_0^\infty\int_0^\infty \frac{1}{1+YZ^2}\frac{1}{1+Y}dY dZ. $$
Then integrate against $Z$:
$$ I = 2\int_0^\infty \frac{\pi}{2\sqrt{Y}}\frac{1}{1+Y}dY . $$
Then, let $u=\sqrt{Y}$ to obtain
$$I= \pi\int_0^\infty \frac{2u }{u}\frac{1}{1+u^2}du=\pi^2.$$
Answer: This is not an answer.
For the most inner integral, the antiderivative is not too bad. Hoping no mistake
$$I=\int \frac{\sqrt{e^{2(x+y)+z}}}{(1+e^x+e^y+e^{x+y+z})^2}\,dz$$
$$I=\frac{\sqrt{e^{2( x+ y)+z}}}{\left(1+e^x+e^y\right)
   \left(1+e^x+e^y+e^{x+y+z}\right)}+\frac{\sqrt{e^{x+y}}}{\left(1+e^x+e^y\right)^{3/2}}\tan^{-1} \left(\sqrt{\frac{e^{x+y+z}}{1+e^x+e^y} }\right)$$ The problem is for the definite integral.
If you are able to find it, may be the next could be easier.
Comment: Thank you. But I do not know how can I use the antiderivative for Multivariable Integration. And I feel it is too difficult to find antiderivative. How did you find it?
Comment: @Sakurai.JJ. Using a CAS


How can I adjust this grace note alignment in a Lilypond score?

Question: I'm working on a transcription/editing project.  At one point, the piano part has some grace-note arpeggios while the bass plays a melodic line.  I am trying to make this "look nice" in the full score, and I'm having trouble figuring out how to do it.
If I compile the code below, I get the following (in the third system):

This introduces additional space at the start of the bar (underlined in green), which is OK — but also in the middle of the bar, which makes it harder for the conductor to interpret the rhythmic line.
If I uncomment the line <code>\override SpacingSpanner.strict-grace-spacing = ##t</code>, I get the following:

The rhythmic line in the bass is much easier to read, but the gracenote arpeggios are far too compressed, colliding with both the barlines and their own accidentals.
What I would like is some way to get the arpeggios having something like the width they have in the first example, but without inserting extra space in the middle of a bar.  Extra space at the start of a bar is fine.  Basically, I want to follow Gould's advice on grace note alignment in scores:

Grace notes written after the bar line displace the first beat to the right. All other parts align with the measured value, and not with the grace notes.
In a score, when grace-note groups come after the beginning of the bar, note spacing in one part need not necessarily be expanded to accommodate grace notes in another part, even though the grace notes start later in the bar than the rhythmic alignment suggests. This facilitates score reading, as it prevents distorted note spacing of a single beat.

How can I accomplish this?

Code:
(Apologies for the length, this really was about as minimal as I could make it)
<code>\version "2.24.0"

RHpianonotes = {

% Right hand

\time 2/2
\clef bass

\relative c {
 \transposition c'

R1

\override Score.GraceSpacing.spacing-increment = #1.0
%<<
% {\grace{ s8.^\markup{\italic "very dry, with quick and vigorous arpeggio"}} s8}
%\\
{ \stemUp \change Staff = "lower" \grace { d32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral }% >>
 r8 r4
r4 \stemUp \change Staff = "lower" \grace { d,,32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral r8

r2 \stemUp \change Staff = "lower" \grace { d,,32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral r8 r4

r4 \stemUp \change Staff = "lower" \grace { d,,32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral  r8 r2

\stemUp \change Staff = "lower" \grace { d,,32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral r8 r4 r2

\stemUp \change Staff = "lower" \grace { d,,32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral r8 r4
r4 \stemUp \change Staff = "lower" \grace { d,,32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral r8

r2 \stemUp \change Staff = "lower" \grace { d,,32( a' bes \change Staff = "upper" \stemDown e f fis} a8) \stemNeutral r8 r4
}
}

LHpianonotes = {

\time 2/2

\clef bass

\relative c {

%\override Staff.GraceSpacing.spacing-increment = #5.0

R1

%\grace{s8.}
s1*6

}
}

bassnotes = {

\relative c {

\clef bass
\time 2/2
\transposition c

R1

\grace {s8.}
R1*2
%\noPageTurn
%\tag #'partOnly {\pageTurn}

d'4_\p r4 r8 d e d
f4->( d8) r8 r8 d e d
fis8->( f) d4 r8 \clef tenor a'8 b a
\tuplet 3/2 {c->( b) a} eis8. fis16 d4 r8 cis8~

}

}

\score{

\layout {
    \context {
      \Score
      \override SpacingSpanner.base-shortest-duration = #(ly:make-moment 1/16)
%     \override SpacingSpanner.uniform-stretching = ##t
%     \override SpacingSpanner.strict-grace-spacing = ##t
    }
  }

<<
\accidentalStyle Score.modern

\new PianoStaff
<<
    \new Staff = "upper" {\RHpianonotes}
  \new Staff = "lower" {\LHpianonotes}
>>

\new Staff="Staff_bass"
{

<< \bassnotes  >>

}

>>

}

</code>
Answer: Hm, maybe something like this would work for you?
<code>\version "2.24.0"

RHpianonotes = \relative c {
  \time 2/2
  \clef bass

  a''8 \stemNeutral r8 r4
  <<
    r4
    {
      s16 \tiny {
        \stemUp \change Staff = "lower" { d,,32( a' bes \change Staff = "upper" \stemDown e f fis \normalsize }
      }
    }
  >>
  a8) \stemNeutral r8
}

LHpianonotes = {
  \time 2/2
  \clef bass
  s1
}

bassnotes = \relative c {
  \clef bass
  \time 2/2
  fis'8->( f) d4 r8 \clef tenor a'8 b a
}

\score {
  <<
    \accidentalStyle Score.modern
    \new PianoStaff
    <<
      \new Staff = "upper" \RHpianonotes
      \new Staff = "lower" \LHpianonotes
    >>
    \new Staff="Staff_bass" \bassnotes
  >>
}
</code>
Comment: I'm not at a computer with Lilypond right now, so I can't try it out immediately.  But looking at the code:  how would this idea work for an arpeggio at the start of the bar?  In that case, the arpeggio has to fall between the barline and the first beat;  and the first beat in the piano should be aligned with the first beat in the bass.
Comment: @MichaelSeifert Doesn't regular grace behaviour do that already? My suggestion is way you might "fake" this behaviour, as grace columns currently do not really work like this, that is, to get this to work with grace notes would require some significant change in how Lilypond handles these columns.
Comment: Ah, I misunderstood what you were suggesting.  I'll try it out this evening and see how it works in the MWE and in the full score.
Comment: Having tried this out, it *might* work if I used `\teeny` instead of `\tiny`, so that the note heads were close to the same size as the "proper" grace notes.  It's not perfect, though;  there's still a noticeable difference in the weights of the beams between the "fake" grace notes and the "real" grace notes, and there's also still some additional space inserted in the bass line (though less than in my original version.)


calibration according to Kuleshov

Question: i was reading this paper  https://arxiv.org/pdf/1807.00263.pdf in which Kuleshov gives a definition of a well calibrated neural network in a regression task

I would like to ask one thing:
why does he makes a special cases for when $x_t,y_t$ are i.i.d. realizations of random variables $X, Y \sim \mathbb{P}$? when we do regression don't we always assume that  both the independent and dependent variables are jointly distributed? also why is a sufficient condition?
Comment: @BenReiniger but since   X represents the input given to the neural network  by the user, what would it be its distribution? i am superconfused
Answer: You can have realizations $(x_t, y_t)$ from their joint distribution $\mathbb P$ that are not independent. E.g., you could decide to choose $x_{t+1}$ as a function of $y_t$.
As to why Equation (4) is sufficient for Equation (3):
I think he just wants to say that if he uses the quantile function of the $Y$-marginal of $\mathbb P$ as the forcaster $H(X)$, i.e. $H(X)$ would be the same for all $X$, then it would be calibrated. But that is by definition: provided you sample i.i.d. from $\mathbb P$, you will for $t\to\infty$ get relative frequencies that converge to the marginal $Y$-distribution.
Comment: sorry but i  am confused. 1) in a neural network  the output y is always dependent from the input x given by the user, so $y_t$ is always dependent on $x_t$, what do you mean with picking $x_{t+1}$ in place of $x_t$? 2) from where did you understand that he was referring to the Y-marginal distribution for the forecaster? from the fact the he uses Capital $X$ rather than $x$?
Comment: i have found another article where a different author provide a summary https://arxiv.org/pdf/1905.11659.pdf and he says it's equivalent, not sufficient....
Comment: If I understand the author correctly, then $\mathbb P$ is the joint distribution of two random variables $X, Y$ and that is independent of any NN. You can decide to train a NN on $\mathbb P$, but $\mathbb P$ is not related to any NN. And in that $\mathbb P$, you have $Y \sim \mathbb P(Y|X)$ and in regression, you want the mean thereof to be predicted for each $x$ by your NN, that's why you train the NN.
Comment: If I understand the author correctly, then his sample $\{(x_t, y_t)\}$ is indexed by integers $t$. Now, the samples are supposed to be iid. But if you change the sampling scheme in the way I described, the elements of the sample will not be independent anymore. Just take the sample element $(x_t, y_t)$ of step $t$ and then obtain the next sample element, the one for $t+1$, as follows: choose $x_{t+1}$ as some appropriate function $f$ of $y_t$, $x_{t+1} = f(y_t)$. Next, e.g. sample $y_{t+1}$ from $\mathbb P(Y|X=x_{t+1})$. Then your sample is not independent anymore.
Comment: Your second point: I think that because of Equation (4) and the line immediately following that.
Comment: Please, don't extend your question by asking me to read additional papers not mentioned in the original question. Rather, ask a new question.

calibration according to Kuleshov


Is the Klein bottle homeomorphic to the union of two Mobius bands attached along boundary circle?

Question: Question: Determine whether the Klein bottle is homeomorphic to the union of two Mobius bands attached along their boundary circles.

The Klein bottle is the quotient space
$$
K=I^2 /{\sim}, \quad (x,0)\sim(x,1), \; (0,y)\sim(1,1-y), \; \forall x,y\in I
$$
The Möbius band is the quotient space
$$
M=I^2 /{\sim}, \quad (0,y)\sim(1,1-y)
$$
What would be a good way to approach this question? I have not had any success constructing a map between spaces

Edit: I remember that homeomorphism must preserve orientability. So this could be used to disprove a homeomorphism.
The mobius band is non-orientable, as is the klein bottle. What I am not sure about is if we take the union of two non-orientable Mobius bands and attach their boundary circles, do we still get a non-orientable surface.
I think the gluing the boundary step may switch the orientabilty. So we have an orientable surface which therefore cannot be homeomorphic to the non-orientable Klein bottle.
I am unsure how to prove this in a formal way (with equations and notation etc)
Would appreciate your help
Comment: You cannot embed a non-orientable surface into an orientable one for obvious reasons. So the strips stay non-orientable. Non-orientability doesn't cancel, it's more like cancer.
Comment: The way to prove it in a formal way is to first produce a good intuitive picture, such as in the answer of @user326572, and then describe the features of that picture precisely in coordinates.
Comment: @LeeMosher thanks. I am not sure how to construct these pictures
Comment: @amiz9 What is there to construct? The square is $[0,1]^2$ and one of the strips is $\{(x,y-x/2)|x\in[0,1],y\in[1/2,1]\}$. If you don't understand how subspaces and quotient spaces interact, I suggest you work it out in detail yourself.
Answer: This is a diagram of the Klein bottle, note that the diagonal lines divide it into 2 Möbius strips sharing a boundary:

So the answer is yes.
Comment: please can you explain how you arrived at this diagram, as I would not be able to do this myself?
Comment: @amiz9 At first I tried dividing it horizontally by a line in the middle. But that doesn't quite work since the left side of the upper strip gets identified with the right side of the bottom strip. This is a modification of that idea.
Comment: For clarity, I remark that one Mobius strip is the centremost rectangle and the other is taken from the upper and lower triangular fragments. This is the clearest proof, thank you


Ruby on Rails giving me errors...

Question: So i've been following DevTips ruby on rails blog tutorial on YouTube but i keep getting errors:
app/views/posts/new.html.erb:11: syntax error, unexpected keyword_end
app/views/posts/new.html.erb:13: syntax error, unexpected keyword_ensure, expecting ')'
app/views/posts/new.html.erb:15: syntax error, unexpected keyword_end, expecting ')'

Now... For one my code isnt even 15 lines long... which is one reason why im so lost. Here is my code:

New Post

<%= form_for @post do |f| %>
  <%= f.label :title %>

  <%= f.text_field :title %>

  <%= f.label :body %>

  <%= f.text_area :body %>

  <%= f.submit %>
<%= end %>

Any help with this. I'm completely baffled...
Answer:
syntax error, unexpected keyword_end

You need to change <%= end %> to <% end %>

Ruby on Rails giving me errors...


How to get data from function component?

Question: I have a function component (A) import another function component (B).
B has a onChange value, I want to get the onChange value all the time when I import B in A.
I have no idea how to get it.
Here is the code like this:
A:
import B from './B';

const A = () => {
  // I want to get B's onChange value over here
  return (

  );
}

B:
import React, { useState } from 'react';

const B = () => {
  const [value, setValue] = useState('');

  return (
    <SomePicker value={value} onChange={(value) => setValue(value)}
  );
}

Comment: Data flow is unidirectional in React. So you cannot use the state from a child component in its parent component.
Comment: https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs
This one answers you question!
Answer: You can refer below solution.
import B from './B';

const A = () => {
 const getOnChangeValueFromB = (data) => {
   console.log(data)// you will get onChange value here
  };
  // I want to get B's onChange value over here
  return (

  );
}

import React, { useState } from 'react';

const B = (props) => {
  const [value, setValue] = useState('');
const returnValueToA = (value) => {
    setValue(value)
    props.callBack(value);

  }
  return (
    <SomePicker value={value} onChange={(value) => returnValueToA(value)}
  );
}

Comment: Thanks, the answer teach me how to get data correctly.
Comment: Cheers!! @Morton


$X_n$ be a sequence of +ve $L^1$ r.v. converging a.s. to $X\in L^1$ and $E(X_n) \to E(X)$ . Then $E(X_nY)\to E(XY)$ for any bounded r.v. $Y$

Question: Let $\{X_n\}_{n\ge 1}$ be a sequence of positive random variables such that $E(|X_n|)<\infty,\forall n\ge 1$ and $X_n \to X$ almost surely, where $E(|X|)<\infty$. Also assume $\lim_{n \to \infty} E(X_n)=E(X)$.
Then how to show that for any bounded random variable $Y$,  $\lim_{n\to \infty} E(YX_n)=E(YX)$ ?
Comment: @i707107: sorry about that ... see my edit
Answer: Since $Y$ is bounded, $|YX_n|\le MX_n$ for some $M>0$ and $\mathsf{E}MX_n\to \mathsf{E}MX$. The result then follows from the generalized dominated convergence theorem.
Comment: I'm not quite so sure since we don't know $E(|X_n|)\to E(|X|)$ ...
Comment: you're wrongly using the theorem ... $g_n$ are need to be non-negative ... what is your $g_n$ exactly ?
Comment: @user521337 $X_n$ are positive, aren't they?
Comment: ah yes ... thanks


Solr search api indexing referenced fields by their id not value

Question: So i created a basic Solr core and index. In the index i added several diff. content types and added a lot of fields from those CT, including a aggregated field (union of several diff. fields: plain text, entity ref. fields, etc) Now i built a view based on that index (displaying rendered entities), and in the filter added a Fulltext search which will search on the Aggregated field.
For the most part it all works as designed, except that the fields which are entity reference fields (taxonomies) are indexed by their reference id (tid) and not the human readable value. E.g.: if a term (Math) from the vocabulary Subjects is indexed, the value which will be stored by solr is 5 (which is the term id), so when you use the fulltext search field and search Math there will be no results, but if you search 5, the content type where Math is selected will be displayed, not the best UI if you agreee.
Is there any way to search by the human readable values, without me altering the query and then finding the corresponding tid of the value entered in the search and then passing it back to the query, because that kinda defeats the purpose of having a backend search engine.
Thanks,
Will
Answer: Just to provide an answer, maybe it'll be useful to someone.
You can't At least not without a lot of hacking/patching the solr api module.


Why className.proptotype.constructor = newConstructor() does not change the constructor of Javascript Class?

Question: I tried changing the constructor function of a class by
className.proptotype.constructor = newConstrcutor;

This property now refers to the newConstructor but when i try to create an instance of the class, still the old constructor is executed. So,  what exactly is the use of className.proptotype.constructor ?
Thanks
Comment: You must not call the `newConstructor` when assigning it (not that it would work then)
Comment: exact duplicate of [What is the \`constructor\` property really used for?](http://stackoverflow.com/questions/12622137/what-is-the-constructor-property-really-used-for) and maybe have a look at what the [`new` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) does to answer your title question.
Answer: Each constructor has a pointer to an object called prototype. The prototype is the main mechanism that JavaScript supports to share properties and methods among objects of the same type.
In addition, the prototype can be used to support inheritance; not exactly in the way that it is done in other OO languages like Java, c# etc. So you can imagine that there is a mechanism that allows the interpreter to navigate from one prototype to another via a chain that is implicitly formed.
In the same way that constructor point to a prototype object, the prototype can also point to its constructor; You can think of it as a relation between constructors and prototypes.
One of the uses of the className.proptotype.constructor property is when you want to debug your code. A JavaScript debugger would clearly state the type (the constructor it was created from) of an instance.
for more details you can read this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor


Bivariate continuous disfribution and covariance matrix

Question: Let's define two random variables $x_1\sim\mathcal{N}(\mu_1,\sigma^2_1)$, $x_2\sim \mathcal{N}(\mu_2,\sigma^2_2)$. Also, $x=\binom{x_1}{x_2}$. We know
$$\Sigma_{xx}=\left(
  \begin{array}{cc}
    \sigma_1^2 & \rho\sigma_1\sigma_2 \\
    \rho\sigma_1\sigma_2 & \sigma_2 ^2\\
  \end{array}
\right),$$
where $\rho$ is the correlation between $x_1$ and $x_2$.
What happen with $\Sigma_{xx}$ when $x_1$ and $x_2$ have other distribution? (For example Uniform, Exponential, Gamma, ChiSquared, etc.)
Is there any reference using other type of distributions to obtain $\Sigma_{xx}$?
Answer: The covariance matrix does not have such a nice expression in general:
https://en.wikipedia.org/wiki/Covariance_matrix#Definition
Note also that there are no unique bivariate versions of the distributions you mentioned (exponential, chi-squared ...).
You might also be interested in looking at Copulas:
https://en.wikipedia.org/wiki/Copula_(probability_theory)
The bivariate Gaussian copula contains a parameter that quantifies the dependence between the marginals.


Centralizing configuration in python

Question: Currently my configuration options (constants / variables) are a bit fragmented, I have most of them in config.py but some are in the myfile.py at the top.
/utilities/myfile.py
/config.py

An example of what you might find in my myfile.py is:
TEMP_DIR = '/tmp'

If I wanted to move this definition from my myfile.py into my config.py but still use it in my myfile.py, how do I go about it?
I am new to python but I assume it is something along the lines of this at the top of myfile.py
from config

Answer: In myfile.py you could put
import config

and access TEMP_DIR with
config.TEMP_DIR

provided the directory containing config.py is in your PYTHONPATH.
Answer: variant 1
from config import *

this polutes the whole namespace in myfile.py
variant 2
from config import foo, bar, baz

Ever value used in myfile.py have to be mentioned.
variant 3
import config
...
x = config.foo

every value need to refer to config.
Your choice, but i prefer variant 3. To see config.py in myfile.py, you either have to edit your PYTHONPATH or use a relative import:
from ... import config

Comment: I feel that this is important to note because many python users fail to mention this to new python users: if you use the code `import config`, then you need to add on the module when calling an object within it, like so: `x = config.foo` if you use `from config import *`, however, you do _NOT_ need to put the module before the object: `x = foo`. I forget why this is, but it will save you a lot of time and confusion if you remember this when using python.
Answer: Another way to do this is to use execfile. This will make it easier to use different configuration files (for instance specify the configuration file to use on the command line).
Example:
# myconfig.py
TEMP_DIR = "/tmp/"

# myotherconfig.py
TEMP_DIR = "/tmp/foo"

# program.py (the main program)
import sys
config = {}
execfile(sys.argv[1], config)
print config["TEMP_DIR"]

Invoking the program:
$ python program.py myconfig.py
/tmp/
$ python program.py myotherconfig.py
/tmp/foo

Related: Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school
Comment: 4 possible ways to go ... remember zen of python? "There should be one-- and preferably only one --obvious way to do it." ;)
Comment: You are right. We should all use http://docs.python.org/2.7/library/configparser.html :-)
Comment: I must confess I am norwegian.

Centralizing configuration in python


What is NLP? How it is related to Machine Learning?

Question: Is NLP a subtopic within machine learning or it is related to Machine Learning?
If I want to get started at this, how would I start?
Comment: The tag description for [tag:natural-language] provides an answer to your first and second question.
Comment: This is four questions; you need to focus on one question. The answer to the last two questions are probably going to depend on what exactly you want to learn and what your background is.
Answer: Using definition from Wikipedia:

Natural language processing (NLP) is a subfield of linguistics,
computer science, information engineering, and artificial intelligence
concerned with the interactions between computers and human (natural)
languages [...]

NLP uses machine learning for solving linguistic problems, same as medical research can use statistics, but medical research is not statistics.
If you want to learn more about this field, you can check the Stanford's CS224n course lectures that were recorded and are freely available on YouTube. If you want to read about some recent research, I could recommend the blog by Sebastian Ruder from DeepMind. If you were looking for some kind of 'introductory book with code', Natural Language Processing with PyTorch by Delip Rao is nice.
Answer: Question like this may be too broad to answer.
Many people see machine learning is doing supervised learning (regression or classification.) and non-supervised learning (clustering). The data can be structured data (in table format, rows and columns) or unstructured data (text data, image data, etc).
So, if we are doing classification on text data (such as sentiment analysis), it is a NLP and machine learning problem. Similarly, doing document clustering would also be a machine learning problem.
To get started with NLP with machine learning or statistics background, you may read some tutorials to convert unstructured data into structured data, for example, using bag of words, or tfidf.
I personally feel below links are very helpful.
How to Prepare Text Data for Machine Learning with scikit-learn
How to Get Started with Deep Learning for Natural Language Processing


Não consigo inserir dados no sqlite usando javascript

Question: Estou criando um app de smartphone usando Cordova para um projeto da faculdade. o App consiste de um cadastro simples de pacientes. Estou tendo dificuldades em gravar dados no banco.
Inicialmente a gravação estava funcionando, mas esqueci de incluir um campo de id com auto incremento na tabela, e a partir daí nada funcionou. O mais estranho é que a função de callback de sucesso é executada, ou seja, aparentemente não há erro no insert.
também tive o cuidado de testar cada comando em um editor de base de dados sqlite e todos funcionaram corretamente.
O Código Javascript que estou usando está abaixo:
// Criando/abrindo o banco
var db = openDatabase("graudecoma", "1.0", "base de dados da aplicacao", 200000);

// criando a tabela caso ela não exista
    db.transaction(function(transaction){
        transaction.executeSql('CREATE TABLE IF NOT EXISTS pacientes ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "nome" TEXT NOT NULL, "abertura_ocular" INTEGER NOT NULL, "resposta_motora" INTEGER NOT NULL, "resposta_verbal" INTEGER NOT NULL, "diagnostico" TEXT)', [], null, db.onError);
    })

// função callback de erro
db.onError = function(transaction, e) {
  alert("Aconteceu um erro: " + e.message);
  console.log(e.message);
}

// função de callback de sucesso de insert
db.onSuccess = function(transaction, e) {
  alert("Dados Gravados com Sucesso!");
  console.log(e);
}

// função temporaria que lista resultados
db.getResults = function (transaction, r) {
    console.log('deu certo!');
    console.log(r);

   for(var i = 0; i < r.rows.length; i++){
       console.log(r.rows.item(i)[['id']]);
       console.log(r.rows.item(i)[['nome']]);
       console.log(r.rows.item(i)[['diagnostico']]);
   }
}

// aqui vai o insert
db.transaction(function(transaction){
  transaction.executeSql("INSERT INTO pacientes(nome, abertura_ocular, resposta_motora, resposta_verbal, diagnostico) VALUES(?, ?, ?, ?, ?)", [$('#nome').val(), $('input[name="sintoma-1"]:checked').val(), $('input[name="sintoma-2"]:checked').val(), $('input[name="sintoma-3"]:checked').val(), $('#diagnostico').val()], db.onSuccess, db.onError);
})

// consulta no banco
db.transaction(function(transaction){
    transaction.executeSql("SELECT * FROM pacientes", [], db.getResults, db.onError);
})

Como disse inicialmente, estava funcionando, mas após eu alterar o CREATE TABLE para incluir o id eu não consegui mais gravar.
Obs: eu também tive o cuidado de recriar a tabela. também experimentei criar um novo banco graudecoma2 e também uma nova tabela.
Answer: Seu problema é mais simples do que você pensa, remova o AUTOINCREMENT, pois toda chave primaria será por padrão AUTOINCREMENT
Abaixo tem um link com dúvidas frequentes sobre o SQLLite, só que em ingles, pode ser que te ajude futuramente SqlLite
Comment: Puxa, era isso mesmo! valeu mesmo!
Comment: @MarcusVBP caso a resposta atenda a sua pergunta, marque-a como resolvida para auxiliar que outras pessoas com dúvidas similares possam visualizar melhor a resolução.


java.lang.NoClassDefFoundError on older Android SDK versions

Question: I released a version of my app to the Google Play and woke up this morning with a number of unhappy customers.  The latest version of the app integrates support for a Bluetooth Low Energy (BTLE) heart rate monitor.
The app runs fine on Android 4.3 and 4.4 but crashes on 4.0, 4.1, and 4.2 with the following error.
FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: com.eiref.boatcoach.MainActivity
    at com.eiref.boatcoach.WhatToDo.onClick(WhatToDo.java:274)
    at android.view.View.performClick(View.java:4204)
    at android.view.View$PerformClick.run(View.java:17355)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:152)
    at android.app.ActivityThread.main(ActivityThread.java:5132)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)

The error occurs when creating an Intent in a simple Onclick similar to the following…
public void onClick(View v) {
        Intent i = new Intent(this, MainActivity.class);
        startActivity(i);
}

After rushing out and buying a 4.2 tablet so I can replicate the issue, I've come to the conclusion that it has to do with this new version of the app supporting Bluetooth LE, which is enabled in SDK 4.3 and later.  If I delete all references to Bluetooth in MainActivity then the crash goes away on 4.2 and earlier devices.
My understanding from reading the documentation was that one could write an app that includes Bluetooth LE functionality and it would run on older devices, just so long as one was careful not to execute BTLE code using something like the following...
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) return;
    BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    mBluetoothAdapter = manager.getAdapter();
//etc.

Therefore my manifest.xml does not include the following as it would prevent download to older devices and I obviously want to maintain a single code base if possible ...
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />

First question, is my assumption above being able to include BTLE code in SDKs prior to 4.3 correct?  If not, do I really need to create two versions of the app... one for folks using 4.3 and later and one for everyone else?
There are many StackOverflow posts about java.lang.NoClassDefFoundError and I think I've read most of the relevant ones.  Many suggest that I examine the Java Build Path to make sure that Android Private Libraries and Android Dependencies are checked.  They are.  Some suggest moving the gen folder before the src folder, but this doesn't seem to make a difference.
I'd post an image of the Eclipse Java Build Path but as this is my first post I don't have the 10 reputation points needed to insert an image, so here's another post that I followed... Android java.lang.NoClassDefFoundError
So, second question, any other thoughts about what could be wrong with the build path?
many thanks in advance.

Update... somehow by asking a question I got enough points to post images of the java build path.  As @Ashoke points out I do think it has something to do with the wrong build path or support libraries.
Comment: Is your main activity implementing any of the BLE callback methods directly?  Or do you have any static references to them?  All my BLE stuff is in an extending class from my standard stuff and I don't instance this class at all if the OS version is to low.
Comment: Does the same code inside your onClick run on >= 4.3 or is there another code path depending on Android version?
Comment: You definitely shouldn't need two versions of the application. As far as the uses-feature tag, I would recommend that you *do* include it, but set `android:required="false"`. I don't really think that's the root issue, but it's good to do anyway.
Comment: @MichaelKrause - yes exactly the same code path for the different Android Versions.
Comment: @kcoppock - I'll follow your advice but you're right it isn't the root issue.
Comment: @ifor - Thanks!  Putting all the BLE code in a separate class and then only instancing this class if BLE is supported seems to have done the trick.
Comment: I wrote an answer to this effect.
Comment: What is the manifest entry for `MainActivity`?
Answer: Try getting all of the Ble related code into a separate class that you only instance at all if on a device with the necessary API levels.  I think without this the call-backs could be leading to your issues.
Answer: I found that  defining the le callback statically in the activity gets an error, but inclosing it in a function with an api check will not produce the same error.
instead of:
    @TargetApi(Build.VERSION_CODES.LOLLIPOP){
    public class RouteMapActivity extends ActionBarActivity

    private BluetoothAdapter.LeScanCallback mScanCallback = new ScanCallback()    {...}

I used:
private void setUpLeCallbacks(){

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();

        for (BTDeviceName device : mTestPointsToRead) {
            ScanFilter filter = new ScanFilter.Builder().setDeviceAddress(device.le_serial).build();
            filters.add(filter);
        }

        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
            }

            @Override
            public void onScanFailed(int errorCode) {
                super.onScanFailed(errorCode);
            }
        };
    }else {
        mLeScanCallback= new BluetoothAdapter.LeScanCallback() {

            @Override
            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {

            }
        };

    }
}

Comment: @TargetApi(Build.VERSION_CODES.LOLLIPOP) overrides the lint errors.
Comment: how did you add the global variables with out getting VFY warnings from dalivk?
Answer: This is normal to get this exception on <4.3 devices because BLE didn't exist, so your compiled code can't find the corresponding classes in the OS.
Nothing wrong with your build path.
The best solution is indeed to protect your BLE code in a if clause, testing for BLE capability at runtime. You should also filter the OS version in the if like:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {...}

You should declare android:required="false" for this feature, it means that the application prefers to use the feature if present on the device, but that it is designed to function without the specified feature, if necessary.
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />

Comment: Thanks for the feedback.  However, the problem is that MainActivity.class (with my Bluetooth code) can't be found in Android versions <4.3 (causing the exception), therefore we never even get to the 'if' clause.
Comment: I think you should also add an OS check, which will ensure this code is not reached for low OS versions at compilation time (I updated the answer).
Answer: now that you are using APIs that may not be available in older Android versions, make sure you are packaging the app with appropriate support library.
For example, see this android sample BluetoothLeGattSample. It uses below support lib.
    dependencies {
       // Add the support lib that is appropriate for SDK 18
       compile "com.android.support:support-v13:19.0.+"
    }

see android docs for eclipse instructions for support library setup
Comment: Ashoke - Thanks for your advice.  I tried android-support-v13.jar to the Eclipse build path but no joy.


If dentro do button

Question: Eu tenho este button "Receber", e este checkbox que quando está marcado, quer dizer que a conta está quitada:

Eu preciso que quando ele clique no button Receber, e o checkbox já esteja marcado, que ele avise que a conta já foi recebida, e não redirecione a página,
Este é o código do button Receber:
  Receber

Como posso fazer um if dentro do button ?
Comment: Ele não reconhece este comando no button
Answer: O mais correto é fazer a lógica para criar dois botões diferentes:
@if(Model.Quitado){
  Receber
} else {
  Receber
}

Substitua a lógica do botão pela qual for melhor para a sua aplicação.
Comment: Deu certinho, obrigado.

If dentro do button


Views query alter add orderby function FIELD()

Question: I can't figure out how to add following expression to the views query:
ORDER BY FIELD(field_dataid,3,2,1,4)

QueryPluginBase only gives the option to add:
$query->addOrderBy('node_field_data', 'nid', ASC);

But doesn't give the option to add an expression.
The Sql interface has the options to add an expression:
  $query->addExpression('FIELD(node_field_data.nid,3,2,1,4)', 'order_field');
  $query->orderBy('order_field', 'ASC');

But this doesn't work with the views query object.
So how can i add orderby expression to the views query object?
Answer: There is a similar answer here: https://drupal.stackexchange.com/a/200662/79998
You should either use $query->addField() to add the expression and then append or unshift in $query->orderby array,
or you can use directly $query->addOrderBy() to add the expression and order, if it's ok to be added last.
$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,3,2,1,4)', 'ASC', 'order_field');


Mail server compromised. Yahoo refusing mails

Question: I think our mail server has been compromised. Today morning when I checked, there were 1298 refused mails from yahoo. with this message Messages from x.x.x.x.x(our ip) temporarily deferred due to user complaints - 188.8.131.52; see http://postmaster.yahoo.com/421-ts01.html)
Mails are getting delivered to gmail though. I am new to this, can anyone please suggest me where should I start looking ?
We are using Postfix and dovecot on Ubuntu Server 10.04. And I followed this guide here https://help.ubuntu.com/community/MailServer
Answer: FIRST - Check your system for signs of a rootkit as documented here, here or here. I personally like chkrootkit as a quick check.
1298 failed messages can be a lot, depending on what your normal volume is. You should check the bounce messages to see if they look like normal messages from your environment. If they aren't familiar, you've been compromised.

Clean up! If that means a rebuild, tracking down the bad processes, restoring from backup, etc. You'll need to remedy the situation that prompted the block.

I would also recommend doing exactly what the error message states. From there, browse to:
http://help.yahoo.com/l/us/yahoo/mail/postmaster/errors/421-ts01.html
Yahoo states:
When you see this error message in your SMTP logs (where x.x.x.x is your IP address), it's because of either of the following:
We are seeing unusual traffic from your IP address.
Email from your mail server is generating complaints from Yahoo! Mail users.
Please note that this is typically a temporary situation, and we encourage you to retry sending email to our servers approximately four hours after you encounter this error message.
If you see this error consistently over a 48-hour period, please fill out this form to give us enough information that we can actively pursue the issue.
Visit the form mentioned in the warning and work on getting unblocked.
Set the expectation for your users, though. This may take some time.
Comment: here is the output of chkrootkit scan http://paste.ubuntu.com/744939/ 1298 is too much because we have few users. I checked the messages and they are not at all normal. I have taken the following steps, I have deleted the complete queue and changed all the older passwords. Yahoo is now accepting our mails. I have also checked that our mail server is not open relay. What else can I do to ensure that something like this dont happen in future.
Answer: I would start looking at your postfix logs. Look for an increased mail flow higher than what you see in your logs for the past. I would specifically look for mail going to yahoo in case it might be something specific to them.
If you do see an increase in mail flow, look in the logs to see what the increase is. Is it tons of mail to a single user (like a run-away script sending automated messages), or to a large number of people (spam)? Once you identify some of the abnormal mail, just track it back and find where it came from.
You can also run qshape deferred to see if you have mail still queued up for yahoo (which you should since youre getting a 4xx response code). If you do, you can view the messages in /var/spool/postfix/deferred (use postcat to view the messages).
Its also possible that this could just be nothing. If your mail server doesnt send much to begin with, then even a small, but legitimate, increase could have tripped yahoo's spam thresholds.
The block message you provided usually disappears in a few hours if the issue that caused you to get blocked in the first place is resolved.
Comment: Mails are now getting delivered to yahoo. I deleted the older mail queue and changed all the older passwords.
Answer: It CAN be that you've been compromised.  Before that assumption, though, a few questions:

1) Are you sending mass mails out of that server?  If you are, Yahoo recipients may have flagged you as spam, and so they're refusing you.

2) Are you configured as an open relay?  That is to say, can you relay SMTP mail to domains other than your own from machines outside your network?  (To test, use these instructions to send mail to a gmail account or somesuch).  If you are an open relay, it's possible spammers are bouncing mail through your server, and you're getting spam complaints from Yahoo.
Comment: no, the mailserver is not open relay, I checked it using the instructions given on this page http://www.cyberciti.biz/tips/test-mail-server-for-an-open-relay.html , yahoo is now accepting our mails. I deleted the older mail queue and changed all the older passwords. What else I can do to ensure that such thing does not happen again ?
Comment: If you found the root cause, say an account with weak password and fixed it then you are fine.  If you still dont know what happen its best to keep an eye on your logs and next time your mail queue fills up check it for spam. Personal i have seen yahoo do stupid things when it comes to spam so they might be blocking you for forwarding email.
Comment: To be honest, there's NOTHING you can do to make sure it NEVER happens again.  You can take the precautions listed here - check for rootkits, make sure your passwords are strong, make sure you regularly apply security updates - but you're depending on Yahoo's internal processes to not flag you as a spammer.  Ultimately you have no DIRECT control over that.
Answer: I had a similar problem with Trend Micro. Maybe your public address on black list ?
If your user use internet over this IP, perhaps some of them use
torrent or other p2p software.


Permissions in discord.py

Question: I need the command to work if the user has either admin rights or the rights to ban members.  In my dreams it looked like this
<code>I looked for a solution in the documentation, unfortunately I did not find anything suitable
</code>
Answer: <code>@commands.has_permissions(administrator=True, ban_members=True)
</code>
Try and see if this works.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Permissions in discord.py


Java: Using JVM argument -XX:ErrorFile and append the logs in existing log file without pid

Question: I have following configuration for my service

exec java -Djava.io.tmpdir=$tmpdir -Djava.library.path="Some_Path"
  -Xmx"$heapsize"m -XX:+UseConcMarkSweepGC -XX:OnOutOfMemoryError="Do something, may be restart"
  -XX:ErrorFile=/var/log/service/myService/"myServiceCrash".log -jar .jar

I am not able to append the crash logs into the same file. But new file with new PID is created every time.
Requirement : Dump crash logs into same file.
Comment: What is the JDK version you are trying on?
Comment: I am using openjdk version "1.8.0_151"
Comment: Ok great, i will have a look,
Answer: This is expected behavior. For the first time it will write to the file provided in -XX:ErrorFile=, Once the file exists it won't be overwritten and you will then get the default error file.
Ideally there should be some way top show the file creation fails, but it can't be done as part of the error handling code.
Please check the evaluation here - https://bugs.openjdk.java.net/browse/JDK-8189672
Comment: Exactly, it is not customizable. I created my own bash to maintain the single log for the time being. Anyways, thanks... cheers


Rationalizing complex numbers when the denominator has a (+ 1) added to it

Question: If I were to try and rationalize a complex number like $Z + 2W + 3 \over Z + 1$, when I multiply by the conjugate of Z to make the denominator a real number, do I have to write z(conjugate)/z(conjugate) or z(conjugate) + 1/z(conjugate) + 1 or z(conjugate) - 1/z(conjugate) - 1??
(I'm sorry idk how to format the conjugate can someone help edit)
Answer: If $Z,W\in\mathbb{C}$ (and $Z\neq-1$) and if you wish to express $\dfrac{Z+2W+3}{Z+1}$ has a quotient whose denominator is a real number, the natural option consists in multiplying both numerator and denominator with $\overline{Z+1}$, thereby getting$$\frac{Z+2W+3}{Z+1}=\frac{(Z+2W+3)\left(\overline{Z+1}\right)}{(Z+1)\left(\overline{Z+1}\right)}=\frac{(Z+2W+3)\left(\overline Z+1\right)}{\lvert Z+1\rvert^2}.$$


Questions about theorem 2.1 and lemma 2.2 in chapter 3 of Stein's Real Analysis

Question: I have a difficulty dealing with some proofs in theorem 2.1 and lemma 2.2 in chapter 3 of Stein's Real Analysis. The theorem 2.1 and lemma 2.2 are as follows. For reference, pictures containing the theorems and lemma are posted as well.
Theorem 2.1: {$K_\delta$} is an approximation to the identity and $f$ is integrable on $R^d$. Then, $ (f*K_\delta)(x) → f(x)$ as $\delta → 0 $ for every $x$ in the Lebesgue set of $f$. (In particular, the limit holds for almost everywhere $x$)  Theorem 2.1
Lemma 2.2: $f$ is integrable on $R^d$ and $x$ is a point of Lebesgue set of $f$. Let $A(r) = \frac{1}{r^d}\int_{|y|<r}|f(x-y) - f(x)|dy$, whenever $r > 0$. Then, 1) $A(r)$ is a continuous function of $r > 0$, 2) $\lim_{r\to 0}A(r) = 0$, and 3) $A(r)$ is bounded.  Lemma 2.2
The Stein's textbook says the continuity of $A(r)$ follows by invoking the "absolute continuity". Also, the fact that $x$ belongs to the Lebesgue set of $f$ and the measure of a ball of radius $r$ is $v_dr^d$ make the $A(r)$ tend to $0$.  proof of lemma 2.2
This is where I'm stuck to. I can't relate the "absolute continuity" to the countinuity of $A(r)$. Also, I'm not sure how to use the property "$x$ belongs to the Lebesgue set of $f$, and the measure of a ball of radius $r$ is $v_dr^d$ " to show the convergence of $A(r)$.
For reference, let me type the definition of "absolute continuity" and the Lebesgue set of $f$ by Stein.
Absolute Continuity: Suppose $f$ is integrable on $R^d$. Then, for every $\epsilon > 0$ there is a $\delta > 0$ such that $\int_E|f| < \epsilon$ whenever $m(E) < \delta$. absolute continuity
Lebesgue set of $f$: If $f$ is locally integrable on $R^d$, the Lebesgue set of $f$ consists of all points $x ∈ R^d$ for which $f(x)$ is finite and $\lim_{m(B)\to 0}\frac{1}{m(B)}\int_B|f(y)-f(x)|dy = 0$ (where $x ∈ B$). Lebesgue set of $f$
Any help will be appreciated, especially explanation based on Real Analysis would be grateful (bcz I've only studied undergraduate level of Analysis (Rudin's PMA) and just a beginner of Stein's Real Analysis).
Answer: The absolute continuity is used because the difference between the evaluations of the function $A$ at two very close radii is an integral over the difference set between two balls. That is,
$$\int_{|y|< r_1}|f(x-y)-f(x)|dy - \int_{|y|< r_2}|f(x-y)-f(x)|dy= \int_{r_1<|y|< r_2}|f(x-y)-f(x)|dy $$
assuming $0<r_1<r_2$. So you are integrating an integrable function over the set $\{y|r_1<|y|< r_2\}$, whose measure goes to zero as $r_1$ approaches $r_2$ or viceversa. So, $A(r_1)-A(r_2)$ has to go to zero by absolute continuity of the function $|f(x-y)-f(x)|$ (the factor $\frac{1}{r^d}$ does not make much of a difference since it is continuous). In any case, one could use dominated convergence theorem here as well.
Second. You simply check that the thing you want to prove is a special case of the definiton of Lebesgue point. You can make a change of variables and rewrite the integral as
$$ \frac{1}{r^d}\int_{|y|< r}|f(x-y)-f(x)|dy= \frac{1}{r^d}\int_{|z-x|< r}|f(z)-f(x)|dz, $$
and note that the set $\{z||z-x|< r\}$ is a ball that contains $x$, and the factor ${r^d}$ is exactly the size of the ball, up to a fixed multiplicative constant. Therefore, by the definition of Lebesgue point, it has to go to zero as $r$ approaches zero.

Edit: clarifying some details.
So first, for the continuity of $A$ is enough to show the continuity of the function $F:r\mapsto {r^d}A(r)$, because $A(r)=F(r)\frac{1}{r^d}$ and $\frac{1}{r^d}$ is a continuous function (and the product of two continuous fct. is continuous). So, we consider $F$ instead of $A$ (i.e., we throw away the factor $\frac{1}{r^d}$).
Now, fix $r>0$. Fix $\epsilon>0$. By absolute continuity of $g(y):=|f(x-y)-f(x)|$, there exists $\delta$ such that the integral of $g$ over a set $E$ is less than $\epsilon$ if $|E|<\delta$. Now note as before that, for a given $s>0$, we have
$$ |F(r)-F(s)|=\int_{E}g(y)dy, $$
where $E=\{ r<|y|< s\}$ if $s>r$ and $E=\{ s<|y|< r\}$ if $s<r$. In both cases, we have $|E|=C|r^d-s^d|$ for some constant $C$ (just subtract the volumes of the two balls), so that it is less than $\delta$ when $|s-r|<\delta'$, where $\delta'>0$ depends only on $\delta$ and $r$ (you can compute it yourself, but it is not important at all, you simply lnow it exists because of the continuity of the function $s\mapsto C|r^d-s^d|$). So… combining everything together, if $|r-s|<\delta'$, then $|F(r)-F(s)|<\epsilon$, which is the definition of continuity since $\epsilon>0$ is arbitrary. So $f$ is continuous at the point $r$.
When doing analysis, this kind of arguments are used all the time, so you first have to learn to do this by hand and then with some experience you see it immediately and you don't need to write the details every time to convince yourself. Writing all the details, though, is still quite long as you can see XD
Comment: Thanks for the reply. I see the idea that $A(r_1) - A(r_2)$ becomes zero, but could you please explain more in detail (mathematically) about it? Especially, the difference of the integral without the reciprocal $1/r^d$ makes me a little bit confused. (I'm not sure but) it is estimated that there should be an inequality with respect to $|A(r_1) - A(r_2)|$ which should be smaller than some $\epsilon$, but I can't think of how to induce it with the idea you've mentioned. Thanks.
Comment: Sure. Check my edits
Comment: Wow, now I clearly understand your answer. Thank you for your kindness.


Expected cost of algorithm

Question: I am having an algorithm which cost I want to determine, but I am having trouble to do so. In order to do so, I tried to break it down to a well known scenario, to be able to communicate the issue:
Let's say I have an urn with balls of $R$ different colours.
For each color there are $D$ balls in the urn, so in total there are $R\cdot D$ balls in the urn.
Now I am going to draw $m$ balls from the urn.
For some magical reasons, the maximum of balls I can draw of the same colour is $D-1$.
Let's further say there is going to be a cost evoked for each type of ball I draw that is exponential to the number of balls I draw of that type, so $g^i$, where $i$ is the amount of balls I draw of a specific colour.
Whether I draw three red balls and two black balls or three black balls and two red balls does not matter though - that is the same cost.
My goal is to find out what the expected cost is going to be.
Here are the thoughts: First one can say that the expected cost for each colour is
$$
\sum_{i=0}^{D-1} p_m(i) \cdot g^i
$$
where $p_m(i)$ is the probability to draw $i$ balls of this colour.
First question
It is save to say that for the first colour to draw
$$
p_m(i) = \frac{D}{D\cdot R} \cdot \frac{D-1}{D\cdot R-1} \cdot\ ...\ \cdot \frac{D-(i-1)}{D\cdot R-(i-1)}
$$
Is it right, that I can reduce this to the Binomial distribution
$$
p_m(i) = \binom {m}{i} \cdot \left(\frac{D}{D\cdot R}\right)^i \cdot \left(1 - \frac{D}{D\cdot R}\right)^{m-i}
$$
and if so why? I think not, because the binomial distribution is only for independent experiments, and once I have drawn a (let's say red) ball, the probability to draw another red ball goes down. However maybe I am at least able to say
$$
p_m(i) < \binom {m}{i} \cdot \left(\frac{D}{D\cdot R}\right)^i \cdot \left(1 - \frac{D}{D\cdot R}\right)^{m-i} \qquad ?
$$
After all I am going to try to find an upper bound for the cost.
Second question
Can I say that the total expected cost is
$$
R \cdot \sum_{i=0}^{D-1} p_m(i) \cdot g^i \qquad ?
$$
On the one hand, all colours are equal, on the other hand having many balls drawn of one colour reduces the likelihood for other colours to be drawn, so I am not sure. Would this be at least a reasonable approximation as an upper bound?
Answer: The number of balls of a particular color being drawn follows a hypergeometric distribution, with pmf
$$ \Pr\{X = k\} = \frac {\displaystyle \binom {d} {k} \binom {(r-1)d} {m-k}} {\displaystyle \binom {rd} {m}}, k = 0, 1, \ldots, m$$
Therefore the expected cost for this particular color is
$$ E[g^X] = \sum_{k=0}^{d-1} g^k \frac {\displaystyle \binom {d} {k} \binom {(r-1)d} {m-k}} {\displaystyle \binom {rd} {m}}$$
You are correct that since the distribution of each particular color are identical, we have
$$ E\left[\sum_{j=1}^r g^{X_j}\right] = \sum_{j=1}^r E[g^{X_j}] = rE[g^{X_j}]$$
The sum itself does not have a closed form solution (it is a hypergeometric function)
Comment: Thanks for the hypergeometric distribution. After that (answer to my question 2) I am not sure I can follow: Please keep in mind, that I continue to draw all the time. From the entire urn I draw $m$ times. So if I draw a couple of white and red balls, that would change the number of available balls and thus the concrete pmf (still hypergeometric, but with different parameters) of the available black balls?
Comment: Sorry previously I misread that you are drawing $d-1$ balls out from the urn. Now you draw $m$ number of balls out of the urn, so I updated the formula. In this setting I am considering all the draw all in once, not one by one. $X$ is the number of balls of a particular color over all $m$ drawn balls. Finally, if your magical reason is that all color must keep at least one in the urn, I think you just reduce $d$ to $d-1$ and you will be fine.
Comment: How is it making a difference whether I draw all balls at once or one at the time? Shouldn't be the probability be the same?
Comment: Yes then I just misunderstand your doubt
Comment: What I mean is this (considering I am taking one ball out after the other): If you have only two colors (white, black) and you want to know about likelihoods of taking the amount of white balls taken out, you use the Binomial distribution if you put the balls back in - because for each draw you the likelihood of drawing a white does not change. But if don't put the drawn balls back, you need to use the hypergeometric distribution - so a different one. For my scenario you don't put the balls back in, so for each color we have a hypergeometrical distribution.
Comment: But as far as I understand the hypergeometrical, it only discusses two colors (success and non-success). I think I understand that the idea is that for each color it does not matter which other color is drawn - simply that it is a different color. So that is why each color can be considered separately and they can be summed up (manifested in the $R\dot$, since the sum's element are all the same). Is that correct? Also: Can you explain what $g^{X_j}$ is supposed to mean? I guess the $X$ is a random variable, but I don't quite get how this relates to my formulas - also with the $j$ vs my $i$.
Comment: Yes I think you get my point. $X_j$ are the number for the $j$-th color and they jointly follows a multi-hypergeometric distribution, but marginally, as you said, follows a hypergeometric distribution. I assume the total cost is the sum of individual cost of each color, so thats why we have the last formula. $j$ is just a dummy variable, indexing different colors.
Comment: You wrote $(r-1)d$ but I think you meant $(d-1)r$, yes? However, I did some experiments, and none of this seems to be correct: https://math.stackexchange.com/questions/2399307/expected-cost-of-algorithm-based-on-hypergeometrical-distribution

Expected cost of algorithm


Fretted notes consistantly ~10cents sharp across the fretboard compared to open

Question: I have a baritone ukulele, which is basically a classical nylon-string guitar except missing the 2 bass strings.
I've noticed when I tune I can either have fretted notes in tune or open notes in tune but not both. I adjusted the truss rod and now the fretted notes are all within a few cents of each other but still all sharp of open.
Should I lower the bridge? I do feel the action is a bit high but I can't find anything online about how it will affect tuning/intonation....
It is like, a solid block and angled toward the fretboard, so sanding it down should increase the distance from the saddle to the nut, yes?
I am a beginner and so am hesitant to experiment...
Answer: If all the fretted notes are in tune (pretty much) with each other, the problem is most likely at the nut, not the bridge.  Either the strings are too high in the nut or the distance from the nut to the first fret is too great.  But you probably should get a luthier to look at it.
Comment: I checked around what string height at the nut should be and it seems, according to what I can find, that mine is a half millimeter too high at least.  So yeah I think this is the correct answer
Answer: With a high action, inevitably when strings are pressed down, there will be a slight stretching going on. This could be the cause of sharpness. Another could be that the intonation isn't good. Check that the 12th fret harmonic is exactly the same pitch as the fretted note there, hopefully without pressing too hard, which in itself has been a cause of sharpened pitches. I had a student who used that technique to produce vibrato - quite effectively.
Answer: Other answers have pointed to the high action and very well may be your particular problem, but I've noticed the same kind of symptom a few years ago on a telecaster that I'd purchased. I realized the frets were considerably larger than the ones on my strat, and when I pressed the strings down to the fret-board I was effectively stretching the string sharp. The large frets make string bending and vibrato much easier, but I had to get use to not pushing the string past the point of contact with the fret if I wanted to maintain accurate pitch. It took a little getting used to, but I like it just fine now.


ServiceStack.Text serialization exception (Incorrect number of arguments supplied for call to method 'Void set_Item(Int32, MyApp.MyClass)')

Question: I am trying to deserialize an object that contains nested lists of classes with ServiceStack.Text.
The serialization went well, but when trying to deserialize, I get this error:

System.TypeInitializationException: The type initializer for
  'ServiceStack.Text.Jsv.JsvReader1' threw an exception. --->
  System.TypeInitializationException: The type initializer for
  'ServiceStack.Text.Jsv.JsvReader1' threw an exception. --->
  System.TypeInitializationException: The type initializer for
  'ServiceStack.Text.Common.DeserializeList2' threw an exception. --->
  System.TypeInitializationException: The type initializer for
  'ServiceStack.Text.Jsv.JsvReader1' threw an exception. --->
  System.TypeInitializationException: The type initializer for
  'ServiceStack.Text.Jsv.JsvReader1' threw an exception. --->
  System.TypeInitializationException: The type initializer for
  'ServiceStack.Text.Common.DeserializeList2' threw an exception. --->
  System.TypeInitializationException: The type initializer for
  'ServiceStack.Text.Jsv.JsvReader`1' threw an exception. --->
  System.ArgumentException: Incorrect number of arguments supplied for
  call to method 'Void set_Item(Int32, MyApp.MyClass)'

I have no method named set_Item in my solution, neither can I find a method named like this in the ServiceStack.Text assembly (using reflector). I have no clue of what the problem could be...And I need a fast serialization type, but the fastest I know(protobuf-net) doesn't support nested lists.
Any ideas? The class that caused the problem is below (the protomembers are there because I tested the protobuf method)

    [Serializable]
///
/// Description of Livres.
///
public class Livres : IEnumerable<Livre>
{

    [ProtoMember(1)]
    private List<Livre> listeLivres;

    public List<Livre> ListeLivres
    {
        get { return listeLivres; }
        set { listeLivres = value; }
    }

    public List<string> NomLivres
    {
        get
        {
            List<string> lst = new List<string>();
            foreach (Livre livre in this.listeLivres)
            {
                lst.Add(livre.NomLivre);
            }
            return lst;
        }
    }

    public int Count
    {
        get
        {
            return ((this.listeLivres != null) ? this.listeLivres.Count : 0);
        }
    }

    public Livre this[string nomLivre]
    {
        get
        {
            nomLivre = nomLivre.ToLower();
            if (nomLivre == "")
            {
                return null;
            }
            try
            {
                var u = this.listeLivres.Single(book => book.NomLivre.ToLower() == nomLivre);
                return u;
            }
            catch (InvalidOperationException)
            {
                string pattern = "^[0-9][a-zA-Z]+$";
                Regex reg = new Regex(pattern);
                if (reg.IsMatch(nomLivre))
                {
                    string nom = nomLivre[0].ToString() + " ";
                    nom += nomLivre.Substring(1).ToLower();
                    try
                    {
                        var u = this.listeLivres.Single(book => book.NomLivre.ToLower() == nom);
                        return u;
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
                else
                    return null;
            }
        }
        set
        {
            if (nomLivre == "")
            {
                throw new
                    ArgumentNullException("L'index ne doit pas être une chaine vide.");
            }
            try
            {
                Livre liv = this.listeLivres.Single(book => book.NomLivre == nomLivre);
                liv = value;
            }
            catch (InvalidOperationException ex)
            {
                string pattern = "^[0-9][a-zA-Z]+$";
                Regex reg = new Regex(pattern);
                if (reg.IsMatch(nomLivre))
                {
                    string nom = nomLivre[0].ToString() + " ";
                    nom += nomLivre.Substring(1);
                    try
                    {
                        Livre L = this.listeLivres.Single(book => book.NomLivre == nom);
                        L = value;
                    }
                    catch (Exception e)
                    {
                        throw new ArgumentException("Ce nom de livre n'existe pas dans la liste", e);
                    }
                }
                else
                    throw new ArgumentException("Ce nom de livre n'existe pas dans la liste", ex);
            }
        }
    }
    ///
    /// Obtient ou définit le Livre à l'index spécifié - 1
    /// Exceptions:
    /// ArgumentOutOfRangeException
    ///
    public Livre this[int index]
    {
        get
        {
            if (index < 1 || index > this.listeLivres.Count)
            {
                throw new
                    ArgumentOutOfRangeException("L'index spécifié n'était pas correct");
            }
            return this.listeLivres[index-1];

        }
        set
        {
            if (index < 1 || index > this.listeLivres.Count)
            {
                throw new
                    ArgumentOutOfRangeException("L'index spécifié n'était pas correct");
            }
            this.listeLivres[index - 1] = value;
        }
    }

    #region Constructeurs
    public Livres()
    {
        this.listeLivres = new List<Livre>();
    }
    public Livres(Livre livre)
        : this()
    {
        this.listeLivres.Add(livre);
    }

    #endregion
    ///
    /// Retourne le verset correspondant si il existe, sinon null
    /// Exceptions
    /// ArgumentException
    ///
    /// <param name="referenceComplete">La référence du verset sous forme de chaine (ex: "1 Jean 5:19")</param>
    public Verset GetVerset(string referenceComplete)
    {
        if (string.IsNullOrWhiteSpace(referenceComplete))
            return null;
        string[] tab = referenceComplete.Split();
        try
        {
            string livre = "";
            int chapitre;
            int verset;
            if (tab.Length>2)
            {
                livre = tab[0];
            }
            livre += tab[tab.Length -2];
            string [] tabVerse = tab[tab.Length -1].Split(':');
            chapitre = Convert.ToInt32(tabVerse[0]);
            verset = Convert.ToInt32(tabVerse[1]);
            return this[livre][chapitre][verset];
        }
        catch (Exception ex)
        {
            throw new ArgumentException("Il n'y a aucun verset avec cette référence",ex);
        }
    }

    public void Add(Livre livre)
    {
        this.listeLivres.Add(livre);
    }

    public static Livres operator +(Livres livres, Livre livre)
    {
        livres.Add(livre);
        return livres;
    }

    public IEnumerator<Livre> GetEnumerator()
    {
        foreach (Livre item in this.listeLivres)
        {
            yield return item;
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    public void Serialize(string pathName= "BibleData.txt")
    {
        try
        {
            #region ServiceStack Serializer
            TextWriter tw = new StreamWriter(pathName);
            TypeSerializer<Livres> TypeSrlzr = new TypeSerializer<Livres>();
            TypeSrlzr.SerializeToWriter(this,tw);
            //TypeSerializer.SerializeToWriter(this,tw);
            tw.Close();
            #endregion

        }
        catch (Exception)
        {

            throw;
        }
    }

    public static Livres Deserialize(string pathName= "BibleData.txt")
    {
        try
        {
            Livres Bible;
            #region ServiceStack Deserializer
            TextReader tr = new StreamReader(pathName);

            TypeSerializer<Livres> typeSrlzr = new TypeSerializer<Livres>();
            Bible = typeSrlzr.DeserializeFromReader(tr);
            //Bible = TypeSerializer<Livres>.DeserializeFromReader(tr);
            #endregion

            return Bible;
        }
        catch (Exception) {

            throw;
        }
    }

}

Comment: Can you post an example of the class you're trying to deserialize that's causing the error?
Comment: I've only had a chance to look at this today, unfortunately the code doesn't complile as it has missing a few classes. The JsonSerializer doesn't support cyclical dependencies which could be your problem.
Answer: You don't want to inherit from an IEnumerable as it will not likely behave in the way you expect. i.e. all Enumerables are serialized like a JSON Array/Collection and the additional properties are ignored.
The problem with only having an IEnumerable interface is that there is no way to generically populate it. So whilst you may be able to serialize it, you won't be able to deserialize it.
You would be more successful if you implemented a collection interface that also provides an ability to populate it, i.e. IList<T> or ICollection<T>.
Comment: I had all my classes that implemented IEnumerable implement IList, completed the need functions, and the problem remains the same
Answer: I had the same problem. I needed my classes to inherit IDataErrorInfo, and the problem is in the indexed property. You can fix it yourself in the source code though. In the OrmLiteConfigExtensions find the method GetModelDefinition and look for:
GetValueFn = propertyInfo.GetPropertyGetterFn(),
SetValueFn = propertyInfo.GetPropertySetterFn(),
replace the GetValueFn line only with:
GetValueFn = (propertyInfo.GetIndexParameters().Length == 0)?null:propertyInfo.GetPropertyGetterFn(),
This way it will skip setting the GetValueFn property for indexed properties which throws the exception.


Proxy Error with ColdFusion 8, but not with Railo3.1! Whats going on?

Question: I have installed Apache 2.2.11, jboss 5.1.0.GA, ColdFusion 8.0.1 and Railo 3.1.0.015.
Railo and ColdFusion are served through jboss as exploded WAR and EAR and both are available as VirtualHosts on port 80 through Apache, the details are available here (thank you Indiver Nagpal): http://nagpals.com/blog/post.cfm/running-railo-and-adobe-coldfusion-on-the-same-context-root-in-jboss
I am developing a small project but have now encountered a problem with Apache and/or ColdFusion.
When i navigate to my site http://cf8.local/myproject/user-update.cfm and fill out a form, which on submit triggers a database update and returns to the same site, i get the following error:

502 Proxy Error
  Proxy Error
  The proxy server received an invalid response from an upstream server.
  The proxy server could not handle the request POST /myproject/user-update.cfm.
  Reason: Error reading from remote server

When i open the same site through railo (http://railo.local/myproject/update-user.cfm) everything works as expected (i expect an error debug-output).
What can cause this behaviour? Is it a ColdFusion misconfiguration or an Apache misconfiguration?
Answer: Is the ColdFusion code executing properly?  I would check the ColdFusion error logs to ensure that ColdFusion isn't experiencing an exception or runtime error that the proxy isn't able to return properly.
Comment: i made a change in my code to make my program run. i have forgot to write that railo has shown an error output (as expected) while ColdFusion has greeted me with the mentioned Apache Error. Everything works now.


Generator functions with next() call

Question: I had a look on the new future from ecmascript 6 - generator functions and I'm a bit confused about what .next() function does.
In the official documentation they say, and I quote : A zero arguments function that returns an object with two properties:, information updated on Feb 17, 2015 4:57:46 PM according to their website ( <- link to documentation provided here )
So, let's say we have this generator function :
 function* first(){
    yield 1;
    yield 2;
 }
 var f= first();

When calling f.next() will return {value:1, done:false}. When you call it again will return {value:2, done:true}
BUT, if we have something like this:
function* second() {
  var a = yield "HELLO";
  console.log("a = ", a);

  var b = yield a+ 1;
  console.log("b = ", b);

  return b
}
var f= second();

When you call it like this: f.next() you'll receive {value: "HELLO", done: false}
Next call  will be f.next(1), which will assign 1 to a, and it will output {value: 2, done: false}
Next call will be f.next(1), which will output {value: 1, done: true}
Questions

How it's possible you can call .next() with parameter if in the official documentations it's stated it's a zero parameter function ?
Why at 3rd result has value property equal to 1  and at the second call it's equal to 2?
Why b is 1 and not 2 ?

Thank you !
PS: Of course, there's another usage of generator functions ( to avoid callbacks ), but I'm asking about this particular case.

Comment: While MDN is a good source for JavaScript, you can't really say it's the "official" documentation. Truly official is only the ECMAScript specification.
Comment: I didn't know. I've got a link to it from the guy above. Thank you !
Answer:

How it's possible you can call .next() with parameter if in the official documentations it's stated it's a zero parameter function ?

Quoting the draft version of ES-6,

Arguments may be passed to the next function but their interpretation and validity is dependent upon the target Iterator. The for-of statement and other common users of Iterators do not pass any arguments, so Iterator objects that expect to be used in such a manner must be prepared to deal with being called with no arguments.

So, passing arguments to next doesn't violate the ES6 specifications. In this case, the value passed to next will be assigned to the variable you are assigning the yield expression to.

Why at 3rd result has value property equal to 1 and at the second call it's equal to 2?
Why b is 1 and not 2 ?

The list of operations in the order as they happen

f.next()
yield "HELLO"

So you are getting { value: 'HELLO', done: false }
f.next(1)
var a = 1;
console.log("a = ", a);
yield a + 1

That is why you are getting { value: 2, done: false } in this call.
f.next(1)
var b = 1;
console.log("b = ", b);
return b

That is why you are getting { value: 1, done: true } here.
Comment: yea, but var b= yield a +1 ? Shouldn't it be 2 ?
Comment: @Kosmo I edited my answer a little bit, does it answer your question?
Comment: Yes ! Thank you ! I undestand the concept better now
Answer: Use other values and it becomes much clearer. It's working as intended.
function* second() {
  var a = yield "HELLO";

  console.log("a = ", a);
  var b = yield a+ 1;

  console.log("b = ", b);
  return b
}
var f= second();

console.log('1:',f.next());
console.log('2:',f.next(5));
console.log('3:',f.next(7));

outputs
///1st next()
//yeld returns iterator
{value: "HELLO", done: false}

//2nd next(5)
//the console log gets executed with var a = 5
a = 5
//yeld returns iterator
{value: 6, done: false}

//3rd next(7)
//the console log gets executed with var b = 7
b = 7
//it doesn't use the 'a' var at all, neither does it add +1 to the yeld allocation
//yeld returns iterator
{value: 7, done: true}

Generator functions with next() call


Do two column equivalent systems share the same solution set?

Question: We know that if two system of linear equations are row equivalent then they share the same solution set,but can we say the same for column equivalence as well?i.e.given a system $Ax=b$and another system $Cx=d$ such that $[A|b]$and $[C|d]$are column equivalent,can we conclude that they have the same solution set?
Answer: Note that $[A|\lambda b]$ is column equivalent to $[A|b]$ for any nonzero scalar $\lambda.$  This should be apparent that it breaks solution sets.
For a simple [if somewhat degenerate] example, assuming $A = b = 1$ (i.e. $A, x, b \in \mathbb{R}$) gives $x = 1,$ but this is column equivalent to $x = 2$ by choosing $\lambda = 2.$

If you want, you can look at every "elementary column operation" to answer this question more generally.  It should be apparent that none of them maintains all solution sets.
Comment: "Swapping two columns" shows that $0x = 1$ is column-equivalent to $1x = 0,$ so no.
Comment: But is consistency preserved under column operation?
Comment: I am sure about the operations $C_{ij}$ and $C_{j}(c)$
Comment: Oh I got it....